<commit_before>
#include "../../Flare.h"
#include "FlareObjectiveInfo.h"
#include "../../Player/FlarePlayerController.h"

#define LOCTEXT_NAMESPACE "FlareObjectiveInfo"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareObjectiveInfo::Construct(const FArguments& InArgs)
{
	// Settings
	PC = InArgs._PC;
	CurrentAlpha = 1;
	ObjectiveEnterTime = 0.5;
	CurrentFadeTime = 0;
	LastObjectiveVersion = -1;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	int32 ObjectiveInfoWidth = 400;
	int32 ObjectiveInfoTextWidth = ObjectiveInfoWidth - Theme.SmallContentPadding.Left - Theme.SmallContentPadding.Right;
	FLinearColor ObjectiveColor = Theme.ObjectiveColor;
	ObjectiveColor.A = FFlareStyleSet::GetDefaultTheme().DefaultAlpha;

	// Create the layout
	ChildSlot
	.VAlign(VAlign_Top)
	.HAlign(HAlign_Right)
	[
		SNew(SHorizontalBox)

		// Icon
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SBox)
			.WidthOverride(10)
			[
				SNew(SImage)
				.Image(&Theme.InvertedBrush)
				.ColorAndOpacity(ObjectiveColor)
				.Visibility(this, &SFlareObjectiveInfo::GetVisibility)
			]
		]

		// Text
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SBorder)
			.BorderImage(&Theme.BackgroundBrush)
			.Padding(FMargin(1))
			[
				SNew(SBox)
				.WidthOverride(ObjectiveInfoWidth)
				.Visibility(this, &SFlareObjectiveInfo::GetVisibility)
				.Padding(Theme.SmallContentPadding)
				[
					SNew(SVerticalBox)

					// Header
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetName)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.NameFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]

					// Description
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetDescription)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]

					// Conditions
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SAssignNew(ConditionBox, SVerticalBox)
					]
				]
			]
		]
	];
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

void SFlareObjectiveInfo::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
	SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime);

	float Delta = (PC->HasObjective() ? 1 : -1) * (InDeltaTime / ObjectiveEnterTime);
	CurrentFadeTime = FMath::Clamp(CurrentFadeTime + Delta, 0.0f, 1.0f);
	CurrentAlpha = FMath::InterpEaseOut(0.0f, 1.0f, CurrentFadeTime, 2);

	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (Objective && Objective->Version != LastObjectiveVersion)
	{
		// Update structure
		FLOGV("SFlareObjectiveInfo::Tick : New objective step %d", Objective->Version);
		LastObjectiveVersion = Objective->Version;
		ConditionBox->ClearChildren();
		const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
		int32 ObjectiveInfoWidth = 400;
		int32 ObjectiveInfoTextWidth = ObjectiveInfoWidth - Theme.ContentPadding.Left - Theme.ContentPadding.Right;

		for (int ConditionIndex = 0; ConditionIndex < Objective->Data.ConditionList.Num(); ConditionIndex++)
		{
			// Update structure
			const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
			ConditionBox->AddSlot()
			.AutoHeight()
			[
				SNew(SVerticalBox)

				// Step description
				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(this, &SFlareObjectiveInfo::GetInitialLabel, ConditionIndex)
					.WrapTextAt(ObjectiveInfoTextWidth)
					.TextStyle(&Theme.TextFont)
					.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
					.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
				]

				// Step progress
				+ SVerticalBox::Slot()
				.AutoHeight()
				.VAlign(VAlign_Center)
				[
					SNew(SHorizontalBox)

					// Progress bar
					+ SHorizontalBox::Slot()
					[
						SNew(SBox)
						.WidthOverride(ObjectiveInfoWidth / 2)
						.Visibility(this, &SFlareObjectiveInfo::GetProgressVisibility, ConditionIndex)
						.VAlign(VAlign_Center)
						.Padding(Theme.SmallContentPadding)
						[
							SNew(SProgressBar)
							.Style(&Theme.ProgressBarStyle)
							.Percent(this, &SFlareObjectiveInfo::GetProgress, ConditionIndex)
							.FillColorAndOpacity(this, &SFlareObjectiveInfo::GetColor)
						]
					]

					// Counter
					+ SHorizontalBox::Slot()
					.AutoWidth()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetCounter, ConditionIndex)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
						.Visibility(this, &SFlareObjectiveInfo::GetCounterVisibility, ConditionIndex)
					]

					// Terminal text
					+ SHorizontalBox::Slot()
					.AutoWidth()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetTerminalLabel, ConditionIndex)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]
				]
			];
		}
	}
}

EVisibility SFlareObjectiveInfo::GetVisibility() const
{
	return PC->HasObjective() ? EVisibility::Visible : EVisibility::Collapsed;
}

FText SFlareObjectiveInfo::GetName() const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();

	if (Objective)
	{
		return Objective->Data.Name;
	}
	else
	{
		return LOCTEXT("UnnamedObjective", "Objective");
	}
}

FText SFlareObjectiveInfo::GetDescription() const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective ? Objective->Data.Description : FText());
}

FText SFlareObjectiveInfo::GetInitialLabel(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective && Objective->Data.ConditionList.Num() > ConditionIndex ?
				Objective->Data.ConditionList[ConditionIndex].InitialLabel : FText());
}

FText SFlareObjectiveInfo::GetTerminalLabel(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective && Objective->Data.ConditionList.Num() > ConditionIndex ?
				Objective->Data.ConditionList[ConditionIndex].TerminalLabel : FText());
}

FText SFlareObjectiveInfo::GetCounter(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();

	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return FText();
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];

	if (Condition->MaxCounter == 0)
	{
		return FText();
	}
	else
	{
		return FText::Format(LOCTEXT("ObjectiveCounterFormat", "{0} / {1}"), FText::AsNumber(Condition->Counter), FText::AsNumber(Condition->MaxCounter));
	}
}

EVisibility SFlareObjectiveInfo::GetCounterVisibility(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return EVisibility::Collapsed;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxCounter == 0)
	{
		return EVisibility::Collapsed;
	}
	else
	{
		return EVisibility::Visible;
	}
}

FSlateColor SFlareObjectiveInfo::GetColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.NeutralColor;
	NormalColor.A *= CurrentAlpha;
	return NormalColor;
}

FSlateColor SFlareObjectiveInfo::GetTextColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.NeutralColor;
	NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
	return NormalColor;
}

FLinearColor SFlareObjectiveInfo::GetShadowColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.SmallFont.ShadowColorAndOpacity;
	NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
	return NormalColor;
}

TOptional<float> SFlareObjectiveInfo::GetProgress(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return 0;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxCounter == 0)
	{
		return Condition->Progress / Condition->MaxProgress;
	}
	else
	{
		return Condition->Counter / Condition->MaxCounter;
	}
}

EVisibility SFlareObjectiveInfo::GetProgressVisibility(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return EVisibility::Collapsed;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxProgress == 0 && Condition->MaxCounter == 0)
	{
		return EVisibility::Collapsed;
	}
	else
	{
		return EVisibility::Visible;
	}
}

#undef LOCTEXT_NAMESPACE
<commit_msg>#332 Fix progress bar for counters<commit_after>
#include "../../Flare.h"
#include "FlareObjectiveInfo.h"
#include "../../Player/FlarePlayerController.h"

#define LOCTEXT_NAMESPACE "FlareObjectiveInfo"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareObjectiveInfo::Construct(const FArguments& InArgs)
{
	// Settings
	PC = InArgs._PC;
	CurrentAlpha = 1;
	ObjectiveEnterTime = 0.5;
	CurrentFadeTime = 0;
	LastObjectiveVersion = -1;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	int32 ObjectiveInfoWidth = 400;
	int32 ObjectiveInfoTextWidth = ObjectiveInfoWidth - Theme.SmallContentPadding.Left - Theme.SmallContentPadding.Right;
	FLinearColor ObjectiveColor = Theme.ObjectiveColor;
	ObjectiveColor.A = FFlareStyleSet::GetDefaultTheme().DefaultAlpha;

	// Create the layout
	ChildSlot
	.VAlign(VAlign_Top)
	.HAlign(HAlign_Right)
	[
		SNew(SHorizontalBox)

		// Icon
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SBox)
			.WidthOverride(10)
			[
				SNew(SImage)
				.Image(&Theme.InvertedBrush)
				.ColorAndOpacity(ObjectiveColor)
				.Visibility(this, &SFlareObjectiveInfo::GetVisibility)
			]
		]

		// Text
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SBorder)
			.BorderImage(&Theme.BackgroundBrush)
			.Padding(FMargin(1))
			[
				SNew(SBox)
				.WidthOverride(ObjectiveInfoWidth)
				.Visibility(this, &SFlareObjectiveInfo::GetVisibility)
				.Padding(Theme.SmallContentPadding)
				[
					SNew(SVerticalBox)

					// Header
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetName)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.NameFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]

					// Description
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetDescription)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]

					// Conditions
					+ SVerticalBox::Slot()
					.AutoHeight()
					.Padding(Theme.SmallContentPadding)
					[
						SAssignNew(ConditionBox, SVerticalBox)
					]
				]
			]
		]
	];
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

void SFlareObjectiveInfo::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
	SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime);

	float Delta = (PC->HasObjective() ? 1 : -1) * (InDeltaTime / ObjectiveEnterTime);
	CurrentFadeTime = FMath::Clamp(CurrentFadeTime + Delta, 0.0f, 1.0f);
	CurrentAlpha = FMath::InterpEaseOut(0.0f, 1.0f, CurrentFadeTime, 2);

	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (Objective && Objective->Version != LastObjectiveVersion)
	{
		// Update structure
		FLOGV("SFlareObjectiveInfo::Tick : New objective step %d", Objective->Version);
		LastObjectiveVersion = Objective->Version;
		ConditionBox->ClearChildren();
		const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
		int32 ObjectiveInfoWidth = 400;
		int32 ObjectiveInfoTextWidth = ObjectiveInfoWidth - Theme.ContentPadding.Left - Theme.ContentPadding.Right;

		for (int ConditionIndex = 0; ConditionIndex < Objective->Data.ConditionList.Num(); ConditionIndex++)
		{
			// Update structure
			const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
			ConditionBox->AddSlot()
			.AutoHeight()
			[
				SNew(SVerticalBox)

				// Step description
				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(this, &SFlareObjectiveInfo::GetInitialLabel, ConditionIndex)
					.WrapTextAt(ObjectiveInfoTextWidth)
					.TextStyle(&Theme.TextFont)
					.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
					.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
				]

				// Step progress
				+ SVerticalBox::Slot()
				.AutoHeight()
				.VAlign(VAlign_Center)
				[
					SNew(SHorizontalBox)

					// Progress bar
					+ SHorizontalBox::Slot()
					[
						SNew(SBox)
						.WidthOverride(ObjectiveInfoWidth / 2)
						.Visibility(this, &SFlareObjectiveInfo::GetProgressVisibility, ConditionIndex)
						.VAlign(VAlign_Center)
						.Padding(Theme.SmallContentPadding)
						[
							SNew(SProgressBar)
							.Style(&Theme.ProgressBarStyle)
							.Percent(this, &SFlareObjectiveInfo::GetProgress, ConditionIndex)
							.FillColorAndOpacity(this, &SFlareObjectiveInfo::GetColor)
						]
					]

					// Counter
					+ SHorizontalBox::Slot()
					.AutoWidth()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetCounter, ConditionIndex)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
						.Visibility(this, &SFlareObjectiveInfo::GetCounterVisibility, ConditionIndex)
					]

					// Terminal text
					+ SHorizontalBox::Slot()
					.AutoWidth()
					.Padding(Theme.SmallContentPadding)
					[
						SNew(STextBlock)
						.Text(this, &SFlareObjectiveInfo::GetTerminalLabel, ConditionIndex)
						.WrapTextAt(ObjectiveInfoTextWidth)
						.TextStyle(&Theme.TextFont)
						.ColorAndOpacity(this, &SFlareObjectiveInfo::GetTextColor)
						.ShadowColorAndOpacity(this, &SFlareObjectiveInfo::GetShadowColor)
					]
				]
			];
		}
	}
}

EVisibility SFlareObjectiveInfo::GetVisibility() const
{
	return PC->HasObjective() ? EVisibility::Visible : EVisibility::Collapsed;
}

FText SFlareObjectiveInfo::GetName() const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();

	if (Objective)
	{
		return Objective->Data.Name;
	}
	else
	{
		return LOCTEXT("UnnamedObjective", "Objective");
	}
}

FText SFlareObjectiveInfo::GetDescription() const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective ? Objective->Data.Description : FText());
}

FText SFlareObjectiveInfo::GetInitialLabel(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective && Objective->Data.ConditionList.Num() > ConditionIndex ?
				Objective->Data.ConditionList[ConditionIndex].InitialLabel : FText());
}

FText SFlareObjectiveInfo::GetTerminalLabel(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	return (Objective && Objective->Data.ConditionList.Num() > ConditionIndex ?
				Objective->Data.ConditionList[ConditionIndex].TerminalLabel : FText());
}

FText SFlareObjectiveInfo::GetCounter(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();

	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return FText();
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];

	if (Condition->MaxCounter == 0)
	{
		return FText();
	}
	else
	{
		return FText::Format(LOCTEXT("ObjectiveCounterFormat", "{0} / {1}"), FText::AsNumber(Condition->Counter), FText::AsNumber(Condition->MaxCounter));
	}
}

EVisibility SFlareObjectiveInfo::GetCounterVisibility(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return EVisibility::Collapsed;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxCounter == 0)
	{
		return EVisibility::Collapsed;
	}
	else
	{
		return EVisibility::Visible;
	}
}

FSlateColor SFlareObjectiveInfo::GetColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.NeutralColor;
	NormalColor.A *= CurrentAlpha;
	return NormalColor;
}

FSlateColor SFlareObjectiveInfo::GetTextColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.NeutralColor;
	NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
	return NormalColor;
}

FLinearColor SFlareObjectiveInfo::GetShadowColor() const
{
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	FLinearColor NormalColor = Theme.SmallFont.ShadowColorAndOpacity;
	NormalColor.A *= Theme.DefaultAlpha * CurrentAlpha;
	return NormalColor;
}

TOptional<float> SFlareObjectiveInfo::GetProgress(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return 0;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxCounter == 0)
	{
		return Condition->Progress / Condition->MaxProgress;
	}
	else
	{
		return (float) Condition->Counter / (float) Condition->MaxCounter;
	}
}

EVisibility SFlareObjectiveInfo::GetProgressVisibility(int32 ConditionIndex) const
{
	const FFlarePlayerObjective* Objective = PC->GetCurrentObjective();
	if (!Objective || Objective->Data.ConditionList.Num() <= ConditionIndex)
	{
		return EVisibility::Collapsed;
	}

	const FFlarePlayerObjectiveCondition* Condition = &Objective->Data.ConditionList[ConditionIndex];
	if (Condition->MaxProgress == 0 && Condition->MaxCounter == 0)
	{
		return EVisibility::Collapsed;
	}
	else
	{
		return EVisibility::Visible;
	}
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
// Copyright (c) 2017 Eugene Kozlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Toolbox/Scene/DebugCameraController.h>
#include "EditorSceneSettings.h"
#include "SceneTab.h"
#include "EditorEvents.h"

namespace Urho3D
{

static ResourceRef defaultRenderPath{XMLFile::GetTypeStatic(), "RenderPaths/Forward.xml"};

EditorSceneSettings::EditorSceneSettings(Context* context)
    : Component(context)
    , editorViewportRenderPath_(defaultRenderPath)
{
}

void EditorSceneSettings::RegisterObject(Context* context)
{
    context->RegisterFactory<EditorSceneSettings>();
    URHO3D_ATTRIBUTE("Viewport RenderPath", ResourceRef, editorViewportRenderPath_, defaultRenderPath, AM_DEFAULT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Position", GetCameraPosition, SetCameraPosition, Vector3, Vector3::ZERO, AM_EDIT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Orthographic Size", GetCameraOrthoSize, SetCameraOrthoSize, float, 0, AM_EDIT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Zoom", GetCameraZoom, SetCameraZoom, float, 0, AM_EDIT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera View 2D", GetCamera2D, SetCamera2D, bool, false, AM_FILE | AM_NOEDIT);
}

void EditorSceneSettings::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
{
    Serializable::OnSetAttribute(attr, src);
    using namespace SceneSettingModified;
    SendEvent(E_SCENESETTINGMODIFIED, P_SCENE, GetScene(), P_NAME, attr.name_, P_VALUE, src);
}

Vector3 EditorSceneSettings::GetCameraPosition() const
{
    if (Node* node = GetCameraNode())
        return node->GetPosition();
    return Vector3::ZERO;
}

void EditorSceneSettings::SetCameraPosition(const Vector3& position)
{
    if (Node* node = GetCameraNode())
    {
        node->SetPosition(position);
        node->LookAt({position.x_, position.y_, 0});
    }
}

float EditorSceneSettings::GetCameraOrthoSize() const
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            return camera->GetOrthoSize();
    }
    return 0;
}

void EditorSceneSettings::SetCameraOrthoSize(float size)
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            camera->SetOrthoSize(size);
    }
}

float EditorSceneSettings::GetCameraZoom() const
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            return camera->GetZoom();
    }
    return 0;
}

void EditorSceneSettings::SetCameraZoom(float zoom)
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            camera->SetZoom(zoom);
    }
}

void EditorSceneSettings::OnSceneSet(Scene* scene)
{
    if (scene == nullptr)
        return;

    Node* parent = scene->GetChild("EditorObjects");
    if (parent == nullptr)
    {
        parent = scene->CreateChild("EditorObjects", LOCAL);
        parent->AddTag("__EDITOR_OBJECT__");
    }

    Node* camera = parent->GetChild("EditorCamera");
    if (camera == nullptr)
    {
        camera = parent->CreateChild("__EditorCamera__", LOCAL);
        camera->AddTag("__EDITOR_OBJECT__");
    }

    Camera* cameraComponent = camera->GetOrCreateComponent<Camera>();
    cameraComponent->SetFarClip(160000);

    auto* debug = scene->GetOrCreateComponent<DebugRenderer>(LOCAL);
    debug->SetView(cameraComponent);
    debug->SetTemporary(true);
    debug->SetLineAntiAlias(true);

    SetCamera2D(is2D_);
}

Node* EditorSceneSettings::GetCameraNode()
{
    return GetScene()->GetChild("__EditorCamera__", true);
}

Node* EditorSceneSettings::GetCameraNode() const
{
    return GetScene()->GetChild("__EditorCamera__", true);
}

bool EditorSceneSettings::GetCamera2D() const
{
    return is2D_;
}

void EditorSceneSettings::SetCamera2D(bool is2D)
{
    // Editor objects may not exist during deserialization. CreateEditorObjects() will call this
    // method again.
    if (Node* camera = GetCameraNode())
    {
        if (is2D)
        {
            camera->RemoveComponent<DebugCameraController>();
            camera->GetOrCreateComponent<DebugCameraController2D>();
            Vector3 pos = camera->GetWorldPosition();
            pos.z_ = Abs(pos.z_);
            camera->SetWorldPosition(pos);
            camera->LookAt(pos + Vector3::FORWARD);
            camera->GetComponent<Camera>()->SetOrthographic(true);
        }
        else
        {
            camera->RemoveComponent<DebugCameraController2D>();
            camera->GetOrCreateComponent<DebugCameraController>();
            camera->GetComponent<Camera>()->SetOrthographic(false);
        }
    }

    is2D_ = is2D;
}

}
<commit_msg>Editor: Fix editor camera settings not persisting across reloads.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
// Copyright (c) 2017 Eugene Kozlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Toolbox/Scene/DebugCameraController.h>
#include "EditorSceneSettings.h"
#include "SceneTab.h"
#include "EditorEvents.h"

namespace Urho3D
{

static ResourceRef defaultRenderPath{XMLFile::GetTypeStatic(), "RenderPaths/Forward.xml"};

EditorSceneSettings::EditorSceneSettings(Context* context)
    : Component(context)
    , editorViewportRenderPath_(defaultRenderPath)
{
}

void EditorSceneSettings::RegisterObject(Context* context)
{
    context->RegisterFactory<EditorSceneSettings>();
    URHO3D_ATTRIBUTE("Viewport RenderPath", ResourceRef, editorViewportRenderPath_, defaultRenderPath, AM_DEFAULT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Position", GetCameraPosition, SetCameraPosition, Vector3, Vector3::ZERO, AM_DEFAULT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Orthographic Size", GetCameraOrthoSize, SetCameraOrthoSize, float, 0, AM_DEFAULT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera Zoom", GetCameraZoom, SetCameraZoom, float, 0, AM_DEFAULT);
    URHO3D_ACCESSOR_ATTRIBUTE("Camera View 2D", GetCamera2D, SetCamera2D, bool, false, AM_FILE | AM_NOEDIT);
}

void EditorSceneSettings::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
{
    Serializable::OnSetAttribute(attr, src);
    using namespace SceneSettingModified;
    SendEvent(E_SCENESETTINGMODIFIED, P_SCENE, GetScene(), P_NAME, attr.name_, P_VALUE, src);
}

Vector3 EditorSceneSettings::GetCameraPosition() const
{
    if (Node* node = GetCameraNode())
        return node->GetPosition();
    return Vector3::ZERO;
}

void EditorSceneSettings::SetCameraPosition(const Vector3& position)
{
    if (Node* node = GetCameraNode())
    {
        node->SetPosition(position);
        node->LookAt({position.x_, position.y_, 0});
    }
}

float EditorSceneSettings::GetCameraOrthoSize() const
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            return camera->GetOrthoSize();
    }
    return 0;
}

void EditorSceneSettings::SetCameraOrthoSize(float size)
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            camera->SetOrthoSize(size);
    }
}

float EditorSceneSettings::GetCameraZoom() const
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            return camera->GetZoom();
    }
    return 0;
}

void EditorSceneSettings::SetCameraZoom(float zoom)
{
    if (Node* node = GetCameraNode())
    {
        if (Camera* camera = node->GetComponent<Camera>())
            camera->SetZoom(zoom);
    }
}

void EditorSceneSettings::OnSceneSet(Scene* scene)
{
    if (scene == nullptr)
        return;

    Node* parent = scene->GetChild("EditorObjects");
    if (parent == nullptr)
    {
        parent = scene->CreateChild("EditorObjects", LOCAL);
        parent->AddTag("__EDITOR_OBJECT__");
    }

    Node* camera = parent->GetChild("EditorCamera");
    if (camera == nullptr)
    {
        camera = parent->CreateChild("__EditorCamera__", LOCAL);
        camera->AddTag("__EDITOR_OBJECT__");
    }

    Camera* cameraComponent = camera->GetOrCreateComponent<Camera>();
    cameraComponent->SetFarClip(160000);

    auto* debug = scene->GetOrCreateComponent<DebugRenderer>(LOCAL);
    debug->SetView(cameraComponent);
    debug->SetTemporary(true);
    debug->SetLineAntiAlias(true);

    SetCamera2D(is2D_);
}

Node* EditorSceneSettings::GetCameraNode()
{
    return GetScene()->GetChild("__EditorCamera__", true);
}

Node* EditorSceneSettings::GetCameraNode() const
{
    return GetScene()->GetChild("__EditorCamera__", true);
}

bool EditorSceneSettings::GetCamera2D() const
{
    return is2D_;
}

void EditorSceneSettings::SetCamera2D(bool is2D)
{
    // Editor objects may not exist during deserialization. CreateEditorObjects() will call this
    // method again.
    if (Node* camera = GetCameraNode())
    {
        if (is2D)
        {
            camera->RemoveComponent<DebugCameraController>();
            camera->GetOrCreateComponent<DebugCameraController2D>();
            Vector3 pos = camera->GetWorldPosition();
            pos.z_ = Abs(pos.z_);
            camera->SetWorldPosition(pos);
            camera->LookAt(pos + Vector3::FORWARD);
            camera->GetComponent<Camera>()->SetOrthographic(true);
        }
        else
        {
            camera->RemoveComponent<DebugCameraController2D>();
            camera->GetOrCreateComponent<DebugCameraController>();
            camera->GetComponent<Camera>()->SetOrthographic(false);
        }
    }

    is2D_ = is2D;
}

}
<|endoftext|>


<commit_before>#include <simcode/net/TcpConnection.h>
#include <simcode/base/logger.h>
using namespace simcode;
using namespace net;

TcpConnection::TcpConnection(EventLoop* loop, int connfd, const SockAddr& peerAddr):
    loop_(loop),
    socket_(connfd),
    peerAddr_(peerAddr),
    localAddr_(SockAddr(socket_.getLocalAddr())),
    errcode_(0),
    events_(EPOLLIN|EPOLLPRI),
    revents_(0)
{
    socket_.setKeepAlive(true);
}

void TcpConnection::run()
{
    loop_->runInLoop(socket_.sockfd(), simex::bind(&TcpConnection::eventHandle, this, _1), events_);
}

void TcpConnection::eventHandle(int events)
{
    revents_ = events;
    if (isReading())
    {
        handleRead();
    }
    if (isWriting())
    {
        handleWrite();
    }
}

void TcpConnection::handleRead()
{
    // saved an ioctl()/FIONREAD call to tell how much to read
    int fd = socket_.sockfd();
    const size_t writable = 65536;
    char tmpbuf[65536];
    char extrabuf[65536];
    struct iovec vec[2];
    vec[0].iov_base = tmpbuf;
    vec[0].iov_len = sizeof tmpbuf;
    vec[1].iov_base = extrabuf;
    vec[1].iov_len = sizeof extrabuf;
    // when there is enough space in this buffer, don't read into extrabuf.
    // when extrabuf is used, we read 128k-1 bytes at most.
    const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1;
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0)
    {
        errcode_ = errno;
        LOG_ERROR("read error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
        onClose();
        return;
    }
    else if (n == 0)
    {
        onClose();
        return;
    }
    else if (static_cast<size_t>(n) <= writable)
    {
        readBuf_.append(tmpbuf, n);
    }
    else
    {
        readBuf_.append(tmpbuf, sizeof tmpbuf);
        readBuf_.append(extrabuf, sizeof extrabuf);
    }
    messageCallback_(shared_from_this(), &readBuf_);
}

void TcpConnection::handleWrite()
{
    std::string tmpBuf;
    {
        ScopeLock lock(mutex_);
        tmpBuf.swap(writeBuf_);
    }
    if (!tmpBuf.empty())
    {
        int fd = socket_.sockfd();
        ssize_t n;
        n = ::write(fd, tmpBuf.data(), tmpBuf.size());
        if (n > 0)
        {
            if (n < tmpBuf.size())
            {
                tmpBuf = tmpBuf.substr(n);
                {
                ScopeLock lock(mutex_);
                tmpBuf.append(writeBuf_);
                writeBuf_.swap(tmpBuf);
                }
            }
            else
            {
                {
                ScopeLock lock(mutex_);
                if (writeBuf_.empty())
                {
                    disableWriting();
                    //write complete
                }
                }
            }
        }
        else
        {
            int e = errno;
	    errcode_ = e;
            LOG_ERROR("write error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
            disableWriting();
	    if (e == EINTR){}
	    else if (e == EAGAIN){}
	    else {onClose();}
        }
    }
}

void TcpConnection::send(const char* data, size_t len)
{
    {
    ScopeLock lock(mutex_);
    writeBuf_.append(data, len);
    enableWriting();
    }
    //handleWrite();
}

void TcpConnection::update()
{
    loop_->modifyEvent(socket_.sockfd(), events_);
}

void TcpConnection::onClose()
{
    loop_->removeInLoop(socket_.sockfd());
    if (closeCallback_) closeCallback_();
}
<commit_msg>mod TcpConnection::handleWrite<commit_after>#include <simcode/net/TcpConnection.h>
#include <simcode/base/logger.h>
using namespace simcode;
using namespace net;

TcpConnection::TcpConnection(EventLoop* loop, int connfd, const SockAddr& peerAddr):
    loop_(loop),
    socket_(connfd),
    peerAddr_(peerAddr),
    localAddr_(SockAddr(socket_.getLocalAddr())),
    errcode_(0),
    events_(EPOLLIN|EPOLLPRI),
    revents_(0)
{
    socket_.setKeepAlive(true);
}

void TcpConnection::run()
{
    loop_->runInLoop(socket_.sockfd(), simex::bind(&TcpConnection::eventHandle, this, _1), events_);
}

void TcpConnection::eventHandle(int events)
{
    revents_ = events;
    if (isReading())
    {
        handleRead();
    }
    if (isWriting())
    {
        handleWrite();
    }
}

void TcpConnection::handleRead()
{
    // saved an ioctl()/FIONREAD call to tell how much to read
    int fd = socket_.sockfd();
    const size_t writable = 65536;
    char tmpbuf[65536];
    char extrabuf[65536];
    struct iovec vec[2];
    vec[0].iov_base = tmpbuf;
    vec[0].iov_len = sizeof tmpbuf;
    vec[1].iov_base = extrabuf;
    vec[1].iov_len = sizeof extrabuf;
    // when there is enough space in this buffer, don't read into extrabuf.
    // when extrabuf is used, we read 128k-1 bytes at most.
    const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1;
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0)
    {
        errcode_ = errno;
        LOG_ERROR("read error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
        onClose();
        return;
    }
    else if (n == 0)
    {
        onClose();
        return;
    }
    else if (static_cast<size_t>(n) <= writable)
    {
        readBuf_.append(tmpbuf, n);
    }
    else
    {
        readBuf_.append(tmpbuf, sizeof tmpbuf);
        readBuf_.append(extrabuf, sizeof extrabuf);
    }
    messageCallback_(shared_from_this(), &readBuf_);
}

void TcpConnection::handleWrite()
{
    std::string tmpBuf;
    {
        ScopeLock lock(mutex_);
        tmpBuf.swap(writeBuf_);
    }
    if (!tmpBuf.empty())
    {
        int fd = socket_.sockfd();
        ssize_t n;
        n = ::write(fd, tmpBuf.data(), tmpBuf.size());
        if (n > 0)
        {
            if (n < tmpBuf.size())
            {
                tmpBuf = tmpBuf.substr(n);
                {
                ScopeLock lock(mutex_);
                tmpBuf.append(writeBuf_);
                writeBuf_.swap(tmpBuf);
                }
            }
            else
            {
                {
                ScopeLock lock(mutex_);
                if (writeBuf_.empty())
                {
                    disableWriting();
                    //write complete
                }
                }
            }
        }
        else
        {
            int e = errno;
	    errcode_ = e;
            LOG_ERROR("write error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
            //disableWriting();
	    if (e == EINTR || e == EAGAIN)
	    {
		{
		ScopeLock lock(mutex_);
                tmpBuf.append(writeBuf_);
                writeBuf_.swap(tmpBuf);
		}
	    }
	    else
	    {
		onClose();
	    }
        }
    }
}

void TcpConnection::send(const char* data, size_t len)
{
    {
    ScopeLock lock(mutex_);
    writeBuf_.append(data, len);
    enableWriting();
    }
    //handleWrite();
}

void TcpConnection::update()
{
    loop_->modifyEvent(socket_.sockfd(), events_);
}

void TcpConnection::onClose()
{
    loop_->removeInLoop(socket_.sockfd());
    if (closeCallback_) closeCallback_();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkBallonForce3DFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <iostream>
#include <time.h>

#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkBalloonForce3DFilter.h"
#include "itkMesh.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkSphereSource.h"

int itkBallonForce3DFilterTest(int, char**)
{

  // Define the dimension of the images
  const unsigned int myDimension = 3;

  // Declare the types of the images
  typedef itk::Image<double, myDimension>       myImageType;

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                     MeshType;

  // Declare the type of the gradient image
  typedef itk::CovariantVector<double, myDimension> myGradientType;
  typedef itk::Image<myGradientType, myDimension>   myGradientImageType;
  typedef itk::BalloonForce3DFilter<MeshType, MeshType>  BallonForceFilterType;
  typedef itk::SphereSource< MeshType >                  MeshSourceType;
  typedef itk::ImageRegionIteratorWithIndex<myImageType>  myIteratorType;

  typedef itk::GradientRecursiveGaussianImageFilter< myImageType,
                                                     myGradientImageType >  myFilterType;

  MeshSourceType::Pointer meshSource = MeshSourceType::New();
  meshSource->SetResolutionX( 20 );
  meshSource->SetResolutionY( 20 );

  // Create the image
  myImageType::Pointer inputImage  = myImageType::New();

  myImageType::SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] = 100;

  myImageType::IndexType start;
  start.Fill(0);

  myImageType::RegionType region;
  region.SetIndex( start );
  region.SetSize( size );

  // Initialize Image A
  inputImage->SetRegions( region );
  inputImage->Allocate();

  myIteratorType it( inputImage, region );
  it.GoToBegin();
  while( !it.IsAtEnd() )
    {
    it.Set( 0.0 );
    ++it;
    }

  size[0] = 50;
  size[1] = 50;
  size[2] = 50;

  start[0] = 25;
  start[1] = 25;
  start[2] = 25;

  region.SetIndex( start );
  region.SetSize( size );

  // Set a different value inside
  myIteratorType itn( inputImage, region );
  itn.GoToBegin();
  while( !it.IsAtEnd() )
    {
    itn.Set( 200.0 );
    ++itn;
    }

  // Create a  Filter
  myFilterType::Pointer  gradientFilter = myFilterType::New();

  // Connect the input images
  gradientFilter->SetInput( inputImage );
  gradientFilter->SetSigma( 2.0 );

  try
    {
    gradientFilter->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating GradientFilter"  << std::endl;
    std::cerr << exp << std::endl;
    }

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating SphereSource"  << std::endl;
    std::cerr << exp << std::endl;
    }

  BallonForceFilterType::Pointer ballonFilter = BallonForceFilterType::New();
  ballonFilter->SetInput( meshSource->GetOutput() );
  ballonFilter->SetGradient(  gradientFilter->GetOutput() );

  ballonFilter->SetStiffnessV( 0.00001 );
  ballonFilter->SetStiffnessH( 0.00001 );
  ballonFilter->SetTimeStep( 0.2 );
  ballonFilter->SetStepThreshold1( 1 );
  ballonFilter->SetStepThreshold2( 2 );

  try
    {
    ballonFilter->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating BallonForce3DFilter"  << std::endl;
    std::cerr << exp << std::endl;
    }
  catch( std::exception & stdexp )
    {
    std::cerr << "STL Exception thrown while updating BallonForce3DFilter"  << std::endl;
    std::cerr << stdexp.what() << std::endl;
    }
  catch( ... )
    {
    std::cerr << "Unknown Exception thrown while updating BallonForce3DFilter"  << std::endl;
    }

// All objects should be automatically destroyed at this point
  return EXIT_SUCCESS;

}

<commit_msg>ERR: return error if exception.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkBallonForce3DFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <iostream>
#include <time.h>

#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkBalloonForce3DFilter.h"
#include "itkMesh.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkSphereSource.h"

int itkBallonForce3DFilterTest(int, char**)
{

  // Define the dimension of the images
  const unsigned int myDimension = 3;

  // Declare the types of the images
  typedef itk::Image<double, myDimension>       myImageType;

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                     MeshType;

  // Declare the type of the gradient image
  typedef itk::CovariantVector<double, myDimension> myGradientType;
  typedef itk::Image<myGradientType, myDimension>   myGradientImageType;
  typedef itk::BalloonForce3DFilter<MeshType, MeshType>  BallonForceFilterType;
  typedef itk::SphereSource< MeshType >                  MeshSourceType;
  typedef itk::ImageRegionIteratorWithIndex<myImageType>  myIteratorType;

  typedef itk::GradientRecursiveGaussianImageFilter< myImageType,
                                                     myGradientImageType >  myFilterType;

  MeshSourceType::Pointer meshSource = MeshSourceType::New();
  meshSource->SetResolutionX( 20 );
  meshSource->SetResolutionY( 20 );

  // Create the image
  myImageType::Pointer inputImage  = myImageType::New();

  myImageType::SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] = 100;

  myImageType::IndexType start;
  start.Fill(0);

  myImageType::RegionType region;
  region.SetIndex( start );
  region.SetSize( size );

  // Initialize Image A
  inputImage->SetRegions( region );
  inputImage->Allocate();

  myIteratorType it( inputImage, region );
  it.GoToBegin();
  while( !it.IsAtEnd() )
    {
    it.Set( 0.0 );
    ++it;
    }

  size[0] = 50;
  size[1] = 50;
  size[2] = 50;

  start[0] = 25;
  start[1] = 25;
  start[2] = 25;

  region.SetIndex( start );
  region.SetSize( size );

  // Set a different value inside
  myIteratorType itn( inputImage, region );
  itn.GoToBegin();
  while( !it.IsAtEnd() )
    {
    itn.Set( 200.0 );
    ++itn;
    }

  // Create a  Filter
  myFilterType::Pointer  gradientFilter = myFilterType::New();

  // Connect the input images
  gradientFilter->SetInput( inputImage );
  gradientFilter->SetSigma( 2.0 );

  try
    {
    gradientFilter->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating GradientFilter"  << std::endl;
    std::cerr << exp << std::endl;
    }

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating SphereSource"  << std::endl;
    std::cerr << exp << std::endl;
    }

  BallonForceFilterType::Pointer ballonFilter = BallonForceFilterType::New();
  ballonFilter->SetInput( meshSource->GetOutput() );
  ballonFilter->SetGradient(  gradientFilter->GetOutput() );

  ballonFilter->SetStiffnessV( 0.00001 );
  ballonFilter->SetStiffnessH( 0.00001 );
  ballonFilter->SetTimeStep( 0.2 );
  ballonFilter->SetStepThreshold1( 1 );
  ballonFilter->SetStepThreshold2( 2 );

  try
    {
    ballonFilter->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "ITK Exception thrown while updating BallonForce3DFilter"  << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }
  catch( std::exception & stdexp )
    {
    std::cerr << "STL Exception thrown while updating BallonForce3DFilter"  << std::endl;
    std::cerr << stdexp.what() << std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cerr << "Unknown Exception thrown while updating BallonForce3DFilter"  << std::endl;
    return EXIT_FAILURE;
    }

// All objects should be automatically destroyed at this point
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*
 * Interleaving String
 * Total Accepted: 9515 Total Submissions: 50873
 *
 * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
 *
 * For example,
 * Given:
 * s1 = "aabcc",
 * s2 = "dbbca",
 *
 * When s3 = "aadbbcbcac", return true.
 * When s3 = "aadbbbaccc", return false.
 */
class Solution
{
public:
    bool isInterleave(string s1, string s2, string s3)
    {
        if (s1.empty() || s2.empty())
            return true;

        size_t c1 = 0;
        size_t c2 = 0;
        size_t c3 = 0;
        stack<int> vec;
        while (c1 <= s1.size() && c2 <= s2.size() && c3 <= s3.size())
        {
            if (c1 == s1.size())
            {
                for (int i = 0; i + c3 < s3.size(); i++)
                {
                    if (s2[c2 + i] != s3[c3 + i])
                        return false;
                }
                return true;
            }

            if (c2 == s2.size())
            {
                for (int i = 0; i + c3 < s3.size(); i++)
                {
                    if (s1[c1 + i] != s3[c3 + i])
                        return false;
                }
                return true;
            }

            if (s1[c1] != s3[c3] && s2[c2] != s3[c3])
            {
                if (vec.empty())
                {
                    return false;
                }
                else
                {
                    c2 = vec.top() + 1;
                    vec.pop();
                    c1 = vec.top();
                    vec.pop();
                    c3 = c1 + c2;
                }
            }
            else
            {
                if (s1[c1] == s3[c3] && s2[c2] == s3[c3])
                {
                    vec.push(c1);
                    vec.push(c2);
                    c1++;
                    c3++;
                }
                else
                {
                    if (s1[c1] == s3[c3])
                    {
                        c1++;
                        c3++;
                    }
                    else if (s2[c2] == s3[c3])
                    {
                        c2++;
                        c3++;
                    }
                }
            }
        }

        return true;
    }
};
<commit_msg>Delete UNACCEPTED_Time_Limit_Exceeded_Interleaving_String.cpp<commit_after><|endoftext|>


<commit_before>#include "hornet/java.hh"

#include "hornet/vm.hh"

#include <cassert>
#include <stack>

#include <classfile_constants.h>
#include <jni.h>

namespace hornet {

value_t object_to_value(object* obj)
{
    return reinterpret_cast<value_t>(obj);
}

jint value_to_jint(value_t value)
{
    return static_cast<jint>(value);
}

jlong value_to_jlong(value_t value)
{
   return static_cast<jlong>(value);
}

array* value_to_array(value_t value)
{
   return reinterpret_cast<array*>(value);
}

value_t jint_to_value(jint n)
{
    return static_cast<value_t>(n);
}

value_t jlong_to_value(jlong n)
{
    return static_cast<value_t>(n);
}

#define CONST_INTERP(type, value)                               \
    do {                                                        \
        frame.ostack.push(type##_to_value(value));              \
    } while (0)

#define LOAD_INTERP(type, idx)                                  \
    do {                                                        \
        frame.ostack.push(frame.locals[idx]);                   \
    } while (0)

#define STORE_INTERP(type, idx)                                 \
    do {                                                        \
        frame.locals[idx] = frame.ostack.top();                 \
        frame.ostack.pop();                                     \
    } while (0)

#define BINOP_INTERP(type, op)                                  \
    do {                                                        \
        auto value2 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        auto value1 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        type result = value1 op value2;                         \
        frame.ostack.push(type##_to_value(result));             \
   } while (0)

#define SHL_INTERP(type, mask)                                  \
    do {                                                        \
        auto value2 = value_to_jint(frame.ostack.top());        \
        frame.ostack.pop();                                     \
        auto value1 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        type result = value1 << (value2 & mask);                \
        frame.ostack.push(type##_to_value(result));             \
    } while (0)

void interp(method* method, frame& frame)
{
next_insn:
    assert(frame.pc < method->code_length);

    uint8_t opc = method->code[frame.pc];

    switch (opc) {
    case JVM_OPC_nop:
        break;
    case JVM_OPC_iconst_m1:
    case JVM_OPC_iconst_0:
    case JVM_OPC_iconst_1:
    case JVM_OPC_iconst_2:
    case JVM_OPC_iconst_3:
    case JVM_OPC_iconst_4:
    case JVM_OPC_iconst_5: {
        jint value = opc - JVM_OPC_iconst_0;
        CONST_INTERP(jint, value);
        break;
    }
    case JVM_OPC_lconst_0:
    case JVM_OPC_lconst_1: {
        jlong value = opc - JVM_OPC_lconst_0;
        CONST_INTERP(jlong, value);
        break;
    }
    case JVM_OPC_iload_0:
    case JVM_OPC_iload_1:
    case JVM_OPC_iload_2:
    case JVM_OPC_iload_3: {
        uint16_t idx = opc - JVM_OPC_iload_0;
        LOAD_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lload_0:
    case JVM_OPC_lload_1:
    case JVM_OPC_lload_2:
    case JVM_OPC_lload_3: {
        uint16_t idx = opc - JVM_OPC_lload_0;
        LOAD_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_aload_0:
    case JVM_OPC_aload_1:
    case JVM_OPC_aload_2:
    case JVM_OPC_aload_3: {
        uint16_t idx = opc - JVM_OPC_aload_0;
        LOAD_INTERP(jobject, idx);
        break;
    }
    case JVM_OPC_istore: {
        auto idx = read_opc_u1(method->code + frame.pc);
        STORE_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lstore: {
        auto idx = read_opc_u1(method->code + frame.pc);
        STORE_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_istore_0:
    case JVM_OPC_istore_1:
    case JVM_OPC_istore_2:
    case JVM_OPC_istore_3: {
        uint16_t idx = opc - JVM_OPC_istore_0;
        STORE_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lstore_0:
    case JVM_OPC_lstore_1:
    case JVM_OPC_lstore_2:
    case JVM_OPC_lstore_3: {
        uint16_t idx = opc - JVM_OPC_lstore_0;
        STORE_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_pop: {
        frame.ostack.pop();
        break;
    }
    case JVM_OPC_dup: {
        auto value = frame.ostack.top();
        frame.ostack.push(value);
        break;
    }
    case JVM_OPC_iadd: {
        BINOP_INTERP(jint, +);
        break;
    }
    case JVM_OPC_ladd: {
        BINOP_INTERP(jlong, +);
        break;
    }
    case JVM_OPC_isub: {
        BINOP_INTERP(jint, -);
        break;
    }
    case JVM_OPC_lsub: {
        BINOP_INTERP(jlong, -);
        break;
    }
    case JVM_OPC_imul: {
        BINOP_INTERP(jint, *);
        break;
    }
    case JVM_OPC_lmul: {
        BINOP_INTERP(jlong, *);
        break;
    }
    case JVM_OPC_idiv: {
        BINOP_INTERP(jint, /);
        break;
    }
    case JVM_OPC_ldiv: {
        BINOP_INTERP(jlong, /);
        break;
    }
    case JVM_OPC_irem: {
        BINOP_INTERP(jint, %);
        break;
    }
    case JVM_OPC_lrem: {
        BINOP_INTERP(jlong, %);
        break;
    }
    case JVM_OPC_ishl: {
        SHL_INTERP(jint, 0x1f);
        break;
    }
    case JVM_OPC_lshl: {
        SHL_INTERP(jlong, 0x3f);
        break;
    }
    case JVM_OPC_iand: {
        BINOP_INTERP(jint, &);
        break;
    }
    case JVM_OPC_land: {
        BINOP_INTERP(jlong, &);
        break;
    }
    case JVM_OPC_ior: {
        BINOP_INTERP(jint, |);
        break;
    }
    case JVM_OPC_lor: {
        BINOP_INTERP(jlong, |);
        break;
    }
    case JVM_OPC_ixor: {
        BINOP_INTERP(jint, ^);
        break;
    }
    case JVM_OPC_lxor: {
        BINOP_INTERP(jlong, ^);
        break;
    }
    case JVM_OPC_if_icmpeq: {
        int16_t offset = read_opc_u2(method->code + frame.pc);
        auto value2 = value_to_jint(frame.ostack.top());
        frame.ostack.pop();
        auto value1 = value_to_jint(frame.ostack.top());
        frame.ostack.pop();
        if (value1 == value2) {
            frame.pc += offset;
            goto next_insn;
        }
        break;
    }
    case JVM_OPC_goto: {
        int16_t offset = read_opc_u2(method->code + frame.pc);
        frame.pc += offset;
        goto next_insn;
    }
    case JVM_OPC_return: {
        frame.ostack.empty();
        return;
    }
    case JVM_OPC_invokespecial: {
        break;
    }
    case JVM_OPC_new: {
        auto obj = gc_new_object(nullptr);
        frame.ostack.push(object_to_value(obj));
        break;
    }
    case JVM_OPC_arraylength: {
        auto* arrayref = value_to_array(frame.ostack.top());
        frame.ostack.pop();
        assert(arrayref != nullptr);
        frame.ostack.push(arrayref->length);
        break;
    }
    default:
        fprintf(stderr, "error: unsupported bytecode: %u\n", opc);
        abort();
    }

    frame.pc += opcode_length[opc];

    goto next_insn;
}

}
<commit_msg>interp: aconst_null<commit_after>#include "hornet/java.hh"

#include "hornet/vm.hh"

#include <cassert>
#include <stack>

#include <classfile_constants.h>
#include <jni.h>

namespace hornet {

value_t object_to_value(object* obj)
{
    return reinterpret_cast<value_t>(obj);
}

jint value_to_jint(value_t value)
{
    return static_cast<jint>(value);
}

jlong value_to_jlong(value_t value)
{
   return static_cast<jlong>(value);
}

array* value_to_array(value_t value)
{
   return reinterpret_cast<array*>(value);
}

value_t jint_to_value(jint n)
{
    return static_cast<value_t>(n);
}

value_t jlong_to_value(jlong n)
{
    return static_cast<value_t>(n);
}

#define CONST_INTERP(type, value)                               \
    do {                                                        \
        frame.ostack.push(type##_to_value(value));              \
    } while (0)

#define LOAD_INTERP(type, idx)                                  \
    do {                                                        \
        frame.ostack.push(frame.locals[idx]);                   \
    } while (0)

#define STORE_INTERP(type, idx)                                 \
    do {                                                        \
        frame.locals[idx] = frame.ostack.top();                 \
        frame.ostack.pop();                                     \
    } while (0)

#define BINOP_INTERP(type, op)                                  \
    do {                                                        \
        auto value2 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        auto value1 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        type result = value1 op value2;                         \
        frame.ostack.push(type##_to_value(result));             \
   } while (0)

#define SHL_INTERP(type, mask)                                  \
    do {                                                        \
        auto value2 = value_to_jint(frame.ostack.top());        \
        frame.ostack.pop();                                     \
        auto value1 = value_to_##type(frame.ostack.top());      \
        frame.ostack.pop();                                     \
        type result = value1 << (value2 & mask);                \
        frame.ostack.push(type##_to_value(result));             \
    } while (0)

void interp(method* method, frame& frame)
{
next_insn:
    assert(frame.pc < method->code_length);

    uint8_t opc = method->code[frame.pc];

    switch (opc) {
    case JVM_OPC_nop:
        break;
    case JVM_OPC_aconst_null:
        frame.ostack.push(object_to_value(nullptr));
        break;
    case JVM_OPC_iconst_m1:
    case JVM_OPC_iconst_0:
    case JVM_OPC_iconst_1:
    case JVM_OPC_iconst_2:
    case JVM_OPC_iconst_3:
    case JVM_OPC_iconst_4:
    case JVM_OPC_iconst_5: {
        jint value = opc - JVM_OPC_iconst_0;
        CONST_INTERP(jint, value);
        break;
    }
    case JVM_OPC_lconst_0:
    case JVM_OPC_lconst_1: {
        jlong value = opc - JVM_OPC_lconst_0;
        CONST_INTERP(jlong, value);
        break;
    }
    case JVM_OPC_iload_0:
    case JVM_OPC_iload_1:
    case JVM_OPC_iload_2:
    case JVM_OPC_iload_3: {
        uint16_t idx = opc - JVM_OPC_iload_0;
        LOAD_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lload_0:
    case JVM_OPC_lload_1:
    case JVM_OPC_lload_2:
    case JVM_OPC_lload_3: {
        uint16_t idx = opc - JVM_OPC_lload_0;
        LOAD_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_aload_0:
    case JVM_OPC_aload_1:
    case JVM_OPC_aload_2:
    case JVM_OPC_aload_3: {
        uint16_t idx = opc - JVM_OPC_aload_0;
        LOAD_INTERP(jobject, idx);
        break;
    }
    case JVM_OPC_istore: {
        auto idx = read_opc_u1(method->code + frame.pc);
        STORE_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lstore: {
        auto idx = read_opc_u1(method->code + frame.pc);
        STORE_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_istore_0:
    case JVM_OPC_istore_1:
    case JVM_OPC_istore_2:
    case JVM_OPC_istore_3: {
        uint16_t idx = opc - JVM_OPC_istore_0;
        STORE_INTERP(jint, idx);
        break;
    }
    case JVM_OPC_lstore_0:
    case JVM_OPC_lstore_1:
    case JVM_OPC_lstore_2:
    case JVM_OPC_lstore_3: {
        uint16_t idx = opc - JVM_OPC_lstore_0;
        STORE_INTERP(jlong, idx);
        break;
    }
    case JVM_OPC_pop: {
        frame.ostack.pop();
        break;
    }
    case JVM_OPC_dup: {
        auto value = frame.ostack.top();
        frame.ostack.push(value);
        break;
    }
    case JVM_OPC_iadd: {
        BINOP_INTERP(jint, +);
        break;
    }
    case JVM_OPC_ladd: {
        BINOP_INTERP(jlong, +);
        break;
    }
    case JVM_OPC_isub: {
        BINOP_INTERP(jint, -);
        break;
    }
    case JVM_OPC_lsub: {
        BINOP_INTERP(jlong, -);
        break;
    }
    case JVM_OPC_imul: {
        BINOP_INTERP(jint, *);
        break;
    }
    case JVM_OPC_lmul: {
        BINOP_INTERP(jlong, *);
        break;
    }
    case JVM_OPC_idiv: {
        BINOP_INTERP(jint, /);
        break;
    }
    case JVM_OPC_ldiv: {
        BINOP_INTERP(jlong, /);
        break;
    }
    case JVM_OPC_irem: {
        BINOP_INTERP(jint, %);
        break;
    }
    case JVM_OPC_lrem: {
        BINOP_INTERP(jlong, %);
        break;
    }
    case JVM_OPC_ishl: {
        SHL_INTERP(jint, 0x1f);
        break;
    }
    case JVM_OPC_lshl: {
        SHL_INTERP(jlong, 0x3f);
        break;
    }
    case JVM_OPC_iand: {
        BINOP_INTERP(jint, &);
        break;
    }
    case JVM_OPC_land: {
        BINOP_INTERP(jlong, &);
        break;
    }
    case JVM_OPC_ior: {
        BINOP_INTERP(jint, |);
        break;
    }
    case JVM_OPC_lor: {
        BINOP_INTERP(jlong, |);
        break;
    }
    case JVM_OPC_ixor: {
        BINOP_INTERP(jint, ^);
        break;
    }
    case JVM_OPC_lxor: {
        BINOP_INTERP(jlong, ^);
        break;
    }
    case JVM_OPC_if_icmpeq: {
        int16_t offset = read_opc_u2(method->code + frame.pc);
        auto value2 = value_to_jint(frame.ostack.top());
        frame.ostack.pop();
        auto value1 = value_to_jint(frame.ostack.top());
        frame.ostack.pop();
        if (value1 == value2) {
            frame.pc += offset;
            goto next_insn;
        }
        break;
    }
    case JVM_OPC_goto: {
        int16_t offset = read_opc_u2(method->code + frame.pc);
        frame.pc += offset;
        goto next_insn;
    }
    case JVM_OPC_return: {
        frame.ostack.empty();
        return;
    }
    case JVM_OPC_invokespecial: {
        break;
    }
    case JVM_OPC_new: {
        auto obj = gc_new_object(nullptr);
        frame.ostack.push(object_to_value(obj));
        break;
    }
    case JVM_OPC_arraylength: {
        auto* arrayref = value_to_array(frame.ostack.top());
        frame.ostack.pop();
        assert(arrayref != nullptr);
        frame.ostack.push(arrayref->length);
        break;
    }
    default:
        fprintf(stderr, "error: unsupported bytecode: %u\n", opc);
        abort();
    }

    frame.pc += opcode_length[opc];

    goto next_insn;
}

}
<|endoftext|>


<commit_before>
#include "Table.h"
#include "display.h"
#include <signal.h>
#include <ncurses.h>
#include <cstdlib>
#include <sstream>

using namespace std;

void Table::drawBoard(Dealer* d){
	// using a stringstream rather than a string to make making the banner easier
	stringstream messageString;

	// various variable declarations
	char key;
	char key2;
	int cardX = 0;
	int cardY = 0;
	//int suit = 0;
	//int number = 0;

	// Player 1
	gameDisplay.drawBox(47, 6, 13, 3, 0);		// Money
	mvprintw(7,48,"Money");						// Need to refresh
	gameDisplay.drawBox(47, 8, 13, 3, 0);		// Last action
	mvprintw(9,48,"Action");					// Need to refresh
	gameDisplay.displayCard(47,2,0,0, A_BOLD);
	gameDisplay.displayCard(54,2,0,0, A_BOLD);

	// Player 2
	gameDisplay.drawBox(10, 11, 13, 3, 0);		// Money
	mvprintw(12,11,"Money");					// Need to refresh
	gameDisplay.drawBox(10, 13, 13, 3, 0);		// Last action
	mvprintw(14,11,"Action");					// Need to refresh
	gameDisplay.displayCard(10,7,0,0, A_BOLD);
	gameDisplay.displayCard(17,7,0,0, A_BOLD);

	// Player 3
	gameDisplay.drawBox(10, 23, 13, 3, 0);		// Money
	mvprintw(24,11,"Money");					// Need to refresh
	gameDisplay.drawBox(10, 25, 13, 3, 0);		// Last action
	mvprintw(26,11,"Action");					// Need to refresh
	gameDisplay.displayCard(10,19,0,0, A_BOLD);
	gameDisplay.displayCard(17,19,0,0, A_BOLD);

	// Player 4    HUMAN
	gameDisplay.drawBox(35, 33, 13, 3, 0);		// Money
	mvprintw(34,36,"Money");					// Need to refresh
	gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
	mvprintw(36,36,"Action");					// Need to refresh
	gameDisplay.displayCard(35,29,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(42,29,rand()%5,rand()%15, A_BOLD);

	// Player 5
	gameDisplay.drawBox(78, 23, 13, 3, 0);		// Money
	mvprintw(24,79,"Money");					// Need to refresh
	gameDisplay.drawBox(78, 25, 13, 3, 0);		// Last action
	mvprintw(26,79,"Action");					// Need to refresh
	gameDisplay.displayCard(78,19,0,0, A_BOLD);
	gameDisplay.displayCard(85,19,0,0, A_BOLD);

	// Player 6
	gameDisplay.drawBox(78, 11, 13, 3, 0);		// Money
	mvprintw(12,79,"Money");					// Need to refresh
	gameDisplay.drawBox(78, 13, 13, 3, 0);		// Last action
	mvprintw(14,79,"Action");					// Need to refresh
	gameDisplay.displayCard(78,7,0,0, A_BOLD);
	gameDisplay.displayCard(85,7,0,0, A_BOLD);

	// Flop
	mvprintw(15,51,"Flop");
	gameDisplay.displayCard(38,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(44,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(50,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(56,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(62,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.drawBox(46, 23, 15, 3, 0);		// Money in Side Pot
	mvprintw(24,47,"Side Pot");
	gameDisplay.drawBox(46, 21, 15, 3, 0);		// Money in Pot
	mvprintw(22,47,"Main Pot");

	// Choices
	mvprintw(34,74,"Options");

	gameDisplay.drawBox(50, 28, 19, 6, 0);		// Top Left
	mvprintw(30,55,"Check/Call");
	gameDisplay.drawBox(50, 35, 19, 6, 0);		// Bottom Left
	mvprintw(37,55,"Free Money");
	gameDisplay.drawBox(69, 28, 18, 6, 0);		// Top Middle
	mvprintw(30,75,"Raise");
	gameDisplay.drawBox(69, 35, 18, 6, 0);		// Bottom Middle
	mvprintw(37,75,"ALL IN");
	gameDisplay.drawBox(87, 28, 19, 6, 0);		// Top Right
	mvprintw(30,94,"Fold");
	gameDisplay.drawBox(87, 35, 19, 6, 0);		// Bottom Right
	mvprintw(37,94,"Quit");

	int keynew = 0;
	int bet = 0;
	bool isTurn = true;

	// infinite loop for the main program, you can press ctrl-c to quit
	for (;;) {
		// Refresh every textbox
		// Money per player
		// Pot Money
		// Side Pot Money
		// CPU actions

		if (isTurn){
			// calls the game display to capture some input
	    	key = gameDisplay.captureInput();
    		keynew = key - 48;
			// if a mouse event occurred
			if (key == -1) {
				// make a banner message
				messageString.str("");
				messageString << "A mouse event occurred x=" \
					<< gameDisplay.getMouseEventX() << ", y=" \
					<< gameDisplay.getMouseEventY() << ", bstate=" \
					<< gameDisplay.getMouseEventButton();
				// display a banner message
				gameDisplay.bannerTop(messageString.str());
				// record the location of the mouse event
				cardX = gameDisplay.getMouseEventX();
				cardY = gameDisplay.getMouseEventY();
				// Some of the mouse click values are defined in display.h

				// check if it was a left click
				if (gameDisplay.getMouseEventButton()&LEFT_CLICK) {

					// Top Left
					// Check/Call
					if((cardX >= 50) && (cardX <= 68) && (cardY >= 28) && (cardY <= 33)){
						gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
						mvprintw(36,36,"Check/Call");
						messageString.str("");
						messageString << "You Checked/Called";
						gameDisplay.bannerBottom(messageString.str());
					}

					// Bottom Left
					else if((cardX >= 50) && (cardX <= 68) && (cardY >= 35) && (cardY <= 40)){
						mvprintw(37,55,"Cheater   ");
						messageString.str("");
						messageString << "You Cheated";
						gameDisplay.bannerBottom(messageString.str());
					}

					// Top Middle
					// Raise
					else if((cardX >= 69) && (cardX <= 86) && (cardY >= 28) && (cardY <= 33)){

						for(;;){
							key2 = gameDisplay.captureInput();
							keynew = key2 - 48;

							if ((keynew >= 0) && (keynew <= 9)){
								bet = (bet * 10) + keynew;
								messageString.str("");
								messageString << "Press SPACE to confirm                           Money raising: " << bet;
								gameDisplay.bannerBottom(messageString.str());
							}

							if (keynew == -16){
								if (bet != 0){
									gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
									mvprintw(36,36,"Raise");
									messageString.str("");
									messageString << "You bet " << bet << " chip(s)";
									gameDisplay.bannerBottom(messageString.str());
									bet = 0;
									break;
								}
							}
						}
					}

					// Bottom Middle
					// ALL IN
					else if((cardX >= 69) && (cardX <= 86) && (cardY >= 35) && (cardY <= 40)){
						gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
						mvprintw(36,36,"ALL IN");
						messageString.str("");
						messageString << "You went ALL IN!";
						gameDisplay.bannerBottom(messageString.str());
					}

					// Top Right
					// Fold
					else if((cardX >= 87) && (cardX <= 105) && (cardY >= 28) && (cardY <= 33)){
						gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
						mvprintw(36,36,"Fold");
						messageString.str("");
						messageString << "You Folded";
						gameDisplay.bannerBottom(messageString.str());
					}

					// Bottom Right
					// Quit
					else if((cardX >= 87) && (cardX <= 105) && (cardY >= 35) && (cardY <= 40)){
						break;
					}
				}

				/*
				// Not needed
				////////////////////////////////////////////////////////////
				// check if it was a right click
				else if (gameDisplay.getMouseEventButton()&RIGHT_CLICK) {
					// erase a portion of the screen in the shape of a card
					gameDisplay.eraseBox(cardX,cardY,6,5);
				// check for the start of a drag click
				} else if (gameDisplay.getMouseEventButton()&LEFT_DOWN) {
					// record start of the drag
					dragX = cardX;
					dragY = cardY;
				// when the mouse is released
				} else if (gameDisplay.getMouseEventButton()&LEFT_UP) {
					// calculate size of the drag
					int sizeX = abs(dragX-cardX);
					int sizeY = abs(dragY-cardY);
					// get to the top left corner of the drag area
					if (dragX > cardX)
						dragX = cardX;
	                if (dragY > cardY)
	                    dragY = cardY;
					// draw a box around the drag area
					gameDisplay.drawBox(dragX, dragY, sizeX, sizeY, 0);
				}
				////////////////////////////////////////////////////////////
				*/

			}

			/*
			// Not needed
			////////////////////////////////////////////////////////////
			// if a key was pressed
			else if(key > 0) {
				if ((key > 47) && (key < 58)){
					gameDisplay.displayCard(55,10,rand()%5,1, A_BOLD);
					bet = (bet * 10) + keynew;
					messageString.str("");
					messageString << "Money betting: " << bet;
					gameDisplay.bannerBottom(messageString.str());

				}
				else {
					if (bet != 0){
						messageString.str("");
						messageString << "You bet " << bet << " chip(s)";
						gameDisplay.bannerBottom(messageString.str());
						bet = 0;
					}
				}
			}
			////////////////////////////////////////////////////////////
			*/

		}
	}

}

Move Table::getUserMove(){
	return FOLD;
}

int Table::getUserValue(){
	return 100;
}
<commit_msg>shit sorta works<commit_after>
#include "Table.h"
#include "display.h"
#include <signal.h>
#include <ncurses.h>
#include <cstdlib>
#include <sstream>

using namespace std;

void Table::drawBoard(Dealer* d){
	// using a stringstream rather than a string to make making the banner easier
	stringstream messageString;

	// various variable declarations
	char key;
	char key2;
	int cardX = 0;
	int cardY = 0;
	//int suit = 0;
	//int number = 0;

	// Player 1
	gameDisplay.drawBox(47, 6, 13, 3, 0);		// Money
	mvprintw(7,48,"Money");						// Need to refresh
	gameDisplay.drawBox(47, 8, 13, 3, 0);		// Last action
	mvprintw(9,48,"Action");					// Need to refresh
	gameDisplay.displayCard(47,2,0,0, A_BOLD);
	gameDisplay.displayCard(54,2,0,0, A_BOLD);

	// Player 2
	gameDisplay.drawBox(10, 11, 13, 3, 0);		// Money
	mvprintw(12,11,"Money");					// Need to refresh
	gameDisplay.drawBox(10, 13, 13, 3, 0);		// Last action
	mvprintw(14,11,"Action");					// Need to refresh
	gameDisplay.displayCard(10,7,0,0, A_BOLD);
	gameDisplay.displayCard(17,7,0,0, A_BOLD);

	// Player 3
	gameDisplay.drawBox(10, 23, 13, 3, 0);		// Money
	mvprintw(24,11,"Money");					// Need to refresh
	gameDisplay.drawBox(10, 25, 13, 3, 0);		// Last action
	mvprintw(26,11,"Action");					// Need to refresh
	gameDisplay.displayCard(10,19,0,0, A_BOLD);
	gameDisplay.displayCard(17,19,0,0, A_BOLD);

	// Player 4    HUMAN
	gameDisplay.drawBox(35, 33, 13, 3, 0);		// Money
	mvprintw(34,36,"Money");					// Need to refresh
	gameDisplay.drawBox(35, 35, 13, 3, 0);		// Last action
	mvprintw(36,36,"Action");					// Need to refresh
	gameDisplay.displayCard(35,29,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(42,29,rand()%5,rand()%15, A_BOLD);

	// Player 5
	gameDisplay.drawBox(78, 23, 13, 3, 0);		// Money
	mvprintw(24,79,"Money");					// Need to refresh
	gameDisplay.drawBox(78, 25, 13, 3, 0);		// Last action
	mvprintw(26,79,"Action");					// Need to refresh
	gameDisplay.displayCard(78,19,0,0, A_BOLD);
	gameDisplay.displayCard(85,19,0,0, A_BOLD);

	// Player 6
	gameDisplay.drawBox(78, 11, 13, 3, 0);		// Money
	mvprintw(12,79,"Money");					// Need to refresh
	gameDisplay.drawBox(78, 13, 13, 3, 0);		// Last action
	mvprintw(14,79,"Action");					// Need to refresh
	gameDisplay.displayCard(78,7,0,0, A_BOLD);
	gameDisplay.displayCard(85,7,0,0, A_BOLD);

	// Flop
	mvprintw(15,51,"Flop");
	gameDisplay.displayCard(38,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(44,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(50,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(56,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.displayCard(62,16,rand()%5,rand()%15, A_BOLD);
	gameDisplay.drawBox(46, 23, 15, 3, 0);		// Money in Side Pot
	mvprintw(24,47,"Side Pot");
	gameDisplay.drawBox(46, 21, 15, 3, 0);		// Money in Pot
	mvprintw(22,47,"Main Pot");

	// Choices
	mvprintw(34,74,"Options");

	gameDisplay.drawBox(50, 28, 19, 6, 0);		// Top Left
	mvprintw(30,55,"Check/Call");
	gameDisplay.drawBox(50, 35, 19, 6, 0);		// Bottom Left
	mvprintw(37,55,"Free Money");
	gameDisplay.drawBox(69, 28, 18, 6, 0);		// Top Middle
	mvprintw(30,75,"Raise");
	gameDisplay.drawBox(69, 35, 18, 6, 0);		// Bottom Middle
	mvprintw(37,75,"ALL IN");
	gameDisplay.drawBox(87, 28, 19, 6, 0);		// Top Right
	mvprintw(30,94,"Fold");
	gameDisplay.drawBox(87, 35, 19, 6, 0);		// Bottom Right
	mvprintw(37,94,"Quit");

	int keynew = 0;
	int bet = 0;
	bool isTurn = true;

	gameDisplay.captureInput(); //flushes display to screen
}

Move Table::getUserMove(){
	return FOLD;
}

int Table::getUserValue(){
	return 100;
}
<|endoftext|>