Пример #1
0
DWORD CGUIPage::OnMouseMove(DWORD size, void *params)
{
	DWORD retVal;
	if (m_bActive)
	{
		OBJECTLIST::iterator olIter = m_ObjectList.begin();
		IGUIElement *guiElement;
		for(; olIter != m_ObjectList.end(); olIter++)
		{
			guiElement = dynamic_cast<IGUIElement*> (*olIter);
			if(!guiElement)
			{	
				EngineGetToolBox()->SetErrorValue(ERR_NULL_POINTER);
				EngineGetToolBox()->Log(LOGERROR, _T("Could not grab IGUIElement from list of gui elements"));
				return MSG_ERROR;
			}
			retVal = guiElement->OnMousePosition(size, params);
			if(retVal == MSG_HANDLED_STOP || retVal == MSG_ERROR)
			{
				return retVal;
			}
		}
	}
	return MSG_HANDLED_PROCEED;
}
void CGUIEnvironment::updateHoveredElement(core::position2d<s32> mousePos)
{
	IGUIElement* lastHovered = Hovered;

	Hovered = getElementFromPoint(mousePos);

	if (Hovered)
	{
		Hovered->grab();

		if (Hovered != lastHovered)
		{
			SEvent event;
			event.EventType = EET_GUI_EVENT;

			if (lastHovered)
			{
				event.GUIEvent.Caller = lastHovered;
				event.GUIEvent.EventType = EGET_ELEMENT_LEFT;
				lastHovered->OnEvent(event);
			}

			event.GUIEvent.Caller = Hovered;
			event.GUIEvent.EventType = EGET_ELEMENT_HOVERED;
			Hovered->OnEvent(event);
		}
	}

	if (lastHovered)
		lastHovered->drop();
}
Пример #3
0
void KGUIWin32Wnd::UpdateHoveredElement(const KDS_EVENT& event)
{
	KPoint point(event.MouseEvent.X, event.MouseEvent.Y);

	if (GetChildCount() <= 0)
		return ;

	// Window element has only one child.
	IGUIElement * pGUIOver = this->GetChild(0)->HitTest(point);
	if (m_pGUIHover != pGUIOver)
	{
		if (m_pGUIHover != NULL)
		{
			KDS_EVENT msg;
			memset(&msg, 0, sizeof(msg));
			msg.EventType = KET_MOUSE;
			msg.MouseEvent = event.MouseEvent;
			msg.MouseEvent.Event = KME_MOUSE_LEAVE;			// Mouse leave message
			m_pGUIHover->OnEvent(msg);
		}
		if (pGUIOver != NULL)
		{
			KDS_EVENT msg;
			memset(&msg, 0, sizeof(msg));
			msg.EventType = KET_MOUSE;
			msg.MouseEvent = event.MouseEvent;
			msg.MouseEvent.Event	= KME_MOUSE_ENTER;		// Mouse enter message
			pGUIOver->OnEvent(msg);
		}
	}

	m_pGUIHover = pGUIOver;
}
Пример #4
0
/*
Finally, the third function creates a toolbox window. In this simple mesh
viewer, this toolbox only contains a tab control with three edit boxes for
changing the scale of the displayed model.
*/
void createToolBox()
{
	// remove tool box if already there
	IGUIEnvironment* env = Device->getGUIEnvironment();
	IGUIElement* root = env->getRootGUIElement();
	IGUIElement* e = root->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW, true);
	if (e)
		e->remove();

	// create the toolbox window
	IGUIWindow* wnd = env->addWindow(core::rect<s32>(600,45,800,480),
		false, L"Toolset", 0, GUI_ID_DIALOG_ROOT_WINDOW);

	// create tab control and tabs
	IGUITabControl* tab = env->addTabControl(
		core::rect<s32>(2,20,800-602,480-7), wnd, true, true);

	IGUITab* t1 = tab->addTab(L"Config");

	// add some edit boxes and a button to tab one
	env->addStaticText(L"Scale:",
			core::rect<s32>(10,20,60,45), false, false, t1);
	env->addStaticText(L"X:", core::rect<s32>(22,48,40,66), false, false, t1);
	env->addEditBox(L"1.0", core::rect<s32>(40,46,130,66), true, t1, GUI_ID_X_SCALE);
	env->addStaticText(L"Y:", core::rect<s32>(22,82,40,96), false, false, t1);
	env->addEditBox(L"1.0", core::rect<s32>(40,76,130,96), true, t1, GUI_ID_Y_SCALE);
	env->addStaticText(L"Z:", core::rect<s32>(22,108,40,126), false, false, t1);
	env->addEditBox(L"1.0", core::rect<s32>(40,106,130,126), true, t1, GUI_ID_Z_SCALE);

	env->addButton(core::rect<s32>(10,134,85,165), t1, GUI_ID_BUTTON_SET_SCALE, L"Set");

	// quick scale buttons
	env->addButton(core::rect<s32>(65,20,95,40), t1, GUI_ID_BUTTON_SCALE_MUL10, L"* 10");
	env->addButton(core::rect<s32>(100,20,130,40), t1, GUI_ID_BUTTON_SCALE_DIV10, L"* 0.1");

	updateScaleInfo(Model);

	// add transparency control
	env->addStaticText(L"GUI Transparency Control:",
			core::rect<s32>(10,200,150,225), true, false, t1);
	IGUIScrollBar* scrollbar = env->addScrollBar(true,
			core::rect<s32>(10,225,150,240), t1, GUI_ID_SKIN_TRANSPARENCY);
	scrollbar->setMax(255);
	scrollbar->setPos(255);

	// add framerate control
	env->addStaticText(L":", core::rect<s32>(10,240,150,265), true, false, t1);
	env->addStaticText(L"Framerate:",
			core::rect<s32>(12,240,75,265), false, false, t1);
	// current frame info
	env->addStaticText(L"", core::rect<s32>(75,240,200,265), false, false, t1,
			GUI_ID_ANIMATION_INFO);
	scrollbar = env->addScrollBar(true,
			core::rect<s32>(10,265,150,280), t1, GUI_ID_SKIN_ANIMATION_FPS);
	scrollbar->setMax(MAX_FRAMERATE);
	scrollbar->setMin(-MAX_FRAMERATE);
	scrollbar->setPos(DEFAULT_FRAMERATE);
	scrollbar->setSmallStep(1);
}
Пример #5
0
/* ----------------------------------------------------------------------------
remove a GUI object from the display
*/
void DLL_EXPORT IrrGUIRemove( IGUIElement *element )
{
	if ( element )
	{
		IGUIElement * parent = element->getParent();
		if ( parent ) parent->removeChild( element );
	}
}
Пример #6
0
DWORD CGUIPage::OnGetObjectInsideRect(DWORD size, void *params)
{
	DWORD retVal;

	OBJECTLIST::iterator olIter;
	IGUIElement *object;
	OBJINRECT *data;
	
	VERIFY_MESSAGE_SIZE(size, sizeof(OBJINRECT));
	data = (OBJINRECT*)params;

	int x1 = data->x1;
	int x2 = data->x2;
	int y1 = data->y1;
	int y2 = data->y2;

	POSITIONDATA pd;
	IHashString *guiName;

	for(olIter = m_ObjectList.begin();
		olIter != m_ObjectList.end();
		olIter++)
	{
		object = dynamic_cast<IGUIElement*>(*olIter);
		if(!object)
		{	
			m_ToolBox->SetErrorValue(ERR_NULL_POINTER);
			m_ToolBox->Log(LOGERROR, _T("Could not grab IGUIElement from list of gui elements"));
			return MSG_ERROR;
		}
		
		guiName = object->GetName();

		static DWORD msgHash_GetPosition = CHashString(_T("GetPosition")).GetUniqueID();
		retVal = m_ToolBox->SendMessage(msgHash_GetPosition, sizeof(POSITIONDATA), &pd, guiName);
		if(retVal != MSG_HANDLED)
		{
			m_ToolBox->Log(LOGERROR, _T("Could not send GetPosition message to %s\n"), guiName->GetString());
			return MSG_ERROR;
		}

		if( InsideRect((int)pd.m_fXPos, (int)pd.m_fYPos, 
			data->x1, data->y1, data->x2, data->y2) )
		{
			data->list.push_back(object);
		}
	}
	if (data->list.empty())
	{
		return MSG_HANDLED_PROCEED;
	}
	else
	{
		return MSG_HANDLED_STOP;
	}
}
Пример #7
0
void Game::RocketLibInit()
{
    // Generic OS initialisation, creates a window and attaches OpenGL.
#ifndef _WIN64 //TODO: Improve paths
    char* path = "../";
#else
    char* path = "../../";
#endif
    if (!RocketLibSystem::Initialise(path) ||
            !RocketLibSystem::OpenWindow(L"Pulse", true))
    {
        RocketLibSystem::Shutdown();
        return;
    }

    // Rocket initialisation.
    Rocket::Core::SetRenderInterface(m_pOpenGLRenderer);
    Rocket::Core::SetSystemInterface(m_pSystemInterface);
    Rocket::Core::Initialise();
    Rocket::Controls::Initialise();

    // Create the main Rocket context and set it on the RocketLibSystem's input layer.
    Rocket::Core::Vector2i contextSize;
    int WindowSize[4];
    RocketLibSystem::GetViewport( WindowSize );
    contextSize.x = WindowSize[2];
    contextSize.y = WindowSize[3];
    m_pRocketContext = Rocket::Core::CreateContext("main", contextSize);
    if (m_pRocketContext == NULL)
    {
        Rocket::Core::Shutdown();
        RocketLibSystem::Shutdown();
        return;
    }

    m_pEnv->sys->pGUISystem->SetContext(m_pRocketContext);

    Rocket::Debugger::Initialise(m_pRocketContext);
    Input::SetContext(m_pRocketContext);

    RocketLibSystem::LoadFonts("/Assets/GUI/");

    // Set the Rocketlib logger font size
    IGUIElement* pElement = m_pEnv->sys->pGUISystem->GetLogElement();
    if (pElement)
    {
        pElement->SetProperty("font-size", "18pt");
        pElement->RemoveReference();
    }

    Rocket::Core::GetSystemInterface()->LogMessage(Rocket::Core::Log::LT_INFO, "Hello");

}
Пример #8
0
/*
Function hasModalDialog() checks if we currently have a modal dialog open.
*/
bool hasModalDialog()
{
	IGUIEnvironment* env = Device->getGUIEnvironment();
	IGUIElement * focused = env->getFocus();
	while ( focused )
	{
		if ( focused->isVisible() && focused->hasType(EGUIET_MODAL_SCREEN) )
			return true;
		focused = focused->getParent();
	}
	return false;
}
Пример #9
0
bool viewprt::checkForWindow(s32 element, s32 x, s32 y)
{
   IGUIEnvironment* env = device->getGUIEnvironment();
   IGUIElement* root = env->getRootGUIElement();
   IGUIElement* e = root->getElementFromId(element, true);
   if (e) {
            core::rect< s32 > infos;
            infos=e->getAbsolutePosition();
            return infos.isPointInside(position2d<s32>(x,y));
      }
   return false;
}
Пример #10
0
bool Desktop::OnGUIElementClosed(irr::SEvent::SGUIEvent event)
{
  IGUIElement* pElem = event.Caller;
  switch ( pElem->getType() )
  {
  case	EGUIET_WINDOW:
    {
      InGameAppWindow* pWnd = NULL;

      m_mutexApps.Lock();
      AppWindowVector::iterator it = m_arrApps.begin();
      while ( it != m_arrApps.end() )
      {
	      if ( (*it)->GetGUIWindow() == pElem )
	      {
          // get the InGameAppWindow object
		      pWnd = (*it);
          // remove it from the active apps list
		      m_arrApps.erase(it);
          // notify the AppBar that the app has closed
          if ( m_pAppBar )
            m_pAppBar->setActiveApp(NULL);
          // notify the model that the app has been closed
          FCViewEvent e(VE_AppClosed, pWnd->GetOptionID());
          m_owner.GetContainer()->GetController()->OnViewEvent(e);
          // delete the InGameAppWindow Object
		      delete pWnd;
          // set focus back to the desktop
          Environment->setFocus(this);
		      break;
	      }
	      it++;
      }
      m_mutexApps.Unlock();
    }
    break;

  case  EGUIET_ELEMENT:
    {
      FCDialog* pDlg = NULL;

      if ( (pElem == (IGUIElement*)GetUtilityWindow(pElem)) )
      {
        CloseUtilityWindow(pElem);
      }
    }
    break;
  }

  return false;
}
Пример #11
0
// add a gui element to the page list
DWORD CGUIPage::OnAddGUIElementToPage(DWORD size, void *params)
{
	OBJECTLIST::iterator olIter;
	GUIPAGEMESSAGE *gpm;
	IObject *guiObject;
	static CHashString managerName(_T("CGUIManager"));
	CGUIManager *manager;

	// make sure message is valid
	VERIFY_MESSAGE_SIZE(size, sizeof(GUIPAGEMESSAGE));

	// downcast parameters to struct we expect
	gpm = (GUIPAGEMESSAGE *)params;

	// ask gui manager for the object to add
	manager = dynamic_cast<CGUIManager*>(EngineGetToolBox()->GetComponent( &managerName ));
	if (!manager)
	{
		EngineGetToolBox()->SetErrorValue(ERR_NULL_POINTER);
		EngineGetToolBox()->Log(LOGERROR, _T("could not cast IComponent from EngineToolBox to CGUIManager\n")); 
		return MSG_ERROR;
	}
	guiObject = manager->GetObject(gpm->name, gpm->compType);
	if(guiObject == NULL)
	{
		EngineGetToolBox()->SetErrorValue(ERR_NULL_POINTER);
		EngineGetToolBox()->Log(LOGERROR, _T("could not get the gui object from the gui manager: %s object not found\n"), gpm->name);
		return MSG_ERROR;
	}

	// check if object is already on list
	for(olIter = m_ObjectList.begin(); olIter != m_ObjectList.end(); olIter++)
	{
		if ( (*olIter)->GetName()->GetUniqueID() == guiObject->GetName()->GetUniqueID() )
		{
			// object is already on page
			return MSG_NOT_HANDLED;
		}
	}
	// now add object to list
	m_ObjectList.push_back(guiObject);
	m_SortedMap.clear();
	IGUIElement *guiElement = dynamic_cast<IGUIElement*>(guiObject);
	guiElement->SetWidthRatio(m_fWidthRatio);
	guiElement->SetHeightRatio(m_fHeightRatio);
	guiElement->SetZoomFactor(m_fZoomFactor);
	guiElement->SetPageOffset(m_iPageOffsetX, m_iPageOffsetY);
	return MSG_HANDLED_STOP;
}
Пример #12
0
void CGUIPage::SortGUIElements()
{
	IGUIElement *guiElement;
	OBJECTLIST::iterator olIter = m_ObjectList.begin();
	
	// clear sorted map
	m_SortedMap.clear();

	while(olIter != m_ObjectList.end())
	{
		guiElement = dynamic_cast<IGUIElement*>((*olIter));
		if(guiElement == NULL)
		{
			m_ToolBox->SetErrorValue(ERR_NULL_POINTER);
			m_ToolBox->Log(LOGERROR, _T("Could not cast to IGUIElement: %s"), (*olIter)->GetName());
			continue;
		}
		// insert gui element into sorted map
		m_SortedMap.insert(make_pair(guiElement->GetZOrder(), guiElement));		

		IHashString *type = guiElement->GetComponentType();		
		if (type)
		{
			static DWORD dwGroup = CHashString(_T("CGUIGroup")).GetUniqueID();
			if (type->GetUniqueID() == dwGroup)
			{
				CGUIGroup *group = dynamic_cast<CGUIGroup*>(guiElement);
				if (group)
				{
					group->SortElements();
				}
			}
		}

		olIter++;
	}
	
	// now clear object list
	m_ObjectList.clear();

	SORTEDGUIMAP::iterator sgmIter = m_SortedMap.begin();
	while(sgmIter != m_SortedMap.end())
	{
		// added the gui elements into the list in sorted order
		m_ObjectList.push_back(sgmIter->second);	
		sgmIter++;
	}
}
Пример #13
0
EventPropagation BubbleWidget::focused(const int playerID)
{
    if (m_element != NULL)
    {
        // bring element to top (with a hack because irrlicht does not appear to offer a built-in way to do this)
        m_element->grab();

        IGUIElement* parent = m_parent;
        if (parent == NULL) parent = GUIEngine::getGUIEnv()->getRootGUIElement();

        parent->removeChild(m_element);
        parent->addChild(m_element);
        m_element->drop();
    }
    return EVENT_LET;
}
Пример #14
0
	/*
		Handle key-up events
	*/
	bool OnKeyUp(irr::EKEY_CODE keyCode)
	{
		// Don't handle keys if we have a modal dialog open as it would lead 
		// to unexpected application behaviour for the user.
		if ( hasModalDialog() )
			return false;
		
		if (keyCode == irr::KEY_ESCAPE)
		{
			if (Device)
			{
				scene::ICameraSceneNode * camera =
					Device->getSceneManager()->getActiveCamera();
				if (camera)
				{
					camera->setInputReceiverEnabled( !camera->isInputReceiverEnabled() );
				}
				return true;
			}
		}
		else if (keyCode == irr::KEY_F1)
		{
			if (Device)
			{
				IGUIElement* elem = Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_POSITION_TEXT);
				if (elem)
					elem->setVisible(!elem->isVisible());
			}
		}
		else if (keyCode == irr::KEY_KEY_M)
		{
			if (Device)
				Device->minimizeWindow();
		}
		else if (keyCode == irr::KEY_KEY_L)
		{
			UseLight=!UseLight;
			if (Model)
			{
				Model->setMaterialFlag(video::EMF_LIGHTING, UseLight);
				Model->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, UseLight);
			}
		}
		return false;
	}
Пример #15
0
/** Makes a new roll for RandomLvl perso attributes
  *
  * This class is static to get access to thegsCreatePerso::getHandlerList()
  * function.
  *
  * The tThis pointer get access to the current erCreatePerso instance but 
  * none test is done, so if this pointer is NULL, this cause a segfault.
  *
  * \param root The root IGUIElement pointer
  * \param tThis A pointer to the current erCreatePerso instance
  */
void RainbruRPG::Events::erCreatePerso::roll(IGUIElement* root,
					     erCreatePerso* tThis){
  LOGI("Rolling new perso");

  IGUIElement* guiE;
  stringw win;

  int lGet=0;
  int lAvail=0;
  int ran=0;

  AttrbHandlerList* handlerList=gsCreatePerso::getHandlerList();

  AttrbHandlerList::const_iterator iter;
    // Iterate through list and output each element.
    for (iter=handlerList->begin(); iter != handlerList->end(); iter++){
      ran=getRandomInteger(RANDOM_LVL_MIN,RANDOM_LVL_MAX );
      win=StringConv::getSingleton().itow(ran);
      lGet+=ran;
      lAvail+=10;

      if (  (*iter)->type== AT_RANDOM_LVL){
	guiE=root->getElementFromId((*iter)->irrId, true);
	if (guiE)
	  guiE->setText(win.c_str());
	else
	  LOGE("Cannot change AT_RANDOM_LVL text");
      }

    }

  tThis->setLevelGet(lGet);
  tThis->setLevelAvail(lAvail);
  // Get the level get/total static text
  guiE=root->getElementFromId(10000, true);

  ostringstream oss;
  oss << "Levels (get/total available) : ";
  oss << lGet;
  oss << "/";
  oss << lAvail;

  stringw wi=StringConv::getSingleton().stow(oss.str());
  guiE->setText(wi.c_str());
}
Пример #16
0
touch_gui_button_id TouchScreenGUI::getButtonID(s32 x, s32 y)
{
	IGUIElement* rootguielement = m_guienv->getRootGUIElement();

	if (rootguielement != NULL) {
		gui::IGUIElement *element =
				rootguielement->getElementFromPoint(core::position2d<s32>(x,y));

		if (element) {
			for (unsigned int i = 0; i < after_last_element_id; i++) {
				if (element == m_buttons[i].guibutton) {
					return (touch_gui_button_id) i;
				}
			}
		}
	}
	return after_last_element_id;
}
Пример #17
0
/*
  Update the display of the model scaling
*/
void updateScaleInfo(scene::ISceneNode* model)
{
	IGUIElement* toolboxWnd = Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_DIALOG_ROOT_WINDOW, true);
	if (!toolboxWnd)
		return;
	if (!model)
	{
		toolboxWnd->getElementFromId(GUI_ID_X_SCALE, true)->setText( L"-" );
		toolboxWnd->getElementFromId(GUI_ID_Y_SCALE, true)->setText( L"-" );
		toolboxWnd->getElementFromId(GUI_ID_Z_SCALE, true)->setText( L"-" );
	}
	else
	{
		core::vector3df scale = model->getScale();
		toolboxWnd->getElementFromId(GUI_ID_X_SCALE, true)->setText( core::stringw(scale.X).c_str() );
		toolboxWnd->getElementFromId(GUI_ID_Y_SCALE, true)->setText( core::stringw(scale.Y).c_str() );
		toolboxWnd->getElementFromId(GUI_ID_Z_SCALE, true)->setText( core::stringw(scale.Z).c_str() );
	}
}
Пример #18
0
/// Sets the zoom for this page and all underlying gui elements
/// \param value - value to set zoom to
void CGUIPage::SetZoomFactor(float value)
{	
	m_fZoomFactor = value;

	IGUIElement *guiElement;
	OBJECTLIST::iterator olIter = m_ObjectList.begin();
	
	while(olIter != m_ObjectList.end())
	{
		guiElement = dynamic_cast<IGUIElement*>((*olIter));
		if(guiElement == NULL)
		{
			m_ToolBox->SetErrorValue(ERR_NULL_POINTER);
			m_ToolBox->Log(LOGERROR, _T("Could not cast to IGUIElement: %s"), (*olIter)->GetName());
		}
		
		guiElement->SetZoomFactor(value);
		olIter++;
	}
}
Пример #19
0
void SSGUIStatusBar::draw()
{
	IVideoDriver *driver = Environment->getVideoDriver();

	if (!IsVisible)
		return;

	if (Background)
	{
		driver->draw2DImage(Background, AbsoluteRect.UpperLeftCorner, rect<s32>(position2d<s32>(0,0), Background->getOriginalSize()), 0, SColor(255,255,255,255), true);

		IGUIElement *ElementUnderCursor = Environment->getRootGUIElement()->getElementFromPoint(CursorControl->getPosition());

		s32 index = -1;
		
		while (ElementUnderCursor && ElementUnderCursor != this && ElementUnderCursor != Environment->getRootGUIElement() && index == -1)
		{
			index = RegisteredElements.binary_search(ElementUnderCursor);

			if (ElementUnderCursor != this && index == -1)
				ElementUnderCursor = ElementUnderCursor->getParent();
		}

		if (index >= 0 || ElementUnderCursor == this)
		{
			if (ElementUnderCursor->getType() == EGUIET_BUTTON)
				Label.Text = ((SSGUIButton*)ElementUnderCursor)->getHelpText().c_str();
			if (ElementUnderCursor->getType() == EGUIET_SCROLL_BAR)
				Label.Text = ((SSGUIScrollBar*)ElementUnderCursor)->getHelpText().c_str();
			if (ElementUnderCursor->getType() == EGUIET_WINDOW)
				Label.Text = ((SSGUISatelliteInfoWindow*)ElementUnderCursor)->getHelpText().c_str();
			if (ElementUnderCursor == this)
				Label.Text = HelpText.c_str();

			if (Label.Text)
				Label.Font->draw(Label.Text, Label.Rect, Label.Color, false, true);
		}
		else
			Label.Text = 0;
	}
}
Пример #20
0
DWORD CGUIPage::OnGetPageItemList(DWORD size, void *param)
{
	VERIFY_MESSAGE_SIZE(size, sizeof(GUIELEMLIST));
	GUIELEMLIST *gel = (GUIELEMLIST*) param;
	
	IGUIElement *guiElement;
	OBJECTLIST::iterator olIter = m_ObjectList.begin();
	while(olIter != m_ObjectList.end())
	{
		guiElement = dynamic_cast<IGUIElement*>((*olIter));
		if(guiElement == NULL)
		{
			m_ToolBox->SetErrorValue(ERR_NULL_POINTER);
			m_ToolBox->Log(LOGERROR, _T("Could not cast to IGUIElement: %s"), (*olIter)->GetName());
		}
		gel->m_vNames.push_back(guiElement->GetName()->GetString());
		gel->m_vTypes.push_back(guiElement->GetComponentType()->GetString());
		olIter++;
	}
	return MSG_HANDLED_STOP;
}
Пример #21
0
UINT CGUIPage::UpdatePageItemVertexBuffer(void **pDest, UINT offset, IVertexBufferObject *vb)
{
	UINT writtenVerts = 0, curOffset = offset;
	
	OBJECTLIST::iterator olIter = m_ObjectList.begin();
	IGUIElement *guiElement;
	for(; olIter != m_ObjectList.end(); olIter++)
	{
		guiElement = dynamic_cast<IGUIElement*> (*olIter);
		if(!guiElement)
		{	
			EngineGetToolBox()->SetErrorValue(ERR_NULL_POINTER);
			EngineGetToolBox()->Log(LOGERROR, _T("Could not grab IGUIElement from list of gui elements"));
			return MSG_ERROR;
		}
		UINT tempWritten = guiElement->UpdateBuffer(pDest, curOffset, vb);
		writtenVerts += tempWritten;
		curOffset += tempWritten;
	}		
	return writtenVerts;
}
Пример #22
0
DWORD CGUIPage::OnGetObjectUnderCursor(DWORD size, void *params)
{
	OBJECTLIST::iterator olIter;
	IGUIElement *lesserGE = NULL;
	IGUIElement *newGE;
	OBJUNDERCURSOR *data;
	
	VERIFY_MESSAGE_SIZE(size, sizeof(OBJUNDERCURSOR));
	data = (OBJUNDERCURSOR*)params;

	float fCursorPosX = data->m_fPosX;
	float fCursorPosY = data->m_fPosY;

	data->m_Name = NULL;
	data->m_CompType = NULL;

	for(olIter = m_ObjectList.begin();
		olIter != m_ObjectList.end();
		olIter++)
	{
		newGE = dynamic_cast<IGUIElement*>(*olIter);
		if(!newGE)
		{	
			EngineGetToolBox()->SetErrorValue(ERR_NULL_POINTER);
			EngineGetToolBox()->Log(LOGERROR, _T("Could not grab IGUIElement from list of gui elements"));
			return MSG_ERROR;
		}
		if(newGE->IsCursorOver(fCursorPosX, fCursorPosY))
		{
			if(lesserGE==NULL)
			{	
				lesserGE = newGE;
			}
			else if( lesserGE->GetZOrder() > newGE->GetZOrder() )
			{
					lesserGE = newGE;
			}
		}
	}
	if(lesserGE)
	{
		data->m_Name = lesserGE->GetName();
		data->m_CompType = lesserGE->GetComponentType();
	}

	if(data->m_Name == NULL)
	{	
		return MSG_HANDLED_PROCEED;
	}
	else
	{
		return MSG_HANDLED_STOP;
	}

}
Пример #23
0
	/*
		Handle key-up events
	*/
	bool OnKeyUp(irr::EKEY_CODE keyCode)
	{
		if (keyCode == irr::KEY_ESCAPE)
		{
			if (Device)
			{
				scene::ICameraSceneNode * camera =
					Device->getSceneManager()->getActiveCamera();
				if (camera)
				{
					camera->setInputReceiverEnabled( !camera->isInputReceiverEnabled() );
				}
				return true;
			}
		}
		else if (keyCode == irr::KEY_F1)
		{
			if (Device)
			{
				IGUIElement* elem = Device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(GUI_ID_POSITION_TEXT);
				if (elem)
					elem->setVisible(!elem->isVisible());
			}
		}
		else if (keyCode == irr::KEY_KEY_M)
		{
			if (Device)
				Device->minimizeWindow();
		}
		else if (keyCode == irr::KEY_KEY_L)
		{
			UseLight=!UseLight;
			if (Model)
			{
				Model->setMaterialFlag(video::EMF_LIGHTING, UseLight);
				Model->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, UseLight);
			}
		}
		return false;
	}
Пример #24
0
int run(IrrlichtDevice *device)
{
    while (device->run())
        if (device->isWindowActive()) {
            device->getVideoDriver()->beginScene(true, true, SColor(0, 100, 100, 100));
            device->getSceneManager()->drawAll();
            device->getGUIEnvironment()->drawAll();
            device->getVideoDriver()->endScene();

            IGUIElement *stat = device->getGUIEnvironment()->getRootGUIElement()->getElementFromId(
                    100);
            if (stat) {
                stringw str = L"FPS: ";
                str += (s32) device->getVideoDriver()->getFPS();

                stat->setText(str.c_str());
            }
        }

    device->drop();
    return 0;
}
//! called if an event happened.
bool CGUITextureCacheBrowser::OnEvent(const SEvent &event)
{
	switch(event.EventType)
	{
	case EET_GUI_EVENT:
		if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
		{
			if (event.GUIEvent.Caller == (IGUIElement*)this)
				Dragging = false;
			return true;
		}
		else
		if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
		{
			if (event.GUIEvent.Caller == CloseButton)
			{
				remove();
				return true;
			}
		}
		break;
	case EET_MOUSE_INPUT_EVENT:
		switch(event.MouseInput.Event)
		{
		case EMIE_LMOUSE_PRESSED_DOWN:
			DragStart.X = event.MouseInput.X;
			DragStart.Y = event.MouseInput.Y;

			if (getElementFromPoint(DragStart) == this)
			{
				if (!Environment->hasFocus(this))
				{
					Dragging = true;
					//Environment->setFocus(this);
					if (Parent)
						Parent->bringToFront(this);
				}
				return true;
			}
			else
			{
				if (Panel->getAbsolutePosition().isPointInside(DragStart))
				{
					// select an image
					IGUIElement* el = Panel->getElementFromPoint(DragStart);
					if (el && el != Panel)
					{
						if (el->getType() == EGUIET_IMAGE)
						{
							setSelected(el->getID());
						}
					}
					else
					{
						setSelected();
					}
				}
			}
			break;
		case EMIE_LMOUSE_LEFT_UP:
			Dragging = false;
			//Environment->removeFocus(this);
			return true;
		case EMIE_MOUSE_MOVED:
			if (Dragging)
			{
				// gui window should not be dragged outside its parent
				if (Parent)
					if (event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
						event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
						event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
						event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1)

						return true;
					

				move(core::position2d<s32>(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y));
				DragStart.X = event.MouseInput.X;
				DragStart.Y = event.MouseInput.Y;
				return true;
			}
			break;
		}
	}

	return Parent ? Parent->OnEvent(event) : false;
}
Пример #26
0
void GUIConfirmRegistration::regenerateGui(v2u32 screensize)
{
	acceptInput();
	removeChildren();

	/*
		Calculate new sizes and positions
	*/
	core::rect<s32> rect(screensize.X / 2 - 600 / 2, screensize.Y / 2 - 360 / 2,
			screensize.X / 2 + 600 / 2, screensize.Y / 2 + 360 / 2);

	DesiredRect = rect;
	recalculateAbsolutePosition(false);

	v2s32 size = rect.getSize();
	v2s32 topleft_client(0, 0);

	const wchar_t *text;

	/*
		Add stuff
	*/
	s32 ypos = 30;
	{
		std::string address = m_address;
		if (address.empty())
			address = "localhost";
		core::rect<s32> rect2(0, 0, 540, 180);
		rect2 += topleft_client + v2s32(30, ypos);
		static const std::string info_text_template = strgettext(
				"You are about to join the server at %1$s with the "
				"name \"%2$s\" for the first time. If you proceed, a "
				"new account using your credentials will be created "
				"on this server.\n"
				"Please retype your password and click Register and "
				"Join to confirm account creation or click Cancel to "
				"abort.");
		char info_text_buf[1024];
		porting::mt_snprintf(info_text_buf, sizeof(info_text_buf),
				info_text_template.c_str(), address.c_str(),
				m_playername.c_str());

		wchar_t *info_text_buf_wide = utf8_to_wide_c(info_text_buf);
		gui::IGUIEditBox *e = new gui::intlGUIEditBox(info_text_buf_wide, true,
				Environment, this, ID_message, rect2, false, true);
		delete[] info_text_buf_wide;
		e->drop();
		e->setMultiLine(true);
		e->setWordWrap(true);
		e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
	}

	ypos += 210;
	{
		core::rect<s32> rect2(0, 0, 540, 30);
		rect2 += topleft_client + v2s32(30, ypos);
		gui::IGUIEditBox *e = Environment->addEditBox(m_pass_confirm.c_str(),
				rect2, true, this, ID_confirmPassword);
		e->setPasswordBox(true);
	}

	ypos += 60;
	{
		core::rect<s32> rect2(0, 0, 230, 35);
		rect2 = rect2 + v2s32(size.X / 2 - 220, ypos);
		text = wgettext("Register and Join");
		Environment->addButton(rect2, this, ID_confirm, text);
		delete[] text;
	}
	{
		core::rect<s32> rect2(0, 0, 120, 35);
		rect2 = rect2 + v2s32(size.X / 2 + 70, ypos);
		text = wgettext("Cancel");
		Environment->addButton(rect2, this, ID_cancel, text);
		delete[] text;
	}
	{
		core::rect<s32> rect2(0, 0, 200, 20);
		rect2 += topleft_client + v2s32(30, ypos - 40);
		text = wgettext("Passwords do not match!");
		IGUIElement *e = Environment->addStaticText(
				text, rect2, false, true, this, ID_message);
		e->setVisible(false);
		delete[] text;
	}
}
Пример #27
0
// -----------------------------------------------------------------------------
void DynamicRibbonWidget::buildInternalStructure()
{
    //printf("****DynamicRibbonWidget::buildInternalStructure()****\n");

    // ---- Clean-up what was previously there
    for (unsigned int i=0; i<m_children.size(); i++)
    {
        IGUIElement* elem = m_children[i].m_element;
        if (elem != NULL && m_children[i].m_type == WTYPE_RIBBON)
        {
            elem->remove();
            m_children.erase(i);
            i--;
        }
    }
    m_rows.clearWithoutDeleting(); // rows already deleted above, don't double-delete

    m_left_widget->m_element->setVisible(true);
    assert( m_left_widget->ok() );
    assert( m_right_widget->ok() );

    // ---- determine column amount
    const float row_height = (float)(m_h - m_label_height)/(float)m_row_amount;
    float ratio_zoom = (float)row_height / (float)(m_child_height - m_label_height);
    m_col_amount = (int)roundf( m_w / ( m_child_width*ratio_zoom ) );

    // ajust column amount to not add more item slots than we actually need
    const int item_count = (int) m_items.size();
    //Log::info("DynamicRibbonWidget", "%d items; %d cells", item_count, row_amount * m_col_amount);
    if (m_row_amount*m_col_amount > item_count)
    {
        m_col_amount = (int)ceil((float)item_count/(float)m_row_amount);
        //Log::info("DynamicRibbonWidget", "Adjusting m_col_amount to be %d", m_col_amount);
    }

    assert( m_left_widget->ok() );
    assert( m_right_widget->ok() );

    // Hide arrows when everything is visible
    if (item_count <= m_row_amount*m_col_amount)
    {
        m_scrolling_enabled = false;
        m_left_widget->m_element->setVisible(false);
        m_right_widget->m_element->setVisible(false);
    }
    else
    {
        m_scrolling_enabled = true;
        m_left_widget->m_element->setVisible(true);
        m_right_widget->m_element->setVisible(true);
    }

    // ---- add rows
    int added_item_count = 0;
    for (int n=0; n<m_row_amount; n++)
    {
        RibbonWidget* ribbon;
        if (m_combo)
        {
            ribbon = new RibbonWidget(RIBBON_COMBO);
        }
        else
        {
            ribbon = new RibbonWidget(RIBBON_TOOLBAR);
        }
        ribbon->setListener(this);
        ribbon->m_reserved_id = m_ids[n];

        ribbon->m_x = m_x + (m_scrolling_enabled ? m_arrows_w : 0);
        ribbon->m_y = m_y + (int)(n*row_height);
        ribbon->m_w = m_w - (m_scrolling_enabled ? m_arrows_w*2 : 0);
        ribbon->m_h = (int)(row_height);
        ribbon->m_type = WTYPE_RIBBON;

        std::stringstream name;
        name << this->m_properties[PROP_ID] << "_row" << n;
        ribbon->m_properties[PROP_ID] = name.str();
        ribbon->m_event_handler = this;

        // calculate font size
        if (m_col_amount > 0)
        {
            m_font->setScale(GUIEngine::getFont()->getScale() *
                getFontScale((ribbon->m_w / m_col_amount) - 30));
        }

        // add columns
        for (int i=0; i<m_col_amount; i++)
        {
            // stretch the *texture* within the widget (and the widget has the right aspect ratio)
            // (Yeah, that's complicated, but screenshots are saved compressed horizontally so it's hard to be clean)
            IconButtonWidget* icon = new IconButtonWidget(IconButtonWidget::SCALE_MODE_STRETCH, false, true);
            icon->m_properties[PROP_ICON]="textures/transparence.png";

            // set size to get proper ratio (as most textures are saved scaled down to 256x256)
            icon->m_properties[PROP_WIDTH] = m_properties[PROP_CHILD_WIDTH];
            icon->m_properties[PROP_HEIGHT] = m_properties[PROP_CHILD_HEIGHT];
            icon->m_w = atoi(icon->m_properties[PROP_WIDTH].c_str());
            icon->m_h = atoi(icon->m_properties[PROP_HEIGHT].c_str());
            icon->setLabelFont(m_font);

            // If we want each icon to have its own label, we must make it non-empty, otherwise
            // it will assume there is no label and none will be created (FIXME: that's ugly)
            if (m_properties[PROP_LABELS_LOCATION] == "each") icon->m_text = " ";

            //Log::info("DynamicRibbonWidget", "Ribbon text = %s", m_properties[PROP_TEXT].c_str());

            ribbon->m_children.push_back( icon );
            added_item_count++;

            // stop adding columns when we have enough items
            if (added_item_count == item_count)
            {
                assert(!m_scrolling_enabled); // we can see all items, so scrolling must be off
                break;
            }
            else if (added_item_count > item_count)
            {
                assert(false);
                break;
            }
        }
        m_children.push_back( ribbon );
        m_rows.push_back( ribbon );
        ribbon->add();

        // stop filling rows when we have enough items
        if (added_item_count == item_count)
        {
            assert(!m_scrolling_enabled); // we can see all items, so scrolling must be off
            break;
        }
    }

#ifdef DEBUG
    if (!m_scrolling_enabled)
    {
        // debug checks
        int childrenCount = 0;
        for (unsigned int n=0; n<m_rows.size(); n++)
        {
            childrenCount += m_rows[n].m_children.size();
        }
        assert(childrenCount == (int)m_items.size());
    }
#endif
}
Пример #28
0
//! called if an event happened.
bool CGUIContextMenu::OnEvent(const SEvent& event)
{
	if (isEnabled())
	{

		switch(event.EventType)
		{
		case EET_GUI_EVENT:
			switch(event.GUIEvent.EventType)
			{
			case EGET_ELEMENT_FOCUS_LOST:
				if (event.GUIEvent.Caller == this && !isMyChild(event.GUIEvent.Element) && AllowFocus)
				{
					// set event parent of submenus
					IGUIElement * p =  EventParent ? EventParent : Parent;
					setEventParent(p);

					SEvent event;
					event.EventType = EET_GUI_EVENT;
					event.GUIEvent.Caller = this;
					event.GUIEvent.Element = 0;
					event.GUIEvent.EventType = EGET_ELEMENT_CLOSED;
					if ( !p->OnEvent(event) )
					{
						if ( CloseHandling & ECMC_HIDE )
						{
							setVisible(false);
						}
						if ( CloseHandling & ECMC_REMOVE )
						{
							remove();
						}
					}

					return false;
				}
				break;
			case EGET_ELEMENT_FOCUSED:
				if (event.GUIEvent.Caller == this && !AllowFocus)
				{
					return true;
				}
				break;
			default:
				break;
			}
			break;
		case EET_MOUSE_INPUT_EVENT:
			switch(event.MouseInput.Event)
			{
			case EMIE_LMOUSE_LEFT_UP:
				{
					// menu might be removed if it loses focus in sendClick, so grab a reference
					grab();
					const u32 t = sendClick(core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
					if ((t==0 || t==1) && Environment->hasFocus(this))
						Environment->removeFocus(this);
					drop();
				}
				return true;
			case EMIE_LMOUSE_PRESSED_DOWN:
				return true;
			case EMIE_MOUSE_MOVED:
				if (Environment->hasFocus(this))
					highlight(core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y), true);
				return true;
			default:
				break;
			}
			break;
		default:
			break;
		}
	}

	return IGUIElement::OnEvent(event);
}
Пример #29
0
bool Universe::Run()
{
	bool continueFlag; //Continue game or not
	char inPacket[256]; //Holds the input packet
	char outPacket[256]; //Holds the output packet
	int iResult; //The result of 'Receive' and 'Send'

	continueFlag = true;

	connectSocket = new ClientSocket(serverAddress, serverPort);
	printf("Connected to the server\n");
	CreatePacket(outPacket, LogIn, "%s%s", login, password);
	connectSocket->Send(outPacket);

	game = NULL;
	currentCharacter = NULL;
	
	ClientGUIInit();

	//variables for camera
	cameraY = 50.0f;
	ISceneNode* camPos=render->smgr->addEmptySceneNode();
	camPos->setPosition(vector3df(50.0f,cameraY,10.0f));
	camera=render->smgr->addCameraSceneNode(NULL, vector3df(50.0f, 50.0f, 10.0f), vector3df(50.0f, 0.0f, 40.0f));

	scene::ISceneNode* lnode; 
	lnode = render->smgr->addLightSceneNode(NULL, camPos->getPosition(), video::SColorf(1.0f, 1.0f, 1.0f, 1.0f), 800.0f);
	render->smgr->setAmbientLight(video::SColor(0, 60, 60, 60));
	
	state = Continue;

	int lastUpdate = render->device->getTimer()->getTime();

	while (render->device->run() && state == Continue)
	{
		//Receving packet from the server
		iResult = connectSocket->Receive(inPacket);
		if (iResult)
		{
			if (iResult > 0)
			{ //Packet received
				switch (GetPacketType(inPacket))
				{
					case LoggedIn:
						char gameName[256];
						int locationId;
						ScanPacket(inPacket, "%s%i", gameName, &locationId);
						game = new Game(gameName, Client);
						printf("Game %s initialized\n", game->name);
						currentLocation = game->data->GetLocation(locationId);
						DrawScene();
						break;
					case NPCSpawned:
						currentLocation->SpawnNPC(new CurrentNPC(inPacket));
						break;
					case StaticSpawned:
					{
						CurrentStatic* currentStatic = new CurrentStatic(inPacket);
						currentLocation->SpawnStatic(currentStatic);
						break;
					}
					case ItemSpawned:
						char spawnType; //TODO: SpawnType as char
						ScanPacket(inPacket, "%i%i%f%f%b", NULL, NULL, NULL, NULL, &spawnType);
						switch(spawnType)
						{
							case Ground:
								currentLocation->SpawnItem(new CurrentItem(inPacket));
								break;
							case Inventory:
								currentCharacter->SpawnItem(new CurrentItem(inPacket));
								break;
						}
						break;
					case CharacterSpawned:
						if (!currentCharacter)
						{
							currentCharacter = new CurrentCharacter(inPacket);
							currentLocation->SpawnCharacter(currentCharacter);
						}
						else
						{
							currentLocation->SpawnCharacter(new CurrentCharacter(inPacket));
						}
						break;
					case SkillSpawned:
						currentCharacter->SpawnSkill(new CurrentSkill(inPacket));
						break;
					case NPCUnspawned:
						currentLocation->UnSpawnNPC(currentLocation->GetNPC(PacketGetInt(inPacket, 1)));
						break;
					case StaticUnspawned:
						currentLocation->UnSpawnStatic(currentLocation->GetStatic(PacketGetInt(inPacket, 1)));
						break;
					case ItemUnspawned:
						switch(PacketGetByte(inPacket, 5))
						{
							case Ground:
								currentLocation->UnSpawnItem(currentLocation->GetItem(PacketGetInt(inPacket, 1)));
								break;
							case Inventory:
								//currentCharacter->UnSpawnItem(currentCharacter->GetItem(PacketGetInt(inPacket, 1)));
								break;
						}
						break;
					case CharacterUnspawned:
						currentLocation->UnSpawnCharacter(currentLocation->GetCharacter(PacketGetInt(inPacket, 1)));
						break;
					case Say:
					{
						IGUIElement* eb = guienv->getRootGUIElement()->getElementFromId(ChatBox)->getElementFromId(ChatEditBox);
						char messageType; //TODO: MessageType as char
						int senderCurrentCharacterId;
						wchar_t messageText[CHAT_MESSAGE_MAX_LENGTH];
						ScanPacket(inPacket, "%b%i%ws", &messageType, &senderCurrentCharacterId, messageText);
						CurrentCharacter* sender = game->data->GetCharacter(senderCurrentCharacterId);
						
						wchar_t wLogin[64];
						mbstowcs(wLogin, sender->login, 63);
						
						int offset = wcslen(eb->getText()) + wcslen(wLogin) + wcslen(messageText) + 3 - (CHAT_MAX_LENGTH - 1);
						if (offset < 0)
							offset = 0;
						else if (offset >= CHAT_MAX_LENGTH)
							offset = CHAT_MAX_LENGTH - 1;

						wchar_t wstr[CHAT_MAX_LENGTH];
						swprintf(wstr, L"%ls\n%ls: %ls", eb->getText() + offset, wLogin, messageText);
						eb->setText(wstr);
						//delete wstr;
						break;
					}
					case CharacterMoving:
					{
						int currentCharacterId;
						f32 x, y;
						ScanPacket(inPacket, "%i%f%f", &currentCharacterId, &x, &y);
						CurrentCharacter* movingCurrentCharacter = currentLocation->GetCharacter(currentCharacterId);
						movingCurrentCharacter->setAnimation(EMAT_RUN);
						render->moveNode(movingCurrentCharacter->node, vector3df(x * CELL_SIZE, 0, y * CELL_SIZE), movingCurrentCharacter->base->speed);
						//TEST
						movingCurrentCharacter->x = x;
						movingCurrentCharacter->y = y;
						break;
					}
					case HpChanged:
					{
						int characterId, changedHp;
						CurrentCharacter *character;
						ScanPacket(inPacket, "%i%i", &characterId, &changedHp);

						if (character = currentLocation->GetCharacter(characterId))
							character->hp = changedHp;
						
						break;

					}
					case CharacterDied:
					{
						//okay	
						break;
					}
					case CharacterMoved:
					{
						int characterId;
						f32 whereX, whereY;

						ScanPacket(inPacket, "%i%f%f", &characterId, &whereX, &whereY);

						printf("CLIENT CHAR ID: %d\n", characterId);
						printf("CLIENT WHERE X: %.f\n", whereX);
						printf("CLIENT WHERE Y: %.f\n", whereY);
						CurrentCharacter *character = currentLocation->GetCharacter(characterId);

						if (character)
						{
							printf("CLIENT TEST 1\n");
							
							//character->node->setPosition(vector3df(whereX * CELL_SIZE, character->node->getPosition().Y, whereY * CELL_SIZE)); //TODO: Why setPosition is not working?!!
							render->moveNode(character->node, vector3df(whereX * CELL_SIZE, character->node->getPosition().Y, whereY * CELL_SIZE), 1000000.0f);

							printf("CLIENT TEST 2\n");
							character->x = whereX;
							character->y = whereY;
						}

						break;
					}
					case DialogOpened:
					{
						char title[256];
						char text[4096];
						wchar_t wstr[512];

						//npcID = PacketGetInt(inPacket, 1);
						//strcpy(title, PacketGetString(inPacket, 5));
						sprintf(title, "[%d] %s", PacketGetInt(inPacket, 1), PacketGetString(inPacket, 5));
						strcpy(text, PacketGetString(inPacket, strlen(PacketGetString(inPacket, 5)) + 5 + 1));

						mbstowcs(wstr, title, 255);
						IGUIWindow* wnd = guienv->addWindow(rect<s32>(256, 128, 256 + 256, 128 + 320), false, wstr, NULL, -1);
						
						char patterns[][256] = {
							"<p\\s+rect\\s*=\\s*\\\"(.*?);(.*?);(.*?);(.*?)\\\">(.*?)</p>",
							"<button\\s+rect\\s*=\\s*\\\"(.*?);(.*?);(.*?);(.*?)\\\"\\s+onclick\\s*=\\s*\\\"(.*?)\\\">(.*?)</button>",
							/*
							"<p>(.*?)</p>",
							"<p>(.*?)</p>",
							"<p>(.*?)</p>",*/
							};
						char** result;
						int patternsCount = 2;
						const char *error;
						int erroffset;
						int count;
						int ovector[30];
						
						const unsigned char *tables = NULL;
						tables = pcre_maketables();

						for (int i = 0; i < patternsCount; i++)
						{
							pcre *re = pcre_compile ((char*)patterns[i], 0, &error, &erroffset, NULL);
							count = pcre_exec(re, NULL, (char*)text, strlen(text), 0, NULL, ovector, 30);
							if (count > 0)
							{
								result = new char*[count];
								for (int c = 0; c < 2 * count; c += 2)
								{
									if (ovector[c] >= 0)
									{
										result[c / 2] = new char[ovector[c + 1] - ovector[c] + 1];
										memcpy(result[c / 2], text + ovector[c], ovector[c + 1] - ovector[c]);
										result[c / 2][ovector[c + 1] - ovector[c]] = '\0';
										//printf("%d, %d\n", ovector[c], ovector[c + 1]);
										//printf("%s\n", result[c / 2]);
									}
									else
									{
										result[c / 2] = NULL;
									}
								}

								switch (i)
								{
									case 0: //p
									{
										wchar_t wstr[1024];
										mbstowcs(wstr, result[5], 1023);
										guienv->addStaticText(wstr, rect<s32>(atoi(result[1]), atoi(result[2]), atoi(result[1]) + atoi(result[3]), atoi(result[2]) + atoi(result[4])), false, true, wnd, DialogElement, false);
										break;
									}
									case 1: //button
									{
										wchar_t wstr[256];
										mbstowcs(wstr, result[6], 255);
										guienv->addButton(rect<s32>(atoi(result[1]), atoi(result[2]), atoi(result[1]) + atoi(result[3]), atoi(result[2]) + atoi(result[4])), wnd, DialogElement + atoi(result[5]), wstr, NULL);
										break;
									}
								}
								
								for (int j = 0; j < count; j++)
									if (result[j])
										delete result[j];
								delete result;
							}
						}
						break;
					}
					case PlayEffect:
					{
						CurrentMapObject<MapObject>* currentMapObject;
						int currentMapObjectId = PacketGetInt(inPacket, 2);
						int skillId = PacketGetInt(inPacket, 6);
						switch (PacketGetByte(inPacket, 1))
						{
							case 0: //NPC
								currentMapObject = (CurrentMapObject<MapObject>*)currentLocation->GetNPC(currentMapObjectId);
								break;
							case 3: //Character
								currentMapObject = (CurrentMapObject<MapObject>*)currentLocation->GetCharacter(currentMapObjectId);
								break;
						}
						render->PlayEffect(currentMapObject->node, game->resources->GetSkill(skillId)->effectTextures);
						break;
					}
					case PlayAdvancedEffect:
						int skillId = PacketGetInt(inPacket, 1);
						f32 xStart = PacketGetInt(inPacket, 5) * CELL_SIZE;
						f32 yStart = PacketGetInt(inPacket, 9) * CELL_SIZE;
						f32 xEnd = PacketGetInt(inPacket, 13) * CELL_SIZE;
						f32 yEnd = PacketGetInt(inPacket, 17) * CELL_SIZE;
						render->Effect2(vector3df(xStart, 5.0f, yStart), vector3df(xEnd, 5.0f, yEnd)); //TEST
						break;
				}
			}
			else if (iResult == -1)
			{ //Disconnected from the server
				printf("Disconnected from the server\n");
				delete Universe::instance->login;
				delete Universe::instance->password;
				Universe::instance->login = NULL;
				Universe::instance->password = NULL;
				Universe::instance->state = NextLevel;
			}
			else
			{ //Wrong packet from the client
				printf("Warning! Wrong packet from server. Error code: %d\n", iResult);
			}
		}

		//Drawing

		if ((render->device->getTimer()->getTime() - lastUpdate) > 30)
		{
			lastUpdate = render->device->getTimer()->getTime();
			if (game)
			{
				if (currentCharacter)
				{
					render->Km = camPos->getPosition();
					render->Kt = camera->getTarget();
					//Kt.X = currentCharacter->x * CELL_SIZE;
					//Kt.Z = currentCharacter->y * CELL_SIZE;
					vector3df pos = currentCharacter->node->getPosition();
					render->Kt.X = pos.X;
					render->Kt.Z = pos.Z;
					render->Km.X = render->Kt.X;
					render->Km.Z = render->Kt.Z - 30;
					render->Km.Y = cameraY;

					camera->setPosition(render->Km);
					camera->setTarget(render->Kt);

					//vector3df lPos = camera->getPosition();
					vector3df lPos = currentCharacter->node->getPosition();
					lPos.Y = 15;
					//lPos.Z += 20;
					lnode->setPosition(lPos);
				}
				
				

				render->driver->beginScene(true, true, SColor(255,100,101,140));
					render->smgr->drawAll();
					guienv->drawAll();
				render->driver->endScene();
			}
		}
	}

	ClientGUIDestroy();

	delete connectSocket;
	if (game)
	{
		delete game;
		render->smgr->clear();
	}

	if (state == NextLevel)
		return false;
	return true;
}
Пример #30
0
EventPropagation EventHandler::onGUIEvent(const SEvent& event)
{
    if (event.EventType == EET_GUI_EVENT)
    {
        if (event.GUIEvent.Caller == NULL) return EVENT_LET;
        const s32 id = event.GUIEvent.Caller->getID();

        switch (event.GUIEvent.EventType)
        {
            case EGET_BUTTON_CLICKED:
            case EGET_SCROLL_BAR_CHANGED:
            case EGET_CHECKBOX_CHANGED:
            case EGET_LISTBOX_SELECTED_AGAIN:
            {
                Widget* w = GUIEngine::getWidget(id);
                if (w == NULL) break;
                if (w->m_deactivated)
                {
                    GUIEngine::getCurrentScreen()->onDisabledItemClicked(w->m_properties[PROP_ID].c_str());
                    return EVENT_BLOCK;
                }

                w->onClick();

                // These events are only triggered by mouse (or so I hope)
                // The player that owns the mouser receives "game master" priviledges
                return onWidgetActivated(w, PLAYER_ID_GAME_MASTER);

                // These events are only triggered by keyboard/mouse (or so I hope...)
                //const int playerID = input_manager->getPlayerKeyboardID();
                //if (input_manager->masterPlayerOnly() && playerID != PLAYER_ID_GAME_MASTER) break;
                //else if (playerID != -1) return onWidgetActivated(w, playerID);
                //else break;
            }
            case EGET_ELEMENT_HOVERED:
            {
                Widget* w = GUIEngine::getWidget(id);

                if (w == NULL) break;

                if (!w->m_focusable) return GUIEngine::EVENT_BLOCK;

                // When a modal dialog is shown, don't select widgets out of the dialog
                if (ModalDialog::isADialogActive() && !ModalDialog::getCurrent()->isMyChild(w))
                {
                    // check for parents too before discarding event
                    if (w->m_event_handler != NULL)
                    {
                        if (!ModalDialog::getCurrent()->isMyChild(w->m_event_handler))
                        {
                            break;
                        }
                    }
                }

                // select ribbons on hover
                if (w->m_event_handler != NULL && w->m_event_handler->m_type == WTYPE_RIBBON)
                {
                    // FIXME: don't make a special case for ribbon here, there should be a generic callback
                    //        that all widgets may hook onto
                    RibbonWidget* ribbon = (RibbonWidget*)(w->m_event_handler);
                    if (ribbon == NULL) break;

                    // give the mouse "game master" priviledges
                    const int playerID = PLAYER_ID_GAME_MASTER; //input_manager->getPlayerKeyboardID();

                    if (playerID == -1) break;
                    if (input_manager->masterPlayerOnly() && playerID != PLAYER_ID_GAME_MASTER) break;

                    ribbon->mouseHovered(w, playerID);
                    if (ribbon->m_event_handler != NULL) ribbon->m_event_handler->mouseHovered(w, playerID);
                    ribbon->setFocusForPlayer(playerID);
                }
                else
                {
                    // focus on hover for other widgets
                    // give the mouse "game master" priviledges
                    const int playerID = PLAYER_ID_GAME_MASTER; //input_manager->getPlayerKeyboardID();
                    if (input_manager->masterPlayerOnly() && playerID != PLAYER_ID_GAME_MASTER) break;
                    if (playerID != -1)
                    {
                        // lists don't like that combined with scrollbars
                        // (FIXME: find why instead of working around)
                        if (w->getType() != WTYPE_LIST)
                        {
                            w->setFocusForPlayer(playerID);
                        }
                    }
                }

                break;
            }
                /*
                 case EGET_ELEMENT_LEFT:
                 {
                 Widget* el = getWidget(id);
                 if(el == NULL) break;

                 break;
                 }
                 */

            case EGET_ELEMENT_FOCUSED:
            {
                Widget* w = GUIEngine::getWidget(id);
                if (w == NULL) break;

                // forbid list for gaining "irrLicht focus", then they will process key events and
                // we don't want that since we do our own custom processing for keys
                if (w->m_type == WTYPE_LIST)
                {
                    // FIXME: fix that better
                    // cheap way to remove the focus from the element (nope, IGUIEnv::removeFocus doesn't work)
                    // Obviously will not work if the list is the first item of the screen.
                    IGUIElement* elem = getCurrentScreen()->getFirstWidget()->getIrrlichtElement();
                    if (elem->getType() == EGUIET_LIST_BOX)
                    {
                        elem = getCurrentScreen()->getLastWidget()->getIrrlichtElement();
                        assert(elem->getType() != EGUIET_LIST_BOX);
                    }
                    GUIEngine::getGUIEnv()->setFocus( elem );
                    return EVENT_BLOCK; // confirms to irrLicht that we processed it
                }


                break;
            }

            case EGET_LISTBOX_CHANGED:
            {
                Widget* w = GUIEngine::getWidget(id);
                if (w == NULL) break;
                assert(w->getType() == WTYPE_LIST);

                const int playerID = input_manager->getPlayerKeyboardID();
                if (input_manager->masterPlayerOnly() && playerID != PLAYER_ID_GAME_MASTER) break;
                if (!w->isFocusedForPlayer(playerID)) w->setFocusForPlayer(playerID);

                break;
            }
            case EGET_EDITBOX_ENTER:
            {
                // currently, enter pressed in text ctrl events can only happen in dialogs.
                // FIXME : find a cleaner way to route the event to its proper location
                if (ModalDialog::isADialogActive()) ModalDialog::onEnterPressed();
                break;
            }
            default:
                break;
        } // end switch
    }

    /*
     EGET_BUTTON_CLICKED, EGET_SCROLL_BAR_CHANGED, EGET_CHECKBOX_CHANGED, EGET_TAB_CHANGED,
     EGET_MENU_ITEM_SELECTED, EGET_COMBO_BOX_CHANGED, EGET_SPINBOX_CHANGED, EGET_EDITBOX_ENTER,

     EGET_LISTBOX_CHANGED, EGET_LISTBOX_SELECTED_AGAIN,
     EGET_FILE_SELECTED, EGET_FILE_CHOOSE_DIALOG_CANCELLED,
     EGET_MESSAGEBOX_YES, EGET_MESSAGEBOX_NO, EGET_MESSAGEBOX_OK, EGET_MESSAGEBOX_CANCEL,
     EGET_TABLE_CHANGED, EGET_TABLE_HEADER_CHANGED, EGET_TABLE_SELECTED_AGAIN
     EGET_ELEMENT_FOCUS_LOST, EGET_ELEMENT_FOCUSED, EGET_ELEMENT_HOVERED, EGET_ELEMENT_LEFT,
     EGET_ELEMENT_CLOSED,
     */
    return EVENT_LET;
}