VGUI2: Creating a panel

From Valve Developer Community
Jump to navigation Jump to search


Requerimientos

Haber leido y comprendido (o comprender):

Codigos:

  • C++ (!!!!)
  • Script

Este tutorial es sobre crear una interfaz simple e interactiva:

Entendiendo como funciona VGUI2

Cada dialogo VGUI2 que ves mientras usas juegos basados en source es llamado, básicamente, Panel.

Cada Panel consiste en tres componentes:

  • Scheme (Esquema)
  • Control Settings (Propiedades de control)
  • Code (Código)

The Scheme - El Esquema

El esquema es un archivo de configuración general que almacena información sobre el color de ciertos elementos como botones, comboboxes, labels, etc. Un archivo de esquema típico es SourceScheme.res, por ejemplo. Si planeas crear un panel semejante a los otros paneles en el menu, deberías usar el mismo archivo de esquema que ellos usan.

Control Settings - Propiedades de Control

El archivo de las propiedades de control almacena información sobre la posición relativa de tu panel y de sus elementos.

Cada panel tiene su propio archivo de recuersos. Para crearlos, hay dos maneras: Puedes crear uno por tu cuenta usando un editor como notepad, o puedes usar Valves InGame Resource Editor.

Código

El código es la parte más importante de un panel, desde el código se decide que hacer si el usuario clickea un botón. Para crear y destruir un panel, se usa código. Afortunadamente puedes establecer muchas más cosas que en el(los)archivo(s) de recursos. El códido es la cosa más importante de este tutorial.

Creando un panel

Ok, let us assume we want to create a door, for real this time. Since we are not able to create a door from scratch, the first thing we do is to step by at the building centre. What we ask for, is a basic door. It works, but we have still plans to customize it.

Empezando

La clase panel es la clase base de todos los elementos VGUI2. Para obtener una visión general acerca de todos los elementos VGUI2, demos un vistazo dentro de la carpeta vgui_elements. Por supuesto, no solo compramos un poco de madera en nuestro centro local de construcción.

La clase importante es la clase EditablePanel que hereda desde la clase Panel. Nuestro panel será una nueva clase que hereda desde la clase EditablePanel. Esto resulta en diversas ventajas: podemos codificar metodos relativos al contenido del panel, podemos sobreescribir métodos de la clase base y muchas más cosas útiles.

Puedes crear un nuevo archivo MyPanel.cpp debajo de Source Files dentro del proyecto client.

MyPanel.cpp

// //Los siguientes archivos include son necesarios para compilar tu MyPanel.cpp.
#include "cbase.h"
#include "IMyPanel.h"
using namespace vgui;
#include <vgui/IVGui.h>
#include <vgui_controls/Frame.h>

//CMyPanel class: Tutorial example class
class CMyPanel : public vgui::Frame
{
	DECLARE_CLASS_SIMPLE(CMyPanel, vgui::Frame); 
	//CMyPanel : This Class / vgui::Frame : BaseClass

	CMyPanel(vgui::VPANEL parent); 	// Constructor
	~CMyPanel(){};				// Destructor

protected:
	//VGUI overrides:
	virtual void OnTick();
	virtual void OnCommand(const char* pcCommand);

private:
	//Other used VGUI control Elements:

};

El constructor: El argumento es vgui::VPANEL parent. Después de leer la VGUI Documentation, deberias saber que todo panel tiene un padre y porque lo tiene.

Bajo el codigo de arriba, añade:

// Constuctor: Initializes the Panel
CMyPanel::CMyPanel(vgui::VPANEL parent)
: BaseClass(NULL, "MyPanel")
{
	SetParent( parent );
	
	SetKeyBoardInputEnabled( true );
	SetMouseInputEnabled( true );
	
	SetProportional( true );
	SetTitleBarVisible( true );
	SetMinimizeButtonVisible( false );
	SetMaximizeButtonVisible( false );
	SetCloseButtonVisible( false );
	SetSizeable( false );
	SetMoveable( false );
	SetVisible( true );


	SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme"));

	LoadControlSettings("resource/UI/MyPanel.res");

	vgui::ivgui()->AddTickSignal( GetVPanel(), 100 );
	
	DevMsg("MyPanel has been constructed\n");
}

Las primeras lineas son bastante sencillas de entender. SetScheme es usada para establecer el la fuente del esquema, que es el esquema estándart para Half-Life 2. Conseguimos un puntero al esquema llamando a LoadSchemeFromFile(...). La función LoadControlSettings es usada para cargar el archivo de configuraciones de control de resolución. La última línea esta explicada en la codumentación VGUI2.

Siguiendo al codigo expuesto arriba, añade:

//Class: CMyPanelInterface Class. Used for construction.
class CMyPanelInterface : public IMyPanel
{
private:
	CMyPanel *MyPanel;
public:
	CMyPanelInterface()
	{
		MyPanel = NULL;
	}
	void Create(vgui::VPANEL parent)
	{
		MyPanel = new CMyPanel(parent);
	}
	void Destroy()
	{
		if (MyPanel)
		{
			MyPanel->SetParent( (vgui::Panel *)NULL);
			delete MyPanel;
		}
	}
};
static CMyPanelInterface g_MyPanel;
IMyPanel* mypanel = (IMyPanel*)&g_MyPanel;

A continuación puedes crear IMyPanel.h en el mismo directorio.

IMyPanel.h


// IMyPanel.h
class IMyPanel
{
public:
	virtual void		Create( vgui::VPANEL parent ) = 0;
	virtual void		Destroy( void ) = 0;
};

extern IMyPanel* mypanel;

Calling the panel

Para llamar al panel, añadimos unas pocas lineas en el archivo vgui_int.cpp. Vgui_int.cpp incluye funciones que llaman a todos los paneles. La función VGui_CreateGlobalPanels() es donde la adición de los paneles tiene lugar.

This is the point, where you have to decide when the panel should show up. Either you create a panel that can be accessed during the game, or you create a panel for the main menu.

I assume that you want to create a panel for the game.

So, after including the panel, you should add

mypanel->Create(gameParent);

and check to see if gameParent has been declared at the top of the function, if it hasn't then add

VPANEL gameParent = enginevgui->GetPanel( PANEL_CLIENTDLL );

Note: To have your screen appear in-game like the Counter-Strike buy menus or team selection menus, change PANEL_CLIENTDLL to PANEL_INGAMESCREENS , otherwise it will be visible only when you press Escape to go to the game menu.

Then add

mypanel->Destroy();


to the VGui_Shutdown() function.

If you plan to create a panel for the main menu, you need to put this into the construction function (VGui_CreateGlobalPanels()):

VPANEL GameUiDll = enginevgui->GetPanel( PANEL_GAMEUIDLL);
mypanel->Create(GameUiDll);

This will cause the panel to appear when you start your mod.

The control settings

Everything is working, so start the game, and check if you see your panel. Now you have the chance to press CTRL+ALT+SHIFT+B in order to use the VGUI2 Builder. You can drag around the panel and set some properties as well as adding some elements. Do not forget to save your work afterwards.

Adding elements

There are two ways to add new elements. The one way is to use the VGUI2 Builder. Since the VGUI2 Builder doesn’t come with all the essential elements, you should add elements in your code. Therefore, you have the choice in-between 50 elements, individually stored in the vgui_controls folder. Indeed, even this is pretty easy. You add a pointer into the class declaration. Here is an example:

vgui::TextEntry* m_pTime; // Panel class declaration, private section

Add this to the panels constructor:

m_pTime = new vgui::TextEntry(this, "MyTextEntry");
m_pTime->SetPos(15, 310);
m_pTime->SetSize(50, 20);

You'll also have to add the following include to get the constructors for TextEntry:

#include <vgui_controls/TextEntry.h>

Other stuff

Let's do some console stuff. For example, we could need a variable which allows us to set the state of our panel.
Here is an example:

MyPanel.cpp

Underneath all of the other code, add:

ConVar cl_showmypanel("cl_showmypanel", "1", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

This code doesn’t need some explanation, so we continue by adding a method to our class:

void CMyPanel::OnTick()
{
	BaseClass::OnTick();
	SetVisible(cl_showmypanel.GetBool()); //CL_SHOWMYPANEL / 1 BY DEFAULT
}

A command to toggle the panel on or off:

CON_COMMAND(ToggleMyPanel, "Toggles myPanel on or off")
{
	cl_showmypanel.SetValue(!cl_showmypanel.GetBool());
};

Interactive Elements

In the last part of this tutorial we will add some functionality to a button.

void CMyPanel::OnCommand(const char* pcCommand)
{
	if(!Q_stricmp(pcCommand, "turnoff"))
		cl_showmypanel.SetValue(0);
}

You can add a button (using the built-in editor) and set the command value of the button to "turnoff". If the player clicks this button, well, the panel disappers.

Main Menu

To link to your new panel from the main menu, open up GameMenu.res in your /resource/ folder. Add:

	"5"
	{
		"label" "My Panel"
		"command" "engine ToggleMyPanel"
		"notmulti" "1"
	}

And change ConVar cl_showmypanel("cl_showmypanel", "1", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

To: ConVar cl_showmypanel("cl_showmypanel", "0", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

So that it won't pop up before the user clicks it.

You may also want to add mypanel->Activate(); underneath cl_showmypanel.SetValue(!cl_showmypanel.GetBool());. This will focus on your panel. To be able to use the Activate() command, you will need to add:

	void Activate( void )
	{
		if ( MyPanel )
		{
			MyPanel->Activate();
		}
	}

Underneath:

	void Destroy( void )
	{
		if ( MyPanel )
		{
			MyPanel->SetParent( (vgui::Panel *)NULL );
			delete MyPanel;
		}
	}

In MyPanel.cpp.

And add:

virtual void		Activate( void ) = 0;

Underneath:

virtual void		Destroy( void ) = 0;

In IMyPanel.h.

If you want the user to be able to close your panel without having to click the My Panel menu option, add a Button with the command "turnoff" to your panel.

See also