Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/OrxoBlox_FS19/src/orxonox/overlays/OrxonoxOverlay.cc @ 12400

Last change on this file since 12400 was 11795, checked in by landauf, 7 years ago

merged ogre1.9 (including cegui0.8) into new branch

  • Property svn:eol-style set to native
File size: 16.0 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30@file
31@brief Definition of the OrxonoxOverlay class.
32*/
33
34#include "OrxonoxOverlay.h"
35
36#include <cmath>
37#if OGRE_VERSION >= 0x010900
38#   include <Overlay/OgreOverlay.h>
39#   include <Overlay/OgreOverlayManager.h>
40#   include <Overlay/OgrePanelOverlayElement.h>
41#else
42#   include <OgreOverlay.h>
43#   include <OgreOverlayManager.h>
44#   include <OgrePanelOverlayElement.h>
45#endif
46#include <OgreRenderWindow.h>
47#include <OgreMaterialManager.h>
48#include <OgreTechnique.h>
49#include <OgrePass.h>
50
51#include "util/Convert.h"
52#include "util/Exception.h"
53#include "core/GameMode.h"
54#include "core/CoreIncludes.h"
55#include "core/XMLPort.h"
56#include "core/command/ConsoleCommandIncludes.h"
57
58#include "OverlayGroup.h"
59
60namespace orxonox
61{
62    unsigned int OrxonoxOverlay::hudOverlayCounter_s = 0;
63    std::map<std::string, OrxonoxOverlay*> OrxonoxOverlay::overlays_s;
64
65    SetConsoleCommand("OrxonoxOverlay", "scaleOverlay",     &OrxonoxOverlay::scaleOverlay);
66    SetConsoleCommand("OrxonoxOverlay", "scrollOverlay",    &OrxonoxOverlay::scrollOverlay);
67    SetConsoleCommand("OrxonoxOverlay", "toggleVisibility", &OrxonoxOverlay::toggleVisibility);
68    SetConsoleCommand("OrxonoxOverlay", "show",     &OrxonoxOverlay::showOverlay);
69    SetConsoleCommand("OrxonoxOverlay", "rotateOverlay",    &OrxonoxOverlay::rotateOverlay);
70
71    RegisterClass(OrxonoxOverlay);
72
73    OrxonoxOverlay::OrxonoxOverlay(Context* context)
74        : BaseObject(context)
75    {
76        RegisterObject(OrxonoxOverlay);
77
78        this->owner_ = nullptr;
79        this->group_ = nullptr;
80
81        if (!GameMode::showsGraphics())
82            ThrowException(NoGraphics, "Can't create OrxonoxOverlay, graphics engine not initialized");
83
84        // create the Ogre::Overlay
85        overlay_ = Ogre::OverlayManager::getSingleton().create("OrxonoxOverlay_overlay_"
86            + multi_cast<std::string>(hudOverlayCounter_s++));
87
88        // create background panel (can be used to show any picture)
89        this->background_ = static_cast<Ogre::PanelOverlayElement*>(
90            Ogre::OverlayManager::getSingleton().createOverlayElement("Panel",
91            "OrxonoxOverlay_background_" + multi_cast<std::string>(hudOverlayCounter_s++)));
92        this->overlay_->add2D(this->background_);
93
94        // Get aspect ratio from the render window. Later on, we get informed automatically
95        this->windowAspectRatio_ = static_cast<float>(this->getWindowWidth()) / this->getWindowHeight();
96
97        this->size_ = Vector2(1.0f, 1.0f);
98        this->pickPoint_= Vector2(0.0f, 0.0f);
99        this->position_ = Vector2(0.0f, 0.0f);
100        this->angle_ = Degree(0.0);
101        this->bCorrectAspect_ = false;
102        this->rotState_ = RotationState::Horizontal;
103        this->angleChanged(); // updates all other values as well
104
105        setBackgroundMaterial("");
106    }
107
108    /**
109    @brief
110        Make sure everything gets removed/destroyed.
111    @remark
112        We assume that the Ogre::OverlayManager exists (there is an assert in Ogre for that!)
113    */
114    OrxonoxOverlay::~OrxonoxOverlay()
115    {
116        if (this->isInitialized())
117        {
118            // erase ourself from the map with all overlays
119            std::map<std::string, OrxonoxOverlay*>::iterator it = overlays_s.find(this->getName());
120            if (it != overlays_s.end())
121                overlays_s.erase(it);
122
123            Ogre::OverlayManager::getSingleton().destroyOverlayElement(this->background_);
124            Ogre::OverlayManager::getSingleton().destroy(this->overlay_);
125        }
126    }
127
128    /**
129    @brief
130        Loads the OrxonoxOverlay.
131
132        This has to be called before usage, otherwise strange behaviour is
133        guaranteed! (there should be no segfaults however).
134    @copydoc BaseObject::XMLPort()
135    */
136    void OrxonoxOverlay::XMLPort(Element& xmlelement, XMLPort::Mode mode)
137    {
138        SUPER(OrxonoxOverlay, XMLPort, xmlelement, mode);
139
140        XMLPortParam(OrxonoxOverlay, "size",      setSize,      getSize,      xmlelement, mode);
141        XMLPortParam(OrxonoxOverlay, "pickpoint", setPickPoint, getPickPoint, xmlelement, mode);
142        XMLPortParam(OrxonoxOverlay, "position",  setPosition,  getPosition,  xmlelement, mode);
143        XMLPortParam(OrxonoxOverlay, "rotation",  setRotation,  getRotation,  xmlelement, mode);
144        XMLPortParam(OrxonoxOverlay, "correctaspect", setAspectCorrection,   getAspectCorrection,   xmlelement, mode);
145        XMLPortParam(OrxonoxOverlay, "background",    setBackgroundMaterial, getBackgroundMaterial, xmlelement, mode);
146        XMLPortParam(OrxonoxOverlay, "backgroundtex", setBackgroundTexture,  getBackgroundTexture,  xmlelement, mode);
147    }
148
149    void OrxonoxOverlay::changedName()
150    {
151        SUPER(OrxonoxOverlay, changedName);
152
153        OrxonoxOverlay::overlays_s.erase(this->getOldName());
154
155        if (OrxonoxOverlay::overlays_s.find(this->getName()) != OrxonoxOverlay::overlays_s.end())
156            orxout(internal_warning) << "Overlay names should be unique or you cannnot access them via console. Name: \"" << this->getName() << '"' << endl;
157
158        OrxonoxOverlay::overlays_s[this->getName()] = this;
159    }
160
161    //! Only sets the background material name if not ""
162    void OrxonoxOverlay::setBackgroundMaterial(const std::string& material)
163    {
164        if (this->background_ && !material.empty())
165            this->background_->setMaterialName(material);
166    }
167
168    //! Returns the the material name of the background
169    const std::string& OrxonoxOverlay::getBackgroundMaterial() const
170    {
171        if (this->background_)
172            return this->background_->getMaterialName();
173        else
174            return BLANKSTRING;
175    }
176
177    //! Sets the background texture name and creates a new material if necessary
178    void OrxonoxOverlay::setBackgroundTexture(const std::string& texture)
179    {
180        if (this->background_ && this->background_->getMaterial().isNull() && !texture.empty())
181        {
182            // create new material
183            const std::string& materialname = "generated_material" + getUniqueNumberString();
184            Ogre::MaterialPtr material = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().create(materialname, "General"));
185            material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
186            Ogre::TextureUnitState* textureUnitState_ = material->getTechnique(0)->getPass(0)->createTextureUnitState();
187            textureUnitState_->setTextureName(texture);
188            textureUnitState_->setNumMipmaps(0);
189            this->background_->setMaterialName(materialname);
190        }
191    }
192
193    //! Returns the the texture name of the background
194    const std::string& OrxonoxOverlay::getBackgroundTexture() const
195    {
196        if (this->background_)
197        {
198            Ogre::TextureUnitState* tempTx = this->background_->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0);
199            return tempTx->getTextureName();
200        }
201        else
202            return BLANKSTRING;
203    }
204
205    //! Called by BaseObject when visibility has changed.
206    void OrxonoxOverlay::changedVisibility()
207    {
208        SUPER( OrxonoxOverlay, changedVisibility );
209
210        if (!this->overlay_)
211            return;
212
213        // only set to visible if corresponding OverlayGroup is also visible
214        if (this->isVisible() && (!this->getOverlayGroup() || this->getOverlayGroup()->isVisible()) )
215            this->overlay_->show();
216        else
217            this->overlay_->hide();
218    }
219
220    /**
221    @brief
222        Called by the GraphicsManager whenever the window size changes.
223        Calculates the aspect ratio only.
224    */
225    void OrxonoxOverlay::windowResized(unsigned int newWidth, unsigned int newHeight)
226    {
227        this->windowAspectRatio_ = static_cast<float>(newWidth) / newHeight;
228        this->sizeCorrectionChanged();
229    }
230
231    /**
232    @brief
233        Called whenever the rotation angle has changed.
234    */
235    void OrxonoxOverlay::angleChanged()
236    {
237        if (!this->overlay_)
238            return;
239
240        this->overlay_->setRotate(this->angle_);
241        this->sizeCorrectionChanged();
242    }
243
244    /**
245    @brief
246        Called whenever the aspect ratio or the angle has changed.
247        The method calculates a correction factor for the size to compensate
248        for aspect distortion if desired.
249    @remarks
250        This only works when the angle is about 0 or 90 degrees.
251    */
252    void OrxonoxOverlay::sizeCorrectionChanged()
253    {
254        if (this->bCorrectAspect_)
255        {
256            float angle = this->angle_.valueDegrees();
257            if (angle < 0.0)
258                angle = -angle;
259            angle -= 180.0f * static_cast<int>(angle / 180.0);
260
261            // take the reverse if angle is about 90 degrees
262            float tempAspect;
263            if (angle > 89.0f && angle < 91.0f)
264            {
265                tempAspect = 1.0f / this->windowAspectRatio_;
266                rotState_ = RotationState::Vertical;
267            }
268            else if (angle > 179 || angle < 1)
269            {
270                tempAspect = this->windowAspectRatio_;
271                rotState_ = RotationState::Horizontal;
272            }
273            else
274            {
275                tempAspect = 1.0f;
276                rotState_ = RotationState::Inbetween;
277            }
278
279            // note: this is only an approximation that is mostly valid when the
280            // magnitude of the width is about the magnitude of the height.
281            // Correctly we would have to take the square root of width*height
282            this->sizeCorrection_.x = 2.0f / (tempAspect + 1.0f);
283            this->sizeCorrection_.y = tempAspect * this->sizeCorrection_.x;
284        }
285        else
286        {
287            this->sizeCorrection_ = Vector2::UNIT_SCALE;
288        }
289
290        this->sizeChanged();
291    }
292
293    /**
294    @brief
295        Sets the overlay size using the actual corrected size.
296    */
297    void OrxonoxOverlay::sizeChanged()
298    {
299        if (!this->overlay_)
300            return;
301
302        this->overlay_->setScale(size_.x * sizeCorrection_.x, size_.y * sizeCorrection_.y);
303        positionChanged();
304    }
305
306    /**
307    @brief
308        Determines the position of the overlay.
309        This works also well when a rotation angle is applied. The overlay always
310        gets aligned correctly as well as possible.
311    */
312    void OrxonoxOverlay::positionChanged()
313    {
314        if (!this->overlay_)
315            return;
316
317        // transform the angle to a range of 0 - pi/2 first.
318        float angle = this->angle_.valueRadians();
319        if (angle < 0.0)
320            angle = -angle;
321        angle -= math::pi * static_cast<int>(angle / (math::pi));
322        if (angle > math::pi_2)
323            angle = math::pi - angle;
324
325        // do some mathematical fiddling for a bounding box
326        Vector2 actualSize = size_ * sizeCorrection_;
327        float radius = actualSize.length();
328        float phi = atan(actualSize.y / actualSize.x);
329        Vector2 boundingBox(radius * cos(angle - phi), radius * sin(angle + phi));
330
331        // calculate the scrolling offset
332        Vector2 scroll = (position_ - 0.5 - boundingBox * (pickPoint_ - 0.5)) * 2.0;
333        this->overlay_->setScroll(scroll.x, -scroll.y);
334    }
335
336
337    //########### Console commands ############
338
339    /**
340    @brief
341        Scales an overlay by its name.
342    @param name
343        The name of the overlay defined BaseObject::setName() (usually done with the "name"
344        attribute in the xml file).
345    @param scale
346        The scaling factor
347    */
348    /*static*/ void OrxonoxOverlay::scaleOverlay(const std::string& name, float scale)
349    {
350        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
351        if (it != overlays_s.end())
352            it->second->scale(Vector2(scale, scale));
353    }
354
355    /**
356    @brief
357        Toggles the visibility of an Overlay by it's name.
358    @param name
359        The name of the overlay defined BaseObject::setName() (usually done with the "name"
360        attribute in the xml file).
361    */
362    /*static*/ void OrxonoxOverlay::toggleVisibility(const std::string& name)
363    {
364        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
365        if (it != overlays_s.end())
366        {
367            OrxonoxOverlay* overlay= it->second;
368            if(overlay->isVisible())
369            {
370                overlay->hide();
371                orxout(verbose, context::misc::overlays) << "HIDE " << name << endl;
372            }
373            else
374            {
375                overlay->show();
376                orxout(verbose, context::misc::overlays) << "SHOW " << name << endl;
377            }
378        }
379    }
380   
381    /**
382    @brief
383        Shows Overlay by it's name.
384    @param name
385        The name of the overlay defined BaseObject::setName() (usually done with the "name"
386        attribute in the xml file).
387    */
388    /*static*/ void OrxonoxOverlay::showOverlay(const std::string& name)
389    {
390        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
391        if (it != overlays_s.end())
392        {
393            OrxonoxOverlay* overlay= it->second;
394            if(overlay->isVisible())
395                overlay->changedVisibility();
396            else
397                overlay->show();
398        }
399    }
400
401    /**
402    @brief
403        Scrolls an overlay by its name.
404    @param name
405        The name of the overlay defined BaseObject::setName() (usually done with the "name"
406        attribute in the xml file).
407    @param scroll
408        The relative translation of the overlay
409    */
410    /*static*/ void OrxonoxOverlay::scrollOverlay(const std::string& name, const Vector2& scroll)
411    {
412        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
413        if (it != overlays_s.end())
414            it->second->scroll(scroll);
415    }
416
417    /**
418    @brief
419        Rotates an overlay by its name.
420    @param name
421        The name of the overlay defined BaseObject::setName() (usually done with the "name"
422        attribute in the xml file).
423    @param angle
424        The rotation angle in degree
425    */
426    /*static*/ void OrxonoxOverlay::rotateOverlay(const std::string& name, const Degree& angle)
427    {
428        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
429        if (it != overlays_s.end())
430            it->second->rotate(angle);
431    }
432
433    void OrxonoxOverlay::setOverlayGroup(OverlayGroup* group)
434    {
435        if (group != this->group_)
436        {
437            if (this->group_)
438                this->group_->removeElement(this);
439            this->group_ = group;
440            this->changedOverlayGroup();
441        }
442    }
443
444    void OrxonoxOverlay::setBackgroundAlpha(float alpha)
445    {
446        Ogre::MaterialPtr ptr = this->background_->getMaterial();
447        Ogre::TextureUnitState* tempTx = ptr->getTechnique(0)->getPass(0)->getTextureUnitState(0);
448        tempTx->setAlphaOperation(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, alpha);
449    }
450
451    void OrxonoxOverlay::setBackgroundColour(ColourValue colour)
452    {
453        Ogre::MaterialPtr ptr = this->background_->getMaterial();
454        Ogre::TextureUnitState* tempTx = ptr->getTechnique(0)->getPass(0)->getTextureUnitState(0);
455        tempTx->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, colour);
456    }
457
458    void OrxonoxOverlay::setZOrder(unsigned short order)
459    {
460        if (this->overlay_)
461        {
462            this->overlay_->setZOrder(order);
463        }
464    }
465}
Note: See TracBrowser for help on using the repository browser.