Exemple #1
0
bool CTargetFind::isWithinRange(position_t* pos, float range)
{
    return distance(m_PBattleEntity->loc.p, *pos) <= range;
}
/**
* Checks if the mob can detect the target using it's detection (sight, sound, etc)
* This is used to aggro and deaggro (Mobs start to deaggro after failing to detect target).
**/
bool CMobController::CanDetectTarget(CBattleEntity* PTarget, bool forceSight)
{
    if (PTarget->isDead() || PTarget->isMounted()) return false;

    float verticalDistance = abs(PMob->loc.p.y - PTarget->loc.p.y);

    if (verticalDistance > 8)
    {
        return false;
    }

    auto detects = PMob->m_Detects;
    auto currentDistance = distance(PTarget->loc.p, PMob->loc.p) + PTarget->getMod(Mod::STEALTH);

    bool detectSight = (detects & DETECT_SIGHT) || forceSight;
    bool hasInvisible = false;
    bool hasSneak = false;

    if (!PMob->m_TrueDetection)
    {
        hasInvisible = PTarget->StatusEffectContainer->HasStatusEffectByFlag(EFFECTFLAG_INVISIBLE);
        hasSneak = PTarget->StatusEffectContainer->HasStatusEffect(EFFECT_SNEAK);
    }

    if (detectSight && !hasInvisible && currentDistance < PMob->getMobMod(MOBMOD_SIGHT_RANGE) && isFaceing(PMob->loc.p, PTarget->loc.p, 40))
    {
        return CanSeePoint(PTarget->loc.p);
    }

    if ((PMob->m_Behaviour & BEHAVIOUR_AGGRO_AMBUSH) && currentDistance < 3 && !hasSneak)
    {
        return true;
    }

    if ((detects & DETECT_HEARING) && currentDistance < PMob->getMobMod(MOBMOD_SOUND_RANGE) && !hasSneak)
    {
        return CanSeePoint(PTarget->loc.p);
    }

    // everything below require distance to be below 20
    if (currentDistance > 20)
    {
        return false;
    }

    if ((detects & DETECT_LOWHP) && PTarget->GetHPP() < 75)
    {
        return CanSeePoint(PTarget->loc.p);
    }

    if ((detects & DETECT_MAGIC) && PTarget->PAI->IsCurrentState<CMagicState>() &&
        static_cast<CMagicState*>(PTarget->PAI->GetCurrentState())->GetSpell()->hasMPCost())
    {
        return CanSeePoint(PTarget->loc.p);
    }

    if ((detects & DETECT_WEAPONSKILL) && PTarget->PAI->IsCurrentState<CWeaponSkillState>())
    {
        return CanSeePoint(PTarget->loc.p);
    }

    if ((detects & DETECT_JOBABILITY) && PTarget->PAI->IsCurrentState<CAbilityState>())
    {
        return CanSeePoint(PTarget->loc.p);
    }

    return false;
}
Exemple #3
0
    std::list<ESM::Pathgrid::Point> PathFinder::aStarSearch(const ESM::Pathgrid* pathGrid,int start,int goal,float xCell, float yCell)
    {
        cleanUpAStar();
        mGScore[start] = 0;
        mFScore[start] = distance(pathGrid->mPoints[start],pathGrid->mPoints[goal]);

        std::list<int> openset;
        std::list<int> closedset;
        openset.push_back(start);

        int current = -1;

        while(!openset.empty())
        {
            current = openset.front();
            openset.pop_front();

            if(current == goal) break;

            closedset.push_back(current);

            for(int j = 0;j<static_cast<int> (mGraph[current].edges.size());j++)
            {
                //int next = mGraph[current].edges[j].destination
                if(std::find(closedset.begin(),closedset.end(),mGraph[current].edges[j].destination) == closedset.end())
                {
                    int dest = mGraph[current].edges[j].destination;
                    float tentative_g = mGScore[current] + mGraph[current].edges[j].cost;
                    bool isInOpenSet = std::find(openset.begin(),openset.end(),dest) != openset.end();
                    if(!isInOpenSet
                        || tentative_g < mGScore[dest] )
                    {
                        mGraph[dest].parent = current;
                        mGScore[dest] = tentative_g;
                        mFScore[dest] = tentative_g + distance(pathGrid->mPoints[dest],pathGrid->mPoints[goal]);
                        if(!isInOpenSet)
                        {
                            std::list<int>::iterator it = openset.begin();
                            for(it = openset.begin();it!= openset.end();it++)
                            {
                                if(mGScore[*it]>mGScore[dest])
                                    break;
                            }
                            openset.insert(it,dest);
                        }
                    }
                }
            }

        }

        std::list<ESM::Pathgrid::Point> path;
        while(mGraph[current].parent != -1)
        {
            //std::cout << "not empty" << xCell;
            ESM::Pathgrid::Point pt = pathGrid->mPoints[current];
            pt.mX += xCell;
            pt.mY += yCell;
            path.push_front(pt);
            current = mGraph[current].parent;
        }

        if(path.empty())
        {
            ESM::Pathgrid::Point pt = pathGrid->mPoints[goal];
            pt.mX += xCell;
            pt.mY += yCell;
            path.push_front(pt);
        }

        return path;
    }
/* METAR examples
Berlin-Schoenefeld, Germany (EDDB) 52-23N 013-31E 50M
Sep 26, 2013 - 03:50 AM EDT / 2013.09.26 0750 UTC
Wind: from the NNE (020 degrees) at 13 MPH (11 KT):0
Visibility: 3 mile(s):0
Sky conditions: mostly cloudy
Weather: light drizzle
Temperature: 46 F (8 C)
Dew Point: 46 F (8 C)
Relative Humidity: 100%
Pressure (altimeter): 29.83 in. Hg (1010 hPa)
ob: EDDB 260750Z 02011KT 6000 -DZ SCT003 BKN006 08/08 Q1010 TEMPO BKN010
cycle: 8

Station name not available
Aug 18, 2013 - 09:30 PM EDT / 2013.08.19 0130 UTC
Sky conditions: partly cloudy
Temperature: 59 F (15 C)
Dew Point: 57 F (14 C)
Relative Humidity: 93%
Pressure (altimeter): 30.39 in. Hg (1029 hPa)
ob: OPSD 190130Z CALM 09KM P/CLOUDY FEW015ST SCT035 Q1029/30.41 15/14C RH 95 PERCENT A/V OH CLEAR
cycle: 1
*/
void PreFlightWeatherPage::slotNewWeaterReport( QString& file )
{
  QFile report(file);

  QString station = QFileInfo(file).baseName();

  if( file.contains("/weather/METAR/") )
    {
      if ( ! report.open( QIODevice::ReadOnly ) )
        {
          // could not open file ...
          qWarning() << "Cannot open file: " << report.fileName();
          return;
        }

      // METAR report received
      QTextStream stream( &report );
      QString line;

      QHash<QString, QString> reportItems;
      reportItems.insert( "icao", station );

      int lineNo = 0;

      int tempUnit = GeneralConfig::instance()->getUnitTemperature();
      int pressureUnit = GeneralConfig::instance()->getUnitAirPressure();

      while( !stream.atEnd() )
        {
          line = stream.readLine();
          lineNo++;

          // qDebug() << "line=" << line;

          if( line.trimmed().isEmpty() )
            {
              // ignore comment and empty lines
              continue;
            }

          if( lineNo == 1 )
            {
              // Line 1: station name
              // Berlin-Schoenefeld, Germany (EDDB) 52-23N 013-31E 50M
              // Station name not available
              if( line.startsWith( "Station name not available" ) )
                {
                  reportItems.insert( "station", tr("Station name not available") );
                  continue;
                }

              int idx = line.indexOf( "(" + station + ")" );

              if( idx > 0 )
                {
                  reportItems.insert( "station", line.left(idx - 1) );
                  continue;
                }

              reportItems.insert( "station", line );
              continue;
            }

          if( lineNo == 2 )
            {
              // Line 2: Date and time
              // Sep 26, 2013 - 11:50 AM EDT / 2013.09.26 1550 UTC
              if( line.endsWith(" UTC") )
                {
                  int idx = line.indexOf( " / " );

                  if( idx > 0 && line.size() > (idx + 3) )
                    {
                      QString date = line.mid(idx + 3, 13) + ":" +
                                     line.mid(idx + 3 + 13);

                      reportItems.insert( "date", date );
                      continue;
                    }
                }

              reportItems.insert( "date", line );
              continue;
            }

          if( line.startsWith( "Wind: ") )
            {
              // Wind: from the NW (310 degrees) at 5 MPH (4 KT):0
              // Wind: from the W (280 degrees) at 5 MPH (4 KT) (direction variable):0
              // Wind: from the ESE (120 degrees) at 20 MPH (17 KT) gusting to 32 MPH (28 KT) (direction variable):0
              line.replace( " degrees", QChar(Qt::Key_degree) );

              if( line.endsWith( ":0") )
                {
                  line.chop(2);
                }

              // Remove the line beginning.
              line = line.mid(6);
              int loop = 6;

              while( loop-- )
                {
                  QRegExp re = QRegExp("[0-9]+ MPH \\([0-9]+ KT\\)");

                  int idx1 = line.indexOf(re, 0);

                  if( idx1 == -1 )
                    {
                      // No speed value found.
                      break;
                    }

                  int idx2 = line.indexOf( "(", idx1 + 1 );
                  int idx3 = line.indexOf( " KT)", idx1 + 1 );

                  if( idx2 > 0 && idx2 < idx3 )
                    {
                      bool ok;
                      double ws = line.mid(idx2 + 1, idx3 - idx2 -1).toDouble(&ok);

                      if( ok )
                        {
                          Speed speed(0);
                          speed.setKnot( ws );

                          QString wsText = speed.getWindText( true, 0 );

                          line = line.left(idx1) + wsText + line.mid(idx3 + 4);
                        }
                    }
                }

              reportItems.insert( "wind", line );
              continue;
            }

          if( line.startsWith( "Visibility: ") )
            {
              // Visibility: greater than 7 mile(s):0
              // Visibility: less than 1 mile:0
              // Visibility: 3/4 mile(s):0
              if( line.contains( " mile") )
                {
                  int idx2  = line.lastIndexOf( " mile" );
                  int idx1  = line.lastIndexOf( " ", idx2 - 1 );

                  if( idx1 > 0 && idx1 < idx2 )
                    {
                      bool ok = false;
                      double visiDouble = 0.0;

                      QString visiText = line.mid(idx1 + 1, idx2 - idx1 -1);

                      if( visiText.contains("/") )
                        {
                          QStringList visiList = visiText.split("/");

                          if( visiList.size() == 2 )
                            {
                              double arg1 = visiList.at(0).toDouble(&ok);

                              if( ok )
                                {
                                  double arg2 = visiList.at(1).toDouble(&ok);

                                  if( ok && arg2 > 0.0 )
                                    {
                                      visiDouble = arg1 / arg2;
                                    }
                                }
                            }
                        }
                      else
                        {
                          visiDouble = visiText.toDouble( &ok );
                        }

                      if( ok )
                        {
                          Distance distance(0);
                          distance.setMiles( visiDouble );

                          QString visibility = line.mid( 12, idx1 - 11 );

                          if( distance.getKilometers() > 5 )
                            {
                              visibility += distance.getText( true, 0 );
                            }
                          else
                            {
                              visibility += distance.getText( true, 1 );
                            }

                          if( line.contains("mile(s)") )
                            {
                              // This must be tested as first to prevent wrong handling!
                              if( ! line.endsWith( "mile(s):0") )
                                {
                                  line.replace( ":0", "" );
                                  visibility += line.mid( line.indexOf( "mile(s)" ) + 7 );
                                }
                            }
                          else if( line.contains("mile") && ! line.endsWith( "mile:0") )
                            {
                              if( ! line.endsWith( "mile:0") )
                                {
                                  line.replace( ":0", "" );
                                  visibility += line.mid( line.indexOf( "mile" ) + 4 );
                                }
                            }

                          reportItems.insert( "visibility", visibility );
                          continue;
                        }
                    }
                }

              reportItems.insert( "visibility", line.mid(12) );
              continue;
            }

          if( line.startsWith( "Sky conditions: ") )
            {
              // Sky conditions: partly cloudy or mostly cloudy
              reportItems.insert( "sky", line.mid(16) );
              continue;
            }

          if( line.startsWith( "Weather: ") )
            {
              reportItems.insert( "weather", line.mid(9) );
              continue;
            }

          if( line.startsWith( "Temperature: ") )
            {
              // Temperature: 51 F (11 C)
              if( tempUnit == GeneralConfig::Fahrenheit )
                {
                  // Temperature in F
                  int idx = line.indexOf( " F (" );

                  if( idx > 0 )
                    {
                      reportItems.insert("temperature", line.mid(13, idx-13 ) + QChar(Qt::Key_degree) + "F");
                      continue;
                    }
                }
              else
                {
                  // Temperature in C
                  int idx2 = line.lastIndexOf( " C)" );
                  int idx1 = line.lastIndexOf( "(", idx2 -1 );

                  if( idx1 > 0 && idx1+1 < idx2 )
                    {
                      reportItems.insert("temperature", line.mid( idx1+1, idx2-idx1-1 ) + QChar(Qt::Key_degree) + "C");
                      continue;
                    }
                }

              reportItems.insert("temperature", line.mid( 13 ) );
              continue;
            }

          if( line.startsWith( "Dew Point: ") )
            {
              // Dew Point: 42 F (6 C)
              if( tempUnit == GeneralConfig::Fahrenheit )
                {
                  // Dew point in F
                  int idx = line.indexOf( " F (" );

                  if( idx > 0 )
                    {
                      reportItems.insert("dewPoint", line.mid(11, idx-11) + QChar(Qt::Key_degree) + "F");
                      continue;
                    }
                }
              else
                {
                  // Dew point in C
                  int idx2 = line.lastIndexOf( " C)" );
                  int idx1 = line.lastIndexOf( "(", idx2 - 1 );

                  if( idx1 > 0 && idx1+1 < idx2 )
                    {
                      reportItems.insert("dewPoint", line.mid( idx1+1, idx2-idx1-1 ) + QChar(Qt::Key_degree) + "C");
                      continue;
                    }
                }

              reportItems.insert("dewPoint", line.mid( 11 ) );
              continue;
            }

          if( line.startsWith( "Relative Humidity: ") )
            {
              // Relative Humidity: 71%
              reportItems.insert( "humidity", line.mid(19) );
              continue;
            }

          if( line.startsWith( "Pressure (altimeter): ") )
            {
              // Pressure (altimeter): 30.00 in. Hg (1016 hPa)
              if( pressureUnit == GeneralConfig::inHg )
                {
                  // QNH in inch Hg
                  int idx = line.lastIndexOf( " (" );

                  if( idx > 22 )
                    {
                      reportItems.insert("qnh", line.mid(22, idx - 22 ));
                      continue;
                    }
                }
              else
                {
                  // QHN in hPa
                  int idx2 = line.lastIndexOf( " hPa)" );
                  int idx1 = line.lastIndexOf( "(", idx2 - 1 );

                  if( idx1 > 0 && idx1+2 < idx2 )
                    {
                      reportItems.insert("qnh", line.mid( idx1 + 1, idx2 - idx1 + 3 ));
                      continue;
                    }
                }

              reportItems.insert("qnh", line.mid( 22 ));
              continue;
            }

          if( line.startsWith( "ob: ") )
            {
              // Extract the observation line from the report.
              // ob: EDDB 261550Z 31004KT 9999 FEW030 SCT056 11/06 Q1016 NOSIG
              reportItems.insert( "observation", line.mid(4) );
              continue;
            }
        }

      report.close();

      // qDebug() << "ReportItems:" << reportItems;

      m_metarReports.insert( station, reportItems );
      updateIcaoItem( station );
    }
  else if( file.contains("/weather/TAF/") )
    {
      /* TAF Example
      2013/09/26 12:29
      TAF EDDF 261100Z 2612/2718 32008KT 9999 SCT035
            BECMG 2617/2619 04005KT
      */

      // TAF report received. The whole report is stored in the hash as one string.
      if ( ! report.open( QIODevice::ReadOnly ) )
        {
          // could not open file ...
          qWarning() << "Cannot open file: " << report.fileName();
          return;
        }

      // TAF report received
      QTextStream stream( &report );
      QString line;
      QString tafReport;

      int lineNo = 0;

      while( !stream.atEnd() )
        {
          line = stream.readLine();
          lineNo++;

          if( line.trimmed().isEmpty() || lineNo == 1 )
            {
              // ignore comment and empty lines
              // ignore line 1, it contains the date and time
              continue;
            }

          if( tafReport.isEmpty() )
            {
              tafReport = line;
            }
          else
            {
              tafReport += "\n" + line;
            }
        }

      report.close();

      m_tafReports.insert( station, tafReport );

      // qDebug() << "TAFs:" << m_tafReports;
    }

  if( m_displayWidget->isVisible() )
    {
      if( m_list->topLevelItemCount() == 0 )
        {
          return;
        }

      IcaoItem *item = dynamic_cast<IcaoItem *>( m_list->currentItem() );

      if( item == 0 )
        {
          return;
        }

      if( item->getIcao() == station )
        {
          // The display widget is visible and must be updated too, if new
          // station data are available.
          slotDetails();
        }
    }
}
Exemple #5
0
/*!
 * @brief クエストに関わるモンスターの配置を行う / Place quest monsters
 * @return 成功したならばTRUEを返す
 */
bool place_quest_monsters(void)
{
    int i;

    /* Handle the quest monster placements */
    for (i = 0; i < max_quests; i++)
    {
        monster_race *r_ptr;
        u32b mode;
        int j;

        if (quest[i].status != QUEST_STATUS_TAKEN ||
                (quest[i].type != QUEST_TYPE_KILL_LEVEL &&
                 quest[i].type != QUEST_TYPE_RANDOM) ||
                quest[i].level != dun_level ||
                dungeon_type != quest[i].dungeon ||
                (quest[i].flags & QUEST_FLAG_PRESET))
        {
            /* Ignore it */
            continue;
        }

        r_ptr = &r_info[quest[i].r_idx];

        /* Hack -- "unique" monsters must be "unique" */
        if ((r_ptr->flags1 & RF1_UNIQUE) &&
                (r_ptr->cur_num >= r_ptr->max_num)) continue;

        mode = (PM_NO_KAGE | PM_NO_PET);

        if (!(r_ptr->flags1 & RF1_FRIENDS))
            mode |= PM_ALLOW_GROUP;

        for (j = 0; j < (quest[i].max_num - quest[i].cur_num); j++)
        {
            int k;

            for (k = 0; k < SAFE_MAX_ATTEMPTS; k++)
            {
                int x = 0, y = 0;
                int l;

                /* Find an empty grid */
                for (l = SAFE_MAX_ATTEMPTS; l > 0; l--)
                {
                    cave_type    *c_ptr;
                    feature_type *f_ptr;

                    y = randint0(cur_hgt);
                    x = randint0(cur_wid);

                    c_ptr = &cave[y][x];
                    f_ptr = &f_info[c_ptr->feat];

                    if (!have_flag(f_ptr->flags, FF_MOVE) && !have_flag(f_ptr->flags, FF_CAN_FLY)) continue;
                    if (!monster_can_enter(y, x, r_ptr, 0)) continue;
                    if (distance(y, x, p_ptr->y, p_ptr->x) < 10) continue;
                    if (c_ptr->info & CAVE_ICKY) continue;
                    else break;
                }

                /* Failed to place */
                if (!l) return FALSE;

                /* Try to place the monster */
                if (place_monster_aux(0, y, x, quest[i].r_idx, mode))
                {
                    /* Success */
                    break;
                }
                else
                {
                    /* Failure - Try again */
                    continue;
                }
            }

            /* Failed to place */
            if (k == SAFE_MAX_ATTEMPTS) return FALSE;
        }
    }

    return TRUE;
}
Exemple #6
0
void slice_torus (struct msscene *ms, struct surface *current_surface, double fine_pixel, double probe_radius, struct face *fac)
{
	int k, j, i, nfocus, near1, naif;
	double anginc, bigrad;
	double focus[3], vect1[3], vect2[3], vect[3], qvect[3];
	double dtq, tcv[3];
	double *foci = (double *) NULL;
	char message[MAXLINE];
	struct leaf *lf;
	struct circle *cir1, *cir2, *cir3;
	struct circle *lfcir, *torcir;
	struct variety *vty, *atm1, *atm2;
	struct arc *a, *nxta;
	struct arc *torarc;
	struct vertex *torvtx[2];
	struct vertex *qvtx;
	struct vertex *conevtx;
	struct cycle *cyc;
	struct edge *edg;
    struct cept *ex;

	vty = fac -> vty;
	if (vty -> type != TORUS) {
		ex = new_cept (GEOMETRY_ERROR,  INCONSISTENCY,  FATAL_SEVERITY);
		add_function (ex, "slice_torus");
		add_source (ex, "msrender.c");
        add_long (ex, "variety type", (long) vty -> type);
		return;
	}
	if (vty -> tube) {
		slice_elbow (ms, current_surface, fine_pixel, fac);
		return;
	}

	if (debug >= 2) {
		sprintf (message,"render saddle face for atoms %5d %5d",
			vty -> atmnum[0], vty -> atmnum[1]);
		inform(message);
	}

	/* get pointers to atom varieties */
	atm1 = *(current_surface -> variety_handles + fac -> vty -> atmnum[0] - 1);
	atm2 = *(current_surface -> variety_handles + fac -> vty -> atmnum[1] - 1);

	/* check versus window */
	bigrad = distance (atm1 -> center, atm2 -> center) +
		atm1 -> radii[0] + atm2 -> radii[0];

	for (k = 0; k < 3; k++) {
		if (vty -> center[k] + bigrad < ms -> window[0][k]) return;
		if (vty -> center[k] - bigrad > ms -> window[1][k]) return;
	}
	/* leaf circle */
	lfcir = allocate_circle ();
	if (error()) {
		add_object (tail_cept, CIRCLE, "leaf circle");
		add_function (tail_cept, "slice_torus");
		return;
	}
	/* leaf */
	lf = allocate_leaf ();
	if (error()) {
		add_object (tail_cept, LEAF, "leaf");
		add_function (tail_cept, "slice_sphere");
		return;
	}
	/* torus circle radius, center, axis */
	torcir = new_circle (vty -> center, vty -> radii[0], vty -> axis);
	if (torcir == NULL) {
		add_object (tail_cept, CIRCLE, "torus circle");
		add_function (tail_cept, "slice_circle");
		return;
	}
	/* torus arc */
	torarc = allocate_arc ();
	if (error()) {
		add_object (tail_cept, ARC, "torus arc");
		add_function (tail_cept, "slice_torus");
		add_source (tail_cept, "msrender.c");
		return;
	}
	for (j = 0; j < 2; j++) {
		torvtx[j] = allocate_vertex ();
		if (error()) {
			add_object (tail_cept, VERTEX, "torus vertex");
			add_function (tail_cept, "slice_torus");
			add_source (tail_cept, "msrender.c");
			return;
		}
	}
	torarc -> cir = torcir;
	/* copy atom numbers from variety to leaf */
	for (k = 0; k < MAXPA; k++)
		lf -> atmnum[k] = fac -> vty -> atmnum[k];

	/* set up leaf fields */
	lf -> cir = lfcir;
	lf -> shape = fac -> shape;
	lf -> type = fac -> vty -> type;
	lf -> fac = fac;
	lf -> cep = 0;
	lf -> clip_ep = 0;
	lf -> side = OUTSIDE;
	lf -> comp = fac -> comp;
	lf -> input_hue = fac -> input_hue;

	/* both endpoints of saddle face leaf are always accessible */
	for (j = 0; j < 2; j++)
		lf -> where[j] = ACCESSIBLE;

	/* angular increment for rotation of leaf about torus axis */
	anginc = fine_pixel / (vty -> radii[0]);

	/* next we need endpoints for torus arc */
	/* get them from concave arcs bounding saddle face */

	/* intialization */
	cir1 = NULL;
	cir2 = NULL;
	cir3 = NULL;
	qvtx = NULL;
	conevtx = NULL;
	near1 = 0;

	/* look for concave arcs */
	naif = 0;
	for (cyc = fac -> first_cycle; cyc != NULL; cyc = cyc -> next)
		for (edg = cyc -> first_edge; edg != NULL; edg = edg -> next) {
			naif++;
			a = edg -> arcptr;
			if (a -> shape == CONVEX) {
				cir3 = a -> cir;
				continue;
			}
			if (edg -> next == NULL)
				nxta = cyc -> first_edge -> arcptr;
			else
				nxta = edg -> next -> arcptr;
			if (along (edg, vty -> axis))
				cir2 = a -> cir;
			else
				cir1 = a -> cir;
			/* check for cusp vertex */
			if (a -> shape == CONCAVE && nxta -> shape == CONCAVE) {
				/* cusp point joints two concave arcs */
				qvtx = a -> vtx[1-edg->orn];
			}
		}

	dtq = probe_radius * probe_radius - vty -> radii[0] * vty -> radii[0];

	/* later: note: check PI in bubbles */

	if (naif == 1) {
		if (dtq <= 0.0) {
			ex = new_cept (GEOMETRY_ERROR,  INCONSISTENCY,  FATAL_SEVERITY);
			add_function (ex, "slice_torus");
			add_source (ex, "msrender.c");
			add_message(ex, "toroidal face with only one arc, but not cone");
			return;
		}
		if (cir3 == NULL) {
			ex = new_cept (GEOMETRY_ERROR,  INCONSISTENCY,  FATAL_SEVERITY);
			add_function (ex, "slice_torus");
			add_source (ex, "msrender.c");
			add_message(ex, "toroidal face with only one arc, but no contact circle");
			return;
		}
		/* cone */
		qvtx = allocate_vertex ();
		if (error()) {
			add_object (tail_cept, VERTEX, "CUSP VERTEX");
			add_function (tail_cept, "slice_torus");
			add_source (tail_cept, "msrender.c");
			return;
		}
		conevtx = qvtx;
		dtq = sqrt (dtq);
		for (k = 0; k < 3; k++)
			tcv[k] = cir3 -> center[k] - torcir -> center[k];
		normalize (tcv);
		for (k = 0; k < 3; k++)
			qvtx -> center[k] = torcir -> center[k] + dtq * tcv[k];
		/* hope this is enough */
	}
	if (cir1 == NULL) informd2 ("cir1 null");
	if (cir2 == NULL) informd2 ("cir2 null");
	if (qvtx != NULL) informd2 ("cusp present");

	/* check for cusp vertex */
	if (qvtx != NULL) {
		for (k = 0; k < 3; k++)
			qvect[k] = qvtx -> center[k] - vty -> center[k];
		near1 = (dot_product (qvect, vty -> axis) < 0.0);
	}

	/* check for hoop saddle face */
	if (cir1 == NULL || cir2 == NULL) {
		for (j = 0; j < 2; j++)
			torarc -> vtx[j] = NULL;
		informd2 ("complete toroidal hoop");
	}
	else {
		/* concave arc circle centers are endpoints of sphere rolling */
		for (k = 0; k < 3; k++) {
			torvtx[0] -> center[k] = cir1 -> center[k];
			torvtx[1] -> center[k] = cir2 -> center[k];
		}
		for (j = 0; j < 2; j++)
			torarc -> vtx[j] = torvtx[j];
		sprintf (message, "saddle rendering (from): %8.3f %8.3f %8.3f",
			cir1 -> center[0], cir1 -> center[1], cir1 -> center[2]);
		informd2 (message);
		sprintf (message, "saddle rendering (to)  : %8.3f %8.3f %8.3f",
			cir2 -> center[0], cir2 -> center[1], cir2 -> center[2]);
		informd2 (message);
	}

	/* the probe sphere centers are the foci of the leaves */
	nfocus = render_sub_arc (torarc, &foci, anginc);
	if (nfocus < 2) {
		ex = new_cept (LOGIC_ERROR, MSUNDERFLOW, FATAL_SEVERITY);
        add_function (ex, "slice_torus");
        add_source (ex, "msrender.c");
        add_long (ex, "number of foci", (long) nfocus);
		return;
	}
	sprintf (message, "nfocus = %d", nfocus);
	informd2 (message);

	/* create leaves */
	for (i = 0; i < nfocus; i++) {
		for (k = 0; k < 3; k++) {
			focus[k] = (*(foci + 3 * i + k));
			lfcir -> center[k] = focus[k];
			lf -> focus[k] = focus[k];
		}

		/* unit vectors from focus toward atoms */
		for (k = 0; k < 3; k++) {
			vect1[k] = atm1 -> center[k] - focus[k];
			vect2[k] = atm2 -> center[k] - focus[k];
		}
		/* correct for cusp vertex */
		if (qvtx != NULL) {
			if (near1)
				for (k = 0; k < 3; k++)
					vect2[k] = qvtx -> center[k] - focus[k];
			else
				for (k = 0; k < 3; k++)
					vect1[k] = qvtx -> center[k] - focus[k];
		}
		/* normalize vectors to unit length */
		normalize (vect1);
		normalize (vect2);

		/* leaf circle radius is probe radius */
		lfcir -> radius = probe_radius;
		/* set up endpoints of leaf */
		for (k = 0; k < 3; k++) {
			lf -> ends[0][k] = focus[k] + lfcir -> radius * vect1[k];
			lf -> ends[1][k] = focus[k] + lfcir -> radius * vect2[k];
		}
		/* compute leaf circle axis */
		for (k = 0; k < 3; k++)
			vect[k] = focus[k] - vty -> center[k];
		cross (vty -> axis, vect, lfcir -> axis);
		normalize (lfcir -> axis);

		/* clip and render leaf */
		clip_leaf (ms, current_surface, fine_pixel, lf);
		if (error()) return;
	}

	/* return temporary memory */
	if (!free_doubles (foci, 0, VERTS)) {
		ex = new_cept (MEMORY_ERROR,  FREEING,  FATAL_SEVERITY);
		add_variable (ex, VERTS, "foci");
		add_function (ex, "slice_torus");
		add_source (ex, "msrender.c");
		return;
	}

	free_leaf (lf);
	free_arc (torarc);
	free_circle (torcir);
	free_circle (lfcir);
	for (j = 0; j < 2; j++)
		free_vertex (torvtx[j]);
	if (conevtx != NULL) free_vertex (conevtx);
	return;
}
Exemple #7
0
void SpriteBehavior() // Din kod!
{
    SpritePtr i = gSpriteRoot; 
    SpritePtr j = i->next;
    
    int count = 0;
    float dPos;


    FPoint black_hole = {0,0};
    FPoint alignmentVel = {0,0};

    while(i != NULL){
	if(i->ai_type == DOG){
	    i = i->next;
	    continue;
	}

	count = 0;
	while(j != NULL){
	    
	    dPos = distance(i->position, j->position);

	    if(dPos < maxDist){
		count++;

		// Cohesion
		if(i->ai_type == SHEEP || j->ai_type != DOG){
		    black_hole.h += j->position.h;
		    black_hole.v += j->position.v;
		}

		if(j->ai_type != DOG){
		    // Alignment
		    alignmentVel.h += j->speed.h;
		    alignmentVel.v += j->speed.v;
		}
	    }

	    // Separation
	    if(dPos < minDist && (i != j)){
		i->speed.h += 1/(dPos + 0.1)*separationCoeff*(i->position.h - j->position.h);
		i->speed.v += 1/(dPos + 0.1)*separationCoeff*(i->position.v - j->position.v);
	    }

	    if(j->ai_type == DOG && dPos < maxDist){
		i->speed.h += 1/(dPos + 0.1)*10*separationCoeff*(i->position.h - j->position.h);
		i->speed.v += 1/(dPos + 0.1)*10*separationCoeff*(i->position.v - j->position.v);
	    }

	    j = j->next;
	}

	black_hole.h /= count;
	black_hole.v /= count;

	alignmentVel.h /= count;
	alignmentVel.v /= count;

	if(i->ai_type == SHEEP){
	    i->speed.h += cohesionCoeff*(black_hole.h - i->position.h);
	    i->speed.v += cohesionCoeff*(black_hole.v - i->position.v);

	    i->speed.h += alignmentCoeff*alignmentVel.h;
	    i->speed.v += alignmentCoeff*alignmentVel.v;
	}

	i->speed.h += i->randomness*((float)random()/RAND_MAX - 0.5);
	i->speed.v += i->randomness*((float)random()/RAND_MAX - 0.5);
	
	if(normFPoint(i->speed) > maxSpeed) {
	    i->speed.h = maxSpeed*normalizeFPoint(i->speed).h;
	    i->speed.v = maxSpeed*normalizeFPoint(i->speed).v;
	}

	i = i->next;
	j = gSpriteRoot;

	black_hole.h = 0;
	black_hole.v = 0;

	alignmentVel.h = 0;
	alignmentVel.v = 0;
    }
}
QImage Triangledetection::detect(const QImage &source, const QImage &imageBase)
{
    //QImage binary = detectionContour(extraireRouge(source));
    QImage binary = detectionContour(source);
    QImage detection = binary.convertToFormat(QImage::Format_RGB888);

    QVector<QPoint> ligne = hough(detection);
    std::cout << "-> Nombre de ligne detecté : " << ligne.size() << std::endl;

    QVector<QPoint> ligne_angle0,ligne_angle60,ligne_angle120;
    QPoint inter1,inter2,inter3;
    int l1,l2,l3;



    //Avoir les lignes avec des angles pouvant appartenir à un panneau (+ ou - 1°)
    avoirLigneAngle(ligne,ligne_angle0,90,1);
    avoirLigneAngle(ligne,ligne_angle0,270,1);

    avoirLigneAngle(ligne,ligne_angle60,150,1);
    avoirLigneAngle(ligne,ligne_angle60,330,1);

    avoirLigneAngle(ligne,ligne_angle120,210,1);
    avoirLigneAngle(ligne,ligne_angle120,30,1);

    //On determine les intersections et les longueurs des segments
    for(int i=0;i<ligne_angle0.size();i++)
    {
        for(int j=0;j<ligne_angle60.size();j++)
        {
            for(int k=0;k<ligne_angle120.size();k++)
            {

                inter1 = intersection(ligne_angle0[i],ligne_angle60[j]);
                inter2 = intersection(ligne_angle60[j],ligne_angle120[k]);
                inter3 = intersection(ligne_angle120[k],ligne_angle0[i]);

                l1 = distance(inter1,inter2);
                l2 = distance(inter2,inter3);
                l3 = distance(inter3,inter1);

                //Si les distance sont les mêmes et que tous les points sont dans l'image => on a un triangle
                if(l1 == l2 && l2 == l3 && l1 > 30 && l1 < 100 && estPointImage(detection,inter1) && estPointImage(detection,inter2) && estPointImage(detection,inter3))
                {
                    Triangle a;
                    a.p1 = inter1;
                    a.p2 = inter2;
                    a.p3 = inter3;
                    liste_triangle.push_back(a);
                }
            }
        }
    }

    std::cout<<"-> Nombre de triangle detectés avant élimination des doublons : " << liste_triangle.size() << std::endl;

    //On supprime les triangle doublons
    supprimerDoublon();

    //Dessiner les triangles à l'écran
    for(int i=0;i<liste_triangle.size();i++)
        dessiner(detection,liste_triangle[i],qRgb(0,255,127));


    //Generer les images avec les cercles reconnus
    for(int i=0;i<liste_triangle.size();i++)
    {
        int minX = liste_triangle[i].p1.x();
        int minY = liste_triangle[i].p1.y();
        int maxX = liste_triangle[i].p1.x();
        int maxY = liste_triangle[i].p1.y();
        if (liste_triangle[i].p2.x()<minX) minX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()<minY) minY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p2.x()>maxX) maxX = liste_triangle[i].p2.x();
        if (liste_triangle[i].p2.y()>maxY) maxY = liste_triangle[i].p2.y();
        if (liste_triangle[i].p3.x()<minX) minX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()<minY) minY = liste_triangle[i].p3.y();
        if (liste_triangle[i].p3.x()>maxX) maxX = liste_triangle[i].p3.x();
        if (liste_triangle[i].p3.y()>maxY) maxY = liste_triangle[i].p3.y();


        QImage BlueRoadSigns = QImage(maxX-minX, maxY-minY, QImage::Format_RGB32);

        for(int row = 0;row<maxY-minY;row++)
        {
            for (int col=0;col<maxX-minX;col++)
            {
                QColor clrCurrent(imageBase.pixel(col+minX,row+minY));

                int red = clrCurrent.red();
                int green = clrCurrent.green();
                int blue = clrCurrent.blue();

                BlueRoadSigns.setPixel(col, row, qRgb(red,green,blue));
            }
        }

        liste_TrianglesReconnu.push_back(BlueRoadSigns);
    }

    std::cout<<"-> Nombre de triangle detectés : " << liste_triangle.size() << std::endl;

    return detection;
}
void ClassifyIntegralFeature(char *id)
{
	float thr =  0.99f;



	//LPCTSTR file = __targv[1];
	char filename[100];
	CString str(id);
	str = str.Left(str.Find("."));
	sprintf(filename, "InputImage\\%s.bmp",str.GetBuffer(0));
	CImageObject m_Image;
	m_Image.LoadImage(filename);
	printf("Load input image : %s\n", filename);

	//SerializeImage(m_Image.GetBMPPixelPtr(), m_Image.Width(), m_Image.Height(), rt, serialized);
	//m_Image.CreateReshape(serialized, rt.Width(), rt.Height(), 3);	
	CMatLoader convolvedFeatures;
	
	//CNNConvolution(m_Image.m_rgb_pixel,m_Image.Width(), m_Image.Height(),convolvedFeatures);

	//SerializeSTLImage(trainImages, vecImages);
	//    featureLength x imageNum x pooledCountX x pooledCountY    (400 x 2000 x 3 x 3)
	// -> featureLength x pooledCountX x pooledCountY x imageNum    (400 x 3 x 3 x 2000)
	// -> [featureLength x pooledCountX x pooledCountY] x imageNum    
	CMatLoader convolvedFeaturesMatlab(str.GetBuffer(0),"InputImage");
	CMatLoader meanFeature;
	int featureSize = convolvedFeaturesMatlab.dim[0];
	meanFeature.Create(featureSize * 3 * 3,1);

	//CMatLoader pooledFeaturesCatLarge(filename);
	int height = convolvedFeaturesMatlab.dim[2];
	int width = convolvedFeaturesMatlab.dim[3];
	//pooledFeaturesCatLarge.Seriallize();
	int row, col;

	CMatLoader softmaxOptTheta("softmaxOptThetaNoise");
	CMatLoader softmaxOptTheta5320("softmaxOptTheta5320");
	

	vector <short> vecLabel;
	vector <float> vecConfidence;

	CStopWatch w;

	
	
	CIntegralFeature *features = new CIntegralFeature [featureSize];
	
	int i;
	

	// Calculate integral image in separated features
	for (i = 0;i< featureSize;i++)	
	{
		double *separatedFeature = new double[height * width];
		features[i].Create(width, height);
			
		for (col = 0;col < width;col++)
		{
			
			for (row = 0;row < height;row++)
			{
				// row -> col order
				separatedFeature[row * width + col] = convolvedFeaturesMatlab.data[(col * height + row) * featureSize + i];
				//if (i == 13)
				//log.WriteLog("%d,%d,%d,%f\n", i, row, col,convolvedFeatures.data[(col * height + row) * featureSize + i]);
				
			}
		}
		features[i].CalculateIntegralImage(separatedFeature);

		delete [] separatedFeature;
	}


	CLog log("confidence.csv", 1);

	// Calculate mean feature in box area with k x k size
	int k;
	//k = 128/3 - 5;//min(width,height) /2;
	// int step = 19;
	int start = min(width,height) / 3 - 5;
	int end = start / 2;
	int candidate = 0;
	vector <int> vecCandidateLabel;
	
	BOOL found = FALSE;
	CRectEx rtCadidate;
	//vector <CRectEx> vecRect;
	//vector <double> vecScore[4];
	CRectEx rtFinal;

	for (k = start;k>= end ;k-=10)	
	{
		for (row = 0;row <= height - (k * 3) ;row+=k/2)
		{
			for (col = 0;col <= width - (k * 3);col+=k/2)
			{
				int row2, col2;
				int featureIndex = 0;
				for (col2 = 0;col2 < 3;col2++)
				{
					
					for (row2 = 0;row2 < 3;row2++)
					{
						//log.WriteLog("%d,%d,", row,col);		
						//log.WriteLog("%d,%d,", col + (col2 * k), row + (row2 * k));
						for (i=0;i<featureSize;i++)
						{
							meanFeature.data[featureIndex++] = (features[i].GetBlockMeanByIntegralImage(col + (col2 * k), row + (row2 * k), k, k));
							//if (col == 95 && row == 0)
							//	log.WriteLog("%f\n", meanFeature.data[i]);
						}
					}
					
				}
				//log.WriteLog("\n");
				//ClassifySoftmaxRegressionSingle(meanFeature, softmaxOptTheta, vecLabel, vecConfidence);
				//if (vecLabel[0] == 5 ) continue;
				CRectEx rt;
				rt.SetRect(0,0,k*3+8,k*3+8);
				rt.Offset(col,row);

				//m_OvrDisp.DrawRect(rt,color[vecLabel[0]], 10,"%s(%d)",className[vecLabel[0]], vecLabel[0]);
				//log.WriteLog("%s,%d, %.1f, %.1f, %.1f, %.1f,%.1f,",className[vecLabel[0]], vecLabel[0], vecConfidence[0],vecConfidence[1],vecConfidence[2],vecConfidence[3], vecConfidence[4]);

				ClassifySoftmaxRegressionSingle(meanFeature, softmaxOptTheta5320, vecLabel, vecConfidence);
				if (k==start)
					vecCandidateLabel.push_back(vecLabel[0]-1);
				else if (vecLabel[0] == candidate)
				{
					//m_OvrDisp.DrawRect(rt,color[vecLabel[0]], 10,"%s(%d) %.1f %.1f %.1f %.1f",className[vecLabel[0]], vecLabel[0], vecConfidence[0]);
					//vecRect.push_back(rt);
					rtFinal = rt;
					found = TRUE;
				}

				log.WriteLog(",%s,%d,%.1f, %.1f, %.1f, %.1f\n",className[vecLabel[0]], vecLabel[0], vecConfidence[0],vecConfidence[1],vecConfidence[2],vecConfidence[3]);
				if (vecLabel[0] != 5 && vecConfidence[0] > 0.99)		
				{					
					//ClassifySoftmaxRegression(meanFeature, softmaxOptTheta100percentTraining, vecLabel, vecConfidence);
				//	m_OvrDisp.DrawRect(rt,color[vecLabel[0]], 10,"%s(%d) %.1f %.1f %.1f %.1f",className[vecLabel[0]], vecLabel[0], vecConfidence[0]);
				//	goto FINISH;
				}
				else
				{
					//m_OvrDisp.DrawRect(rt,color[vecLabel[0]], 10,"%s(%d) %f",className[vecLabel[0]], vecLabel[0], vecConfidence[0]);
				}


				//m_OvrDisp.DrawRect(rt,MCYAN);
				//log.WriteLog("%d,%f\n",vecLabel[0],vecConfidence[0]);
				
			}
		}

		if (k == start)
		{
			vector <int> histo;
			histo.resize(4);
			for (int l=0;l<(int)vecCandidateLabel.size();l++)
				histo[vecCandidateLabel[l]]++;

			candidate = distance(histo.begin(), max_element(histo.begin(), histo.end())) + 1;
			rtCadidate.SetRect(0,0,k*3+8,k*3+8);
			//rtCadidate.Offset(col,row);
		}
		
	}

	if (found == FALSE)
		printf("%d, %d, %d %d = %s\n", rtCadidate.left,rtCadidate.top,rtCadidate.right,rtCadidate.bottom, className[candidate]);
	else
		printf("%d, %d, %d %d = %s\n", rtCadidate.left,rtFinal.top,rtFinal.right,rtFinal.bottom, className[candidate]);

	printf("Elapsed time in %.0f msec (%d x %d image)\n", w.CheckTime(),m_Image.Width(), m_Image.Height());

	/*for (row = 0;row <= rowSize-3;row+=step)
		//for (row = 0;row < 1;row++)
	{
		for (col = 0;col <= colSize-3;col+=step)
			//for (col = 0;col < 1;col++)
		{
			//w.StartTime();
			//double error = ClassifyMeans(pooledFeaturesLarge,row, col,3,3, meanFeature, vecLabel);
			//if (vecLabel[0] == 0 ) continue;
			ClassifySoftmaxRegression(convolvedFeatures,row, col,3,3, softmaxOptTheta, vecLabel, vecConfidence);
			//if (vecLabel[0] == 5) continue;
			//if (vecConfidence[0] < thr) continue;

			//m_OvrDisp.DrawText(10 + (row *10),10, MGREEN, 20, "%.0f msec", w.CheckTime());

			CRectEx rt;
			rt.SetRect(0,0,63,63);
			rt.Offset(int((float)col / 3.0f * 64.0f),int((float)row / 3.0f * 64.0f));

			m_OvrDisp.DrawRect(rt,color[vecLabel[0]], 10,"%s(%d) %f",className[vecLabel[0]], vecLabel[0], vecConfidence[0]);
			//m_OvrDisp.DrawText(rt.CenterPoint().x,rt.CenterPoint().y,MGREEN, 10,"%s",className[vecLabel[0]]);
			//m_OvrDisp.DrawRect(rt,MRED, 10,"%d,%d,%d,%d",vecLabel[0], vecLabel[1],vecLabel[2],vecLabel[3]);
			//m_OvrDisp.DrawRect(rt,MRED);
		}
	}*/

	//m_OvrDisp.DrawText(10,10, MCYAN, 15, "%d x %d %.0f msec", m_Image.Width(), m_Image.Height(),w.CheckTime());
	delete [] features;
	return;

} 
Exemple #10
0
void kd_tree::neigh_check(array_1d<double> &v, int kk, 
array_1d<int> &neigh, array_1d<double> &dd, int where, int wherefrom){
    
    /*
    This routine provides the backend for nn_srch
    
    v is the point for which we are trying to find nearest neighbors
    
    kk is the number of nearest neighbors we are trying to find
    
    neigh stores the indices of the nearest neighbors
    
    dd stores the (normalized) parameter space distances from v to the nearest neighbors
    
    where indicates what node we are examining now
    
    wherefrom indicates what node we just came from (so this search does not backtrack)
    
    This routine will call itself such that it walks through the tree until all possible
    steps are ruled out (by being obviously farther away than the kkth nearest neighbor
    discovered so far).
    */
    
    int i,j,k,l,side,goon;
    double dtry,dwhere;
    
    /*on what side of where does v belong?*/
    if(v.get_data(tree.get_data(where,0))<data.get_data(where,tree.get_data(where,0)))side=1;
    else side=2;
    
    /*
    the parameter space distance between v and where in the dimension on which where splits
    the tree; if this is longer than the distance to the kkth nearest neighbor, there is no
    point in calculating the full parameter space distance bewtween v and where
    */
    dtry=fabs((v.get_data(tree.get_data(where,0))-data.get_data(where,tree.get_data(where,0)))/\
    (maxs.get_data(tree.get_data(where,0))-mins.get_data(tree.get_data(where,0))));
   
   
    if(dtry<=dd.get_data(kk-1)){
          
        dwhere=distance(where,v);
     
        goon=0;
        if(dwhere<dd.get_data(kk-1)){
            goon=1;
            //make sure that where isn't already one of the nearest neighbors
            for(k=0;k<kk;k++)if(neigh.get_data(k)==where)goon=0;
        }
     
        if(goon==1){
            //add where to the list of nearest neighbors
            for(i=kk-2;i>=0 && dd.get_data(i)>dwhere;i--){
                dd.set(i+1,dd.get_data(i));
                neigh.set(i+1,neigh.get_data(i));
            }
            i++;
        
            dd.set(i,dwhere);
            neigh.set(i,where);
        }
     
        if(wherefrom==tree.get_data(where,3) || wherefrom==tree.get_data(where,side)){
            /*inspect the other side of the tree as split by where (assuming we did not just
            come from there)*/
            if(tree.get_data(where,3-side)>-1){
                neigh_check(v,kk,neigh,dd,tree.get_data(where,3-side),where);
            }
        }
     
    }
   
    if(wherefrom==tree.get_data(where,3)){
        if(tree.get_data(where,side)>-1){
            //check the side of this node v is naturally on
            neigh_check(v,kk,neigh,dd,tree.get_data(where,side),where);
        } 
    }
    else{
        if(tree.get_data(where,3)>-1){
            //check the parent of this node, if that is not where I came from
            neigh_check(v,kk,neigh,dd,tree.get_data(where,3),where);
        }
    }
}
Exemple #11
0
void kd_tree::nn_srch(array_1d<double> &v, int kk, array_1d<int> &neigh, 
array_1d<double> &dd){
    
    /*
    Find the nearest neighbors of the point specified by v.
    
    kk is the number of nearest neighbors to find.
    
    neigh will store the indices of the nearest neighbors.
    
    dd will store the (normalized) parameter space distances from v to its
    nearest neighbors
    */
    
    double before=double(time(NULL));
    
    int i,j,k,l,node,where,behind;
    double ddnode,ddtry;
   
    neigh.set_dim(kk);
    dd.set_dim(kk);
   
    array_1d<int> inn;
    inn.set_name("kd_tree_nn_srch_inn");
    
    /*first, find the node in the tree where you would add v, were you adding
    v to the tree*/
    node=find_node(v);
    
    /*what is the distance from v to that node*/
    ddnode=distance(v,node);
    
    /*set this node as the nearest neighbor (this is just a guess, not
    a final answer*/
    dd.set(0,ddnode);
    neigh.set(0,node);
    
    /*arbitrarily set the first kk-1 nodes as the rest of the nearest neighbors
    (again, just a guess to get things going)*/
    j=1;
    for(i=0;j<kk;i++){
     
        l=1;
        for(k=0;k<j;k++){
            if(neigh.get_data(k)==i)l=0;
        }
        if(l==1){
            dd.set(j,distance(i,v));
            neigh.set(j,i);   
            j++;
        }
    }

    array_1d<double> ddstore;
    ddstore.set_name("kd_tree_nn_srch_ddstore");
   
    for(i=0;i<kk;i++){
        ddstore.set(i,dd.get_data(i));
    }
    
    /*arrange dd so that it is in ascending order of parameter space distance*/
    sort_and_check(ddstore,dd,neigh);
    
    /*
    Check the three subdivisions of the tree defined by node:
    node's ancestors
    node's left hand side daughters
    node's right hand side daughters
    */
    if(tree.get_data(node,3)>=0)neigh_check(v,kk,neigh,dd,tree.get_data(node,3),node);
    if(tree.get_data(node,1)>=0)neigh_check(v,kk,neigh,dd,tree.get_data(node,1),node);
    if(tree.get_data(node,2)>=0)neigh_check(v,kk,neigh,dd,tree.get_data(node,2),node);
    
    if(kk>1){
        search_time+=double(time(NULL))-before;
        search_ct++;
    }
    else{
        search_time_solo+=double(time(NULL))-before;
        search_ct_solo++;
    }
}
Exemple #12
0
double kd_tree::distance(int dex, array_1d<double> &vv){
    return distance(vv,dex);
}
Exemple #13
0
bool AiFollow::execute (const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration)
{
    MWWorld::Ptr target = getTarget();

    if (target.isEmpty() || !target.getRefData().getCount() || !target.getRefData().isEnabled()  // Really we should be checking whether the target is currently registered
                                                                                                 // with the MechanicsManager
            )
        return false; // Target is not here right now, wait for it to return

    actor.getClass().getCreatureStats(actor).setDrawState(DrawState_Nothing);

    AiFollowStorage& storage = state.get<AiFollowStorage>();

    // AiFollow requires the target to be in range and within sight for the initial activation
    if (!mActive)
    {
        storage.mTimer -= duration;

        if (storage.mTimer < 0)
        {
            if ((actor.getRefData().getPosition().asVec3() - target.getRefData().getPosition().asVec3()).length2()
                    < 500*500
                    && MWBase::Environment::get().getWorld()->getLOS(actor, target))
                mActive = true;
            storage.mTimer = 0.5f;
        }
    }
    if (!mActive)
        return false;

    ESM::Position pos = actor.getRefData().getPosition(); //position of the actor

    float followDistance = 180;
    // When there are multiple actors following the same target, they form a group with each group member at 180*(i+1) distance to the target
    int i=0;
    std::list<int> followers = MWBase::Environment::get().getMechanicsManager()->getActorsFollowingIndices(target);
    followers.sort();
    for (std::list<int>::iterator it = followers.begin(); it != followers.end(); ++it)
    {
        if (*it == mFollowIndex)
            followDistance *= (i+1);
        ++i;
    }

    if(!mAlwaysFollow) //Update if you only follow for a bit
    {
         //Check if we've run out of time
        if (mRemainingDuration != 0)
        {
            mRemainingDuration -= duration;
            if (duration <= 0)
                return true;
        }

        if((pos.pos[0]-mX)*(pos.pos[0]-mX) +
            (pos.pos[1]-mY)*(pos.pos[1]-mY) +
            (pos.pos[2]-mZ)*(pos.pos[2]-mZ) < followDistance*followDistance) //Close-ish to final position
        {
            if(actor.getCell()->isExterior()) //Outside?
            {
                if(mCellId == "") //No cell to travel to
                    return true;
            }
            else
            {
                if(mCellId == actor.getCell()->getCell()->mName) //Cell to travel to
                    return true;
            }
        }
    }

    //Set the target destination from the actor
    ESM::Pathgrid::Point dest = target.getRefData().getPosition().pos;

    float dist = distance(dest, pos.pos[0], pos.pos[1], pos.pos[2]);
    const float threshold = 10;

    if (storage.mMoving)  //Stop when you get close
        storage.mMoving = (dist > followDistance);
    else
        storage.mMoving = (dist > followDistance + threshold);

    if(!storage.mMoving)
    {
        actor.getClass().getMovementSettings(actor).mPosition[1] = 0;

        // turn towards target anyway
        float directionX = target.getRefData().getPosition().pos[0] - actor.getRefData().getPosition().pos[0];
        float directionY = target.getRefData().getPosition().pos[1] - actor.getRefData().getPosition().pos[1];
        zTurn(actor, std::atan2(directionX,directionY), osg::DegreesToRadians(5.f));
    }
    else
    {
        pathTo(actor, dest, duration); //Go to the destination
    }

    //Check if you're far away
    if(dist > 450)
        actor.getClass().getCreatureStats(actor).setMovementFlag(MWMechanics::CreatureStats::Flag_Run, true); //Make NPC run
    else if(dist  < 325) //Have a bit of a dead zone, otherwise npc will constantly flip between running and not when right on the edge of the running threshhold
        actor.getClass().getCreatureStats(actor).setMovementFlag(MWMechanics::CreatureStats::Flag_Run, false); //make NPC walk

    return false;
}
Exemple #14
0
		void PathSearch::update(long timeslice)
		{

			startTime = clock();

			while (1)
			{

				currentTime = clock();
				float _elapsedTime = currentTime - startTime;

				if (_elapsedTime < timeslice)
				{
					SearchNode* _currentNode = searchQueue->front();
					searchQueue->pop();

					if (_currentNode != goalNode)
					{

						for (int i = 0; i < _currentNode->edges.size(); i++)
							if (!nodeState[_currentNode->edges[i]])
							{

								PlannerNode* _newPlanner = new PlannerNode;
								_newPlanner->parent = _currentNode->myPlanner;
								_newPlanner->Vertex = _currentNode->edges[i];
								_currentNode->edges[i]->myPlanner = _newPlanner;
								_currentNode->edges[i]->heuristicCost = distance(_currentNode->edges[i]->data, goalNode->data);
								_currentNode->edges[i]->givenCost = _currentNode->givenCost + distance(_currentNode->edges[i]->data, _currentNode->myPlanner->Vertex->data);
								cleanMe.push_back(_newPlanner);

								searchQueue->push(_currentNode->edges[i]);
								nodeState[_currentNode->edges[i]] = true;

							}

					}
					else
					{

						PlannerNode* _cPlanner = goalNode->myPlanner;

						while (1)
						{

							solution.push_back(_cPlanner);

							if (_cPlanner->Vertex == startNode)
								break;

							if (_cPlanner->Vertex != startNode && _cPlanner->Vertex != goalNode)
								_cPlanner->Vertex->data->setFill(0xFF0000FF);

							_cPlanner = _cPlanner->parent;

						}

						reachedGoal = true;
						return;

					}

				}
				else return;

			}

		}
Exemple #15
0
Handle<Value> ZipFile::readFileSync(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("first argument must be a file name inside the zip")));

    std::string name = TOSTR(args[0]);
  
    // TODO - enforce valid index
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    struct zip_file *zf_ptr;

    int idx = -1;
    
    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), name);
    if (it!=zf->names.end()) {
        idx = distance(zf->names.begin(), it);
    }

    if (idx == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << name << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    if ((zf_ptr=zip_fopen_index(zf->archive, idx, 0)) == NULL) {
        zip_fclose(zf_ptr);
        std::stringstream s;
        s << "cannot open file #" << idx << " in " << name << ": archive error: " << zip_strerror(zf->archive) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    struct zip_stat st;
    zip_stat_index(zf->archive, idx, 0, &st);
  
    std::vector<unsigned char> data;
    data.clear();
    data.resize( st.size );
    
    int result =  0;
    result = (int)zip_fread( zf_ptr, reinterpret_cast<void*> (&data[0]), data.size() );

    if (result < 0) {
        zip_fclose(zf_ptr);
        std::stringstream s;
        s << "error reading file #" << idx << " in " << name << ": archive error: " << zip_file_strerror(zf_ptr) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    #if NODE_VERSION_AT_LEAST(0,3,0)
        node::Buffer *retbuf = Buffer::New((char *)&data[0],data.size());
    #else
        node::Buffer *retbuf = Buffer::New(data.size());
        std::memcpy(retbuf->data(), (char *)&data[0], data.size());
    #endif
    
    zip_fclose(zf_ptr);
    return scope.Close(retbuf->handle_);
}
void
Mass_spring_viewer::compute_forces()
{
    // clear forces
    for (unsigned int i=0; i<body_.particles.size(); ++i)
        body_.particles[i].force = vec2(0,0);


    /** \todo (Part 1) Implement center force
     */
    if (external_force_ == Center)
    {
      float c = 10.f;
      for (std::vector<Particle>::iterator p_it = body_.particles.begin (); p_it != body_.particles.end (); ++p_it)
        p_it->force += c * (vec2 (0.f, 0.f) - p_it->position);
    }


    /** \todo (Part 1) Implement damping force
     \li The damping coefficient is given as member damping_
     */
    /// Do damping only for explicit methods
    if (integration_ != Implicit)
      for (std::vector<Particle>::iterator p_it = body_.particles.begin (); p_it != body_.particles.end (); ++p_it)
        p_it->force -= damping_ * p_it->velocity;


    /** \todo (Part 1) Implement gravitation force
     \li Particle mass available as particle_mass_
     */
    if (external_force_ == Gravitation)
    {
      for (std::vector<Particle>::iterator p_it = body_.particles.begin (); p_it != body_.particles.end (); ++p_it)
        p_it->force += 9.81 * p_it->mass * vec2 (0.f, -1.f);
    }


    /** \todo (Part 1) Implement force based boundary collisions
     \li Collision coefficient given as collision_stiffness_
     */
    // collision forces
    if (collisions_ == Force_based)
    {
        float planes[4][3] = {
            {  0.0,  1.0, 1.0 },
            {  0.0, -1.0, 1.0 },
            {  1.0,  0.0, 1.0 },
            { -1.0,  0.0, 1.0 }
        };

        for (std::vector<Particle>::iterator p_it = body_.particles.begin (); p_it != body_.particles.end (); ++p_it)
        {
          for (size_t plane_i = 0; plane_i < 4; ++plane_i)
          {
            float d = planes[plane_i][0] * p_it->position[0] +
                      planes[plane_i][1] * p_it->position[1] +
                      planes[plane_i][2] - particle_radius_;

            if (d < 0.f)
              p_it->force += collision_stiffness_ * (-d) * vec2 (planes[plane_i][0],
                                                                 planes[plane_i][1]);
          }
        }
    }


    /** \todo (Part 1) Compute force of the interactive mass spring
     \li Required coefficients are given as spring_stiffness_ and spring_damping_
     */
    if (mouse_spring_.active)
    {
        Particle& particle = body_.particles[ mouse_spring_.particle_index ];

        vec2 pos0 = particle.position;
        vec2 pos1 = mouse_spring_.mouse_position;

        particle.force += -(spring_stiffness_ * norm (pos0 - pos1) +
                            spring_damping_ * dot (particle.velocity, pos0 - pos1) / norm (pos0 - pos1)) * (pos0 - pos1) / norm (pos0 - pos1);
    }


    /** \todo (Part 1) Compute spring forces
     \li Required information about springs in the scene are found in body_.springs
     \li Required coefficients are given as spring_stiffness_ and spring_damping_
     */

    for (std::vector<Spring>::iterator s_it = body_.springs.begin (); s_it != body_.springs.end (); ++s_it)
    {
      const vec2 &pos0 = s_it->particle0->position;
      const vec2 &pos1 = s_it->particle1->position;
      const vec2 &vel0 = s_it->particle0->velocity;
      const vec2 &vel1 = s_it->particle1->velocity;

      vec2 force = -(spring_stiffness_ * (norm (pos0 - pos1) - s_it->rest_length) +
                     spring_damping_ * dot (vel0 - vel1, pos0 - pos1) / norm (pos0 - pos1)) * (pos0 - pos1) / norm (pos0 - pos1);
      s_it->particle0->force += force;
      s_it->particle1->force += -force;
    }



    /** \todo (Part 2) Compute more forces in part 2 of the exercise: triangle-area forces, binding forces, etc.
     */
    if (area_forces_) {
        for (std::vector<Triangle>::iterator t_it = body_.triangles.begin (); t_it != body_.triangles.end (); ++t_it)
        {
            /*
            F_i = - k_A * (area - A) * d_area/d_i


            */

            const vec2& p0 = t_it->particle0->position;
            const vec2& p1 = t_it->particle1->position;
            const vec2& p2 = t_it->particle2->position;
            vec2 d_area_0 = perp(0.5 * (p1 - p2));
            vec2 d_area_1 = perp(0.5 * (p2 - p0));
            vec2 d_area_2 = perp(0.5 * (p0 - p1));

            float tmp = - area_stiffness_ * (t_it->area() - t_it->rest_area);

            t_it->particle0->force += tmp * d_area_0;
            t_it->particle1->force += tmp * d_area_1;
            t_it->particle2->force += tmp * d_area_2;
        }
    }


    if (equilibrium_forces_) {
        for (std::vector<Particle>::iterator p_it1 = body_.particles.begin (); p_it1 != body_.particles.end (); ++p_it1) {
            for (std::vector<Particle>::iterator p_it2 = p_it1+1; p_it2 != body_.particles.end (); ++p_it2) {
                const vec2 &p1 = p_it1->position;
                const vec2 &p2 = p_it2->position;
                float dist = distance(p1, p2);
                vec2 d = p1 - p2;
                float f = 0.1f / (dist*dist);

                p_it1->force += f*d;
                p_it2->force += -f*d;
            }
        }

    }
}
Exemple #17
0
/* zipfile.replaceFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Replace_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();
    
    zip_int64_t len; 
    if (args[3]->IsUndefined()) 
      len = -1; 
    else 
      len = args[3]->Int32Value();

    int idx = -1;
    
    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), archive_file);
    if (it!=zf->names.end()) {
        idx = distance(zf->names.begin(), it);
    }

    if (idx == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << archive_file << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    int ret = zip_replace(zf->archive, idx, source);        
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
Exemple #18
0
void creategraph(void)
{
    /* fill up nodearray with desired nodes: for this benchmark, the
     * details of the graph are hardwired rather than read from
     * file. the graph details are:
       0 (0,0)      {6,11,17}
       1 (100,0)    {6,17}
       2 (200,0)    {8,13}
       3 (300,0)    {5,16}
       4 (400,0)    {12,14,17}
       5 (0,100)    {3,9}
       6 (100,100)  {0,1}
       7 (200,100)  {11,12,15}
       8 (300,100)  {2,14}
       9 (400,100)  {5,11,14}
       10 (0,200)   {13,15}
       11 (100,200) {0,7,9,12,13,16}
       12 (200,200) {4,7,11,13}
       13 (300,200) {2,10,11,12}
       14 (400,200) {4,8,9}
       15 (0,300)   {7,10,16}
       16 (100,300) {3,11,15}
       17 (200,300) {0,1,4}
    */

    int i,x,y,a[NUMNODES];
    Adjptr tmp;

    /* node 0 */
    x = 0; y = 0; a[0] = 6; a[1] = 11; a[2] = 17; a[3] = -1;
    createnode(x,y,a);
    
    /* node 1 */
    x = 100; y = 0; a[0] = 6; a[1] = 17; a[2] = -1;
    createnode(x,y,a);
    
    /* node 2 */
    x = 200; y = 0; a[0] = 8; a[1] = 13; a[2] = -1;
    createnode(x,y,a);
    
    /* node 3 */
    x = 300; y = 0; a[0] = 5; a[1] = 16; a[2] = -1;
    createnode(x,y,a);
    
    /* node 4 */
    x = 400; y = 0; a[0] = 12; a[1] = 14; a[2] = 17; a[3] = -1;
    createnode(x,y,a);
    
    /* node 5 */
    x = 0; y = 100; a[0] = 3; a[1] = 9; a[2] = -1;
    createnode(x,y,a);
    
    /* node 6 */
    x = 100; y = 100; a[0] = 0; a[1] = 1; a[2] = -1;
    createnode(x,y,a);
    
    /* node 7 */
    x = 200; y = 100; a[0] = 11; a[1] = 12; a[2] = 15; a[3] = -1;
    createnode(x,y,a);
    
    /* node 8 */
    x = 300; y = 100; a[0] = 2; a[1] = 14; a[2] = -1;
    createnode(x,y,a);
    
    /* node 9 */
    x = 400; y = 100; a[0] = 5; a[1] = 11; a[2] = 14; a[3] = -1;
    createnode(x,y,a);
    
    /* node 10 */
    x = 0; y = 200; a[0] = 13; a[1] = 15; a[2] = -1;
    createnode(x,y,a);
    
    /* node 11 */
    x = 100; y = 200; a[0] = 0; a[1] = 7; a[2] = 9; a[3] = 12; a[4] = 13; a[5] = 16; a[6] = -1;
    createnode(x,y,a);
    
    /* node 12 */
    x = 200; y = 200; a[0] = 4; a[1] = 7; a[2] = 11; a[3] = 13; a[4] = -1;
    createnode(x,y,a);
    
    /* node 13 */
    x = 300; y = 200; a[0] = 2; a[1] = 10; a[2] = 11; a[3] = 12; a[4] = -1;
    createnode(x,y,a);
    
    /* node 14 */
    x = 400; y = 200; a[0] = 4; a[1] = 8; a[2] = 9; a[3] = -1;
    createnode(x,y,a);
    
    /* node 15 */
    x = 0; y = 300; a[0] = 7; a[1] = 10; a[2] = 16; a[3] = -1;
    createnode(x,y,a);
    
    /* node 16 */
    x = 100; y = 300; a[0] = 3; a[1] = 11; a[2] = 15; a[3] = -1;
    createnode(x,y,a);
    
    /* node 17 */
    x = 200; y = 300; a[0] = 0; a[1] = 1; a[2] = 4; a[3] = -1;
    createnode(x,y,a);

    /* now that all node are set up, compute edge lengths */
    for (i = 0; i < NUMNODES; i++)
    {
	tmp = nodearray[i].adjlist;
	while (tmp != NULL)
	{
	    tmp->edgelength = distance(i,tmp->nodeindex);
	    tmp = tmp->next;
	}
    }
}
Exemple #19
0
void slice_elbow (struct msscene *ms, struct surface *current_surface, double fine_pixel, struct face *fac)
{
	char message[MAXLINE];
	struct leaf *lf;
	struct circle *lfcir, *torcir;
	struct arc *torarc;
	struct vertex *torvtx[2];
	int i, j, k, nfocus, atmnum;
	double anginc, bigrad;
	double atmcen[3], ccens[2][3], cradii[2];
	double focus[3], vect[3], z_axis[3], base[3];
	struct variety *vty;
	double *foci;
    struct cept *ex;
	
	vty = fac -> vty;
	atmnum = vty -> atmnum[0];
	if (debug >= 2) {
		sprintf (message,"render elbow face for atom %5d", atmnum);
		inform(message);
	}
	for (k = 0; k < 3; k++)
		atmcen[k] = *(current_surface -> atom_centers + 3 * (atmnum - 1) + k);
	for (j = 0; j < 2; j++)
		cradii[j] = vty -> radii[1];
	for (j = 0; j < 2; j++)
		for (k = 0; k < 3; k++) {
			ccens[j][k] = vty -> ccens[j][k];
		}
	bigrad = distance (atmcen, ccens[0]) + cradii[0];
	for (k = 0; k < 3; k++) {
		if (atmcen[k] + bigrad < ms -> window[0][k]) return;
		if (atmcen[k] - bigrad > ms -> window[1][k]) return;
	}
	/* leaf circle */
	lfcir = allocate_circle ();
	if (lfcir == NULL) {
		ex = new_cept (MEMORY_ERROR,  ALLOCATION,  FATAL_SEVERITY);
		add_object (ex, CIRCLE, "leaf circle");
		add_function (ex, "slice_elbow");
		add_source (ex, "msrender.c");
		return;
	}
	/* leaf */
	lf = allocate_leaf ();
	if (lf == NULL) {
		add_object (tail_cept, LEAF, "leaf");
		add_function (tail_cept, "slice_sphere");
		return;
	}
	/* torus circle radius, center, axis */
	torcir = new_circle (vty -> center, vty -> radii[0], vty -> axis);
	if (torcir == NULL) {
		add_object (tail_cept, CIRCLE, "torus circle");
		add_function (tail_cept, "slice_elbow");
		return;
	}
	/* torus arc */
	torarc = allocate_arc ();
	if (torarc == NULL) {
		add_object (tail_cept, ARC, "torus arc");
		add_function (tail_cept, "slice_elbow");
		add_source (tail_cept, "msrender.c");
		return;
	}
	for (j = 0; j < 2; j++) {
		torvtx[j] = allocate_vertex ();
		if (error()) {
			add_object (tail_cept, VERTEX, "torus vertex");
			add_function (tail_cept, "slice_elbow");
			add_source (tail_cept, "msrender.c");
			return;
		}
	}
	/* set up leaf fields */
	for (k = 0; k < MAXPA; k++)
		lf -> atmnum[k] = vty -> atmnum[k];
	lf -> cir = lfcir;
	lf -> shape = CONVEX;		/* to avoid reversing normal vector */
	lf -> type = vty -> type;
	lf -> fac = fac;
	lf -> cep = 0;
	lf -> clip_ep = 0;
	lf -> side = OUTSIDE;
	lf -> comp = fac -> comp;
	lf -> input_hue = fac -> input_hue;
	for (j = 0; j < 2; j++)
		lf -> where[j] = ACCESSIBLE;

	/* setup torus central circle for subdivision */
	anginc = fine_pixel / ((vty -> radii[0] + cradii[0]));
	torcir -> radius = vty -> radii[0];
	for (k = 0; k < 3; k++) {
		torcir -> center[k] = vty -> center[k];
		torcir -> axis[k] = vty -> axis[k];
	}
	torarc -> cir = torcir;
	for (j = 0; j < 2; j++) {
		torarc -> vtx[j] = torvtx[j];
		for (k = 0; k < 3; k++)
			torvtx[j] -> center[k] = ccens[j][k];
	}
	foci = (double *) NULL;
	nfocus = render_sub_arc (torarc, &foci, anginc);
	if (nfocus < 2) {
		ex = new_cept (LOGIC_ERROR, MSUNDERFLOW, FATAL_SEVERITY);
        add_function (ex, "slice_elbow");
        add_source (ex, "msrender.c");
        add_long (ex, "number of foci", (long) nfocus);
		return;
	}

	/* create leaves */
	for (i = 0; i < nfocus; i++) {
		for (k = 0; k < 3; k++) {
			focus[k] = (*(foci + 3 * i + k));
			lfcir -> center[k] = focus[k];
			lf -> focus[k] = focus[k];
		}
		lfcir -> radius = cradii[0];
		/* compute tangent to torus central circle */
		for (k = 0; k < 3; k++)
			vect[k] = focus[k] - vty -> center[k];
		cross (vty -> axis, vect, lfcir -> axis);
		normalize (lfcir -> axis);
		for (k = 0; k < 3; k++)
			z_axis[k] = ((k == 2) ? 1.0 : 0.0);
		cross (lfcir -> axis, z_axis, base);
		if (norm (base) <= 0.0) {
			continue;
		}
		normalize (base);
		for (k = 0; k < 3; k++) {
			lf -> ends[0][k] = lfcir -> center[k] - lfcir -> radius * base[k];
			lf -> ends[1][k] = lfcir -> center[k] + lfcir -> radius * base[k];
		}
		/* clip and render leaf */
		clip_leaf (ms, current_surface, fine_pixel, lf);
		if (error()) return;
	}
	free_doubles (foci, 0, VERTS);
	free_leaf (lf);
	free_arc (torarc);
	free_circle (torcir);
	free_circle (lfcir);
	for (j = 0; j < 2; j++)
		free_vertex (torvtx[j]);
}
Exemple #20
0
bool CEnmityContainer::IsWithinEnmityRange(CBattleEntity* PEntity)
{
	return distance(m_EnmityHolder->loc.p, PEntity->loc.p) <= m_EnmityHolder->m_enmityRange;
}
void KW_CS2Surf::GetSSMesh()
{
	//faces in each subspace,each vector<int> represents a face composed of vertices with indices <int>
	vector<vector<vector<int>>> vecTotalFaceVer;
	//faces in each subspace,each int represents the face id of the facet in a subspace (a face may contain many facets(eg,triangles))
	vector<vector<int>> vecTotalFace;
	//the order of each element in vecTotalFaceVer&vecTotalFace is consistent with the order of subspaces
	vecTotalFaceVer.resize(this->iSSspacenum);
	vecTotalFace.resize(this->iSSspacenum);
	for (unsigned int i=0;i<this->vecResortFace.size();i++)
	{
		ResortedFace currFace=vecResortFace.at(i);
		vector<int> currFaceVertexInd=currFace.vecFaceVertexInd;
		//the two subspace this face belongs to
		for (unsigned int j=0;j<currFace.vecOrient.size();j++)
		{
			int icurrSSId=currFace.vecSubspaceId.at(j);
			if (!currFace.vecOrient.at(j))
			{
				reverse(currFaceVertexInd.begin(),currFaceVertexInd.end());
			}
			vecTotalFaceVer.at(icurrSSId).push_back(currFaceVertexInd);
			vecTotalFace.at(icurrSSId).push_back(i);
			//reverse back to the originally saved order
			if (!currFace.vecOrient.at(j))
			{
				reverse(currFaceVertexInd.begin(),currFaceVertexInd.end());
			}
		}
	}

	//id of vertices stored in vecTotalFaceVer is the global vertex id,need to convert it 
	//to the id within each subspace mesh
	//all the vertices are collected from the faces, so isolated vertices caused by the 
	//subspace combination will not be taken account into consideration

	//subspace number after combination
	int iSSNumAfterComb=0;
	for (unsigned int i=0;i<vecTotalFaceVer.size();i++)
	{
		set<int> setSSVer;
		vector<vector<set<int>::iterator>> vecFaceSetIter;
		//put all vertex indices in, store the iterator
		for (unsigned int j=0;j<vecTotalFaceVer.at(i).size();j++)
		{
			vector<set<int>::iterator> currFaceSetIter;
			for (unsigned int k=0;k<vecTotalFaceVer.at(i).at(j).size();k++)
			{
				pair<set<int>::iterator, bool> pairResult=setSSVer.insert(vecTotalFaceVer.at(i).at(j).at(k));
				currFaceSetIter.push_back(pairResult.first);
			}
			vecFaceSetIter.push_back(currFaceSetIter);
		}
		//get the id within the subspace according to the iterator
		vector<vector<int>> vecLocalVerInd;
		for (unsigned int j=0;j<vecFaceSetIter.size();j++)
		{
			vector<int> LocalFace;
			for (unsigned int k=0;k<vecFaceSetIter.at(j).size();k++)
			{
				int iLocalId=distance(setSSVer.begin(),vecFaceSetIter.at(j).at(k));
				LocalFace.push_back(iLocalId);
			}
			vecLocalVerInd.push_back(LocalFace);
		}
		//convert to triangular mesh
		//a simple method (012345->012 023 034 045),may have bug 
		vector<vector<int>> vecTriLocalVerInd;
		vector<int> vecTriFaceId;//the subspace face id of each triangle
		for (unsigned int j=0;j<vecLocalVerInd.size();j++)
		{
			vector<int> vecCurrFace=vecLocalVerInd.at(j);
			int iSecondVerLocalId=1;
			int iFacetFaceId=vecTotalFace.at(i).at(j);
			for (unsigned int k=0;k<vecCurrFace.size()-2;k++)
			{
				vector<int> vecTriFace;
				vecTriFace.push_back(vecCurrFace.at(0));
				vecTriFace.push_back(vecCurrFace.at(iSecondVerLocalId));
				vecTriFace.push_back(vecCurrFace.at(iSecondVerLocalId+1));
				iSecondVerLocalId++;
				vecTriLocalVerInd.push_back(vecTriFace);
				vecTriFaceId.push_back(iFacetFaceId);
			}
		}
		//store all the points
		vector<Point_3> vecAllPoint;
		for (set<int>::iterator SetIter=setSSVer.begin();SetIter!=setSSVer.end();SetIter++)
		{
			vecAllPoint.push_back(Point_3(vecSSver.at(3*(*SetIter)),
				vecSSver.at(3*(*SetIter)+1),
				vecSSver.at(3*(*SetIter)+2)));
		}
		KW_Mesh currSSMesh;
		//if a subspace has been combined into others,still save it as an empty one,
		//in order to keep the order of subspaces
		if (!vecAllPoint.empty() && !vecTriLocalVerInd.empty())
		{
			//Convert_Array_To_KW_Mesh<HalfedgeDS> triangle(vecAllPoint,vecLocalVerInd);
			Convert_Array_To_KW_Mesh<HalfedgeDS> triangle(vecAllPoint,vecTriLocalVerInd);
			currSSMesh.delegate(triangle);
			//record the face id of each triangle
			assert(currSSMesh.size_of_facets()==vecTriFaceId.size());
			Facet_iterator FaceIter=currSSMesh.facets_begin();
			for (unsigned int j=0;j<vecTriFaceId.size();j++)
			{
				FaceIter->SetReserved(vecTriFaceId.at(j));
				FaceIter++;
			}
		}
		//save the subspace mesh
		if (!currSSMesh.empty())
		{
			iSSNumAfterComb++;
			OBJHandle::UnitizeCGALPolyhedron(currSSMesh,false,false);
		}
		this->vecSSMesh.push_back(currSSMesh);
		////test
		//if (!currSSMesh.empty())
		//{
		//	OBJHandle::UnitizeCGALPolyhedron(currSSMesh,false,false);
		//	this->vecSinglePoly.push_back(currSSMesh);
		//}
	}
	DBWindowWrite("initial subzone no.: %d\n",this->iSSspacenum);
	DBWindowWrite("subzone no. after combination: %d\n",iSSNumAfterComb);
}
Exemple #22
0
void load(int data[12], int position[8]){
// initialize variables
	 int x1,y1,x2,y2,x3,y3,x4,y4,dis[6],dismin,dismax,pos1x,pos1y,pos2x,pos2y,pos3x,pos3y,pos4x,pos4y; 
    
    int score1 = 0;
    int score2 = 0;
    int score3 = 0;
    int score4 = 0;

	int maxscore;
	int minscore;

  ////start loding the data from the camera sensor////////
    x1 = data[0];      y1 = data[1];	       x2 = data[3];	    y2 = data[4];
    x3 = data[6];      y3 = data[7];	       x4 = data[9];        y4 = data[10];
   
   
   
   //calculate the distance between detected points
    dis[0] = distance (x1,y1,x2,y2);      dis[1] = distance (x1,y1,x3,y3);  //12,13
    dis[2] = distance (x1,y1,x4,y4);      dis[3] = distance (x2,y2,x3,y3);  //14,23
    dis[4] = distance (x4,y4,x2,y2);      dis[5] = distance (x4,y4,x3,y3);  //42,43
    dismin = min(dis);     dismax = max(dis);
   
   
   
 ///////////////start assign scores///////////  
 //find the which one is the min and which one is max.  
  
   if (dismin==dis[0]){
        minscore=0;
     }
    if (dismax==dis[0]){
		maxscore=0;
     }
    if (dismin==dis[1]){
		minscore=1;
     }
    if (dismax==dis[1]){
		maxscore=1;
        
    }
    if (dismin==dis[2]){
		minscore=2;
        
    }
    if (dismax==dis[2]){
		maxscore=2;
        
    }
    if (dismin==dis[3]){
		minscore=3;
        
    }
    if (dismax==dis[3]){
        
    }
    if (dismin==dis[4]){
		minscore=4;
        
    }
    if (dismax==dis[4]){
		maxscore=4;
        
    }
    if (dismin==dis[5]){
		minscore=5;
        
    }
    if (dismax==dis[5]){
		maxscore=5;
        
    }
//assign scores
	 switch(maxscore){
	 case 0:
	    score1 += 2;
        score2 += 2;
		break;
	 case 1:
	 	score1 += 2;
        score3 += 2;
		break;
	 case 2:
	 	score1 += 2;
        score4 += 2;
		break;
	 case 3:
	 	score2 += 2;
        score3 += 2;
		break;
	 case 4:
	 	score4 += 2;
        score2 += 2;
		break;
	 case 5:
	 	score4 += 2;
        score3 += 2;
		break;
	 }

	 switch(minscore){
	 case 0:
	    score1 += 1;
        score2 += 1;
		break;
	 case 1:
	 	score1 += 1;
        score3 += 1;
		break;
	 case 2:
	 	score1 += 1;
        score4 += 1;
		break;
	 case 3:
	 	score2 += 1;
        score3 += 1;
		break;
	 case 4:
	 	score4 += 1;
        score2 += 1;
		break;
	 case 5:
	 	score4 += 1;
        score3 += 1;
		break;
	 }

//assign the position according to the score.
//assign value for x1 and y1
	if (score1==0)
	{
		pos1x = x1;
        pos1y = y1;	
	}else if  (score1==1)
	{
		pos2x = x1;
        pos2y = y1;
	}else if  (score1==2)
	{
		pos3x = x1;
        pos3y = y1;
	}else if  (score1==3)
	{
		pos4x = x1;
        pos4y = y1;
	}
//assign value for x2 and y2
		if (score2==0)
	{
		pos1x = x2;
        pos1y = y2;	
	}else if  (score2==1)
	{
		pos2x = x2;
        pos2y = y2;
	}else if  (score2==2)
	{
		pos3x = x2;
        pos3y = y2;
	}else if  (score2==3)
	{
		pos4x = x2;
        pos4y = y2;
	}
//assign value for x3 and y3
		if (score3==0)
	{
		pos1x = x3;
        pos1y = y3;	
	}else if  (score3==1)
	{
		pos2x = x3;
        pos2y = y3;
	}else if  (score3==2)
	{
		pos3x = x3;
        pos3y = y3;
	}else if  (score3==3)
	{
		pos4x = x3;
        pos4y = y3;
	}	
//assign value for x4 and y4	
		if (score4==0)
	{
		pos1x = x4;
        pos1y = y4;	
	}else if  (score4==1)
	{
		pos2x = x4;
        pos2y = y4;
	}else if  (score4==2)
	{
		pos3x = x4;
        pos3y = y4;
	}else if  (score4==3)
	{
		pos4x = x4;
        pos4y = y4;
	}		
	
//assign the position according to the score.

    position[0] = pos1x;      position[1] = pos1y;		      position[2] = pos2x;		    position[3] = pos2y;
    position[4] = pos3x;	  position[5] = pos3y;	          position[6] = pos4x;		    position[7] = pos4y;
}
Exemple #23
0
const Sample_entry* Note_map_get_entry(
        const Note_map* map,
        double cents,
        double force,
        Random* random)
{
    assert(map != NULL);
    assert(isfinite(cents));
    assert(isfinite(force) || (isinf(force) && force < 0));
    assert(random != NULL);

    Random_list* key =
        &(Random_list){ .force = force, .freq = NAN, .cents = cents };
    Random_list* estimate_low = AAiter_get_at_most(map->iter, key);
    Random_list* choice = NULL;
    double choice_d = INFINITY;

    if (estimate_low != NULL)
    {
        choice = estimate_low;
        choice_d = distance(choice, key);
        double min_tone = key->cents - choice_d;
        Random_list* candidate = AAiter_get_prev(map->iter);
        while (candidate != NULL && candidate->cents >= min_tone)
        {
            double d = distance(candidate, key);
            if (d < choice_d)
            {
                choice = candidate;
                choice_d = d;
                min_tone = key->cents - choice_d;
            }
            candidate = AAiter_get_prev(map->iter);
        }
    }

    Random_list* estimate_high = AAiter_get_at_least(map->iter, key);
    if (estimate_high != NULL)
    {
        double d = distance(estimate_high, key);
        if (choice == NULL || choice_d > d)
        {
            choice = estimate_high;
            choice_d = d;
        }

        double max_tone = key->cents + choice_d;
        Random_list* candidate = AAiter_get_next(map->iter);
        while (candidate != NULL && candidate->cents <= max_tone)
        {
            d = distance(candidate, key);
            if (d < choice_d)
            {
                choice = candidate;
                choice_d = d;
                max_tone = key->cents + choice_d;
            }
            candidate = AAiter_get_next(map->iter);
        }
    }

    if (choice == NULL)
    {
//        fprintf(stderr, "empty map\n");
        return NULL;
    }

    assert(choice->entry_count > 0);
    assert(choice->entry_count < NOTE_MAP_RANDOMS_MAX);
//    state->middle_tone = choice->freq;
    int index = Random_get_index(random, choice->entry_count);
    assert(index >= 0);
//    fprintf(stderr, "%d\n", index);

    return &choice->entries[index];
}
Exemple #24
0
int main(int argc, char *argv[])
{
   PALETTE pal;
   BITMAP *buffer;
   BITMAP *planet;
   char buf[256];

   if (allegro_init() != 0)
      return 1;
   install_keyboard();
   install_mouse();

   if (set_gfx_mode(GFX_AUTODETECT, 320, 240, 0, 0) != 0) {
      if (set_gfx_mode(GFX_SAFE, 320, 240, 0, 0) != 0) {
	 set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
	 allegro_message("Unable to set any graphic mode\n%s\n",
			 allegro_error);
	 return 1;
      }
   }

   replace_filename(buf, argv[0], "planet.pcx", sizeof(buf));

   planet = load_bitmap(buf, pal);
   if (!planet) {
      set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
      allegro_message("Error reading %s\n", buf);
      return 1;
   }

   buffer = create_bitmap(SCREEN_W, SCREEN_H);
   clear_bitmap(buffer);

   set_palette(pal);

   create_rgb_table(&rgb_table, pal, NULL);
   rgb_map = &rgb_table;

   create_light_table(&light_table, pal, 0, 0, 0, NULL);
   color_map = &light_table;

   set_trans_blender(0, 0, 0, 128);

   do {
      poll_mouse();

      draw_gouraud_sprite(buffer, planet, SCREEN_W/2, SCREEN_H/2,
			  distance(SCREEN_W/2, SCREEN_H/2, mouse_x, mouse_y),
			  distance(SCREEN_W/2 + planet->w, SCREEN_H/2,
				   mouse_x, mouse_y),
			  distance(SCREEN_W/2 + planet->w,
				   SCREEN_H/2 + planet->h, mouse_x, mouse_y),
			  distance(SCREEN_W/2, SCREEN_H/2 + planet->h,
				   mouse_x, mouse_y));

      textout_ex(buffer, font, "Gouraud Shaded Sprite Demo", 0, 0,
		 palette_color[10], -1);

      show_mouse(buffer);
      blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
      show_mouse(NULL);

   } while (!keypressed());

   destroy_bitmap(planet);
   destroy_bitmap(buffer);

   return 0;
}
Exemple #25
0
bool Sphere::intersects (const Sphere& other_sphere) const
{
  return distance(other_sphere) < 0 ? true : false;
}
Exemple #26
0
/*
Initialize index tables and pointers
*/
void init_indices() {
    int temp[2048];
    int index;
    int i,j;
    int u1,u2;
    int rot,val;

    for( i = 0; i < 4096; i++) {
        KK_index[i] = ILLEGAL;
        KK_WP_index[i] = ILLEGAL;
    }

    /*without pawn*/
    for( i = 0; i < 2048; i++) {
        temp[i] = ILLEGAL;
    }

    index = 0;
    for(i = 0;i < 64;i++) {
        for(j = 0;j < 64;j++) {
            if(distance(SQ6488(i),SQ6488(j)) <= 1)
                continue;
            /*rotations*/
            u1 = i;
            u2 = j;
            rot = 0;

            if(file64(u1) > FILED) {
                u1 = MIRRORF64(u1);
                u2 = MIRRORF64(u2);
                rot ^= rotF;
            }
            if(rank64(u1) > RANK4) {
                u1 = MIRRORR64(u1);
                u2 = MIRRORR64(u2);
                rot ^= rotR;
            }
            if(rank64(u1) > file64(u1)) {
                u1 = MIRRORD64(u1);
                u2 = MIRRORD64(u2);
                rot ^= rotD;
            }
            if(file64(u1) == rank64(u1)) {
                if(rank64(u2) > file64(u2)) {
                    u1 = MIRRORD64(u1);
                    u2 = MIRRORD64(u2);
                    rot ^= rotD;
                }
            }

            val = (u1 << 6) | u2;

            /*actual index*/
            if(file64(u1) == rank64(u1)) {
                u1 = K_TR[u1];
                u2 = K1_TR[u2];
            } else {
                u1 = K_TR[u1];
                u2 = u2;
            }

            if(temp[u1 * 64 + u2] == ILLEGAL) {
                temp[u1 * 64 + u2] = index;
                KK_index[i * 64 + j] = index;
                KK_rotation[i * 64 + j] = rot;
                KK_square[index] = val;
                index++;
            } else {
                KK_index[i * 64 + j] = temp[u1 * 64 + u2];
                KK_rotation[i * 64 + j] = rot;
            }
        }
    }
    /*with pawn*/
    for( i = 0; i < 2048; i++) {
        temp[i] = ILLEGAL;
    }

    index = 0;
    for( i = 0;i < 64;i++) {
        for( j = 0; j < 64;j++) {
            if(distance(SQ6488(i),SQ6488(j)) <= 1)
                continue;

            /*reflection*/
            u1 = i;
            u2 = j;
            rot = 0;
            if(file64(u1) > FILED) {
                u1 = MIRRORF64(u1);
                u2 = MIRRORF64(u2);
                rot ^= rotF;
            }

            val = (u1 << 6) | u2;
            /*actual index*/
            u1 = K2_TR[u1];
            u2 = u2;

            if(temp[u1 * 64 + u2] == ILLEGAL) {
                temp[u1 * 64 + u2] = index;
                KK_WP_index[i * 64 + j] = index;
                KK_WP_rotation[i * 64 + j] = rot;
                KK_WP_square[index] = val;
                index++;
            } else {
                KK_WP_index[i * 64 + j] = temp[u1 * 64 + u2];
                KK_WP_rotation[i * 64 + j] = rot;
            }
            /*end*/
        }
    }
}
void CMobController::Move()
{
    if (!PMob->PAI->CanFollowPath())
    {
        return;
    }
    if (PMob->PAI->PathFind->IsFollowingScriptedPath() && PMob->PAI->CanFollowPath())
    {
        PMob->PAI->PathFind->FollowPath();
        return;
    }

    // attempt to teleport
    if (PMob->getMobMod(MOBMOD_TELEPORT_TYPE) == 1)
    {
        if (m_Tick >= m_LastSpecialTime + std::chrono::milliseconds(PMob->getBigMobMod(MOBMOD_TELEPORT_CD)))
        {
            CMobSkill* teleportBegin = battleutils::GetMobSkill(PMob->getMobMod(MOBMOD_TELEPORT_START));

            if (teleportBegin)
            {
                m_LastSpecialTime = m_Tick;
                MobSkill(PMob->targid, teleportBegin->getID());
            }
        }
    }

    bool move = PMob->PAI->PathFind->IsFollowingPath();
    float attack_range = PMob->GetMeleeRange();

    if (PMob->getMobMod(MOBMOD_ATTACK_SKILL_LIST) > 0)
    {
        auto skillList {battleutils::GetMobSkillList(PMob->getMobMod(MOBMOD_ATTACK_SKILL_LIST))};

        if (!skillList.empty())
        {
            auto skill {battleutils::GetMobSkill(skillList.front())};
            if (skill)
            {
                attack_range = skill->getDistance();
            }
        }
    }

    float currentDistance = distance(PMob->loc.p, PTarget->loc.p);
    if (PMob->getMobMod(MOBMOD_SHARE_POS) > 0)
    {
        CMobEntity* posShare = (CMobEntity*)PMob->GetEntity(PMob->getMobMod(MOBMOD_SHARE_POS) + PMob->targid, TYPE_MOB);
        PMob->loc = posShare->loc;
    }
    else if (((currentDistance > attack_range - 0.2f) || move) && PMob->PAI->CanFollowPath())
    {
        //#TODO: can this be moved to scripts entirely?
        if (PMob->getMobMod(MOBMOD_DRAW_IN) > 0)
        {
            if (currentDistance >= PMob->GetMeleeRange() * 2 && battleutils::DrawIn(PTarget, PMob, PMob->GetMeleeRange() - 0.2f))
                FaceTarget();
        }
        if (PMob->speed != 0 && PMob->getMobMod(MOBMOD_NO_MOVE) == 0 && m_Tick >= m_LastSpecialTime)
        {
            // attempt to teleport to target (if in range)
            if (PMob->getMobMod(MOBMOD_TELEPORT_TYPE) == 2)
            {
                CMobSkill* teleportBegin = battleutils::GetMobSkill(PMob->getMobMod(MOBMOD_TELEPORT_START));

                if (teleportBegin && currentDistance <= teleportBegin->getDistance())
                {
                    MobSkill(PMob->targid, teleportBegin->getID());
                    m_LastSpecialTime = m_Tick;
                    return;
                }
            }
            else if (CanMoveForward(currentDistance))
            {
                if (!PMob->PAI->PathFind->IsFollowingPath() || distanceSquared(PMob->PAI->PathFind->GetDestination(), PTarget->loc.p) > 10)
                {
                    //path to the target if we don't have a path already
                    PMob->PAI->PathFind->PathInRange(PTarget->loc.p, attack_range - 0.2f, PATHFLAG_WALLHACK | PATHFLAG_RUN);
                }
                PMob->PAI->PathFind->FollowPath();
                if (!PMob->PAI->PathFind->IsFollowingPath())
                {
                    //arrived at target - move if there is another mob under me
                    if (PTarget->objtype == TYPE_PC)
                    {
                        for (auto PSpawnedMob : static_cast<CCharEntity*>(PTarget)->SpawnMOBList)
                        {
                            if (PSpawnedMob.second != PMob && !PSpawnedMob.second->PAI->PathFind->IsFollowingPath() && distance(PSpawnedMob.second->loc.p, PMob->loc.p) < 1.f)
                            {
                                auto angle = getangle(PMob->loc.p, PTarget->loc.p) + 64;
                                position_t new_pos {PMob->loc.p.x - (cosf(rotationToRadian(angle)) * 1.5f),
                                    PTarget->loc.p.y, PMob->loc.p.z + (sinf(rotationToRadian(angle)) * 1.5f), 0, 0};
                                if (PMob->PAI->PathFind->ValidPosition(new_pos))
                                {
                                    PMob->PAI->PathFind->PathTo(new_pos, PATHFLAG_WALLHACK | PATHFLAG_RUN);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                FaceTarget();
            }
        }
    }
    else
    {
        FaceTarget();
    }
}
void
MS_E2_ZS_CollectorOverLanes::extendTo(SUMOReal length) {
    bool done = false;
    while (!done) {
        done = true;
        LengthVector::iterator leni = myLengths.begin();
        LaneVectorVector::iterator lanei = myLaneCombinations.begin();
        DetectorVectorVector::iterator deti = myDetectorCombinations.begin();
        for (; leni != myLengths.end(); leni++, lanei++, deti++) {
            if ((*leni) < length) {
                done = false;
                // copy current values
                LaneVector lv = *lanei;
                DetectorVector dv = *deti;
                SUMOReal clength = *leni;
                assert(lv.size() > 0);
                assert(dv.size() > 0);
                // erase previous elements
                assert(leni != myLengths.end());
                myLengths.erase(leni);
                myLaneCombinations.erase(lanei);
                myDetectorCombinations.erase(deti);
                // get the lane to look before
                MSLane* toExtend = lv.back();
                // and her predecessors
                std::vector<MSLane*> predeccessors = getLanePredeccessorLanes(toExtend);
                if (predeccessors.size() == 0) {
                    int off = 1;
                    MSEdge& e = toExtend->getEdge();
                    const std::vector<MSLane*>& lanes = e.getLanes();
                    int idx = (int) distance(lanes.begin(), find(lanes.begin(), lanes.end(), toExtend));
                    while (predeccessors.size() == 0) {
                        if (idx - off >= 0) {
                            MSLane* tryMe = lanes[idx - off];
                            predeccessors = getLanePredeccessorLanes(tryMe);
                        }
                        if (predeccessors.size() == 0 && idx + off < (int) lanes.size()) {
                            MSLane* tryMe = lanes[idx + off];
                            predeccessors = getLanePredeccessorLanes(tryMe);
                        }
                        off++;
                    }
                }

                /*                LaneContinuations::const_iterator conts =
                                    laneContinuations.find(toExtend->id());
                                assert(conts!=laneContinuations.end());
                                const std::vector<std::string> &predeccessors =
                                    (*conts).second;*/
                // go through the predeccessors and extend the detector
                for (std::vector<MSLane*>::const_iterator i = predeccessors.begin(); i != predeccessors.end(); i++) {
                    // get the lane
                    MSLane* l = *i;
                    // compute detector length
                    SUMOReal lanelen = length - clength;
                    if (lanelen > l->getLength()) {
                        lanelen = l->getLength() - (SUMOReal) 0.2;
                    }
                    // build new info
                    LaneVector nlv = lv;
                    nlv.push_back(l);
                    DetectorVector ndv = dv;
                    MSE2Collector* coll = 0;
                    if (myAlreadyBuild.find(l) == myAlreadyBuild.end()) {
                        coll = buildCollector(0, 0, l, (SUMOReal) 0.1, lanelen);
                    } else {
                        coll = myAlreadyBuild.find(l)->second;
                    }
                    myAlreadyBuild[l] = coll;
                    ndv.push_back(coll);
                    // store new info
                    myLaneCombinations.push_back(nlv);
                    myDetectorCombinations.push_back(ndv);
                    myLengths.push_back(clength + lanelen);
                }
                // restart
                leni = myLengths.end() - 1;
            }
        }
    }
}
Exemple #29
0
 float PathFinder::getDistToNext(float x, float y, float z)
 {
     ESM::Pathgrid::Point nextPoint = *mPath.begin();
     return distance(nextPoint, x, y, z);
 }
Exemple #30
0
bool CTargetFind::isWithinArea(position_t* pos)
{
    return distance(*m_PRadiusAround, *pos) <= m_radius;
}