DebugHud::DebugHud(Context* context) :
    Object(context),
    profilerMaxDepth_(M_MAX_UNSIGNED),
    profilerInterval_(1000),
    useRendererStats_(false),
    mode_(DEBUGHUD_SHOW_NONE)
{
    UI* ui = GetSubsystem<UI>();
    UIElement* uiRoot = ui->GetRoot();

    statsText_ = new Text(context_);
    statsText_->SetAlignment(HA_LEFT, VA_TOP);
    statsText_->SetPriority(100);
    statsText_->SetVisible(false);
    uiRoot->AddChild(statsText_);

    modeText_ = new Text(context_);
    modeText_->SetAlignment(HA_LEFT, VA_BOTTOM);
    modeText_->SetPriority(100);
    modeText_->SetVisible(false);
    uiRoot->AddChild(modeText_);

    profilerText_ = new Text(context_);
    profilerText_->SetAlignment(HA_RIGHT, VA_TOP);
    profilerText_->SetPriority(100);
    profilerText_->SetVisible(false);
    uiRoot->AddChild(profilerText_);

    SubscribeToEvent(E_POSTUPDATE, HANDLER(DebugHud, HandlePostUpdate));
}
Пример #2
0
Console::Console(Context* context) :
    Object(context),
    historyRows_(DEFAULT_HISTORY_SIZE),
    historyPosition_(0)
{
    UI* ui = GetSubsystem<UI>();
    UIElement* uiRoot = ui->GetRoot();

    background_ = new BorderImage(context_);
    background_->SetBringToBack(false);
    background_->SetClipChildren(true);
    background_->SetEnabled(true);
    background_->SetVisible(false); // Hide by default
    background_->SetPriority(200); // Show on top of the debug HUD
    background_->SetLayout(LM_VERTICAL);

    rowContainer_ = new UIElement(context_);
    rowContainer_->SetClipChildren(true);
    rowContainer_->SetLayout(LM_VERTICAL);
    background_->AddChild(rowContainer_);

    lineEdit_ = new LineEdit(context_);
    lineEdit_->SetFocusMode(FM_FOCUSABLE); // Do not allow defocus with ESC
    background_->AddChild(lineEdit_);

    uiRoot->AddChild(background_);

    SetNumRows(DEFAULT_CONSOLE_ROWS);

    SubscribeToEvent(lineEdit_, E_TEXTFINISHED, HANDLER(Console, HandleTextFinished));
    SubscribeToEvent(lineEdit_, E_UNHANDLEDKEY, HANDLER(Console, HandleLineEditKey));
    SubscribeToEvent(E_SCREENMODE, HANDLER(Console, HandleScreenMode));
    SubscribeToEvent(E_LOGMESSAGE, HANDLER(Console, HandleLogMessage));
    SubscribeToEvent(E_POSTUPDATE, HANDLER(Console, HandlePostUpdate));
}
Пример #3
0
void UIDrag::CreateGUI()
{
    auto* cache = GetSubsystem<ResourceCache>();
    auto* ui = GetSubsystem<UI>();

    UIElement* root = ui->GetRoot();
    // Load the style sheet from xml
    root->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

    for (int i=0; i < 10; i++)
    {
        auto* b = new Button(context_);
        root->AddChild(b);
        // Reference a style from the style sheet loaded earlier:
        b->SetStyleAuto();
        b->SetMinWidth(250);
        b->SetPosition(IntVector2(50*i, 50*i));

        // Enable the bring-to-front flag and set the initial priority
        b->SetBringToFront(true);
        b->SetPriority(i);

        // Set the layout mode to make the child text elements aligned vertically
        b->SetLayout(LM_VERTICAL, 20, {40, 40, 40, 40});
        auto dragInfos = {"Num Touch", "Text", "Event Touch"};
        for (auto name: dragInfos)
            b->CreateChild<Text>(name)->SetStyleAuto();

        if (i % 2 == 0)
            b->AddTag("SomeTag");

        SubscribeToEvent(b, E_CLICK, URHO3D_HANDLER(UIDrag, HandleClick));
        SubscribeToEvent(b, E_DRAGMOVE, URHO3D_HANDLER(UIDrag, HandleDragMove));
        SubscribeToEvent(b, E_DRAGBEGIN, URHO3D_HANDLER(UIDrag, HandleDragBegin));
        SubscribeToEvent(b, E_DRAGCANCEL, URHO3D_HANDLER(UIDrag, HandleDragCancel));
    }

    for (int i = 0; i < 10; i++)
    {
        auto* t = new Text(context_);
        root->AddChild(t);
        t->SetStyleAuto();
        t->SetName("Touch "+ String(i));
        t->SetVisible(false);
        t->SetPriority(100);     // Make sure it has higher priority than the buttons
    }
}
Пример #4
0
void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
    // Ensure UI-elements are not detached
    if (!background_->GetParent())
    {
        UI* ui = GetSubsystem<UI>();
        UIElement* uiRoot = ui->GetRoot();
        uiRoot->AddChild(background_);
        uiRoot->AddChild(closeButton_);
    }

    if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
        return;

    printing_ = true;
    rowContainer_->DisableLayoutUpdate();

    Text* text = nullptr;
    for (unsigned i = 0; i < pendingRows_.Size(); ++i)
    {
        rowContainer_->RemoveItem((unsigned)0);
        text = new Text(context_);
        text->SetText(pendingRows_[i].second_);

        // Highlight console messages based on their type
        text->SetStyle(logStyles[pendingRows_[i].first_]);

        rowContainer_->AddItem(text);
    }

    pendingRows_.Clear();

    rowContainer_->EnsureItemVisibility(text);
    rowContainer_->EnableLayoutUpdate();
    rowContainer_->UpdateLayout();
    UpdateElements();   // May need to readjust the height due to scrollbar visibility changes
    printing_ = false;
}
Пример #5
0
void HelloGUI::InitWindow()
{
    // Create the Window and add it to the UI's root node
    window_ = new Window(context_);
    uiRoot_->AddChild(window_);

    // Set Window size and layout settings
    window_->SetMinSize(384, 192);
    window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
    window_->SetAlignment(HA_CENTER, VA_CENTER);
    window_->SetName("Window");

    // Create Window 'titlebar' container
    UIElement* titleBar = new UIElement(context_);
    titleBar->SetMinSize(0, 24);
    titleBar->SetVerticalAlignment(VA_TOP);
    titleBar->SetLayoutMode(LM_HORIZONTAL);

    // Create the Window title Text
    Text* windowTitle = new Text(context_);
    windowTitle->SetName("WindowTitle");
    windowTitle->SetText("Hello GUI!");

    // Create the Window's close button
    Button* buttonClose = new Button(context_);
    buttonClose->SetName("CloseButton");

    // Add the controls to the title bar
    titleBar->AddChild(windowTitle);
    titleBar->AddChild(buttonClose);

    // Add the title bar to the Window
    window_->AddChild(titleBar);

    // Apply styles
    window_->SetStyleAuto();
    windowTitle->SetStyleAuto();
    buttonClose->SetStyle("CloseButton");

    // Subscribe to buttonClose release (following a 'press') events
    SubscribeToEvent(buttonClose, E_RELEASED, HANDLER(HelloGUI, HandleClosePressed));

    // Subscribe also to all UI mouse clicks just to see where we have clicked
    SubscribeToEvent(E_UIMOUSECLICK, HANDLER(HelloGUI, HandleControlClicked));
}
Пример #6
0
void Menu::ShowPopup(bool enable)
{
    if (!popup_)
        return;
    
    if (enable)
    {
        // Find the UI root element for showing the popup
        UIElement* root = GetRoot();
        if (!root)
            return;
        
        OnShowPopup();
        
        if (popup_->GetParent() != root)
            root->AddChild(popup_);
        popup_->SetPosition(GetScreenPosition() + popupOffset_);
        popup_->SetVisible(true);
        popup_->SetVar(originHash, (void*)this);
        popup_->BringToFront();
    }
    else
    {
        // If the popup has child menus, hide their popups as well
        PODVector<UIElement*> children;
        popup_->GetChildren(children, true);
        for (PODVector<UIElement*>::ConstIterator i = children.Begin(); i != children.End(); ++i)
        {
            Menu* menu = dynamic_cast<Menu*>(*i);
            if (menu)
                menu->ShowPopup(false);
        }
        
        popup_->SetVar(originHash, Variant::EMPTY);
        popup_->SetVisible(false);
        popup_->Remove();
    }
    
    showPopup_ = enable;
    selected_ = enable;
}
Пример #7
0
void Script::EvaluateLine(String & line)
{
	/// Default line processed once?
	lineProcessed = true;

	line.SetComparisonMode(String::NOT_CASE_SENSITIVE);
	// "80Gray50Alpha.png"
#define DEFAULT_TEXTURE_SOURCE	"black50Alpha.png"
#define DEFAULT_TEXT_SIZE_RATIO	0.3f
	
	/// Some state began, take not of it?
	if (line.Contains("Wait("))
	{
		WaitScript * wait = new WaitScript(line, this);
		wait->SetDeleteOnEnd(true);
		ScriptMan.PlayScript(wait);
	}
	else if (line.StartsWith("Key:"))
	{
		String keyStr = line.Tokenize(":")[1];
		keyStr.RemoveSurroundingWhitespaces();
		int keyCode = GetKeyForString(keyStr);
		assert(keyCode != 0);
		InputMan.KeyDown(MainWindow(), keyCode, false);
		InputMan.KeyUp(MainWindow(), keyCode);
		lineFinished = true;
	}
	else if (line.Contains("PlayScript("))
	{
		List<String> tokens = line.Tokenize("(),");
		// Source of script within the parenthesis.
		String source = tokens[1];
		bool wait = true;
		Script * scriptParent = this;
		if (tokens.Size() >= 3)
		{
			wait = tokens[2].ParseBool();
			if (!wait)
			{
				scriptParent = NULL;
				this->lineFinished = true;
			}
		}
		Script * script = new Script(source, scriptParent);
		script->source = source;
		bool loaded = script->Load();
		assert(loaded);
		ScriptMan.PlayScript(script);
	}
	else if (line == "DisableActiveUI")
	{
		InputMan.DisableActiveUI();
		lineFinished = true;
		uiDisabled = true;
	}
	else if (line == "EnableActiveUI")
	{
		InputMan.EnableActiveUI();
		lineFinished = true;
	}
	else if (line.Contains("PreloadTexturesInDirectory("))
	{
		// Fetch the stuff, do the buff
		String dir = line.Tokenize("()")[1];
		List<String> files;
		int num = GetFilesInDirectory(dir, files);
		for (int i = 0; i < files.Size(); ++i)
		{
			String path = dir + "/" + files[i];
			Texture * tex = TexMan.LoadTexture(path);
			Graphics.QueueMessage(new GMBufferTexture(tex));
		}
		lineFinished = true;
	}
	else if (line.Contains("Begin("))
	{
		String stateBeginning = line.Tokenize("()")[1];
		if (stateBeginning == "Cutscene")
		{
			BeginCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("End("))
	{
		String stateEnding = line.Tokenize("()")[1];
		if (stateEnding == "Cutscene")
		{
			EndCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("EndScript"))
	{
		// End it.
		scriptState = ENDING;
	}
	else if (line.Contains("EnterGameState("))
	{
		String name = line.Tokenize("()")[1];		
		StateChanger * changer = new StateChanger(line, this);
		ScriptMan.PlayScript(changer);
	}
	else if (line.Contains("FadeTo(") || line.Contains("FadeIn("))
	{
		FadeInEffect * fade = new FadeInEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeInBackground("))
	{
		FadeInBackground * fade = new FadeInBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOutBackground("))
	{
		FadeOutBackground * fade = new FadeOutBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOut"))
	{
		FadeOutEffect * fade = new FadeOutEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeText("))
	{
		FadeTextEffect * text = new FadeTextEffect(line, this);
		ScriptMan.PlayScript(text);
		lineFinished = true;
	}
	else if (line.Contains("PlaySong("))
	{
		// Just play it.
		String song = line.Tokenize("()")[1];
		TrackMan.PlayTrack(song);
		// Line finished straight away.
		lineFinished = true;
	}
	else if (line.Contains("Dialogue")){
		/// If raw string, output it straight away! (should later be queued to some kind of dialogue-manager?)
		if (line.Contains("\"")){
			/// Create dialogue UI and append it to the current UI!
			String text = line.Tokenize("\"")[1];
			std::cout<<"\n"<<text;
			UIButton * dialogue = new UIButton("Dialogue");
			dialogue->exitable = false;
			dialogue->text = text;
			dialogue->activationMessage = "PopFromStack(this)&Remove(this)&ContinueEvent("+this->name+")";
			dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
			dialogue->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
			dialogue->sizeRatioY = 0.3f;
			dialogue->alignmentY = 0.15f;
			dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!
			Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
			Graphics.QueueMessage(GMPushUI::ToUI("Dialogue", ActiveUI()));
		}
		/// If no quotes, load the specified dialogue-file and begin processing that instead, waiting until it is finished.!
		else {
			/// Give the npc a dialogue?
		//	assert(false);
			// Send it tot he state too, to attach to the appropriate thingymajig.
			Message * message = new Message(line);
			/// Set this event as
			message->scriptOrigin = this;
			MesMan.QueueMessage(message);
			/// Instant thingies.
			lineFinished = true;
		}
	}
	else if (line.Contains("Answer")){
		///  Go to EndAnswers..!
		lineFinished = true;
		for (int i = currentLine; i < lines.Size(); ++i){
			String line = lines[i];
			if (line.Contains("EndAnswers")){
				currentLine = i;
				lineFinished = true;
				return;
			}
		}
		assert(false && "No EndAnswers found? No good, jaow ;___;");
	}
	else if (line.Contains("BeginAlternatives") || line.Contains("BeginQuestion")){
		/// Create dialogue UI and append it to the current UI!
		String text = line.Tokenize("\"")[1];
		std::cout<<"\n"<<text;
		UIElement * dialogue = new UIElement();
		dialogue->exitable = false;
		dialogue->name = "AlternativesDialogue";
	//	dialogue->activationMessage = "Remove(this)&ContinueEvent("+this->name+")";
		dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
		dialogue->sizeRatioY = 0.3f;
		dialogue->alignmentY = 0.15f;
		dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!

		UILabel * dialogueText = new UILabel();
		dialogueText->text = text;
		dialogueText->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
		dialogueText->sizeRatioX = 0.5f;
		dialogueText->alignmentX = 0.25f;
		dialogue->AddChild(dialogueText);

		UIList * dialogueAnswerList = new UIList();
		dialogueAnswerList->sizeRatioX = 0.5f;
		dialogueAnswerList->alignmentX = 0.75f;
		dialogue->AddChild(dialogueAnswerList);

		int answers = 0;
		List<UIElement*> answerList;
		// Parse and add answers
		for (int i = currentLine+1; i < lines.Size(); ++i){
			String l = lines[i];
			l.SetComparisonMode(String::NOT_CASE_SENSITIVE);
			List<String> tokens = l.Tokenize(" ");
			String token1 = tokens[0];
			token1.SetComparisonMode(String::NOT_CASE_SENSITIVE);

			if (token1 == "text"){
				l.Remove(token1);
				dialogueText->text = l;
				dialogueText->text.RemoveInitialWhitespaces();
				dialogueText->text.Remove("\"");
				dialogueText->text.Remove("\"");
			}
			else if (l.Contains("Answer")){
				++answers;
				UIButton * answerButton = new UIButton();
				answerButton->name = token1;
				l.Remove("Answer");
				l.RemoveInitialWhitespaces();
				l.Remove("\"");
				l.Remove("\"");
				answerButton->textureSource = DEFAULT_TEXTURE_SOURCE;
				answerButton->text = l;
				answerButton->sizeRatioY = 0.2f;
				answerButton->activationMessage = "ActivateDialogueAlternative("+name+","+answerButton->name+")&PopFromStack("+dialogue->name+")&Remove("+dialogue->name+")";
				answerList.Add(answerButton);
			}
			else if (l.Contains("EndAlternatives")){
				// Donelir. o-o
				break;
			}
			else {
				assert(false && "Bad line! Should only be Answer before EndAlternatives!");
			}
		}
		assert(answers);
		float sizeRatioY = 0.95f / answers;
		for (int i = 0; i < answers; ++i){
			UIElement * ans = answerList[i];
		//	ans->sizeRatioY = sizeRatioY; // Stupid to set the sizeRatioY to be this dynamic, yo.
			dialogueAnswerList->AddChild(ans);
		}
		isInAlternativeDialogue = true;
		Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
		Graphics.QueueMessage(GMPushUI::ToUI(dialogue, ActiveUI()));
	}
	else if (line.Contains("elsif") || line.Contains("elseif") || line.Contains("else if"))
	{
		/// Should be in an if-stack, check if we already evaluated.
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		/// If already evaluated, jump to endif.
		if (sl.evaluatedAtLine > 0)
		{
			// Jump to endif.
			JumpToEndif();
			return;
		}
		/// If not, handle the conditional first.
		HandleConditional(line);
	}
	else if (line.Contains("if(") || line.Contains("if ("))
	{
		// Add to stack.
		stack.AddItem(ScriptLevel(ScriptLevel::IF_CLAUSE, currentLine));
		HandleConditional(line);
	}
	else if (line.Contains("else"))
	{
//		if (ifProcessed)
		//	JumpToEndif();
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		if (sl.evaluatedAtLine > 0)
		{
			JumpToEndif();
			return;
		}
		lineFinished = true;
		return;
	}
	else if (line.Contains("endif"))
	{
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		stack.RemoveLast();
		lineFinished = true;
	}
	else if (line.Contains("endwhile"))
	{
		// Go to start!
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::WHILE_LOOP);
		currentLine = sl.evaluatedAtLine;
		String startLine = lines[currentLine];
		HandleConditional(startLine);
//		lineFinished = true;
		// Evaluate?
//		stack.RemoveLast();
	}
	else if (line.Contains("while"))
	{
		stack.AddItem(ScriptLevel(ScriptLevel::WHILE_LOOP, currentLine));
		HandleConditional(line);
	}
/*	else if (line.Contains("CreateInt")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int initialValue = 0;
		if (tokens.Size() >= 3)
			initialValue = tokens[2].ParseInt();
		if (!GameVars.Get(varName)){
			GameVars.CreateInt(varName, initialValue);
		}
		lineFinished = true;
	}
	/*
	else if (line.Contains("SetInt ")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int value = tokens[2].ParseInt();
		GameVars.SetInt(varName, value);
		lineFinished = true;
	}*/
	else if (line.Contains("Repeatable")){
		/// Flag the event as repeatable.
		repeatable = true;
		lineFinished = true;
	}
	// Consider just making an else-clause for all remaining events to be processed by the specific game instead?
	else if (
		line.Contains("SpawnEntity") ||
		line.Contains("OnApproach") ||
		line.Contains("OnInteract") ||
		line.Contains("DisableMovement") ||
		line.Contains("EnableMovement") ||
		line.Contains("Zone(") ||
		line.Contains("PlacePlayer(") ||
		line.Contains("TrackPlayer")
		)
	{
		Message * message = new Message(line);
		/// Set this event as
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		/// Instant thingies.
		lineFinished = true;
	}
	else {
		/// Try evaluate it as an expression.
		Expression exp;
		List<Variable> allVars = GameVars.GetAllExpressionVariables() + variables;
		exp.functionEvaluators = functionEvaluators; // Set evaluators.
		bool parseOK = exp.ParseExpression(line);
		if (line.Contains("SetMovementPattern"))
			int p = 4;;
		if (parseOK)
		{
			ExpressionResult res = exp.Evaluate(allVars);
			/// Continue until it returns true! o.o
			if (res.type != DataType::NO_TYPE)
			{
				if (res.GetBool() == true)
				{
					lineFinished = true;
					return;
				}
			}
		}


//		std::cout<<"\nUndefined event command: "<<line;
//		std::cout<<"\nPassing it as a custom command to the game states for further processing.";
		Message * message = new Message(line);
		/// Set this event as source of it.
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		lineFinished = true;
	//	assert(false && "Undefined event command!");
	};
}
Пример #8
0
void UIDrag::CreateGUI()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    UI* ui = GetSubsystem<UI>();

    UIElement* root = ui->GetRoot();
    // Load the style sheet from xml
    root->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

    for (int i=0; i < 10; i++)
    {
        Button* b = new Button(context_);
        root->AddChild(b);
        // Reference a style from the style sheet loaded earlier:
        b->SetStyle("Button");
        b->SetSize(300, 100);
        b->SetPosition(IntVector2(50*i, 50*i));

        if (i % 2 == 0)
            b->AddTag("SomeTag");

        SubscribeToEvent(b, E_DRAGMOVE, URHO3D_HANDLER(UIDrag, HandleDragMove));
        SubscribeToEvent(b, E_DRAGBEGIN, URHO3D_HANDLER(UIDrag, HandleDragBegin));
        SubscribeToEvent(b, E_DRAGCANCEL, URHO3D_HANDLER(UIDrag, HandleDragCancel));
        SubscribeToEvent(b, E_DRAGEND, URHO3D_HANDLER(UIDrag, HandleDragEnd));

        {
            Text* t = new Text(context_);
            b->AddChild(t);
            t->SetStyle("Text");
            t->SetHorizontalAlignment(HA_CENTER);
            t->SetVerticalAlignment(VA_CENTER);
            t->SetName("Text");
        }

        {
            Text* t = new Text(context_);
            b->AddChild(t);
            t->SetStyle("Text");
            t->SetName("Event Touch");
            t->SetHorizontalAlignment(HA_CENTER);
            t->SetVerticalAlignment(VA_BOTTOM);
        }

        {
            Text* t = new Text(context_);
            b->AddChild(t);
            t->SetStyle("Text");
            t->SetName("Num Touch");
            t->SetHorizontalAlignment(HA_CENTER);
            t->SetVerticalAlignment(VA_TOP);
        }
    }

    for (int i = 0; i < 10; i++)
    {
        Text* t = new Text(context_);
        root->AddChild(t);
        t->SetStyle("Text");
        t->SetName("Touch "+ String(i));
        t->SetVisible(false);
    }
}
void DebugHud::Update()
{
    Graphics* graphics = GetSubsystem<Graphics>();
    Renderer* renderer = GetSubsystem<Renderer>();
    if (!renderer || !graphics)
        return;

    // Ensure UI-elements are not detached
    if (!statsText_->GetParent())
    {
        UI* ui = GetSubsystem<UI>();
        UIElement* uiRoot = ui->GetRoot();
        uiRoot->AddChild(statsText_);
        uiRoot->AddChild(modeText_);
        uiRoot->AddChild(profilerText_);
    }

    if (statsText_->IsVisible())
    {
        unsigned primitives, batches;
        if (!useRendererStats_)
        {
            primitives = graphics->GetNumPrimitives();
            batches = graphics->GetNumBatches();
        }
        else
        {
            primitives = renderer->GetNumPrimitives();
            batches = renderer->GetNumBatches();
        }

        String stats;
        stats.AppendWithFormat("Triangles %u\nBatches %u\nViews %u\nLights %u\nShadowmaps %u\nOccluders %u",
            primitives,
            batches,
            renderer->GetNumViews(),
            renderer->GetNumLights(true),
            renderer->GetNumShadowMaps(true),
            renderer->GetNumOccluders(true));

        if (!appStats_.Empty())
        {
            stats.Append("\n");
            for (HashMap<String, String>::ConstIterator i = appStats_.Begin(); i != appStats_.End(); ++i)
                stats.AppendWithFormat("\n%s %s", i->first_.CString(), i->second_.CString());
        }

        statsText_->SetText(stats);
    }

    if (modeText_->IsVisible())
    {
        String mode;
        mode.AppendWithFormat("Tex:%s Mat:%s Spec:%s Shadows:%s Size:%i Quality:%s Occlusion:%s Instancing:%s API:%s",
            qualityTexts[renderer->GetTextureQuality()],
            qualityTexts[renderer->GetMaterialQuality()],
            renderer->GetSpecularLighting() ? "On" : "Off",
            renderer->GetDrawShadows() ? "On" : "Off",
            renderer->GetShadowMapSize(),
            shadowQualityTexts[renderer->GetShadowQuality()],
            renderer->GetMaxOccluderTriangles() > 0 ? "On" : "Off",
            renderer->GetDynamicInstancing() ? "On" : "Off",
            graphics->GetApiName().CString());

        modeText_->SetText(mode);
    }

    Profiler* profiler = GetSubsystem<Profiler>();
    if (profiler)
    {
        if (profilerTimer_.GetMSec(false) >= profilerInterval_)
        {
            profilerTimer_.Reset();

            if (profilerText_->IsVisible())
            {
                String profilerOutput = profiler->GetData(false, false, profilerMaxDepth_);
                profilerText_->SetText(profilerOutput);
            }

            profiler->BeginInterval();
        }
    }
}
Пример #10
0
void L10n::CreateGUI()
{
    // Get localization subsystem
    auto* l10n = GetSubsystem<Localization>();

    auto* cache = GetSubsystem<ResourceCache>();
    UIElement* root = GetSubsystem<UI>()->GetRoot();
    root->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

    auto* window = new Window(context_);
    root->AddChild(window);
    window->SetMinSize(384, 192);
    window->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
    window->SetAlignment(HA_CENTER, VA_CENTER);
    window->SetStyleAuto();

    auto* windowTitle = new Text(context_);
    windowTitle->SetName("WindowTitle");
    windowTitle->SetStyleAuto();
    window->AddChild(windowTitle);

    // In this place the current language is "en" because it was found first when loading the JSON files
    ea::string langName = l10n->GetLanguage();
    // Languages are numbered in the loading order
    int langIndex = l10n->GetLanguageIndex(); // == 0 at the beginning
    // Get string with identifier "title" in the current language
    ea::string localizedString = l10n->Get("title");
    // Localization::Get returns EMPTY_STRING if the id is empty.
    // Localization::Get returns the id if translation is not found and will be added a warning into the log.

    windowTitle->SetText(localizedString + " (" + ea::to_string(langIndex) + " " + langName + ")");

    auto* b = new Button(context_);
    window->AddChild(b);
    b->SetStyle("Button");
    b->SetMinHeight(24);

    auto* t = b->CreateChild<Text>("ButtonTextChangeLang");
    // The showing text value will automatically change when language is changed
    t->SetAutoLocalizable(true);
    // The text value used as a string identifier in this mode.
    // Remember that a letter case of the id and of the lang name is important.
    t->SetText("Press this button");

    t->SetAlignment(HA_CENTER, VA_CENTER);
    t->SetStyle("Text");
    SubscribeToEvent(b, E_RELEASED, URHO3D_HANDLER(L10n, HandleChangeLangButtonPressed));

    b = new Button(context_);
    window->AddChild(b);
    b->SetStyle("Button");
    b->SetMinHeight(24);
    t = b->CreateChild<Text>("ButtonTextQuit");
    t->SetAlignment(HA_CENTER, VA_CENTER);
    t->SetStyle("Text");

    // Manually set text in the current language
    t->SetText(l10n->Get("quit"));

    SubscribeToEvent(b, E_RELEASED, URHO3D_HANDLER(L10n, HandleQuitButtonPressed));
}
Пример #11
0
void GameMain::CreateMenu()
{

	ResourceCache* cache = GetSubsystem<ResourceCache>();
	UI* ui = GetSubsystem<UI>();
	UIElement* root = ui->GetRoot();
	//GetSubsystem<Input>()->SetMouseVisible(true);
	root->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

	// New Game
	menu.btnNewGame = new Button(context_);
	root->AddChild(menu.btnNewGame);
	menu.btnNewGame->SetHorizontalAlignment(HA_CENTER);
	menu.btnNewGame->SetVerticalAlignment(VA_CENTER);
	menu.btnNewGame->SetName("NewGame");
	menu.btnNewGame->SetStyleAuto();
	menu.btnNewGame->SetSize(200, 50);
	menu.btnNewGame->SetVar("MENU", Variant(1));


	menu.txtNewGame = new Text(context_);
	menu.btnNewGame->AddChild(menu.txtNewGame);
	menu.txtNewGame->SetStyleAuto();
	menu.txtNewGame->SetHorizontalAlignment(HA_CENTER);
	menu.txtNewGame->SetVerticalAlignment(VA_CENTER);
	menu.txtNewGame->SetVisible(true);
	menu.txtNewGame->SetText("New game");
	menu.txtNewGame->SetVar("MENU", Variant(1));


	// options
	menu.btnOptions = new Button(context_);
	root->AddChild(menu.btnOptions);
	menu.btnOptions->SetHorizontalAlignment(HA_CENTER);
	menu.btnOptions->SetVerticalAlignment(VA_CENTER);
	menu.btnOptions->SetName("Options");
	menu.btnOptions->SetStyleAuto();
	menu.btnOptions->SetSize(200, 50);
	menu.btnOptions->SetPosition(menu.btnNewGame->GetPosition() + IntVector2(0, 55));
	menu.btnOptions->SetVar("MENU", Variant(1));


	menu.txtOptions = new Text(context_);
	menu.btnOptions->AddChild(menu.txtOptions);
	menu.txtOptions->SetStyleAuto();
	menu.txtOptions->SetHorizontalAlignment(HA_CENTER);
	menu.txtOptions->SetVerticalAlignment(VA_CENTER);
	menu.txtOptions->SetVisible(true);
	menu.txtOptions->SetText("Options");
	menu.txtOptions->SetVar("MENU", Variant(1));

	//tone
	menu.optTone = new CheckBox(context_);
	root->AddChild(menu.optTone);
	menu.optTone->SetStyleAuto();
	menu.optTone->SetName("Tone");
	menu.optTone->SetVisible(true);
	menu.optTone->SetHorizontalAlignment(HA_CENTER);
	menu.optTone->SetVerticalAlignment(VA_CENTER);
	menu.optTone->SetPosition(menu.btnOptions->GetPosition() + IntVector2(120, 0));
	menu.optTone->SetVar("MENU", Variant(1));


	menu.txtTone = new Text(context_);
	menu.optTone->AddChild(menu.txtTone);
	menu.txtTone->SetStyleAuto();
	menu.txtTone->SetHorizontalAlignment(HA_LEFT);
	menu.txtTone->SetVerticalAlignment(VA_CENTER);
	menu.txtTone->SetPosition(IntVector2(20, 0));
	menu.txtTone->SetVisible(true);
	menu.txtTone->SetText("Tonemapping");
	menu.txtTone->SetVar("MENU", Variant(1));


	// Exit
	menu.btnExit = new Button(context_);
	root->AddChild(menu.btnExit);

	menu.btnExit->SetHorizontalAlignment(HA_CENTER);
	menu.btnExit->SetVerticalAlignment(VA_CENTER);
	menu.btnExit->SetStyleAuto();
	menu.btnExit->SetSize(200, 50);
	menu.btnExit->SetName("Exit");
	menu.btnExit->SetPosition(menu.btnOptions->GetPosition() + IntVector2(0, 55));
	menu.btnExit->SetVar("MENU", Variant(1));

	menu.txtExit = new Text(context_);
	menu.btnExit->AddChild(menu.txtExit);
	menu.txtExit->SetStyleAuto();
	menu.txtExit->SetHorizontalAlignment(HA_CENTER);
	menu.txtExit->SetVerticalAlignment(VA_CENTER);
	//exitBtnText->SetName("Exit");
	menu.txtExit->SetVisible(true);
	menu.txtExit->SetText("Exit");
	menu.txtExit->SetVar("MENU", Variant(1));


	GetSubsystem<Input>()->SetMouseVisible(true);

	menu.isActive = true;

}
Пример #12
0
void Typography::Start()
{
    // Execute base class startup
    Sample::Start();

    // Enable OS cursor
    GetSubsystem<Input>()->SetMouseVisible(true);

    // Load XML file containing default UI style sheet
    auto* cache = GetSubsystem<ResourceCache>();
    auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");

    // Set the loaded style as default style
    auto* ui = GetSubsystem<UI>();
    UIElement* root = ui->GetRoot();
    root->SetDefaultStyle(style);

    // Create a UIElement to hold all our content
    // (Don't modify the root directly, as the base Sample class uses it)
    uielement_ = new UIElement(context_);
    uielement_->SetAlignment(HA_CENTER, VA_CENTER);
    uielement_->SetLayout(LM_VERTICAL, 10, IntRect(20, 40, 20, 40));
    root->AddChild(uielement_);

    // Add some sample text.
    CreateText();

    // Add a checkbox to toggle the background color.
    CreateCheckbox("White background", URHO3D_HANDLER(Typography, HandleWhiteBackground))
        ->SetChecked(false);

    // Add a checkbox to toggle SRGB output conversion (if available).
    // This will give more correct text output for FreeType fonts, as the FreeType rasterizer
    // outputs linear coverage values rather than SRGB values. However, this feature isn't
    // available on all platforms.
    CreateCheckbox("Graphics::SetSRGB", URHO3D_HANDLER(Typography, HandleSRGB))
        ->SetChecked(GetSubsystem<Graphics>()->GetSRGB());

    // Add a checkbox for the global ForceAutoHint setting. This affects character spacing.
    CreateCheckbox("UI::SetForceAutoHint", URHO3D_HANDLER(Typography, HandleForceAutoHint))
        ->SetChecked(ui->GetForceAutoHint());

    // Add a drop-down menu to control the font hinting level.
    const char* levels[] = {
        "FONT_HINT_LEVEL_NONE",
        "FONT_HINT_LEVEL_LIGHT",
        "FONT_HINT_LEVEL_NORMAL",
        nullptr
    };
    CreateMenu("UI::SetFontHintLevel", levels, URHO3D_HANDLER(Typography, HandleFontHintLevel))
        ->SetSelection(ui->GetFontHintLevel());

    // Add a drop-down menu to control the subpixel threshold.
    const char* thresholds[] = {
        "0",
        "3",
        "6",
        "9",
        "12",
        "15",
        "18",
        "21",
        nullptr
    };
    CreateMenu("UI::SetFontSubpixelThreshold", thresholds, URHO3D_HANDLER(Typography, HandleFontSubpixel))
        ->SetSelection(ui->GetFontSubpixelThreshold() / 3);

    // Add a drop-down menu to control oversampling.
    const char* limits[] = {
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        nullptr
    };
    CreateMenu("UI::SetFontOversampling", limits, URHO3D_HANDLER(Typography, HandleFontOversampling))
        ->SetSelection(ui->GetFontOversampling() - 1);

    // Set the mouse mode to use in the sample
    Sample::InitMouseMode(MM_FREE);
}
void GameEconomicGameClientStateSplash::HandlerSplashUpdate(StringHash eventType, VariantMap& eventData)
{
    /// Get Needed SubSystems
    ResourceCache* cache_ = GetSubsystem<ResourceCache>();
    Renderer* renderer_ = GetSubsystem<Renderer>();
    Graphics* graphics_ = GetSubsystem<Graphics>();
    UI* ui_ = GetSubsystem<UI>();

    /// Check scene status
    if(Existence -> scene_-> GetAsyncProgress()==1&&SplashTimer.GetMSec(false)>3600&&splashcompleted==false)
    {
        /// change splash
        splashcompleted = true;

        /// Create a scene node for the camera, which we will move around
        /// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
        Node * cameraNode_ = Existence -> scene_->GetChild("MainCamera", true);

        /// If camera exist change viewport
        if(cameraNode_)
        {
            /// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
            /// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
            /// use, but now we just use full screen and default render path configured	SetOrthographic ( in the engine command line options
            Existence -> viewport = new Viewport(context_, Existence->scene_, cameraNode_->GetComponent<Camera>());
            renderer_->SetViewport(0, Existence->viewport);

            /// Get current rendering path
            Existence->effectRenderPath =Existence-> viewport->GetRenderPath() -> Clone();

            /// loadd resources
            Existence->effectRenderPath->Append(cache_->GetResource<XMLFile>("PostProcess/Bloom.xml"));
            Existence->effectRenderPath->Append(cache_->GetResource<XMLFile>("PostProcess/FXAA2.xml"));

            /// Make the bloom mixing parameter more pronounced
            Existence->effectRenderPath->SetShaderParameter("BloomMix", Vector2(Existence->GameConfig->VideoBloomParam1,
                    Existence->GameConfig->VideoBloomParam2));
            Existence->effectRenderPath->SetEnabled("Bloom", false);
            Existence->effectRenderPath->SetEnabled("FXAA2", false);

            /// Pointer render path to new
            Existence->viewport->SetRenderPath(Existence->effectRenderPath);

            /// Turn on effects
            Existence->effectRenderPath->ToggleEnabled("Bloom");
            Existence->effectRenderPath->ToggleEnabled("FXAA2");
        }

        /// Change UI
        UIElement * uiRoot_ = ui_->GetRoot();

        BorderImage * Splash = (BorderImage * ) uiRoot_ -> GetChild("Splash", true);

        if(Splash!=NULL)
        {
            /// Remove splash
            Splash -> Remove();
        }


        /// Get rendering window size as floats
        float width = (float)graphics_->GetWidth();
        float height = (float)graphics_->GetHeight();

        /// Create LetterBox Sprite
        Sprite* LetterBoxSprite = new Sprite(context_);
        LetterBoxSprite->SetName("LetterBoxSprite");

        /// Get letter box image
        Texture2D* texture = cache_ ->GetResource<Texture2D>("Resources/Textures/LetterBox.png");

        /// Set letter box properties
        LetterBoxSprite->SetTexture(texture); // Set texture
        LetterBoxSprite->SetSize(width,height);
        LetterBoxSprite->SetAlignment(HA_CENTER, VA_CENTER);

        /// Create letter box image to UIElement
        UIElement * LetterBoxUIElement = new UIElement(context_);
        LetterBoxUIElement->AddChild(LetterBoxSprite);

        /// Add letter box UIElement to ui
        uiRoot_->AddChild(LetterBoxUIElement);

        /// Set style of UIElements
        LetterBoxUIElement->SetOpacity(.8);

        LetterBoxSprite->SetStyleAuto();
        LetterBoxUIElement->SetStyleAuto();

        /// Create HangarsSymbolSmall Sprite
        Sprite* HangarsSymbolSmallSprite = new Sprite(context_);
        HangarsSymbolSmallSprite->SetName("HangarsSymbolSmallSprite");

        /// Get letter box image
        Texture2D* HangarsSymbolTexture = cache_ ->GetResource<Texture2D>("Resources/Textures/HangarsSymbolSmall.png");

        /// Set letter box properties
        HangarsSymbolSmallSprite->SetTexture(HangarsSymbolTexture); // Set texture
        HangarsSymbolSmallSprite->SetSize(HangarsSymbolTexture->GetWidth()/2,HangarsSymbolTexture->GetHeight()/2);
        HangarsSymbolSmallSprite->SetAlignment(HA_LEFT, VA_TOP);

        /// Create letter box image to UIElement
        UIElement * HangarsSymbolSmallUIElement = new UIElement(context_);
        HangarsSymbolSmallUIElement->AddChild(HangarsSymbolSmallSprite);

        /// Add letter box UIElement to ui
        uiRoot_->AddChild(HangarsSymbolSmallUIElement);

        /// Set style of UIElements
        HangarsSymbolSmallUIElement->SetOpacity(.8);
        HangarsSymbolSmallUIElement->SetPosition((width/2)-((HangarsSymbolTexture->GetWidth()/2)/2),250);

        HangarsSymbolSmallSprite->SetStyleAuto();
        HangarsSymbolSmallUIElement->SetStyleAuto();

        /// Load fonts
        Font * Mionta = cache_ ->GetResource<Font>("Resources/Fonts/mionta.ttf");
        Font * Neuton = cache_ ->GetResource<Font>("Resources/Fonts/Neuton-SC-Light.ttf");

        /// Create logo text
        Text * LogoText = new Text(context_);
        LogoText -> SetTextAlignment(HA_CENTER);
        LogoText -> SetFont(Mionta,32);
        LogoText -> SetText("HANGARS");
        LogoText -> SetColor(Color(.9f,.9f,.9f));

        /// Create LetterBox UI Element
        UIElement * LogoTextUIElement = new UIElement(context_);

        LogoTextUIElement->AddChild(LogoText);

        /// Add to UI
        uiRoot_->AddChild(LogoTextUIElement);

        ///TitleText->SetStyleAuto();
        LogoTextUIElement->SetStyleAuto();

        /// Move text to a position
        LogoTextUIElement->SetPosition((width/2)-240,200);

        /// Create a event
        VariantMap gamestatechange;
        gamestatechange[GameState::P_CMD] = GAME_STATE_LOGIN;

        cout << "Debug: Attempt to send a state change" << endl;

        SendEvent(G_STATES_CHANGE,gamestatechange);
    }
    return ;

}