Ejemplo n.º 1
0
void MapPainterSVG::DrawWay(const StyleConfig& styleConfig,
                            const Projection& projection,
                            const MapParameter& parameter,
                            const WayData& data)
{
    std::map<LineStyle,std::string>::const_iterator styleNameEntry=lineStyleNameMap.find(*data.lineStyle);

    assert(styleNameEntry!=lineStyleNameMap.end());

    if (!data.lineStyle->GetDash().empty() &&
            data.lineStyle->GetGapColor().GetA()>0.0) {
        DrawPath(projection,
                 parameter,
                 data.lineStyle->GetGapColor(),
                 data.lineWidth,
                 emptyDash,
                 data.startIsClosed ? data.lineStyle->GetEndCap() : data.lineStyle->GetJoinCap(),
                 data.endIsClosed ? data.lineStyle->GetEndCap() : data.lineStyle->GetJoinCap(),
                 data.transStart,data.transEnd);
    }

    DrawPath(projection,
             parameter,
             styleNameEntry->second,
             data.lineWidth,
             data.startIsClosed ? data.lineStyle->GetEndCap() : data.lineStyle->GetJoinCap(),
             data.endIsClosed ? data.lineStyle->GetEndCap() : data.lineStyle->GetJoinCap(),
             data.transStart,data.transEnd);
}
void FGameplayDebuggerCategory_AI::DrawData(APlayerController* OwnerPC, FGameplayDebuggerCanvasContext& CanvasContext)
{
	const bool bReducedMode = IsSimulateInEditor();
	bShowCategoryName = !bReducedMode;

	UWorld* MyWorld = OwnerPC->GetWorld();
	AActor* SelectedActor = FindLocalDebugActor();

	DrawPawnIcons(MyWorld, SelectedActor, OwnerPC ? OwnerPC->GetPawn() : nullptr, CanvasContext);
	if (bReducedMode)
	{
		if (DataPack.bHasController)
		{
			DrawPath(MyWorld);
		}
	}
	else
	{
		if (SelectedActor)
		{
			DrawOverheadInfo(*SelectedActor, CanvasContext);
		}

		DrawPath(MyWorld);
	}

	const bool bShowClassNames = !bReducedMode || DataPack.bHasController;
	if (bShowClassNames)
	{
		CanvasContext.Printf(TEXT("Controller Name: {yellow}%s"), *DataPack.ControllerName);
		CanvasContext.Printf(TEXT("Pawn Name: {yellow}%s"), *DataPack.PawnName);
	}

	if (DataPack.bIsUsingCharacter)
	{
		CanvasContext.Printf(TEXT("Movement Mode: {yellow}%s{white}, Base: {yellow}%s"), *DataPack.MovementModeInfo, *DataPack.MovementBaseInfo);
		CanvasContext.Printf(TEXT("NavData: {yellow}%s{white}, Path following: {yellow}%s"), *DataPack.NavDataInfo, *DataPack.PathFollowingInfo);
	}

	if (DataPack.bIsUsingBehaviorTree)
	{
		CanvasContext.Printf(TEXT("Behavior: {yellow}%s{white}, Tree: {yellow}%s"), *DataPack.CurrentAIState, *DataPack.CurrentAIAssets);
		CanvasContext.Printf(TEXT("Active task: {yellow}%s"), *DataPack.CurrentAITask);
	}

	if (DataPack.bIsUsingGameplayTasks)
	{
		if (DataPack.NumTickingTasks > 0)
		{
			CanvasContext.Printf(TEXT("Ticking tasks: {yellow}%d%s"), DataPack.NumTickingTasks, *DataPack.TickingTaskInfo);
		}

		CanvasContext.Printf(TEXT("Gameplay tasks: {yellow}%d%s"), DataPack.NumTasksInQueue, *DataPack.TaskQueueInfo);
	}

	if (DataPack.bIsUsingCharacter)
	{
		CanvasContext.Printf(TEXT("Montage: {yellow}%s"), *DataPack.MontageInfo);
	}
}
Ejemplo n.º 3
0
int main()
{

	std::vector< Coord > path;
	
	Point *start = new Point( 5, 1, 0, nullptr );
	Point *end = new Point( 5, 15, 0, nullptr );

	glfwInit();
	DrawPath( path );
	GLFWwindow *wind = glfwCreateWindow( 800, 600, "A* Pathfinding", nullptr, nullptr );

	glfwMakeContextCurrent( wind );
	Reshape( wind, 800, 600 );

	glfwSetWindowSizeCallback( wind, Reshape );
	glfwSetCursorPosCallback( wind, mousePosCallBack );
	glfwSetMouseButtonCallback( wind, mouseClickCallBack );

	srand( time(nullptr) );

	for( int y = 0; y < walls.size(); y++ )
	{

		for( int x = 0; x < walls[y].size(); x++ )
		{

			walls[x][y] = 1;

		}

	}

	while( !glfwWindowShouldClose( wind ) )
	{

		glClear( GL_COLOR_BUFFER_BIT );
		glLoadIdentity();

		glTranslatef( 0.0f, 0.0f, -1.0f );

		path = AStar( walls, *start, *end );
		DrawMap();
		DrawPath( path );

		std::this_thread::sleep_for( std::chrono::milliseconds(17) );

		//ResetKeys();
		glfwPollEvents();
		glfwSwapBuffers( wind );

	}

	glfwTerminate();

}
void AnyAngleAlgorithm::ShowPath(const MapEnvironment *env, float r, float g, float b)
{
    env->SetColor(r, g, b);

    if (!UsingXYLocCont()) {
        DrawPath(env, this->xyloc_path_, true);
    }

    else {
        DrawPath(env, this->xyloc_cont_path_, true);
    }
}
void AnyAngleAlgorithm::ShowSmoothedPath(const MapEnvironment *env, float r, float g, float b)
{
    if (!ShouldSmoothPaths())
        return;

    env->SetColor(r, g, b);

    if (!UsingXYLocCont()) {
        DrawPath(env, this->smoothed_xyloc_path_, false);
    }

    else {
        DrawPath(env, this->smoothed_xyloc_cont_path_, false);
    }
}
Ejemplo n.º 6
0
void MapGrid::draw(ALLEGRO_MOUSE_STATE mouse, std::string *title, std::string *description, bool waveInProgress)
{
    hover = NULL;
    for (int i = 0; i < GridHeight; i++)
    {
        for (int j = 0; j < GridWidth; j++)
        {
            if (grid[i][j].draw(mouse))
            {
                hover = &grid[i][j];
            }
        }
    }
    if(clicked != NULL && !waveInProgress){
        clicked->draw(mouse);
        *title = clicked->GetName();
		*description = clicked->GetDescription();
		if (!clicked->IsParentNull()) {
			//std::string newDesc = "";
			//std::stringstream sstm;
			//sstm << "DEBUG: Parent X: " << clicked->GetParentX() << " Parent Y: " << clicked->GetParentY() << " My fScore: " << clicked->GetFScore() << " my gScore: " << clicked->GetGScore();
			//newDesc = sstm.str();
			//*description = newDesc;
		}

    }
    if(hover != NULL && !waveInProgress){
        hover->draw(mouse);
    }
	DrawPath();
}
Ejemplo n.º 7
0
void K1999::CalcRaceLine()
{
	const unsigned int stepsize = 128;
	
	//abort if the track isn't long enough
	if (tx.size() < stepsize)
		return;
	
 //
 // Smoothing loop
 //
 for (int Step = stepsize; (Step /= 2) > 0;)
 {
  for (int i = Iterations * int(sqrt(float(Step))); --i >= 0;)
   Smooth(Step);
  Interpolate(Step);
 }
 
 //
 // Compute curvature along the path
 //
 for (int i = Divs; --i >= 0;)
 {
  int next = (i + 1) % Divs;
  int prev = (i - 1 + Divs) % Divs;

  double rInverse = GetRInverse(prev, tx[i], ty[i], next);
  tRInverse[i] = rInverse;
 }

#ifdef DRAWPATH
 std::ofstream ofs("k1999.path");
 DrawPath(ofs);
#endif
} 
Ejemplo n.º 8
0
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::RefreshGeometry()
{
    if (point1Id > NULL_ID)
    {
        const QSharedPointer<VPointF> first = Visualization::data->GeometricObject<VPointF>(point1Id);
        DrawPoint(lineP1, first->toQPointF(), supportColor);

        if (point4Id <= NULL_ID)
        {
            DrawLine(line, QLineF(first->toQPointF(), Visualization::scenePos), mainColor);
        }
        else
        {
            const QSharedPointer<VPointF> second = Visualization::data->GeometricObject<VPointF>(point4Id);
            DrawPoint(lineP4, second->toQPointF(), supportColor);

            if (qFuzzyCompare(angle1, EMPTY_ANGLE) || qFuzzyCompare(angle2, EMPTY_ANGLE))
            {
                DrawLine(line, QLineF(first->toQPointF(), second->toQPointF()), mainColor);
            }
            else
            {
                VSpline spline(*first, *second, angle1, angle2, kAsm1, kAsm2, kCurve);
                DrawPath(this, spline.GetPath(PathDirection::Show), mainColor, Qt::SolidLine, Qt::RoundCap);
            }
        }
    }
}
Ejemplo n.º 9
0
void Painter::Draw()
{
	glClear(GL_COLOR_BUFFER_BIT);
	DrawCoordinate();
	DrawPath();
	glFlush();
}
Ejemplo n.º 10
0
void QTPFSPathDrawer::DrawPaths(const MoveDef* md) const {
	const QTPFS::PathCache& pathCache = pm->pathCaches[md->pathType];
	const QTPFS::PathCache::PathMap& paths = pathCache.GetLivePaths();

	QTPFS::PathCache::PathMap::const_iterator pathsIt;

	CVertexArray* va = GetVertexArray();

	for (pathsIt = paths.begin(); pathsIt != paths.end(); ++pathsIt) {
		DrawPath(pathsIt->second, va);

		#ifdef QTPFS_TRACE_PATH_SEARCHES
		#define PM QTPFS::PathManager
		const PM::PathTypeMap::const_iterator typeIt = pm->pathTypes.find(pathsIt->first);
		const PM::PathTraceMap::const_iterator traceIt = pm->pathTraces.find(pathsIt->first);
		#undef PM

		if (typeIt == pm->pathTypes.end() || traceIt == pm->pathTraces.end())
			continue;
		// this only happens if source-node was equal to target-node
		if (traceIt->second == NULL)
			continue;

		DrawSearchExecution(typeIt->second, traceIt->second);
		#endif
	}
}
void AGameplayDebuggingHUDComponent::DrawBasicData(APlayerController* PC, class UGameplayDebuggingComponent *DebugComponent)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
	PrintString(DefaultContext, TEXT("\n{R=0,G=255,B=0,A=255}BASIC DATA\n"));

	UFont* OldFont = DefaultContext.Font;
	DefaultContext.Font = GEngine->GetMediumFont();
	PrintString(DefaultContext, FString::Printf(TEXT("Controller Name: {yellow}%s\n"), *DebugComponent->ControllerName));
	DefaultContext.Font = OldFont;

	PrintString(DefaultContext, FString::Printf(TEXT("Pawn Name: {yellow}%s{white}, Pawn Class: {yellow}%s\n"), *DebugComponent->PawnName, *DebugComponent->PawnClass));

	// movement
	if (DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Movement Mode: {yellow}%s{white}, Base: {yellow}%s\n"), *DebugComponent->MovementModeInfo, *DebugComponent->MovementBaseInfo));
		PrintString(DefaultContext, FString::Printf(TEXT("NavData: {yellow}%s{white}, Path following: {yellow}%s\n"), *DebugComponent->NavDataInfo, *DebugComponent->PathFollowingInfo));
	}

	// logic
	if (DebugComponent->bIsUsingBehaviorTree)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Behavior: {yellow}%s{white}, Tree: {yellow}%s\n"), *DebugComponent->CurrentAIState, *DebugComponent->CurrentAIAssets));
		PrintString(DefaultContext, FString::Printf(TEXT("Active task: {yellow}%s\n"), *DebugComponent->CurrentAITask));
	}
		
	// ability + animation
	if (DebugComponent->bIsUsingAbilities && DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Ability: {yellow}%s{white}, Montage: {yellow}%s\n"), *DebugComponent->AbilityInfo, *DebugComponent->MontageInfo));
	}
	else if (DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Montage: {yellow}%s\n"), *DebugComponent->MontageInfo));
	}
	else if (DebugComponent->bIsUsingAbilities)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Ability: {yellow}%s\n"), *DebugComponent->AbilityInfo));
	}

	// gameplay tasks
	int32 NumTasks = 0;
	if (DebugComponent->GameplayTasksState.Len() > 0)
	{
		int32 SearchStart = -2;
		int32 PrevStart = 0;
		do {
			PrevStart = SearchStart + 1;
			SearchStart = DebugComponent->GameplayTasksState.Find(TEXT("\n"), ESearchCase::IgnoreCase, ESearchDir::FromStart, PrevStart);
			NumTasks++;
		} while (SearchStart >= 0 && SearchStart > PrevStart);
		
		NumTasks--;
	}
	PrintString(DefaultContext, FString::Printf(TEXT("GameplayTasks: {yellow}%d\n%s\n"), NumTasks, *DebugComponent->GameplayTasksState));

	DrawPath(PC, DebugComponent);
#endif //!(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
void AGameplayDebuggingHUDComponent::DrawOverHeadInformation(APlayerController* PC, class UGameplayDebuggingComponent *DebugComponent)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
	APawn* MyPawn = Cast<APawn>(DebugComponent->GetSelectedActor());
	const FVector Loc3d = MyPawn ? MyPawn->GetActorLocation() + FVector(0.f, 0.f, MyPawn->GetSimpleCollisionHalfHeight()) : FVector::ZeroVector;

	if (OverHeadContext.Canvas->SceneView == NULL || OverHeadContext.Canvas->SceneView->ViewFrustum.IntersectBox(Loc3d, FVector::ZeroVector) == false)
	{
		return;
	}

	const FVector ScreenLoc = OverHeadContext.Canvas->Project(Loc3d);
	static const FVector2D FontScale(1.f, 1.f);
	UFont* Font = GEngine->GetSmallFont();

	float TextXL = 0.f;
	float YL = 0.f;
	FString ObjectName = FString::Printf( TEXT("{yellow}%s {white}(%s)"), *DebugComponent->ControllerName, *DebugComponent->PawnName);
	CalulateStringSize(OverHeadContext, OverHeadContext.Font, ObjectName, TextXL, YL);

	bool bDrawFullOverHead = MyPawn != nullptr && GetDebuggingReplicator()->GetSelectedActorToDebug() == MyPawn;
	float IconXLocation = OverHeadContext.DefaultX;
	float IconYLocation = OverHeadContext.DefaultY;
	if (bDrawFullOverHead)
	{
		OverHeadContext.DefaultX -= (0.5f*TextXL*FontScale.X);
		OverHeadContext.DefaultY -= (1.2f*YL*FontScale.Y);
		IconYLocation = OverHeadContext.DefaultY;
		OverHeadContext.CursorX = OverHeadContext.DefaultX;
		OverHeadContext.CursorY = OverHeadContext.DefaultY;
	}

	if (DebugComponent->DebugIcon.Len() > 0)
	{
		UTexture2D* RegularIcon = (UTexture2D*)StaticLoadObject(UTexture2D::StaticClass(), NULL, *DebugComponent->DebugIcon, NULL, LOAD_NoWarn | LOAD_Quiet, NULL);
		if (RegularIcon)
		{
			FCanvasIcon Icon = UCanvas::MakeIcon(RegularIcon);
			if (Icon.Texture)
			{
				const float DesiredIconSize = bDrawFullOverHead ? 32.f : 16.f;
				DrawIcon(OverHeadContext, FColor::White, Icon, IconXLocation, IconYLocation - DesiredIconSize, DesiredIconSize / Icon.Texture->GetSurfaceWidth());
			}
		}
	}

	if (bDrawFullOverHead)
	{
		OverHeadContext.FontRenderInfo.bEnableShadow = bDrawFullOverHead;
		PrintString(OverHeadContext, bDrawFullOverHead ? FColor::White : FColor(255, 255, 255, 128), FString::Printf(TEXT("%s\n"), *ObjectName));
		OverHeadContext.FontRenderInfo.bEnableShadow = false;
	}

	if (EngineShowFlags.DebugAI)
	{
		DrawPath(PC, DebugComponent);
	}
#endif //!(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
Ejemplo n.º 13
0
void wxSVGCanvasCairo::DrawCanvasPath(wxSVGCanvasPathCairo& canvasPath, wxSVGMatrix& matrix,
		const wxCSSStyleDeclaration& style, wxSVGSVGElement& svgElem) {
	// check Filter
	if (style.GetFilter().GetCSSPrimitiveType() == wxCSS_URI && style.GetFilter().GetStringValue().length() > 1) {
		wxString filterId = style.GetFilter().GetStringValue().substr(1);
		wxSVGElement* filterElem = (wxSVGElement*) svgElem.GetElementById(filterId);
		// feGaussianBlur
		if (filterElem && filterElem->GetDtd() == wxSVG_FILTER_ELEMENT && filterElem->GetFirstChild() != NULL
				&& ((wxSVGSVGElement*) filterElem->GetFirstChild())->GetDtd() == wxSVG_FEGAUSSIANBLUR_ELEMENT) {
			float stdX = ((wxSVGFEGaussianBlurElement*) filterElem->GetFirstChild())->GetStdDeviationX().GetAnimVal();
			float stdY = ((wxSVGFEGaussianBlurElement*) filterElem->GetFirstChild())->GetStdDeviationY().GetAnimVal();
			if (stdX <= 0 || stdY <= 0)
				return;
			int dx = int(floor(stdX * 3 * sqrt(2 * M_PI) / 4 + 0.5));
			int dy = int(floor(stdY * 3 * sqrt(2 * M_PI) / 4 + 0.5));
			
			wxSVGRect rect = canvasPath.GetResultBBox(style, matrix.Inverse());
			rect.SetX(rect.GetX() - 2*dx);
			rect.SetY(rect.GetY() - 2*dy);
			rect.SetWidth(rect.GetWidth() + 4*dx);
			rect.SetHeight(rect.GetHeight() + 4*dy);
			
			int width = (int) rect.GetWidth();
			int height = (int) rect.GetHeight();
			cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
			cairo_t* cr = cairo_create(surface);
			wxSVGMatrix matrix2 = wxSVGMatrix(1, 0, 0, 1, - rect.GetX(), - rect.GetY()).Multiply(matrix);
			DrawPath(cr, canvasPath, matrix2, style, svgElem);
			gaussianBlur(surface, dx, dy);
			
			// draw surface
			cairo_save(m_cr);
			SetMatrix(m_cr, wxSVGMatrix(1, 0, 0, 1, rect.GetX(), rect.GetY()));
			cairo_set_source_surface(m_cr, surface, 0, 0);
			cairo_rectangle(m_cr, 0, 0, width, height);
			cairo_paint(m_cr); // fill the rectangle using the pattern
			cairo_new_path(m_cr);
			cairo_restore(m_cr);
			
			cairo_destroy(cr);
			cairo_surface_destroy(surface);
			return;
		}
	}
	DrawPath(m_cr, canvasPath, matrix, style, svgElem);
}
Ejemplo n.º 14
0
void wxGraphicsContext::DrawLines( size_t n, const wxPoint2DDouble *points, int fillStyle)
{
    wxASSERT(n > 1);
    wxGraphicsPath path = CreatePath();
    path.MoveToPoint(points[0].m_x, points[0].m_y);
    for ( size_t i = 1; i < n; ++i)
        path.AddLineToPoint( points[i].m_x, points[i].m_y );
    DrawPath( path , fillStyle);
}
Ejemplo n.º 15
0
FX_BOOL CFDE_GdiDevice::DrawRoundRectangle(IFDE_Pen* pPen,
                                           FX_FLOAT fPenWidth,
                                           const CFX_RectF& rect,
                                           const CFX_SizeF& round,
                                           const CFX_Matrix* pMatrix) {
  CFDE_GdiPath path;
  path.AddRoundRectangle(rect, round);
  return DrawPath(pPen, fPenWidth, &path, pMatrix);
}
Ejemplo n.º 16
0
void CLabelTestDlg::OnPaint()
{
	PAINTSTRUCT ps;
	BeginPaint(&ps);

	DrawPath();
	CreateLabel();
	DisplayPercentage();

	EndPaint(&ps);
}
Ejemplo n.º 17
0
FX_BOOL CFDE_GdiDevice::DrawChord(IFDE_Pen* pPen,
                                  FX_FLOAT fPenWidth,
                                  const CFX_RectF& rect,
                                  FX_FLOAT startAngle,
                                  FX_FLOAT sweepAngle,
                                  const CFX_Matrix* pMatrix) {
  CFX_ArcF chord;
  chord.Set(rect, startAngle, sweepAngle);
  CFDE_GdiPath path;
  path.AddChord(chord);
  return DrawPath(pPen, fPenWidth, &path, pMatrix);
}
Ejemplo n.º 18
0
void
FieldView::DrawPaths(wxDC& dc, const CC_sheet& sheet)
{
	if (mDrawPaths && mAnimation && mAnimation->GetNumberSheets() && (static_cast<unsigned>(mAnimation->GetNumberSheets()) > mShow->GetCurrentSheetNum()))
	{
		CC_coord origin = GetShowFieldOffset();
		mAnimation->GotoSheet(mShow->GetCurrentSheetNum());
		for (auto point = mShow->GetSelectionList().begin(); point != mShow->GetSelectionList().end(); ++point)
		{
			DrawPath(dc, mAnimation->GenPathToDraw(*point, origin), mAnimation->EndPosition(*point, origin));
		}
	}
}
Ejemplo n.º 19
0
bool FieldView::DrawAllPaths(){
    Field::Paths paths = field->GetPaths();
    const size_t size = paths.size();
    bool result = true;
    //if there is at least one path, then...
    //simply draw every existing path
    if(!paths.empty())
        for(size_t i = 0; i < size; i++)
            if(!DrawPath(paths[i]))
                result = false;
    paths.clear();
    return result;
}
void PreviewWindow::Render(wxDC& dc)
{
	dc.SetBackground(wxBrush(backgroundColour));
	dc.Clear();		
	DrawPath(dc);
	DrawTrajectory(dc);
	DrawOrigin(dc);
	wxString text;
	text << wxT("X: ") << offset.x << wxT("  Y: ") << offset.y
		<< wxT("  Z: ") << wheelPosition;
	dc.SetTextForeground(wxColour(255, 255, 255));
	dc.DrawText(text, 40, 10);
}
void AGameplayDebuggingHUDComponent::DrawBasicData(APlayerController* PC, class UGameplayDebuggingComponent *DebugComponent)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
	PrintString(DefaultContext, TEXT("\n{R=0,G=255,B=0,A=255}BASIC DATA\n"));

	UFont* OldFont = DefaultContext.Font;
	DefaultContext.Font = GEngine->GetMediumFont();
	PrintString(DefaultContext, FString::Printf(TEXT("Controller Name: {yellow}%s\n"), *DebugComponent->ControllerName));
	DefaultContext.Font = OldFont;

	PrintString(DefaultContext, FString::Printf(TEXT("Pawn Name: {yellow}%s{white}, Pawn Class: {yellow}%s\n"), *DebugComponent->PawnName, *DebugComponent->PawnClass));

	// movement
	if (DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Movement Mode: {yellow}%s{white}, Base: {yellow}%s\n"), *DebugComponent->MovementModeInfo, *DebugComponent->MovementBaseInfo));
		PrintString(DefaultContext, FString::Printf(TEXT("NavData: {yellow}%s{white}, Path following: {yellow}%s\n"), *DebugComponent->NavDataInfo, *DebugComponent->PathFollowingInfo));
	}

	// logic
	if (DebugComponent->bIsUsingBehaviorTree)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Behavior: {yellow}%s{white}, Tree: {yellow}%s\n"), *DebugComponent->CurrentAIState, *DebugComponent->CurrentAIAssets));
		PrintString(DefaultContext, FString::Printf(TEXT("Active task: {yellow}%s\n"), *DebugComponent->CurrentAITask));
	}
		
	// ability + animation
	if (DebugComponent->bIsUsingAbilities && DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Ability: {yellow}%s{white}, Montage: {yellow}%s\n"), *DebugComponent->AbilityInfo, *DebugComponent->MontageInfo));
	}
	else if (DebugComponent->bIsUsingCharacter)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Montage: {yellow}%s\n"), *DebugComponent->MontageInfo));
	}
	else if (DebugComponent->bIsUsingAbilities)
	{
		PrintString(DefaultContext, FString::Printf(TEXT("Ability: {yellow}%s\n"), *DebugComponent->AbilityInfo));
	}

	// putting gameplay tasks' stuff last since it can expand heavily
	PrintString(DefaultContext, FString::Printf(TEXT("GameplayTasks:\n{yellow}%s\n"), *DebugComponent->GameplayTasksState));

	DrawPath(PC, DebugComponent);
#endif //!(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
Ejemplo n.º 22
0
void BotDebugDrawMesh( BotDebugInterface_t *in )
{
	static DebugDrawQuake dd;

	dd.init( in );

	if ( !cmd.enabled )
	{
		return;
	}

	if ( !cmd.nav )
	{
		return;
	}

	if ( !cmd.nav->mesh || !cmd.nav->query )
	{
		return;
	}

	if ( cmd.shownodes )
	{
		duDebugDrawNavMeshNodes( &dd, *cmd.nav->query );
	}

	if ( cmd.showportals )
	{
		duDebugDrawNavMeshPortals( &dd, *cmd.nav->mesh );
	}

	duDebugDrawNavMeshWithClosedList(&dd, *cmd.nav->mesh, *cmd.nav->query, DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST);
	BotDrawNavEdit( &dd );

	for ( int i = 0; i < MAX_CLIENTS; i++ )
	{
		Bot_t *bot = &agents[ i ];

		if ( bot->nav == cmd.nav )
		{
			DrawPath( bot, dd );
		}
	}
}
Ejemplo n.º 23
0
//---------------------------------------------------------------------------------------------------------------------
void VisToolSplinePath::RefreshGeometry()
{
    if (path.CountPoint() > 0)
    {
        QVector<VSplinePoint> pathPoints = path.GetSplinePath();
        if (path.CountPoint() == 1)
        {
            QGraphicsEllipseItem *point = this->getPoint(0);
            DrawPoint(point, pathPoints.at(0).P().toQPointF(), supportColor);

            if (mode == Mode::Creation)
            {
                QLineF sceneLine = QLineF(pathPoints.at(0).P().toQPointF(), Visualization::scenePos);
                DrawLine(line, sceneLine, mainColor, lineStyle);

                path[0].SetAngle2(sceneLine.angle());
                emit PathChanged(path);
            }
        }
        else
        {
            for (int i = 0; i < pathPoints.size(); ++i)
            {
                QGraphicsEllipseItem *point = this->getPoint(static_cast<unsigned>(i));
                DrawPoint(point, pathPoints.at(i).P().toQPointF(), supportColor);
            }

            if (mode == Mode::Creation)
            {
                QLineF sceneLine = QLineF(pathPoints.at(pathPoints.size() - 1).P().toQPointF(),
                                          Visualization::scenePos);
                DrawLine(line, sceneLine, mainColor, lineStyle);

                path[pathPoints.size() - 1].SetAngle2(sceneLine.angle());
                emit PathChanged(path);
            }

            DrawPath(this, path.GetPath(PathDirection::Show), mainColor, Qt::SolidLine, Qt::RoundCap);
        }
        Visualization::toolTip = QString(tr("<b>Curve path</b>: <b>Enter</b> - finish creation"));
    }
}
Ejemplo n.º 24
0
void touchmind::view::node::NodeViewManager::DrawNodePaths(touchmind::Context *pContext,
                                                           ID2D1RenderTarget *pRenderTarget,
                                                           std::shared_ptr<model::node::NodeModel> node) {
  PATH_DIRECTION pathDirection;
  touchmind::NODE_SIDE nodePosition = node->GetAncestorPosition();
  switch (nodePosition) {
  case touchmind::NODE_SIDE_RIGHT:
    pathDirection = PATH_DIRECTION_RIGHT;
    break;
  case touchmind::NODE_SIDE_LEFT:
    pathDirection = PATH_DIRECTION_LEFT;
    break;
  case touchmind::NODE_SIDE_UNDEFINED:
    pathDirection = PATH_DIRECTION_AUTO;
    break;
  default:
    pathDirection = PATH_DIRECTION_AUTO;
  }

  for (size_t i = 0; i < node->GetActualChildrenCount(); ++i) {
    std::shared_ptr<touchmind::model::node::NodeModel> child = node->GetChild(i);
    DrawPath(pContext, pRenderTarget, child);
  }
}
Ejemplo n.º 25
0
/* Main window process messages callback function */
LRESULT CALLBACK WndProc( HWND hWnd, UINT message,
                          WPARAM wParam, LPARAM lParam )
{
  PAINTSTRUCT ps;
  HDC hdc;
  static RECT rt, boardRect, xAxisRect, yAxisRect, figureRect, pathLenRect;
  static Point fig1, fig2;
  static Point path[MAX_PATH_QUEUE];
  static HBRUSH hBlackBrush, hWhiteBrush, hRedBrush;
  static HPEN hPen;
  static ChessFigure *chessFigures;
  static int nChessFigures, currentChessFigure = 0 , pathLen = -1;
  int mX, mY;
  
  switch (message)
  {
  case WM_CREATE:
    /* Initializing chess figures */
    nChessFigures = CreateChessFigures(&chessFigures);
    /* Initializing board data */
    srand((unsigned)time(NULL));
    fig1.x = (int)((double)rand() / RAND_MAX * BOARD_X);
    fig1.y = (int)((double)rand() / RAND_MAX * BOARD_Y);
    fig2.x = (int)((double)rand() / RAND_MAX * BOARD_X);
    fig2.y = (int)((double)rand() / RAND_MAX * BOARD_Y);
    pathLen = SearchTurns(path, MAX_PATH_QUEUE, &fig1, &fig2,
      &chessFigures[currentChessFigure]);
    /* Creating instruments */
    hBlackBrush = CreateSolidBrush(RGB(0x00, 0x00, 0x00));
    hWhiteBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));
    hRedBrush = CreateSolidBrush(RGB(0xFF, 0x00, 0x00));
    hPen = CreatePen(PS_SOLID, 4, RGB(0xFF, 0x10, 0x10));
    break;
  case WM_SIZE:
    break;
  case WM_PAINT:
    hdc = BeginPaint(hWnd, &ps);

    /* Calculating render rectangles */
    GetClientRect(hWnd, &rt);

    /* Board rectangle */
    boardRect.left = rt.left + AXIS_WIDTH;
    boardRect.right = rt.right;
    boardRect.top = rt.top + CAPTION_HEIGHT;
    boardRect.bottom = rt.bottom - AXIS_HEIGHT;

    /* Correcting aspect */
    if ((double)(boardRect.right - boardRect.left) / BOARD_X >
        (double)(boardRect.bottom - boardRect.top) / BOARD_Y)
    {
      boardRect.right = (long)(boardRect.left +
        (double)(boardRect.bottom - boardRect.top) / BOARD_Y * BOARD_X);
    }
    else
    {
      boardRect.bottom = (long)(boardRect.top +
        (double)(boardRect.right - boardRect.left) / BOARD_X * BOARD_Y);
    }
    
    /* 'X' axis rectangle */
    xAxisRect.left   = boardRect.left;
    xAxisRect.right  = boardRect.right;
    xAxisRect.top    = boardRect.bottom;
    xAxisRect.bottom = boardRect.bottom + AXIS_HEIGHT;

    /* 'Y' axis rectangle */
    yAxisRect.left   = rt.left;
    yAxisRect.right  = rt.left + AXIS_WIDTH;
    yAxisRect.top    = boardRect.top;
    yAxisRect.bottom = boardRect.bottom;

    /* Figure name rectangle */
    figureRect.left   = rt.left + AXIS_WIDTH;
    figureRect.right  = rt.left + AXIS_WIDTH + FIGURE_WIDTH;
    figureRect.top    = rt.top;
    figureRect.bottom = rt.top + CAPTION_HEIGHT;

    /* Path length string rectangle */
    pathLenRect.left   = rt.left + FIGURE_WIDTH + AXIS_WIDTH;
    pathLenRect.right  = rt.left + FIGURE_WIDTH + AXIS_WIDTH + PATH_WIDTH;
    pathLenRect.top    = rt.top;
    pathLenRect.bottom = rt.top + CAPTION_HEIGHT;

    /* Drawing figure caption */
    DrawFigureCaption(hdc, &figureRect,
      chessFigures[currentChessFigure].name);

    /* Drawing path length caption */
    DrawPathLenCaption(hdc, &pathLenRect, pathLen);

    /* Drawing chessboard */
    DrawChessboard(hdc, &boardRect, hBlackBrush, hWhiteBrush);

    /* Drawing axes */
    DrawXAxis(hdc, &xAxisRect);
    DrawYAxis(hdc, &yAxisRect);

    /* Drawing path */
    DrawPath(hdc, &boardRect, &fig1, path, pathLen, hPen, hRedBrush);

    /* Drawing figures labels */
    DrawFigureName(hdc, &boardRect, &fig1, "Fig.1");
    DrawFigureName(hdc, &boardRect, &fig2, "Fig.2");
    
    EndPaint(hWnd, &ps);
    break;
  case WM_CHAR:
    /* Quiting on escape */
    if (wParam == 27)
      SendMessage(hWnd, WM_DESTROY, 0, 0);
    break;
  case WM_LBUTTONUP:
    mX = LOWORD(lParam);
    mY = HIWORD(lParam);

    /* Changing first figure position */
    if (_isInRect(&boardRect, mX, mY))
    {
      fig1.x = _getXRectPart(&boardRect, BOARD_X, mX);
      fig1.y = _getYRectPart(&boardRect, BOARD_Y, mY);
      pathLen = SearchTurns(path, MAX_PATH_QUEUE, &fig1, &fig2,
        &chessFigures[currentChessFigure]);

      InvalidateRect(hWnd, &rt, TRUE);
    }
    /* Changing figure type (next) */
    else if (_isInRect(&figureRect, mX, mY))
    {
      currentChessFigure = (currentChessFigure + 1) % nChessFigures;
      pathLen = SearchTurns(path, MAX_PATH_QUEUE, &fig1, &fig2,
        &chessFigures[currentChessFigure]);

      InvalidateRect(hWnd, &rt, TRUE);
    }
    break;
  case WM_RBUTTONUP:
    mX = LOWORD(lParam);
    mY = HIWORD(lParam);

    if (_isInRect(&boardRect, mX, mY))
    {
      /* Changing second figure position */
      fig2.x = _getXRectPart(&boardRect, BOARD_X, mX);
      fig2.y = _getYRectPart(&boardRect, BOARD_Y, mY);
      pathLen = SearchTurns(path, MAX_PATH_QUEUE, &fig1, &fig2,
        &chessFigures[currentChessFigure]);

      InvalidateRect(hWnd, &rt, TRUE);
    }
    /* Changing figure type (previous) */
    else if (_isInRect(&figureRect, mX, mY))
    {
      currentChessFigure =
        (currentChessFigure + nChessFigures - 1) % nChessFigures;
      pathLen = SearchTurns(path, MAX_PATH_QUEUE, &fig1, &fig2,
        &chessFigures[currentChessFigure]);

      InvalidateRect(hWnd, &rt, TRUE);
    }
    break;
  case WM_DESTROY:
    /* Destroying created chess figures */
    DestroyChessFigures(chessFigures, nChessFigures);
    /* Destroying created instruments */
    DeleteObject(hBlackBrush);
    DeleteObject(hWhiteBrush);
    DeleteObject(hRedBrush);
    DeleteObject(hPen);
    /* Quiting */
    PostQuitMessage(0);
    break;
  default:
    return DefWindowProc(hWnd, message, wParam, lParam);
  }

  return 0;
} /* End of 'WndProc' function */
Ejemplo n.º 26
0
/**
**	Draw unit on map.
**
**	@param unit	Pointer to the unit.
*/
local void DrawUnit(Unit* unit)
{
    int x;
    int y;
    int r;
    UnitType* type;
    UnitStats* stats;

    type=unit->Type;

    x=Map2ScreenX(unit->X)+unit->IX;
    y=Map2ScreenY(unit->Y)+unit->IY;

    if( type->UnitType==UnitTypeFly ) {
	DrawShadow(unit,type,x,y);
    }

    DrawSelectionRectangle(unit,type,x,y);

    PlayerPixels(unit->Player);
    DrawUnitType(type,unit->Frame,x,y);

    stats=unit->Stats;

    //
    //	For debug draw sight, react and attack range!
    //
    if( NumSelected==1 && unit->Selected ) {
	if( ShowSightRange ) {
	    DrawRectangle(ColorGreen
		,x+TileSizeX/2-stats->SightRange*TileSizeX
		,y+TileSizeY/2-stats->SightRange*TileSizeY
		,stats->SightRange*TileSizeX*2
		,stats->SightRange*TileSizeY*2);
	}
	if( type->CanAttack ) {
	    if( ShowReactRange ) {
		r= (unit->Player->Type==PlayerHuman)
			? type->ReactRangeHuman
			: type->ReactRangeComputer;
		if( r ) {
		    DrawRectangle(ColorBlue
			,x+TileSizeX/2-r*TileSizeX
			,y+TileSizeY/2-r*TileSizeY
			,r*TileSizeX*2
			,r*TileSizeY*2);
		}
	    }
	    if( ShowAttackRange && stats->AttackRange ) {
		DrawRectangle(ColorRed
		    ,x+TileSizeX/2-stats->AttackRange*TileSizeX
		    ,y+TileSizeY/2-stats->AttackRange*TileSizeY
		    ,stats->AttackRange*TileSizeX*2
		    ,stats->AttackRange*TileSizeY*2);
	    }
	}
    }

    //
    //	For debug draw destination. FIXME: should become orders
    //
    if( ShowOrders && unit->Selected && (KeyModifiers&ModifierShift)) {
	DrawPath(unit);
    }

    // FIXME: johns: ugly check here should be removed!
    if( unit->Command.Action!=UnitActionDie ) {
	DrawDecoration(unit,type,x,y);
    }
}
Ejemplo n.º 27
0
// Move along the path. Return false if end of path reached.
CCSBot::PathResult CCSBot::UpdatePathMovement(bool allowSpeedChange)
{
	if (m_pathLength == 0)
		return PATH_FAILURE;

	if (cv_bot_walk.value != 0.0f)
		Walk();

	// If we are navigating a ladder, it overrides all other path movement until complete
	if (UpdateLadderMovement())
		return PROGRESSING;

	// ladder failure can destroy the path
	if (m_pathLength == 0)
		return PATH_FAILURE;

	// we are not supposed to be on a ladder - if we are, jump off
	if (IsOnLadder())
		Jump(MUST_JUMP);

	assert(m_pathIndex < m_pathLength);

	// Check if reached the end of the path
	bool nearEndOfPath = false;
	if (m_pathIndex >= m_pathLength - 1)
	{
		Vector toEnd(pev->origin.x, pev->origin.y, GetFeetZ());
		Vector d = GetPathEndpoint() - toEnd; // can't use 2D because path end may be below us (jump down)

		const float walkRange = 200.0f;

		// walk as we get close to the goal position to ensure we hit it
		if (d.IsLengthLessThan(walkRange))
		{
			// don't walk if crouching - too slow
			if (allowSpeedChange && !IsCrouching())
				Walk();

			// note if we are near the end of the path
			const float nearEndRange = 50.0f;
			if (d.IsLengthLessThan(nearEndRange))
				nearEndOfPath = true;

			const float closeEpsilon = 20.0f;
			if (d.IsLengthLessThan(closeEpsilon))
			{
				// reached goal position - path complete
				DestroyPath();

				// TODO: We should push and pop walk state here, in case we want to continue walking after reaching goal
				if (allowSpeedChange)
					Run();

				return END_OF_PATH;
			}
		}
	}

	// To keep us moving smoothly, we will move towards
	// a point farther ahead of us down our path.
	int prevIndex = 0;				// closest index on path just prior to where we are now
	const float aheadRange = 300.0f;
	int newIndex = FindPathPoint(aheadRange, &m_goalPosition, &prevIndex);

	// BOTPORT: Why is prevIndex sometimes -1?
	if (prevIndex < 0)
		prevIndex = 0;

	// if goal position is near to us, we must be about to go around a corner - so look ahead!
	const float nearCornerRange = 100.0f;
	if (m_pathIndex < m_pathLength - 1 && (m_goalPosition - pev->origin).IsLengthLessThan(nearCornerRange))
	{
		ClearLookAt();
		InhibitLookAround(0.5f);
	}

	// if we moved to a new node on the path, setup movement
	if (newIndex > m_pathIndex)
	{
		SetPathIndex(newIndex);
	}

	if (!IsUsingLadder())
	{
		// Crouching

		// if we are approaching a crouch area, crouch
		// if there are no crouch areas coming up, stand
		const float crouchRange = 50.0f;
		bool didCrouch = false;
		for (int i = prevIndex; i < m_pathLength; i++)
		{
			const CNavArea *to = m_path[i].area;

			// if there is a jump area on the way to the crouch area, don't crouch as it messes up the jump
			// unless we are already higher than the jump area - we must've jumped already but not moved into next area
			if ((to->GetAttributes() & NAV_JUMP)/* && to->GetCenter()->z > GetFeetZ()*/)
				break;

			Vector close;
			to->GetClosestPointOnArea(&pev->origin, &close);

			if ((close - pev->origin).Make2D().IsLengthGreaterThan(crouchRange))
				break;

			if (to->GetAttributes() & NAV_CROUCH)
			{
				Crouch();
				didCrouch = true;
				break;
			}
		}

		if (!didCrouch && !IsJumping())
		{
			// no crouch areas coming up
			StandUp();
		}
		// end crouching logic
	}

	// compute our forward facing angle
	m_forwardAngle = UTIL_VecToYaw(m_goalPosition - pev->origin);

	// Look farther down the path to "lead" our view around corners
	Vector toGoal;

	if (m_pathIndex == 0)
	{
		toGoal = m_path[1].pos;
	}
	else if (m_pathIndex < m_pathLength)
	{
		toGoal = m_path[m_pathIndex].pos - pev->origin;

		// actually aim our view farther down the path
		const float lookAheadRange = 500.0f;
		if (!m_path[m_pathIndex].ladder && !IsNearJump() && toGoal.Make2D().IsLengthLessThan(lookAheadRange))
		{
			float along = toGoal.Length2D();
			int i;
			for (i = m_pathIndex + 1; i < m_pathLength; i++)
			{
				Vector delta = m_path[i].pos - m_path[i - 1].pos;
				float segmentLength = delta.Length2D();

				if (along + segmentLength >= lookAheadRange)
				{
					// interpolate between points to keep look ahead point at fixed distance
					float t = (lookAheadRange - along) / (segmentLength + along);
					Vector target;

					if (t <= 0.0f)
						target = m_path[i - 1].pos;
					else if (t >= 1.0f)
						target = m_path[i].pos;
					else
						target = m_path[i - 1].pos + t * delta;

					toGoal = target - pev->origin;
					break;
				}

				// if we are coming up to a ladder or a jump, look at it
				if (m_path[i].ladder || (m_path[i].area->GetAttributes() & NAV_JUMP))
				{
					toGoal = m_path[i].pos - pev->origin;
					break;
				}

				along += segmentLength;
			}

			if (i == m_pathLength)
			{
				toGoal = GetPathEndpoint() - pev->origin;
			}
		}
	}
	else
	{
		toGoal = GetPathEndpoint() - pev->origin;
	}

	m_lookAheadAngle = UTIL_VecToYaw(toGoal);

	// initialize "adjusted" goal to current goal
	Vector adjustedGoal = m_goalPosition;

	// Use short "feelers" to veer away from close-range obstacles
	// Feelers come from our ankles, just above StepHeight, so we avoid short walls, too
	// Don't use feelers if very near the end of the path, or about to jump
	// TODO: Consider having feelers at several heights to deal with overhangs, etc.
	if (!nearEndOfPath && !IsNearJump() && !IsJumping())
	{
		FeelerReflexAdjustment(&adjustedGoal);
	}

	// draw debug visualization
	if ((cv_bot_traceview.value == 1.0f && IsLocalPlayerWatchingMe()) || cv_bot_traceview.value == 10.0f)
	{
		DrawPath();

		const Vector *pos = &m_path[m_pathIndex].pos;
		UTIL_DrawBeamPoints(*pos, *pos + Vector(0, 0, 50), 1, 255, 255, 0);
		UTIL_DrawBeamPoints(adjustedGoal, adjustedGoal + Vector(0, 0, 50), 1, 255, 0, 255);
		UTIL_DrawBeamPoints(pev->origin, adjustedGoal + Vector(0, 0, 50), 1, 255, 0, 255);
	}

	// dont use adjustedGoal, as it can vary wildly from the feeler adjustment
	if (!IsAttacking() && IsFriendInTheWay(&m_goalPosition))
	{
		if (!m_isWaitingBehindFriend)
		{
			m_isWaitingBehindFriend = true;

			const float politeDuration = 5.0f - 3.0f * GetProfile()->GetAggression();
			m_politeTimer.Start(politeDuration);
		}
		else if (m_politeTimer.IsElapsed())
		{
			// we have run out of patience
			m_isWaitingBehindFriend = false;
			ResetStuckMonitor();

			// repath to avoid clump of friends in the way
			DestroyPath();
		}
	}
	else if (m_isWaitingBehindFriend)
	{
		// we're done waiting for our friend to move
		m_isWaitingBehindFriend = false;
		ResetStuckMonitor();
	}

	// Move along our path if there are no friends blocking our way,
	// or we have run out of patience
	if (!m_isWaitingBehindFriend || m_politeTimer.IsElapsed())
	{
		// Move along path
		MoveTowardsPosition(&adjustedGoal);

		// Stuck check
		if (m_isStuck && !IsJumping())
		{
			Wiggle();
		}
	}

	// if our goal is high above us, we must have fallen
	bool didFall = false;
	if (m_goalPosition.z - GetFeetZ() > JumpCrouchHeight)
	{
		const float closeRange = 75.0f;
		Vector2D to(pev->origin.x - m_goalPosition.x, pev->origin.y - m_goalPosition.y);
		if (to.IsLengthLessThan(closeRange))
		{
			// we can't reach the goal position
			// check if we can reach the next node, in case this was a "jump down" situation
			if (m_pathIndex < m_pathLength - 1)
			{
				if (m_path[m_pathIndex + 1].pos.z - GetFeetZ() > JumpCrouchHeight)
				{
					// the next node is too high, too - we really did fall of the path
					didFall = true;
				}
			}
			else
			{
				// fell trying to get to the last node in the path
				didFall = true;
			}
		}
	}

	// This timeout check is needed if the bot somehow slips way off
	// of its path and cannot progress, but also moves around
	// enough that it never becomes "stuck"
	const float giveUpDuration = 5.0f; // 4.0f
	if (didFall || gpGlobals->time - m_areaEnteredTimestamp > giveUpDuration)
	{
		if (didFall)
		{
			PrintIfWatched("I fell off!\n");
		}

		// if we havent made any progress in a long time, give up
		if (m_pathIndex < m_pathLength - 1)
		{
			PrintIfWatched("Giving up trying to get to area #%d\n", m_path[m_pathIndex].area->GetID());
		}
		else
		{
			PrintIfWatched("Giving up trying to get to end of path\n");
		}

		Run();
		StandUp();
		DestroyPath();

		return PATH_FAILURE;
	}

	return PROGRESSING;
}
Ejemplo n.º 28
0
void wxGraphicsContext::DrawEllipse( wxDouble x, wxDouble y, wxDouble w, wxDouble h)
{
    wxGraphicsPath path = CreatePath();
    path.AddEllipse(x,y,w,h);
    DrawPath(path);
}
Ejemplo n.º 29
0
void wxGraphicsContext::DrawRoundedRectangle( wxDouble x, wxDouble y, wxDouble w, wxDouble h, wxDouble radius)
{
    wxGraphicsPath path = CreatePath();
    path.AddRoundedRectangle(x,y,w,h,radius);
    DrawPath(path);
}
Ejemplo n.º 30
0
// Use A* algorithm to calculate shortest path between intersections
vector<unsigned> DirectedPath(unsigned startid, unsigned endid) {
    unordered_map<unsigned, bool> flag; //if node is visited
    unordered_map<unsigned, double> dist; //weight of edge
    unordered_map<unsigned, pair<unsigned, unsigned>> prev; //the previous node&edge of key
    prev[startid] = make_pair(startid, 0);
    LatLon end = getIntersectionPosition(endid);
    priority_queue<pair<unsigned, double>, vector<pair<unsigned, double>>, comparenorm> Q; // the node to be visited
    vector<unsigned> Path;
    Q.push(make_pair(startid, 0));
    unordered_map<unsigned, unsigned>* outedges; //the out going edges of an intersection
    
//    unordered_map<unsigned, unordered_map<unsigned, pair<unsigned, unsigned>>>::iterator memo;
//    bool found_memo = false;
//    unsigned memoid = 0;
    
    /**************************DEBUG USE***************************/
    bool DEBUG = 0; //enable to draw the process of computing the path
    /***************************************************************/
    
    while (!Q.empty()) {
        unsigned currentid = Q.top().first; // accessing the weight of the edge, or distance 
        Q.pop();

        if (currentid == endid) break;
        if (flag[currentid] != 1) {
            flag[currentid] = 1;
            
//            memo = Memoize(currentid, endid); //unfinished implementation of memoization
//            if (memo != Memo.end()) {
//                found_memo = true;
//                memoid = currentid;
//                cout << "i broke out" <<endl;
//                break;  
//            }
            
//            vector<unsigned> testdraw; //for debug use
            
            outedges = &getOutEdges(currentid); //obtain the outgoing edges and the other end point
            for (unordered_map<unsigned, unsigned>::const_iterator iter = outedges->begin(); iter != outedges->end(); iter++) {
                //for all the street segments around the current intersections
                
                //street segment id
                unsigned path_segment = iter->first; 
                //the other end point intersection id
                unsigned nextid = iter->second;
                
                // how long it takes to travel through this segment
                double travel_time = find_segment_travel_time(path_segment) + dist[currentid];
                
                //if the current street segment is on the same street with the next street segment
                if (getStreetSegmentStreetID(path_segment) != getStreetSegmentStreetID(prev[currentid].second))
                    travel_time += 0.25;

//                if (DEBUG) {
//                    testdraw.push_back(path_segment);
//                    DrawPath(testdraw, t_color(64, 153, 255));
//                }
                
                // if the current path to next intersection is found to be faster than the 
                // previous path, update the path and time 
                if ((dist[nextid] == 0) || (travel_time < dist[nextid])) {
                    dist[nextid] = travel_time;
                    prev[nextid] = make_pair(currentid, path_segment);
                }
                
                // get the position of the next intersection id
                LatLon currentposition = getIntersectionPosition(nextid);
                
                // find the distance between the next intersection id and the end point
                double current_distance = find_distance_between_two_points(currentposition, end);
                         
                double weight = ((dist[nextid]) + current_distance * 0.06 / 100);
                
                // put the intersection into the priority queue
                Q.push(make_pair(nextid, weight));

            }
        }
    }
//    if(found_memo){
//        unsigned iter = endid;
//        while (iter != memoid) {
//        pair<unsigned, unsigned> idandpath = ((memo->second).find(iter))->second;
//        Path.insert(Path.begin(), idandpath.second);
//        iter = idandpath.first;
//        }
//        endid = memoid;
//    }
    
    unsigned iter = endid;
    while ((iter != startid) && (dist[endid] != 0)) {
        pair<unsigned, unsigned> idandpath = prev[iter];
        Path.insert(Path.begin(), idandpath.second);
//        if (DEBUG) {
//            bool OneWay = getStreetSegmentOneWay(idandpath.second);
//            StreetSegmentEnds ids = getStreetSegmentEnds(idandpath.second);
//            if (OneWay && (ids.from == iter)) {
//                cout << "ONEWAY PATH: " << idandpath.second << endl;
//                cout << "FROM: "<< ids.from << " TO: " << ids.to << endl;
//                cout << "INSTEAD OF: " << idandpath.first  << " TO: " << iter <<endl;
//                bool connected = are_directly_connected(idandpath.first, iter);
//                cout << "ARE THEY DIRECTLY CONNECTED? " << connected << endl;
//                break;
//            }
//        }
//        Memo[iter] = prev;
//        prev.erase(iter);
        
        iter = idandpath.first;
    }
    if (DEBUG) {
        DrawPath(Path, t_color(255, 0, 0));
        double computed_time = compute_path_travel_time(Path);
        if (computed_time == 0) cout <<"PATH FROM: "<< startid <<" TO "<< endid << " NOT FOUND"<<endl;
    }
    return Path;
}