<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program. If not, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/helper/system/PluginManager.h>
using sofa::helper::system::PluginManager ;

#include <sofa/helper/system/FileRepository.h>
using sofa::helper::system::PluginRepository ;

#include <sofa/helper/system/FileSystem.h>
using sofa::helper::system::PluginRepository;
using sofa::helper::system::DataRepository;
using sofa::helper::system::FileSystem;

#include <sofa/helper/Utils.h>
using sofa::helper::Utils;

#include <sofa/helper/BackTrace.h>
using sofa::helper::BackTrace;

#include <sofa/helper/system/console.h>
using sofa::helper::Console ;

#include <sofa/helper/testing/TestMessageHandler.h>
using sofa::helper::logging::MessageDispatcher ;
using sofa::helper::logging::MainGtestMessageHandler ;

#include <sofa/helper/random.h>

#include "BaseTest.h"

namespace sofa {
namespace helper {
namespace testing {

void initializeOnce()
{
    static bool initialized = false ;
    if(!initialized){
        Console::setColorsStatus(Console::ColorsDisabled) ;

        MessageDispatcher::addHandler( MainGtestMessageHandler::getInstance() ) ;
        BackTrace::autodump() ;

        const std::string pluginDir = Utils::getPluginDirectory() ;
        PluginRepository.addFirstPath(pluginDir);
        PluginManager::getInstance().loadPlugin("SceneCreator") ;
        initialized=true ;
    }
}

int BaseTest::seed = (unsigned int)time(NULL);

BaseTest::BaseTest() :
   m_fatal(sofa::helper::logging::Message::Fatal, __FILE__, __LINE__ ),
   m_error(sofa::helper::logging::Message::Error, __FILE__, __LINE__ )
{
    initializeOnce() ;

    seed = ::testing::UnitTest::GetInstance()->random_seed() ;

    ///if you want to generate the same sequence of pseudo-random numbers than a specific test suites
    ///use the same seed (the seed value is indicated at the 2nd line of test results)
    ///and pass the seed in command argument line ex: SofaTest_test.exe seed 32
    helper::srand(seed);

    ///gtest already use color so we remove the color from the sofa message to make the distinction
    ///clean and avoid ambiguity.
    Console::setColorsStatus(Console::ColorsDisabled) ;

    ///Repeating this for each class is harmless because addHandler test if the handler is already installed and
    ///if so it don't install it again.
    MessageDispatcher::addHandler( MainGtestMessageHandler::getInstance() ) ;
}

BaseTest::~BaseTest() {}

void BaseTest::SetUp()
{
    onSetUp();
}

void BaseTest::TearDown()
{
    onTearDown();
}

} /// testing
} /// helper
} /// sofa

<commit_msg>[SofaKernel] Remove the implicit loading of "SceneCreator" in BaseTest.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program. If not, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/helper/system/PluginManager.h>
using sofa::helper::system::PluginManager ;

#include <sofa/helper/system/FileRepository.h>
using sofa::helper::system::PluginRepository ;

#include <sofa/helper/system/FileSystem.h>
using sofa::helper::system::PluginRepository;
using sofa::helper::system::DataRepository;
using sofa::helper::system::FileSystem;

#include <sofa/helper/Utils.h>
using sofa::helper::Utils;

#include <sofa/helper/BackTrace.h>
using sofa::helper::BackTrace;

#include <sofa/helper/system/console.h>
using sofa::helper::Console ;

#include <sofa/helper/testing/TestMessageHandler.h>
using sofa::helper::logging::MessageDispatcher ;
using sofa::helper::logging::MainGtestMessageHandler ;

#include <sofa/helper/random.h>

#include "BaseTest.h"

namespace sofa {
namespace helper {
namespace testing {

void initializeOnce()
{
    static bool initialized = false ;
    if(!initialized){
        Console::setColorsStatus(Console::ColorsDisabled) ;

        MessageDispatcher::addHandler( MainGtestMessageHandler::getInstance() ) ;
        BackTrace::autodump() ;

        const std::string pluginDir = Utils::getPluginDirectory() ;
        PluginRepository.addFirstPath(pluginDir);
        initialized=true ;
    }
}

int BaseTest::seed = (unsigned int)time(NULL);

BaseTest::BaseTest() :
   m_fatal(sofa::helper::logging::Message::Fatal, __FILE__, __LINE__ ),
   m_error(sofa::helper::logging::Message::Error, __FILE__, __LINE__ )
{
    initializeOnce() ;

    seed = ::testing::UnitTest::GetInstance()->random_seed() ;

    ///if you want to generate the same sequence of pseudo-random numbers than a specific test suites
    ///use the same seed (the seed value is indicated at the 2nd line of test results)
    ///and pass the seed in command argument line ex: SofaTest_test.exe seed 32
    helper::srand(seed);

    ///gtest already use color so we remove the color from the sofa message to make the distinction
    ///clean and avoid ambiguity.
    Console::setColorsStatus(Console::ColorsDisabled) ;

    ///Repeating this for each class is harmless because addHandler test if the handler is already installed and
    ///if so it don't install it again.
    MessageDispatcher::addHandler( MainGtestMessageHandler::getInstance() ) ;
}

BaseTest::~BaseTest() {}

void BaseTest::SetUp()
{
    onSetUp();
}

void BaseTest::TearDown()
{
    onTearDown();
}

} /// testing
} /// helper
} /// sofa

<|endoftext|>


<commit_before>// @(#)root/eve:$Id$
// Author: Matevz Tadel

// Demonstates usage pre-scaling for automatic 2D projections.

const char* esd_geom_file_name =
   "http://root.cern.ch/files/alice_ESDgeometry.root";

void projection_prescale()
{
   TFile::SetCacheFileDir(".");
   TEveManager::Create();

   TEveViewer *pev = gEve->SpawnNewViewer("Projections");

   // camera
   TEveScene* s = gEve->SpawnNewScene("Projected Geom");
   pev->AddScene(s);

   TGLViewer* pgv = pev->GetGLViewer();
   pgv->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
   TGLOrthoCamera* cam = (TGLOrthoCamera*) pgv->CurrentCamera();
   cam->SetZoomMinMax(0.2, 20);

   // projections
   TEveProjectionManager* mng = new TEveProjectionManager();
   {
      mng->SetProjection(TEveProjection::kPT_RPhi);
      TEveProjection* p = mng->GetProjection();
      p->AddPreScaleEntry(0, 0,   4);    // r scale 4 from 0
      p->AddPreScaleEntry(0, 45,  1);    // r scale 1 from 45
      p->AddPreScaleEntry(0, 310, 0.5);
      p->SetUsePreScale(kTRUE);
   }
   {
      mng->SetProjection(TEveProjection::kPT_RhoZ);
      TEveProjection* p = mng->GetProjection();
      // Increase silicon tracker
      p->AddPreScaleEntry(0, 0, 4);     // rho scale 4 from 0
      p->AddPreScaleEntry(1, 0, 4);     // z   scale 4 from 0
      // Normal for TPC
      p->AddPreScaleEntry(0, 45,  1);   // rho scale 1 from 45
      p->AddPreScaleEntry(1, 110, 1);   // z   scale 1 from 110
      // Reduce the rest
      p->AddPreScaleEntry(0, 310, 0.5);
      p->AddPreScaleEntry(1, 250, 0.5);
      p->SetUsePreScale(kTRUE);
   }
   mng->SetProjection(TEveProjection::kPT_RPhi);
   s->AddElement(mng);

   TEveProjectionAxes* axes = new TEveProjectionAxes(mng);
   s->AddElement(axes);
   gEve->AddToListTree(axes, kTRUE);
   gEve->AddToListTree(mng, kTRUE);

   // Simple geometry
   TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
   if (!geom)
      return;

   TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
   TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
   geom->Close();
   delete geom;
   gEve->AddGlobalElement(gsre);
   mng->ImportElements(gsre);

   TEveLine* line = new TEveLine;
   line->SetMainColor(kGreen);
   for (Int_t i=0; i<160; ++i)
      line->SetNextPoint(120*sin(0.2*i), 120*cos(0.2*i), 80-i);
   gEve->AddElement(line);
   mng->ImportElements(line);
   line->SetRnrSelf(kFALSE);

   //-------------------------------------------------------------------------
   // Scaled 3D "projection"
   //-------------------------------------------------------------------------

   TEveViewer *sev = gEve->SpawnNewViewer("Scaled 3D");
   TEveProjectionManager* smng =
      new TEveProjectionManager(TEveProjection::kPT_3D);
   TEveProjection* sp = smng->GetProjection();
   sp->SetUsePreScale(kTRUE);
   sp->AddPreScaleEntry(2,   0,  1);
   sp->AddPreScaleEntry(2, 100,  0.2);

   TEveScene* ss = gEve->SpawnNewScene("Scaled Geom");
   sev->AddScene(ss);
   ss->AddElement(smng);

   smng->ImportElements(gsre);

   //-------------------------------------------------------------------------

   gEve->GetBrowser()->GetTabRight()->SetTab(1);

   gEve->Redraw3D(kTRUE);
}
<commit_msg>The same error as the prev. one.<commit_after>// @(#)root/eve:$Id$
// Author: Matevz Tadel

// Demonstates usage pre-scaling for automatic 2D projections.

const char* esd_geom_file_name =
   "http://root.cern.ch/files/alice_ESDgeometry.root";

void projection_prescale()
{
   TFile::SetCacheFileDir(".");
   TEveManager::Create();

   TEveViewer *pev = gEve->SpawnNewViewer("Projections");

   // camera
   TEveScene* s = gEve->SpawnNewScene("Projected Geom");
   pev->AddScene(s);

   TGLViewer* pgv = pev->GetGLViewer();
   pgv->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
   TGLOrthoCamera& cam = (TGLOrthoCamera&) pgv->CurrentCamera();
   cam.SetZoomMinMax(0.2, 20);

   // projections
   TEveProjectionManager* mng = new TEveProjectionManager();
   {
      mng->SetProjection(TEveProjection::kPT_RPhi);
      TEveProjection* p = mng->GetProjection();
      p->AddPreScaleEntry(0, 0,   4);    // r scale 4 from 0
      p->AddPreScaleEntry(0, 45,  1);    // r scale 1 from 45
      p->AddPreScaleEntry(0, 310, 0.5);
      p->SetUsePreScale(kTRUE);
   }
   {
      mng->SetProjection(TEveProjection::kPT_RhoZ);
      TEveProjection* p = mng->GetProjection();
      // Increase silicon tracker
      p->AddPreScaleEntry(0, 0, 4);     // rho scale 4 from 0
      p->AddPreScaleEntry(1, 0, 4);     // z   scale 4 from 0
      // Normal for TPC
      p->AddPreScaleEntry(0, 45,  1);   // rho scale 1 from 45
      p->AddPreScaleEntry(1, 110, 1);   // z   scale 1 from 110
      // Reduce the rest
      p->AddPreScaleEntry(0, 310, 0.5);
      p->AddPreScaleEntry(1, 250, 0.5);
      p->SetUsePreScale(kTRUE);
   }
   mng->SetProjection(TEveProjection::kPT_RPhi);
   s->AddElement(mng);

   TEveProjectionAxes* axes = new TEveProjectionAxes(mng);
   s->AddElement(axes);
   gEve->AddToListTree(axes, kTRUE);
   gEve->AddToListTree(mng, kTRUE);

   // Simple geometry
   TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
   if (!geom)
      return;

   TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
   TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
   geom->Close();
   delete geom;
   gEve->AddGlobalElement(gsre);
   mng->ImportElements(gsre);

   TEveLine* line = new TEveLine;
   line->SetMainColor(kGreen);
   for (Int_t i=0; i<160; ++i)
      line->SetNextPoint(120*sin(0.2*i), 120*cos(0.2*i), 80-i);
   gEve->AddElement(line);
   mng->ImportElements(line);
   line->SetRnrSelf(kFALSE);

   //-------------------------------------------------------------------------
   // Scaled 3D "projection"
   //-------------------------------------------------------------------------

   TEveViewer *sev = gEve->SpawnNewViewer("Scaled 3D");
   TEveProjectionManager* smng =
      new TEveProjectionManager(TEveProjection::kPT_3D);
   TEveProjection* sp = smng->GetProjection();
   sp->SetUsePreScale(kTRUE);
   sp->AddPreScaleEntry(2,   0,  1);
   sp->AddPreScaleEntry(2, 100,  0.2);

   TEveScene* ss = gEve->SpawnNewScene("Scaled Geom");
   sev->AddScene(ss);
   ss->AddElement(smng);

   smng->ImportElements(gsre);

   //-------------------------------------------------------------------------

   gEve->GetBrowser()->GetTabRight()->SetTab(1);

   gEve->Redraw3D(kTRUE);
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <windows.h>
#elif   qPlatform_POSIX
#include    <unistd.h>
#endif

#include    "../../Characters/Format.h"
#include    "../../Execution/ErrNoException.h"
#include    "../../Execution/Exceptions.h"
#if     qPlatform_Windows
#include    "../../Execution/Platform/Windows/Exception.h"
#endif
#include    "../../Containers/Common.h"
#include    "../../Debug/Trace.h"

#include    "ThroughTmpFileWriter.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::IO;
using   namespace   Stroika::Foundation::IO::FileSystem;
using   namespace   Stroika::Foundation::Memory;

#if     qPlatform_Windows
using   Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif

/*
 ********************************************************************************
 ************************ FileSystem::ThroughTmpFileWriter **********************
 ********************************************************************************
 */
ThroughTmpFileWriter::ThroughTmpFileWriter (const String& realFileName, const String& tmpSuffix)
    : fRealFilePath_ (realFileName)
    , fTmpFilePath_ (realFileName + tmpSuffix)
{
    Require (not realFileName.empty ());
    Require (not tmpSuffix.empty ());
}

ThroughTmpFileWriter::~ThroughTmpFileWriter ()
{
    if (not fTmpFilePath_.empty ()) {
        DbgTrace (L"ThroughTmpFileWriter::DTOR - tmpfile not successfully commited to '%s'", fRealFilePath_.c_str ());
#if     qPlatform_Windows
        (void)::DeleteFileW (fTmpFilePath_.c_str ());
#else
        AssertNotImplemented ();
#endif
    }
}

void    ThroughTmpFileWriter::Commit ()
{
    Require (not fTmpFilePath_.empty ());    // cannot Commit more than once
    // Also - NOTE - you MUST close fTmpFilePath (any file descriptors that have opened it) BEFORE the Commit!
#if     qPlatform_Windows
    try {
        ThrowIfFalseGetLastError (::MoveFileExW (fTmpFilePath_.c_str (), fRealFilePath_.c_str (), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH));
    }
    catch (const Execution::Platform::Windows::Exception& we) {
        // On Win9x - this fails cuz OS not impl...
        if (static_cast<DWORD> (we) == ERROR_CALL_NOT_IMPLEMENTED) {
            ::DeleteFileW (fRealFilePath_.c_str ());
            ThrowIfFalseGetLastError (::MoveFileW (fTmpFilePath_.c_str (), fRealFilePath_.c_str ()));
        }
        else {
            Execution::DoReThrow ();
        }
    }
#elif   qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (::rename (fTmpFilePath_.c_str (), fRealFilePath_.c_str ()));
#else
    AssertNotImplemented ();
#endif
    fTmpFilePath_.clear ();
}
<commit_msg>fixed POSIX ThroughTmpFileWriter<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <windows.h>
#elif   qPlatform_POSIX
#include    <unistd.h>
#endif

#include    "../../Characters/Format.h"
#include    "../../Execution/ErrNoException.h"
#include    "../../Execution/Exceptions.h"
#if     qPlatform_Windows
#include    "../../Execution/Platform/Windows/Exception.h"
#endif
#include    "../../Containers/Common.h"
#include    "../../Debug/Trace.h"

#include    "ThroughTmpFileWriter.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::IO;
using   namespace   Stroika::Foundation::IO::FileSystem;
using   namespace   Stroika::Foundation::Memory;

#if     qPlatform_Windows
using   Execution::Platform::Windows::ThrowIfFalseGetLastError;
#endif

/*
 ********************************************************************************
 ************************ FileSystem::ThroughTmpFileWriter **********************
 ********************************************************************************
 */
ThroughTmpFileWriter::ThroughTmpFileWriter (const String& realFileName, const String& tmpSuffix)
    : fRealFilePath_ (realFileName)
    , fTmpFilePath_ (realFileName + tmpSuffix)
{
    Require (not realFileName.empty ());
    Require (not tmpSuffix.empty ());
}

ThroughTmpFileWriter::~ThroughTmpFileWriter ()
{
    if (not fTmpFilePath_.empty ()) {
        DbgTrace (L"ThroughTmpFileWriter::DTOR - tmpfile not successfully commited to '%s'", fRealFilePath_.c_str ());
#if     qPlatform_Windows
        (void)::DeleteFileW (fTmpFilePath_.c_str ());
#else
        AssertNotImplemented ();
#endif
    }
}

void    ThroughTmpFileWriter::Commit ()
{
    Require (not fTmpFilePath_.empty ());    // cannot Commit more than once
    // Also - NOTE - you MUST close fTmpFilePath (any file descriptors that have opened it) BEFORE the Commit!
#if     qPlatform_Windows
    try {
        ThrowIfFalseGetLastError (::MoveFileExW (fTmpFilePath_.c_str (), fRealFilePath_.c_str (), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH));
    }
    catch (const Execution::Platform::Windows::Exception& we) {
        // On Win9x - this fails cuz OS not impl...
        if (static_cast<DWORD> (we) == ERROR_CALL_NOT_IMPLEMENTED) {
            ::DeleteFileW (fRealFilePath_.c_str ());
            ThrowIfFalseGetLastError (::MoveFileW (fTmpFilePath_.c_str (), fRealFilePath_.c_str ()));
        }
        else {
            Execution::DoReThrow ();
        }
    }
#elif   qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (::rename (fTmpFilePath_.AsTString ().c_str (), fRealFilePath_.AsTString ().c_str ()));
#else
    AssertNotImplemented ();
#endif
    fTmpFilePath_.clear ();
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2013 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
 */

#include "server/zone/objects/creature/DroidObject.h"
#include "server/zone/objects/intangible/PetControlDevice.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/packets/object/StartNpcConversation.h"
#include "server/zone/packets/object/StopNpcConversation.h"
#include "server/zone/templates/mobile/ConversationScreen.h"
#include "server/zone/managers/collision/CollisionManager.h"
#include "server/zone/managers/components/ComponentManager.h"
#include "server/zone/templates/customization/AssetCustomizationManagerTemplate.h"
#include "server/zone/objects/tangible/tool/CraftingTool.h"
#include "server/zone/objects/tangible/components/droid/BaseDroidModuleComponent.h"
#include "server/zone/objects/tangible/components/droid/DroidCraftingModuleDataComponent.h"
#include "server/zone/objects/tangible/components/droid/DroidArmorModuleDataComponent.h"

void DroidObjectImplementation::initializeTransientMembers() {
	AiAgentImplementation::initializeTransientMembers();
	initDroidModules();
}

void DroidObjectImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* object){

	AiAgentImplementation::fillAttributeList( msg, object );

	float percentPower = ((float)power/(float)MAX_POWER)*100.0;
	msg->insertAttribute("@obj_attr_n:battery_power", String::valueOf((int)percentPower) + "%");

	if (paintCount > 0){
		msg->insertAttribute("customization_cnt", paintCount);
	}
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL ){
			module->fillAttributeList(msg, object);
		}
	}

	ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get();
	if( linkedCreature == NULL )
		return;

	StringBuffer fullName;
	fullName << linkedCreature->getFirstName();
	if(!linkedCreature->getLastName().isEmpty())
		fullName << " " << linkedCreature->getLastName();

	msg->insertAttribute("@obj_attr_n:owner", fullName.toString());
}

void DroidObjectImplementation::notifyInsertToZone(Zone* zone) {
	SceneObjectImplementation::notifyInsertToZone(zone);

	if( this->linkedCreature == NULL )
		return;

	ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get();
	if( linkedCreature == NULL )
		return;

	// Decay customized paint (if any)
	if (paintCount > 0){

		// Paint starts to fade when there are 4 calls left
		if (paintCount <= 4){

			// Send player notification of decay
			if( paintCount == 1 ){
				linkedCreature->sendSystemMessage("@pet/pet_menu:customization_gone"); // "Your droid's customization has completely faded away."
			}
			else{
				linkedCreature->sendSystemMessage("@pet/pet_menu:customization_fading"); // "Your droid's customization is fading away."
			}

			// Fade color to white
			String appearanceFilename = getObjectTemplate()->getAppearanceFilename();
			VectorMap<String, Reference<CustomizationVariable*> > variables;
			AssetCustomizationManagerTemplate::instance()->getCustomizationVariables(appearanceFilename.hashCode(), variables, false);
			for(int i = 0; i< variables.size(); ++i){
				String varkey = variables.elementAt(i).getKey();
				if (varkey.contains("color")){
					setCustomizationVariable(varkey, paintCount-1, true); // Palette values 3,2,1,0 are grey->white
				}
			}
		}
		--paintCount;
	}

}

int DroidObjectImplementation::rechargeFromBattery(CreatureObject* player){

	// Find droid battery in player inventory
	ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
	if (inventory == NULL){
		player->sendSystemMessage("Player inventory not found");
		return 0;
	}

	ManagedReference<SceneObject*> batterySceno = NULL;
	for (int i = 0; i < inventory->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> sceno = inventory->getContainerObject(i);
		if( sceno->getObjectTemplate()->getFullTemplateString() == "object/tangible/droid_battery/battery.iff" ){
			batterySceno = sceno;
		}
	}

	// Battery not found
	if( batterySceno == NULL ){
		showFlyText("npc_reaction/flytext","nobattery", 204, 0, 0); // "You don't have a power storage device."
		return 0;
	}

	// Battery found
	ManagedReference<TangibleObject*> batteryTano = cast<TangibleObject*>(batterySceno.get());
	if( batteryTano == NULL ){
		player->sendSystemMessage("Error with droid battery object");
		return 0;
	}

	// Reset power to max
	power = MAX_POWER;

	// Consume battery
	batteryTano->decreaseUseCount();

	showFlyText("npc_reaction/flytext","recharged", 0, 153, 0);  // "*Recharged*"
	doAnimation("power_up");
	return 0;

}

void DroidObjectImplementation::rechargeFromDroid(){

	// Reset power to max
	power = MAX_POWER;

	showFlyText("npc_reaction/flytext","recharged", 0, 153, 0);  // "*Recharged*"
	doAnimation("power_up");
	return;

}

void DroidObjectImplementation::rechargeOtherDroid(DroidObject* otherDroid){

	otherDroid->rechargeFromDroid();
	usePower(100);

}

void DroidObjectImplementation::handleLowPower(){

	// Send fly text
	showFlyText("npc_reaction/flytext","low_power", 204, 0, 0);  // "*Low Power*"
	doAnimation("power_down");

	// Stop following
	setOblivious();
	return;
}

bool DroidObjectImplementation::isPowerDroid(){

	return getObjectTemplate()->getFullTemplateString().contains( "eg_6_power_droid" );

}
void DroidObjectImplementation::initDroidModules(){
	modules.removeAll();
	ManagedReference<SceneObject*> container = getSlottedObject("crafted_components");
	if(container != NULL && container->getContainerObjectsSize() > 0) {
		SceneObject* satchel = container->getContainerObject(0);
		if(satchel != NULL && satchel->getContainerObjectsSize() > 0) {
			for (int i = 0; i < satchel->getContainerObjectsSize(); ++i) {
				ManagedReference<SceneObject*> sceno = satchel->getContainerObject(i);
				if( sceno == NULL )
					continue;
				DataObjectComponentReference* data = sceno->getDataObjectComponent();
				if(data == NULL || data->get() == NULL || !data->get()->isDroidModuleData() ){
					continue;
				}
				BaseDroidModuleComponent* module = cast<BaseDroidModuleComponent*>(data->get());
				if( module != NULL ){
					modules.add(module);
				}
			}
		}
	}
}
CraftingStation* DroidObjectImplementation::getCraftingStation(int type){
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL && module->actsAsCraftingStation()){
			DroidCraftingModuleDataComponent* craftingModule = dynamic_cast<DroidCraftingModuleDataComponent*>(module);
			if( craftingModule != NULL ){
				CraftingStation* craftingStation = craftingModule->getCraftingStation();
				if (craftingStation != NULL) {
					// case here to check each type
					if (craftingModule->validCraftingType(type) || (type == CraftingTool::JEDI && craftingModule->isWeaponDroidGeneric()) || type == CraftingTool::GENERIC && craftingModule->isWeaponDroidGeneric())
					{
						return craftingStation;
					}
				}
			}
		}
	}
	return NULL;
}
void DroidObjectImplementation::onStore() {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->onStore();
	}
}
void DroidObjectImplementation::onCall() {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->onCall();
	}

	calcArmorAndResist();
}
void DroidObjectImplementation::loadSkillMods(CreatureObject* player) {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->loadSkillMods(player);
	}
}
void DroidObjectImplementation::unloadSkillMods(CreatureObject* player) {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->unloadSkillMods(player);
	}
}

 void DroidObjectImplementation::calcArmorAndResist(){

	int level = 0;

	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL && module->isArmorModule()){
			DroidArmorModuleDataComponent* armorModule = dynamic_cast<DroidArmorModuleDataComponent*>(module);
			if( armorModule != NULL ){
				level += armorModule->getModuleLevel();
			}
		}
	}

	// Capped at 6
	if( level > 6 )
		level = 6;

	// Set armor type
	if( level == 0 ){
		armor = 0; // NO ARMOR
	}
	else if( level <= 3 ){
		armor = 1; // LIGHT ARMOR
	}
	else if( level <= 6 ){
		armor = 2; // MEDIUM ARMOR
	}

	// Set damage resistance
	if( level == 1 || level == 4 ){
		resist = 15;
	}
	else if( level == 2 || level == 5 ){
		resist = 25;
	}
	else if( level == 3 || level == 6 ){
		resist = 40;
	}
	else{
		resist = -1;
	}

}
<commit_msg>[fix] compiler warning<commit_after>/*
Copyright (C) 2013 <SWGEmu>

This File is part of Core3.

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
 */

#include "server/zone/objects/creature/DroidObject.h"
#include "server/zone/objects/intangible/PetControlDevice.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/packets/object/StartNpcConversation.h"
#include "server/zone/packets/object/StopNpcConversation.h"
#include "server/zone/templates/mobile/ConversationScreen.h"
#include "server/zone/managers/collision/CollisionManager.h"
#include "server/zone/managers/components/ComponentManager.h"
#include "server/zone/templates/customization/AssetCustomizationManagerTemplate.h"
#include "server/zone/objects/tangible/tool/CraftingTool.h"
#include "server/zone/objects/tangible/components/droid/BaseDroidModuleComponent.h"
#include "server/zone/objects/tangible/components/droid/DroidCraftingModuleDataComponent.h"
#include "server/zone/objects/tangible/components/droid/DroidArmorModuleDataComponent.h"

void DroidObjectImplementation::initializeTransientMembers() {
	AiAgentImplementation::initializeTransientMembers();
	initDroidModules();
}

void DroidObjectImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* object){

	AiAgentImplementation::fillAttributeList( msg, object );

	float percentPower = ((float)power/(float)MAX_POWER)*100.0;
	msg->insertAttribute("@obj_attr_n:battery_power", String::valueOf((int)percentPower) + "%");

	if (paintCount > 0){
		msg->insertAttribute("customization_cnt", paintCount);
	}
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL ){
			module->fillAttributeList(msg, object);
		}
	}

	ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get();
	if( linkedCreature == NULL )
		return;

	StringBuffer fullName;
	fullName << linkedCreature->getFirstName();
	if(!linkedCreature->getLastName().isEmpty())
		fullName << " " << linkedCreature->getLastName();

	msg->insertAttribute("@obj_attr_n:owner", fullName.toString());
}

void DroidObjectImplementation::notifyInsertToZone(Zone* zone) {
	SceneObjectImplementation::notifyInsertToZone(zone);

	if( this->linkedCreature == NULL )
		return;

	ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get();
	if( linkedCreature == NULL )
		return;

	// Decay customized paint (if any)
	if (paintCount > 0){

		// Paint starts to fade when there are 4 calls left
		if (paintCount <= 4){

			// Send player notification of decay
			if( paintCount == 1 ){
				linkedCreature->sendSystemMessage("@pet/pet_menu:customization_gone"); // "Your droid's customization has completely faded away."
			}
			else{
				linkedCreature->sendSystemMessage("@pet/pet_menu:customization_fading"); // "Your droid's customization is fading away."
			}

			// Fade color to white
			String appearanceFilename = getObjectTemplate()->getAppearanceFilename();
			VectorMap<String, Reference<CustomizationVariable*> > variables;
			AssetCustomizationManagerTemplate::instance()->getCustomizationVariables(appearanceFilename.hashCode(), variables, false);
			for(int i = 0; i< variables.size(); ++i){
				String varkey = variables.elementAt(i).getKey();
				if (varkey.contains("color")){
					setCustomizationVariable(varkey, paintCount-1, true); // Palette values 3,2,1,0 are grey->white
				}
			}
		}
		--paintCount;
	}

}

int DroidObjectImplementation::rechargeFromBattery(CreatureObject* player){

	// Find droid battery in player inventory
	ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
	if (inventory == NULL){
		player->sendSystemMessage("Player inventory not found");
		return 0;
	}

	ManagedReference<SceneObject*> batterySceno = NULL;
	for (int i = 0; i < inventory->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> sceno = inventory->getContainerObject(i);
		if( sceno->getObjectTemplate()->getFullTemplateString() == "object/tangible/droid_battery/battery.iff" ){
			batterySceno = sceno;
		}
	}

	// Battery not found
	if( batterySceno == NULL ){
		showFlyText("npc_reaction/flytext","nobattery", 204, 0, 0); // "You don't have a power storage device."
		return 0;
	}

	// Battery found
	ManagedReference<TangibleObject*> batteryTano = cast<TangibleObject*>(batterySceno.get());
	if( batteryTano == NULL ){
		player->sendSystemMessage("Error with droid battery object");
		return 0;
	}

	// Reset power to max
	power = MAX_POWER;

	// Consume battery
	batteryTano->decreaseUseCount();

	showFlyText("npc_reaction/flytext","recharged", 0, 153, 0);  // "*Recharged*"
	doAnimation("power_up");
	return 0;

}

void DroidObjectImplementation::rechargeFromDroid(){

	// Reset power to max
	power = MAX_POWER;

	showFlyText("npc_reaction/flytext","recharged", 0, 153, 0);  // "*Recharged*"
	doAnimation("power_up");
	return;

}

void DroidObjectImplementation::rechargeOtherDroid(DroidObject* otherDroid){

	otherDroid->rechargeFromDroid();
	usePower(100);

}

void DroidObjectImplementation::handleLowPower(){

	// Send fly text
	showFlyText("npc_reaction/flytext","low_power", 204, 0, 0);  // "*Low Power*"
	doAnimation("power_down");

	// Stop following
	setOblivious();
	return;
}

bool DroidObjectImplementation::isPowerDroid(){

	return getObjectTemplate()->getFullTemplateString().contains( "eg_6_power_droid" );

}
void DroidObjectImplementation::initDroidModules(){
	modules.removeAll();
	ManagedReference<SceneObject*> container = getSlottedObject("crafted_components");
	if(container != NULL && container->getContainerObjectsSize() > 0) {
		SceneObject* satchel = container->getContainerObject(0);
		if(satchel != NULL && satchel->getContainerObjectsSize() > 0) {
			for (int i = 0; i < satchel->getContainerObjectsSize(); ++i) {
				ManagedReference<SceneObject*> sceno = satchel->getContainerObject(i);
				if( sceno == NULL )
					continue;
				DataObjectComponentReference* data = sceno->getDataObjectComponent();
				if(data == NULL || data->get() == NULL || !data->get()->isDroidModuleData() ){
					continue;
				}
				BaseDroidModuleComponent* module = cast<BaseDroidModuleComponent*>(data->get());
				if( module != NULL ){
					modules.add(module);
				}
			}
		}
	}
}
CraftingStation* DroidObjectImplementation::getCraftingStation(int type){
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL && module->actsAsCraftingStation()){
			DroidCraftingModuleDataComponent* craftingModule = dynamic_cast<DroidCraftingModuleDataComponent*>(module);
			if( craftingModule != NULL ){
				CraftingStation* craftingStation = craftingModule->getCraftingStation();
				if (craftingStation != NULL) {
					// case here to check each type
					if (craftingModule->validCraftingType(type) || (type == CraftingTool::JEDI && craftingModule->isWeaponDroidGeneric()) || (type == CraftingTool::GENERIC && craftingModule->isWeaponDroidGeneric()))
					{
						return craftingStation;
					}
				}
			}
		}
	}
	return NULL;
}
void DroidObjectImplementation::onStore() {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->onStore();
	}
}
void DroidObjectImplementation::onCall() {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->onCall();
	}

	calcArmorAndResist();
}
void DroidObjectImplementation::loadSkillMods(CreatureObject* player) {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->loadSkillMods(player);
	}
}
void DroidObjectImplementation::unloadSkillMods(CreatureObject* player) {
	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		module->unloadSkillMods(player);
	}
}

 void DroidObjectImplementation::calcArmorAndResist(){

	int level = 0;

	for( int i=0; i<modules.size(); i++){
		BaseDroidModuleComponent* module = modules.get(i);
		if( module != NULL && module->isArmorModule()){
			DroidArmorModuleDataComponent* armorModule = dynamic_cast<DroidArmorModuleDataComponent*>(module);
			if( armorModule != NULL ){
				level += armorModule->getModuleLevel();
			}
		}
	}

	// Capped at 6
	if( level > 6 )
		level = 6;

	// Set armor type
	if( level == 0 ){
		armor = 0; // NO ARMOR
	}
	else if( level <= 3 ){
		armor = 1; // LIGHT ARMOR
	}
	else if( level <= 6 ){
		armor = 2; // MEDIUM ARMOR
	}

	// Set damage resistance
	if( level == 1 || level == 4 ){
		resist = 15;
	}
	else if( level == 2 || level == 5 ){
		resist = 25;
	}
	else if( level == 3 || level == 6 ){
		resist = 40;
	}
	else{
		resist = -1;
	}

}
<|endoftext|>


<commit_before>#include "Event.h"
#include "AssignmentSystem.h"

#include "Components\OwnerComponent.h"

#include "Events\CardAssignedEvent.h"
#include "..\Events\FightStartedEvent.h"

using namespace PinnedDownNet::Components;
using namespace PinnedDownNet::Data;
using namespace PinnedDownNet::Events;
using namespace PinnedDownGameplay::Events;
using namespace PinnedDownServer::Systems;

AssignmentSystem::AssignmentSystem()
{
}

void AssignmentSystem::InitSystem(Game* game)
{
	GameSystem::InitSystem(game);

	this->game->eventManager->AddListener(this, AssignCardAction::AssignCardActionType);
	this->game->eventManager->AddListener(this, CardCreatedEvent::CardCreatedEventType);
	this->game->eventManager->AddListener(this, CardRemovedEvent::CardRemovedEventType);
	this->game->eventManager->AddListener(this, EndTurnAction::EndTurnActionType);
	this->game->eventManager->AddListener(this, ResolveFightAction::ResolveFightActionType);
	this->game->eventManager->AddListener(this, TurnPhaseChangedEvent::TurnPhaseChangedEventType);
}

void AssignmentSystem::OnEvent(Event & newEvent)
{
	if (newEvent.GetEventType() == AssignCardAction::AssignCardActionType)
	{
		auto assignCardAction = static_cast<AssignCardAction&>(newEvent);
		this->OnAssignCard(assignCardAction);
	}
	else if (newEvent.GetEventType() == CardCreatedEvent::CardCreatedEventType)
	{
		auto cardCreatedEvent = static_cast<CardCreatedEvent&>(newEvent);
		this->OnCardCreated(cardCreatedEvent);
	}
	else if (newEvent.GetEventType() == CardRemovedEvent::CardRemovedEventType)
	{
		auto cardRemovedEvent = static_cast<CardRemovedEvent&>(newEvent);
		this->OnCardRemoved(cardRemovedEvent);
	}
	else if (newEvent.GetEventType() == EndTurnAction::EndTurnActionType)
	{
		auto endTurnAction = static_cast<EndTurnAction&>(newEvent);
		this->OnEndTurn(endTurnAction);
	}
	else if (newEvent.GetEventType() == ResolveFightAction::ResolveFightActionType)
	{
		auto resolveFightAction = static_cast<ResolveFightAction&>(newEvent);
		this->OnResolveFight(resolveFightAction);
	}
	else if (newEvent.GetEventType() == TurnPhaseChangedEvent::TurnPhaseChangedEventType)
	{
		auto turnPhaseChangedEvent = static_cast<TurnPhaseChangedEvent&>(newEvent);
		this->OnTurnPhaseChanged(turnPhaseChangedEvent);
	}
}

void AssignmentSystem::OnAssignCard(AssignCardAction& assignCardAction)
{
	// Check owners.
	auto assignedCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(assignCardAction.assignedCard, OwnerComponent::OwnerComponentType);
	auto targetCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(assignCardAction.targetCard, OwnerComponent::OwnerComponentType);

	if (assignedCardOwner != nullptr && assignedCardOwner->owner != INVALID_ENTITY_ID && targetCardOwner != nullptr && targetCardOwner->owner == INVALID_ENTITY_ID)
	{
		// Check for previous assignment.
		auto assignment = this->currentAssignments.find(assignCardAction.assignedCard);

		if (assignment != this->currentAssignments.end())
		{
			this->currentAssignments.erase(assignment);
		}

		// Assign card.
		this->currentAssignments.insert(std::pair<Entity, Entity>(assignCardAction.assignedCard, assignCardAction.targetCard));

		// Notify listeners.
		auto cardAssignedEvent = std::make_shared<CardAssignedEvent>(assignCardAction.assignedCard, assignCardAction.targetCard);
		this->game->eventManager->QueueEvent(cardAssignedEvent);
	}
}

void AssignmentSystem::OnCardCreated(CardCreatedEvent& cardCreatedEvent)
{
	if (cardCreatedEvent.owner != INVALID_ENTITY_ID)
	{
		this->playerCards.push_back(cardCreatedEvent.serverEntity);
	}
	else
	{
		this->enemyCards.push_back(cardCreatedEvent.serverEntity);
	}
}

void AssignmentSystem::OnCardRemoved(CardRemovedEvent& cardRemovedEvent)
{
	auto ownerComponent = this->game->entityManager->GetComponent<OwnerComponent>(cardRemovedEvent.serverEntity, OwnerComponent::OwnerComponentType);

	if (ownerComponent->owner != INVALID_ENTITY_ID)
	{
		this->playerCards.remove(cardRemovedEvent.serverEntity);
	}
	else
	{
		this->enemyCards.remove(cardRemovedEvent.serverEntity);
	}
}

void AssignmentSystem::OnEndTurn(EndTurnAction& endTurnAction)
{
	if (this->currentTurnPhase != TurnPhase::Assignment)
	{
		return;
	}

	// Notify listeners.
	auto turnPhaseChangedEvent = std::make_shared<TurnPhaseChangedEvent>(TurnPhase::Fight);
	this->game->eventManager->QueueEvent(turnPhaseChangedEvent);
}

void AssignmentSystem::OnResolveFight(ResolveFightAction& resolveFightAction)
{
	// Get assignment.
	auto assignedCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(resolveFightAction.assignedCard, OwnerComponent::OwnerComponentType);

	if (assignedCardOwner != nullptr && assignedCardOwner->owner != INVALID_ENTITY_ID)
	{
		auto assignment = this->currentAssignments.find(resolveFightAction.assignedCard);

		if (assignment != this->currentAssignments.end())
		{
			// Start fight.
			auto fightStartedEvent = std::make_shared<FightStartedEvent>(assignment->first, assignment->second);
			this->game->eventManager->QueueEvent(fightStartedEvent);
		}
	}
}

void AssignmentSystem::OnTurnPhaseChanged(TurnPhaseChangedEvent& turnPhaseChangedEvent)
{
	this->currentTurnPhase = turnPhaseChangedEvent.newTurnPhase;
}<commit_msg>ADDED: Gameplay - Error if not all player ships are assigned.<commit_after>#include "Event.h"
#include "AssignmentSystem.h"

#include "Components\OwnerComponent.h"

#include "Events\CardAssignedEvent.h"
#include "Events\ErrorMessageEvent.h"
#include "..\Events\FightStartedEvent.h"

using namespace PinnedDownNet::Components;
using namespace PinnedDownNet::Data;
using namespace PinnedDownNet::Events;
using namespace PinnedDownGameplay::Events;
using namespace PinnedDownServer::Systems;

AssignmentSystem::AssignmentSystem()
{
}

void AssignmentSystem::InitSystem(Game* game)
{
	GameSystem::InitSystem(game);

	this->game->eventManager->AddListener(this, AssignCardAction::AssignCardActionType);
	this->game->eventManager->AddListener(this, CardCreatedEvent::CardCreatedEventType);
	this->game->eventManager->AddListener(this, CardRemovedEvent::CardRemovedEventType);
	this->game->eventManager->AddListener(this, EndTurnAction::EndTurnActionType);
	this->game->eventManager->AddListener(this, ResolveFightAction::ResolveFightActionType);
	this->game->eventManager->AddListener(this, TurnPhaseChangedEvent::TurnPhaseChangedEventType);
}

void AssignmentSystem::OnEvent(Event & newEvent)
{
	if (newEvent.GetEventType() == AssignCardAction::AssignCardActionType)
	{
		auto assignCardAction = static_cast<AssignCardAction&>(newEvent);
		this->OnAssignCard(assignCardAction);
	}
	else if (newEvent.GetEventType() == CardCreatedEvent::CardCreatedEventType)
	{
		auto cardCreatedEvent = static_cast<CardCreatedEvent&>(newEvent);
		this->OnCardCreated(cardCreatedEvent);
	}
	else if (newEvent.GetEventType() == CardRemovedEvent::CardRemovedEventType)
	{
		auto cardRemovedEvent = static_cast<CardRemovedEvent&>(newEvent);
		this->OnCardRemoved(cardRemovedEvent);
	}
	else if (newEvent.GetEventType() == EndTurnAction::EndTurnActionType)
	{
		auto endTurnAction = static_cast<EndTurnAction&>(newEvent);
		this->OnEndTurn(endTurnAction);
	}
	else if (newEvent.GetEventType() == ResolveFightAction::ResolveFightActionType)
	{
		auto resolveFightAction = static_cast<ResolveFightAction&>(newEvent);
		this->OnResolveFight(resolveFightAction);
	}
	else if (newEvent.GetEventType() == TurnPhaseChangedEvent::TurnPhaseChangedEventType)
	{
		auto turnPhaseChangedEvent = static_cast<TurnPhaseChangedEvent&>(newEvent);
		this->OnTurnPhaseChanged(turnPhaseChangedEvent);
	}
}

void AssignmentSystem::OnAssignCard(AssignCardAction& assignCardAction)
{
	// Check owners.
	auto assignedCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(assignCardAction.assignedCard, OwnerComponent::OwnerComponentType);
	auto targetCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(assignCardAction.targetCard, OwnerComponent::OwnerComponentType);

	if (assignedCardOwner != nullptr && assignedCardOwner->owner != INVALID_ENTITY_ID && targetCardOwner != nullptr && targetCardOwner->owner == INVALID_ENTITY_ID)
	{
		// Check for previous assignment.
		auto assignment = this->currentAssignments.find(assignCardAction.assignedCard);

		if (assignment != this->currentAssignments.end())
		{
			this->currentAssignments.erase(assignment);
		}

		// Assign card.
		this->currentAssignments.insert(std::pair<Entity, Entity>(assignCardAction.assignedCard, assignCardAction.targetCard));

		// Notify listeners.
		auto cardAssignedEvent = std::make_shared<CardAssignedEvent>(assignCardAction.assignedCard, assignCardAction.targetCard);
		this->game->eventManager->QueueEvent(cardAssignedEvent);
	}
}

void AssignmentSystem::OnCardCreated(CardCreatedEvent& cardCreatedEvent)
{
	if (cardCreatedEvent.owner != INVALID_ENTITY_ID)
	{
		this->playerCards.push_back(cardCreatedEvent.serverEntity);
	}
	else
	{
		this->enemyCards.push_back(cardCreatedEvent.serverEntity);
	}
}

void AssignmentSystem::OnCardRemoved(CardRemovedEvent& cardRemovedEvent)
{
	auto ownerComponent = this->game->entityManager->GetComponent<OwnerComponent>(cardRemovedEvent.serverEntity, OwnerComponent::OwnerComponentType);

	if (ownerComponent->owner != INVALID_ENTITY_ID)
	{
		this->playerCards.remove(cardRemovedEvent.serverEntity);
	}
	else
	{
		this->enemyCards.remove(cardRemovedEvent.serverEntity);
	}
}

void AssignmentSystem::OnEndTurn(EndTurnAction& endTurnAction)
{
	if (this->currentTurnPhase != TurnPhase::Assignment)
	{
		return;
	}

	// Check if all player ships assigned.
	for (auto itPlayerShips = this->playerCards.begin(); itPlayerShips != this->playerCards.end(); ++itPlayerShips)
	{
		auto playerShip = *itPlayerShips;

		auto itAssignment = this->currentAssignments.find(playerShip);

		if (itAssignment == this->currentAssignments.end())
		{
			// Error: Player ship not assigned.
			auto errorMessageEvent = std::make_shared<ErrorMessageEvent>("Error_NotAllPlayerShipsAssigned");
			this->game->eventManager->QueueEvent(errorMessageEvent);

			return;
		}
	}

	// Notify listeners.
	auto turnPhaseChangedEvent = std::make_shared<TurnPhaseChangedEvent>(TurnPhase::Fight);
	this->game->eventManager->QueueEvent(turnPhaseChangedEvent);
}

void AssignmentSystem::OnResolveFight(ResolveFightAction& resolveFightAction)
{
	// Get assignment.
	auto assignedCardOwner = this->game->entityManager->GetComponent<OwnerComponent>(resolveFightAction.assignedCard, OwnerComponent::OwnerComponentType);

	if (assignedCardOwner != nullptr && assignedCardOwner->owner != INVALID_ENTITY_ID)
	{
		auto assignment = this->currentAssignments.find(resolveFightAction.assignedCard);

		if (assignment != this->currentAssignments.end())
		{
			// Start fight.
			auto fightStartedEvent = std::make_shared<FightStartedEvent>(assignment->first, assignment->second);
			this->game->eventManager->QueueEvent(fightStartedEvent);
		}
	}
}

void AssignmentSystem::OnTurnPhaseChanged(TurnPhaseChangedEvent& turnPhaseChangedEvent)
{
	this->currentTurnPhase = turnPhaseChangedEvent.newTurnPhase;
}<|endoftext|>


<commit_before>//
//  68000.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 08/03/2019.
//  Copyright © 2019 Thomas Harte. All rights reserved.
//

#ifndef MC68000_h
#define MC68000_h

#include <cstdint>
#include <iomanip>
#include <iostream>
#include <tuple>
#include <vector>

#include "../../ClockReceiver/ClockReceiver.hpp"
#include "../RegisterSizes.hpp"

namespace CPU {
namespace MC68000 {

/*!
	A microcycle is an atomic unit of 68000 bus activity — it is a single item large enough
	fully to specify a sequence of bus events that occur without any possible interruption.

	Concretely, a standard read cycle breaks down into at least two microcycles:

		1) a 5 half-cycle length microcycle in which the address strobe is signalled; and
		2) a 3 half-cycle length microcycle in which at least one of the data strobes is
		signalled, and the data bus is sampled.

	That is, assuming DTack were signalled when microcycle (1) ended. If not then additional
	wait state microcycles would fall between those two parts.

	The 68000 data sheet defines when the address becomes valid during microcycle (1), and
	when the address strobe is actually asserted. But those timings are fixed. So simply
	telling you that this was a microcycle during which the address trobe was signalled is
	sufficient fully to describe the bus activity.

	(Aside: see the 68000 template's definition for options re: implicit DTack; if your
	68000 owner can always predict exactly how long it will hold DTack following observation
	of an address-strobing microcycle, it can just supply those periods for accounting and
	avoid the runtime cost of actual DTack emulation. But such as the bus allows.)
*/
struct Microcycle {
	/*
		The operation code is composed of several parts; a compound low part
		that can be masked off with TypeMask identifies the type of the cycle;
		some of the other status lines are also present in the top parts of the int.
	*/
	static const int TypeMask		= 3;

	/// A NewAddress cycle is one in which the address strobe is initially low but becomes high;
	/// this correlates to states 0 to 5 of a standard read/write cycle.
	static const int Idle			= 0;

	/// A NewAddress cycle is one in which the address strobe is initially low but becomes high;
	/// this correlates to states 0 to 5 of a standard read/write cycle.
	static const int NewAddress		= 1;

	/// A SameAddress cycle is one in which the address strobe is continuously asserted, but neither
	/// of the data strobes are.
	static const int SameAddress	= 2;

	/// A Reset cycle is one in which the RESET output is asserted.
	static const int Reset			= 3;

	/// Indicates that the address and both data select strobes are active.
	static const int SelectWord		= 1 << 2;

	/// Indicates that the address strobe and exactly one of the data strobes are active; you can determine
	/// which by inspecting the low bit of the provided address. The RW line indicates a read.
	static const int SelectByte		= 1 << 3;

	/// If set, indicates a read. Otherwise, a write.
	static const int Read 			= 1 << 4;

	/// Contains the value of line FC0.
	static const int IsData 		= 1 << 5;

	/// Contains the value of line FC1.
	static const int IsProgram 		= 1 << 6;

	int operation = 0;
	HalfCycles length = HalfCycles(4);

	/*!
		For expediency, this provides a full 32-bit byte-resolution address — e.g.
		if reading indirectly via an address register, this will indicate the full
		value of the address register.

		The receiver should ignore bits 0 and 24+.
	*/
	const uint32_t *address = nullptr;
	RegisterPair16 *value = nullptr;

	bool operator ==(const Microcycle &rhs) const {
		return
			std::make_tuple(value, address, length, operation, value) ==
			std::make_tuple(rhs.value, rhs.address, rhs.length, rhs.operation, rhs.value);
	}

	// Various inspectors.

	/*! @returns true if any data select line is active; @c false otherwise. */
	inline bool data_select_active() const {
		return bool(operation & (SelectWord | SelectByte));
	}

	/*!
		@returns 0 if this byte access wants the low part of a 16-bit word; 8 if it wants the high part.
	*/
	inline unsigned int byte_shift() const {
		return (((*address) & 1) << 3) ^ 8;
	}

	/*!
		Obtains the mask to apply to a word that will leave only the byte this microcycle is selecting.

		@returns 0x00ff if this byte access wants the low part of a 16-bit word; 0xff00 if it wants the high part.
	*/
	inline uint16_t byte_mask() const {
		return uint16_t(0xff00) >> (((*address) & 1) << 3);
	}

	/*!
		Obtains the mask to apply to a word that will leave only the byte this microcycle **isn't** selecting.
		i.e. this is the part of a word that should be untouched by this microcycle.

		@returns 0xff00 if this byte access wants the low part of a 16-bit word; 0x00ff if it wants the high part.
	*/
	inline uint16_t untouched_byte_mask() const {
		return uint16_t(uint16_t(0xff) << (((*address) & 1) << 3));
	}

	/*!
		Assuming this cycle is a byte write, mutates @c destination by writing the byte to the proper upper or
		lower part, retaining the other half.
	*/
	uint16_t write_byte(uint16_t destination) const {
		return uint16_t((destination & untouched_byte_mask()) | (value->halves.low << byte_shift()));
	}

	/*!
		@returns non-zero if this is a byte read and 68000 LDS is asserted.
	*/
	inline int lower_data_select() const {
		return (operation & SelectByte) & ((*address & 1) << 3);
	}

	/*!
		@returns non-zero if this is a byte read and 68000 UDS is asserted.
	*/
	inline int upper_data_select() const {
		return (operation & SelectByte) & ~((*address & 1) << 3);
	}

	/*!
		@returns the address being accessed at the precision a 68000 supplies it —
		only 24 address bit precision, with the low bit shifted out. So it's the
		68000 address at word precision: address 0 is the first word in the address
		space, address 1 is the second word (i.e. the third and fourth bytes) in
		the address space, etc.
	*/
	uint32_t word_address() const {
		return (address ? (*address) & 0x00fffffe : 0) >> 1;
	}
};

/*!
	This is the prototype for a 68000 bus handler; real bus handlers can descend from this
	in order to get default implementations of any changes that may occur in the expected interface.
*/
class BusHandler {
	public:
		/*!
			Provides the bus handler with a single Microcycle to 'perform'.

			FC0 and FC1 are provided inside the microcycle as the IsData and IsProgram
			flags; FC2 is provided here as is_supervisor — it'll be either 0 or 1.
		*/
		HalfCycles perform_bus_operation(const Microcycle &cycle, int is_supervisor) {
			return HalfCycles(0);
		}

		void flush() {}

		/*!
			Provides information about the path of execution if enabled via the template.
		*/
		void will_perform(uint32_t address, uint16_t opcode) {}
};

#include "Implementation/68000Storage.hpp"

class ProcessorBase: public ProcessorStorage {
};

struct ProcessorState {
	uint32_t data[8];
	uint32_t address[7];
	uint32_t user_stack_pointer, supervisor_stack_pointer;
	uint32_t program_counter;
	uint16_t status;

	// TODO: More state needed to indicate current instruction, the processor's
	// progress through it, and anything it has fetched so far.
//			uint16_t current_instruction;
};

template <class T, bool dtack_is_implicit, bool signal_will_perform = false> class Processor: public ProcessorBase {
	public:
		Processor(T &bus_handler) : ProcessorBase(), bus_handler_(bus_handler) {}

		void run_for(HalfCycles duration);

		using State = ProcessorState;
		/// @returns The current processor state.
		State get_state();

		/// Sets the processor to the supplied state.
		void set_state(const State &);

		/// Sets the DTack line — @c true for active, @c false for inactive.
		inline void set_dtack(bool dtack) {
			dtack_ = dtack;
		}

		/// Sets the VPA (valid peripheral address) line — @c true for active, @c false for inactive.
		inline void set_is_peripheral_address(bool is_peripheral_address) {
			is_peripheral_address_ = is_peripheral_address;
		}

		/// Sets the bus error line — @c true for active, @c false for inactive.
		void set_bus_error(bool bus_error) {
			bus_error_ = bus_error;
		}

		/// Sets the interrupt lines, IPL0, IPL1 and IPL2.
		void set_interrupt_level(int interrupt_level) {
			bus_interrupt_level_ = interrupt_level;
		}

		/// Sets the bus request line.
		void set_bus_request(bool bus_request) {
			bus_request_ = bus_request;
		}

		/// Sets the bus acknowledge line.
		void set_bus_acknowledge(bool bus_acknowledge) {
			bus_acknowledge_ = bus_acknowledge;
		}

	private:
		T &bus_handler_;
};

#include "Implementation/68000Implementation.hpp"

}
}

#endif /* MC68000_h */
<commit_msg>Eliminates constructions of std::tuple for performance reasons.<commit_after>//
//  68000.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 08/03/2019.
//  Copyright © 2019 Thomas Harte. All rights reserved.
//

#ifndef MC68000_h
#define MC68000_h

#include <cstdint>
#include <iomanip>
#include <iostream>
#include <tuple>
#include <vector>

#include "../../ClockReceiver/ClockReceiver.hpp"
#include "../RegisterSizes.hpp"

namespace CPU {
namespace MC68000 {

/*!
	A microcycle is an atomic unit of 68000 bus activity — it is a single item large enough
	fully to specify a sequence of bus events that occur without any possible interruption.

	Concretely, a standard read cycle breaks down into at least two microcycles:

		1) a 5 half-cycle length microcycle in which the address strobe is signalled; and
		2) a 3 half-cycle length microcycle in which at least one of the data strobes is
		signalled, and the data bus is sampled.

	That is, assuming DTack were signalled when microcycle (1) ended. If not then additional
	wait state microcycles would fall between those two parts.

	The 68000 data sheet defines when the address becomes valid during microcycle (1), and
	when the address strobe is actually asserted. But those timings are fixed. So simply
	telling you that this was a microcycle during which the address trobe was signalled is
	sufficient fully to describe the bus activity.

	(Aside: see the 68000 template's definition for options re: implicit DTack; if your
	68000 owner can always predict exactly how long it will hold DTack following observation
	of an address-strobing microcycle, it can just supply those periods for accounting and
	avoid the runtime cost of actual DTack emulation. But such as the bus allows.)
*/
struct Microcycle {
	/*
		The operation code is composed of several parts; a compound low part
		that can be masked off with TypeMask identifies the type of the cycle;
		some of the other status lines are also present in the top parts of the int.
	*/
	static const int TypeMask		= 3;

	/// A NewAddress cycle is one in which the address strobe is initially low but becomes high;
	/// this correlates to states 0 to 5 of a standard read/write cycle.
	static const int Idle			= 0;

	/// A NewAddress cycle is one in which the address strobe is initially low but becomes high;
	/// this correlates to states 0 to 5 of a standard read/write cycle.
	static const int NewAddress		= 1;

	/// A SameAddress cycle is one in which the address strobe is continuously asserted, but neither
	/// of the data strobes are.
	static const int SameAddress	= 2;

	/// A Reset cycle is one in which the RESET output is asserted.
	static const int Reset			= 3;

	/// Indicates that the address and both data select strobes are active.
	static const int SelectWord		= 1 << 2;

	/// Indicates that the address strobe and exactly one of the data strobes are active; you can determine
	/// which by inspecting the low bit of the provided address. The RW line indicates a read.
	static const int SelectByte		= 1 << 3;

	/// If set, indicates a read. Otherwise, a write.
	static const int Read 			= 1 << 4;

	/// Contains the value of line FC0.
	static const int IsData 		= 1 << 5;

	/// Contains the value of line FC1.
	static const int IsProgram 		= 1 << 6;

	int operation = 0;
	HalfCycles length = HalfCycles(4);

	/*!
		For expediency, this provides a full 32-bit byte-resolution address — e.g.
		if reading indirectly via an address register, this will indicate the full
		value of the address register.

		The receiver should ignore bits 0 and 24+.
	*/
	const uint32_t *address = nullptr;
	RegisterPair16 *value = nullptr;

	bool operator ==(const Microcycle &rhs) const {
		if(value != rhs.value) return false;
		if(address != rhs.address) return false;
		if(length != rhs.length) return false;
		if(operation != rhs.operation) return false;
		return true;
	}

	// Various inspectors.

	/*! @returns true if any data select line is active; @c false otherwise. */
	inline bool data_select_active() const {
		return bool(operation & (SelectWord | SelectByte));
	}

	/*!
		@returns 0 if this byte access wants the low part of a 16-bit word; 8 if it wants the high part.
	*/
	inline unsigned int byte_shift() const {
		return (((*address) & 1) << 3) ^ 8;
	}

	/*!
		Obtains the mask to apply to a word that will leave only the byte this microcycle is selecting.

		@returns 0x00ff if this byte access wants the low part of a 16-bit word; 0xff00 if it wants the high part.
	*/
	inline uint16_t byte_mask() const {
		return uint16_t(0xff00) >> (((*address) & 1) << 3);
	}

	/*!
		Obtains the mask to apply to a word that will leave only the byte this microcycle **isn't** selecting.
		i.e. this is the part of a word that should be untouched by this microcycle.

		@returns 0xff00 if this byte access wants the low part of a 16-bit word; 0x00ff if it wants the high part.
	*/
	inline uint16_t untouched_byte_mask() const {
		return uint16_t(uint16_t(0xff) << (((*address) & 1) << 3));
	}

	/*!
		Assuming this cycle is a byte write, mutates @c destination by writing the byte to the proper upper or
		lower part, retaining the other half.
	*/
	uint16_t write_byte(uint16_t destination) const {
		return uint16_t((destination & untouched_byte_mask()) | (value->halves.low << byte_shift()));
	}

	/*!
		@returns non-zero if this is a byte read and 68000 LDS is asserted.
	*/
	inline int lower_data_select() const {
		return (operation & SelectByte) & ((*address & 1) << 3);
	}

	/*!
		@returns non-zero if this is a byte read and 68000 UDS is asserted.
	*/
	inline int upper_data_select() const {
		return (operation & SelectByte) & ~((*address & 1) << 3);
	}

	/*!
		@returns the address being accessed at the precision a 68000 supplies it —
		only 24 address bit precision, with the low bit shifted out. So it's the
		68000 address at word precision: address 0 is the first word in the address
		space, address 1 is the second word (i.e. the third and fourth bytes) in
		the address space, etc.
	*/
	uint32_t word_address() const {
		return (address ? (*address) & 0x00fffffe : 0) >> 1;
	}
};

/*!
	This is the prototype for a 68000 bus handler; real bus handlers can descend from this
	in order to get default implementations of any changes that may occur in the expected interface.
*/
class BusHandler {
	public:
		/*!
			Provides the bus handler with a single Microcycle to 'perform'.

			FC0 and FC1 are provided inside the microcycle as the IsData and IsProgram
			flags; FC2 is provided here as is_supervisor — it'll be either 0 or 1.
		*/
		HalfCycles perform_bus_operation(const Microcycle &cycle, int is_supervisor) {
			return HalfCycles(0);
		}

		void flush() {}

		/*!
			Provides information about the path of execution if enabled via the template.
		*/
		void will_perform(uint32_t address, uint16_t opcode) {}
};

#include "Implementation/68000Storage.hpp"

class ProcessorBase: public ProcessorStorage {
};

struct ProcessorState {
	uint32_t data[8];
	uint32_t address[7];
	uint32_t user_stack_pointer, supervisor_stack_pointer;
	uint32_t program_counter;
	uint16_t status;

	// TODO: More state needed to indicate current instruction, the processor's
	// progress through it, and anything it has fetched so far.
//			uint16_t current_instruction;
};

template <class T, bool dtack_is_implicit, bool signal_will_perform = false> class Processor: public ProcessorBase {
	public:
		Processor(T &bus_handler) : ProcessorBase(), bus_handler_(bus_handler) {}

		void run_for(HalfCycles duration);

		using State = ProcessorState;
		/// @returns The current processor state.
		State get_state();

		/// Sets the processor to the supplied state.
		void set_state(const State &);

		/// Sets the DTack line — @c true for active, @c false for inactive.
		inline void set_dtack(bool dtack) {
			dtack_ = dtack;
		}

		/// Sets the VPA (valid peripheral address) line — @c true for active, @c false for inactive.
		inline void set_is_peripheral_address(bool is_peripheral_address) {
			is_peripheral_address_ = is_peripheral_address;
		}

		/// Sets the bus error line — @c true for active, @c false for inactive.
		void set_bus_error(bool bus_error) {
			bus_error_ = bus_error;
		}

		/// Sets the interrupt lines, IPL0, IPL1 and IPL2.
		void set_interrupt_level(int interrupt_level) {
			bus_interrupt_level_ = interrupt_level;
		}

		/// Sets the bus request line.
		void set_bus_request(bool bus_request) {
			bus_request_ = bus_request;
		}

		/// Sets the bus acknowledge line.
		void set_bus_acknowledge(bool bus_acknowledge) {
			bus_acknowledge_ = bus_acknowledge;
		}

	private:
		T &bus_handler_;
};

#include "Implementation/68000Implementation.hpp"

}
}

#endif /* MC68000_h */
<|endoftext|>


<commit_before>#include "DefenseBase.h"

DefenseBase::DefenseBase()
{
	zgrada.setSize(sf::Vector2f(150, 70));
	zgrada.setPosition(0, 530);
	zgrada.setFillColor(sf::Color::Red);

	detectionLine.setSize(sf::Vector2f(800, 2));
	detectionLine.setPosition(600, 0);
	detectionLine.setRotation(90);
	detectionLine.setFillColor(sf::Color::Green);

	collisionLine.setSize(sf::Vector2f(800, 2));
	collisionLine.setPosition(200, 0);
	collisionLine.setRotation(90);
	collisionLine.setFillColor(sf::Color::White);

}

void DefenseBase::draw(sf::RenderWindow* window)
{
	window->draw(zgrada);
	window->draw(detectionLine);
	window->draw(collisionLine);
}

void DefenseBase::checkFirstWall(RocketManager* rockets)
{
	if(rockets->hasRocketsAt(detectionLine.getPosition().x))
	{
		Rocket* r = rockets->getRocketAt((detectionLine.getPosition().x));
		det_rockets.push_back(r);
		std::cout << "Detected rocket" << std::endl;
	}
}

void DefenseBase::gatherPoints(RocketManager* rockets)
{
	for(unsigned int i = 0; i < det_rockets.size(); i++)
	{
	    //Zbog trenutne interpolacije koja radi sa tri tacke uzimamo x,y poz na 3 mesta

		//pozicija tacaka je izabrana nasumicno, cisto da ima dovoljno udaljene tacke
		//da precizno opise funkciju

		if(det_rockets[i]->getType() == 0)
		{
		if(det_rockets[i]->getShape().getPosition().x == 500)
		{
			det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
			std::cout<<"Dodao\n";
		}

		if(det_rockets[i]->getShape().getPosition().x == 400)
		{
			det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
			std::cout<<"Dodao\n";
		}

		if(det_rockets[i]->getShape().getPosition().x == 300)
		{
			det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
			std::cout<<"Dodao\n";
		}

		if(det_rockets[i]->getCount() == 3)
		{

			Rocket *r = rockets->getRocket(RocketManager::DEFENSE);
			float tmp[3];

			//treba nam niz tacaka za onaj algo. interpolacije pa to ovde popunjavamo
			float x[3], y[3];
			for(int j = 0; j < 3; ++j)
			{
				x[j] = det_rockets[i]->points[j].x;
				y[j] = det_rockets[i]->points[j].y;
			//	std::cout<<x[j]<<" "<<y[j]<<std::endl;
			}

			std::cout<<"Odbrana raketa..bum"<<std::endl;

			interpolation(x, y, tmp);
			//tmp = r->getFun();

			float startX = -400;
			float startY = 300;
			float targetX = -400 + collisionLine.getPosition().x;
			float targetY = tmp[0]*targetX*targetX + tmp[1]*targetX + tmp[2];
			float midX = (startX + targetX)/2;
			float midY = (startY + targetY)/2;

			float x1[3];
			float y1[3];

			x1[0] = startX; x1[1] = midX; x1[2] = targetX;
			y1[0] = startY; y1[1] = midY; y1[2] = targetY;
			//std::cout << startX << " " << midX << " " << targetX << std::endl;
			//std::cout << startY << " " << midY << " " << targetY << std::endl;
			//interpolation(x1, y1, r->getFun());
			//r->setActive(true);
			r->setType(1);
			r->setFun(0, -0.5, 0);
			r->setX(-400);
			r->setY(300);

			//na osnovu ovih tacaka treba da se uradi interpolacija
			//i da se dobije funkcija, pa mozemo da nadjemo gde se sece sa pravom
			det_rockets.pop_back();
		}
		}

	}
}

void DefenseBase::setTarget()
{
	//uzmi odgavarajuci niz tacaka
	//uradi interpolaciju
	//dobijemo funkciju
	//izracunamo funkciju u tacki
	//posaljemo raketu u toj tacki
}<commit_msg>racunanje putanje za odbranu<commit_after>#include "DefenseBase.h"

DefenseBase::DefenseBase()
{
	zgrada.setSize(sf::Vector2f(150, 70));
	zgrada.setPosition(0, 530);
	zgrada.setFillColor(sf::Color::Red);

	detectionLine.setSize(sf::Vector2f(800, 2));
	detectionLine.setPosition(600, 0);
	detectionLine.setRotation(90);
	detectionLine.setFillColor(sf::Color::Green);

	collisionLine.setSize(sf::Vector2f(800, 2));
	collisionLine.setPosition(200, 0);
	collisionLine.setRotation(90);
	collisionLine.setFillColor(sf::Color::White);

}

void DefenseBase::draw(sf::RenderWindow* window)
{
	window->draw(zgrada);
	window->draw(detectionLine);
	window->draw(collisionLine);
}

void DefenseBase::checkFirstWall(RocketManager* rockets)
{
	if(rockets->hasRocketsAt(detectionLine.getPosition().x))
	{
		Rocket* r = rockets->getRocketAt((detectionLine.getPosition().x));
		det_rockets.push_back(r);
		//std::cout << "Detected rocket" << std::endl;
	}
}

void DefenseBase::gatherPoints(RocketManager* rockets)
{
	for(unsigned int i = 0; i < det_rockets.size(); i++)
	{
	    //Zbog trenutne interpolacije koja radi sa tri tacke uzimamo x,y poz na 3 mesta

		//pozicija tacaka je izabrana nasumicno, cisto da ima dovoljno udaljene tacke
		//da precizno opise funkciju

		if(det_rockets[i]->getType() == 0)
		{
			if(det_rockets[i]->getShape().getPosition().x == 500)
			{
				det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
				//std::cout<<"Dodao\n";
			}

			if(det_rockets[i]->getShape().getPosition().x == 400)
			{
				det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
				//std::cout<<"Dodao\n";
			}

			if(det_rockets[i]->getShape().getPosition().x == 300)
			{
				det_rockets[i]->setPoint(det_rockets[i]->getShape().getPosition());
				//std::cout<<"Dodao\n";
			}

			if(det_rockets[i]->getCount() == 3)
			{

				Rocket *r = rockets->getRocket(RocketManager::DEFENSE);
				float tmp[3];		//funkcija napadacke rakete

				//treba nam niz tacaka za onaj algo. interpolacije pa to ovde popunjavamo
				float x[3], y[3];
				for(int j = 0; j < 3; ++j)
				{
					x[j] = det_rockets[i]->points[j].x - 400;	//transliramo u nas koordinatni sistem za racunanje pozicije
					y[j] = det_rockets[i]->points[j].y - 300;	//PONETI PAPIR SA KOORDINATNIM SISTEMOM
					std::cout<<x[j]<<" "<<y[j]<<std::endl;
				}

				std::cout<<"Odbrana raketa..bum"<<std::endl;

				interpolation(x, y, tmp);		//sacuvamo putanju detektovane rakete u tmp

				float startX = -400;			//raketa krece iz tacke(-400, -300)
				float startY = -300;
				float targetX = -400 + collisionLine.getPosition().x;	//pozicija prave na kojoj gadjamo
				float targetY = tmp[0]*targetX*targetX + tmp[1]*targetX + tmp[2];//vrednost putanje detektovane rakete u toj tacki
				float midX = (startX + targetX)/2;	//damo tacku izmedju, da se krece po linearnoj funkciji
				float midY = (startY + targetY)/2;

				float x1[3];
				float y1[3];

				x1[0] = startX; x1[1] = midX; x1[2] = targetX;	//postavimo vrednosti za interpolaciju
				y1[0] = startY; y1[1] = midY; y1[2] = targetY;
				//std::cout << startX << " " << midX << " " << targetX << std::endl;
				//std::cout << startY << " " << midY << " " << targetY << std::endl;
				interpolation(x1, y1, r->getFun());	//izracunamo linearnu funkciju po kojoj se krece, i ubacimo u odbrambenu raketu
				r->setType(1);
				//r->setFun(0, -0.5, 0);
				r->setX(-400);	//postavljanje zbog crtanja
				r->setY(-300);

				//na osnovu ovih tacaka treba da se uradi interpolacija
				//i da se dobije funkcija, pa mozemo da nadjemo gde se sece sa pravom
				det_rockets.pop_back();
			}
		}

	}
}

void DefenseBase::setTarget()
{
	//uzmi odgavarajuci niz tacaka
	//uradi interpolaciju
	//dobijemo funkciju
	//izracunamo funkciju u tacki
	//posaljemo raketu u toj tacki
}<|endoftext|>


<commit_before>#include "ModuleImGui.h"
#include "PanelConsole.h"

#include <iostream>
#include <string>

ModuleImGui::ModuleImGui(Application * app, bool start_enabled) : Module(app, start_enabled)
{
	show_test_window = true;
	object_p = false;
}

ModuleImGui::~ModuleImGui()
{
	show_test_window = true;
	object_p = false;
	console = nullptr;
}

bool ModuleImGui::Init()
{

	ImGui_ImplSdl_Init(App->window->window);

	ImGuiIO& io = ImGui::GetIO();
	io.IniFilename = "Settings/imgui.ini";

	AddPanel(console = new PanelConsole());

	return true;
}

update_status ModuleImGui::PreUpdate(float dt)
{
	ImGui_ImplSdl_NewFrame(App->window->window);

	ImGuiIO& io = ImGui::GetIO();

	//Set Keyboard / Mouse bindings here

	return update_status::UPDATE_CONTINUE;
}

update_status ModuleImGui::Update(float dt)
{

	for (std::list<Panel*>::iterator it = panels.begin(); it != panels.end(); it++) {
		if((*it)->active)
			(*it)->Draw();
	}

	if (ImGui::BeginMainMenuBar()) {
		if (ImGui::BeginMenu("File")) {
			if (ImGui::Button("Quit")) {
				return update_status::UPDATE_STOP;
			}
			ImGui::EndMenu();
		}
		if (ImGui::BeginMenu("Objects")) {
			ImGui::EndMenu();
		}
		if (ImGui::BeginMenu("View")) {
			ImGui::MenuItem("Object Creation", "O", &object_p);
			ImGui::MenuItem("Console", "1", &console->active);
			ImGui::EndMenu();
		}
		ImGui::EndMainMenuBar();
	}

	show_test_window = true;

	if (show_test_window == true) {
		ImGui::ShowTestWindow(&show_test_window);
		ImGui::ShowMetricsWindow(&show_test_window);
	}

	if (object_p) {
		if (ImGui::Begin("Object Creation")) {
			if (ImGui::Button("Go Random", ImVec2(100, 50))) {
				for (int i = 0; i < 100; i++) {
					float r = 10;
					AddSphere(1, 1, 1, r);
					ImGuiTextBuffer t;
					string st = "Created Sphere n " + std::to_string(i + 1);
					t.append(st.c_str());
					console->ConsoleLog(t.begin());
				}

			}
			ImGui::End();
		}
	}

	ImGui::Render();

	return update_status::UPDATE_CONTINUE;
}

update_status ModuleImGui::PostUpdate(float dt)
{
	return update_status::UPDATE_CONTINUE;
}

bool ModuleImGui::CleanUp()
{
	for (std::list<Panel*>::iterator it = panels.begin(); it != panels.end(); it++) {
		if ((*it) != nullptr) {
			delete (*it);
		}
	}

	panels.clear();

	if (!spheres.empty()) {
		for (std::list<Sphere*>::iterator it = spheres.begin(); it != spheres.end(); it++) {
			if (it._Ptr->_Myval != nullptr) {
				delete it._Ptr->_Myval;
			}
		}
	}

	console = nullptr;

	return true;
}

void ModuleImGui::AddPanel(Panel * n_panel)
{
	panels.push_back(n_panel);
}

Sphere* ModuleImGui::AddSphere(const float x, const float y, const float z, float radius)
{
	math::float3 point = { x, y, z };
	Sphere* s = new Sphere(point, radius);
	spheres.push_back(s);
	return s;
}
<commit_msg>Console Showing spher enumber<commit_after>#include "ModuleImGui.h"
#include "PanelConsole.h"

#include <iostream>
#include <string>

ModuleImGui::ModuleImGui(Application * app, bool start_enabled) : Module(app, start_enabled)
{
	show_test_window = true;
	object_p = false;
}

ModuleImGui::~ModuleImGui()
{
	show_test_window = true;
	object_p = false;
	console = nullptr;
}

bool ModuleImGui::Init()
{

	ImGui_ImplSdl_Init(App->window->window);

	ImGuiIO& io = ImGui::GetIO();
	io.IniFilename = "Settings/imgui.ini";

	AddPanel(console = new PanelConsole());

	return true;
}

update_status ModuleImGui::PreUpdate(float dt)
{
	ImGui_ImplSdl_NewFrame(App->window->window);

	ImGuiIO& io = ImGui::GetIO();

	//Set Keyboard / Mouse bindings here

	return update_status::UPDATE_CONTINUE;
}

update_status ModuleImGui::Update(float dt)
{

	for (std::list<Panel*>::iterator it = panels.begin(); it != panels.end(); it++) {
		if((*it)->active)
			(*it)->Draw();
	}

	if (ImGui::BeginMainMenuBar()) {
		if (ImGui::BeginMenu("File")) {
			if (ImGui::Button("Quit")) {
				return update_status::UPDATE_STOP;
			}
			ImGui::EndMenu();
		}
		if (ImGui::BeginMenu("Objects")) {
			ImGui::EndMenu();
		}
		if (ImGui::BeginMenu("View")) {
			ImGui::MenuItem("Object Creation", "O", &object_p);
			ImGui::MenuItem("Console", "1", &console->active);
			ImGui::EndMenu();
		}
		ImGui::EndMainMenuBar();
	}

	show_test_window = true;

	if (show_test_window == true) {
		ImGui::ShowTestWindow(&show_test_window);
		ImGui::ShowMetricsWindow(&show_test_window);
	}

	if (object_p) {
		if (ImGui::Begin("Object Creation")) {
			if (ImGui::Button("Go Random", ImVec2(100, 50))) {
				for (int i = 0; i < 100; i++) {
					float r = 10;
					AddSphere(1, 1, 1, r);
					ImGuiTextBuffer t;
					string st = "Created Sphere " + std::to_string(i + 1);
					console->ConsoleLog(st.c_str());
				}

			}
			ImGui::End();
		}
	}

	ImGui::Render();

	return update_status::UPDATE_CONTINUE;
}

update_status ModuleImGui::PostUpdate(float dt)
{
	return update_status::UPDATE_CONTINUE;
}

bool ModuleImGui::CleanUp()
{
	for (std::list<Panel*>::iterator it = panels.begin(); it != panels.end(); it++) {
		if ((*it) != nullptr) {
			delete (*it);
		}
	}

	panels.clear();

	if (!spheres.empty()) {
		for (std::list<Sphere*>::iterator it = spheres.begin(); it != spheres.end(); it++) {
			if (it._Ptr->_Myval != nullptr) {
				delete it._Ptr->_Myval;
			}
		}
	}

	console = nullptr;

	return true;
}

void ModuleImGui::AddPanel(Panel * n_panel)
{
	panels.push_back(n_panel);
}

Sphere* ModuleImGui::AddSphere(const float x, const float y, const float z, float radius)
{
	math::float3 point = { x, y, z };
	Sphere* s = new Sphere(point, radius);
	spheres.push_back(s);
	return s;
}
<|endoftext|>


<commit_before>#include "QRenderingWidget.h"
#include <qpainter.h>
#include <QKeyEvent>
#include <ctime>
#include <memory>
#include "BasicRenderer\PrimitiveTypes.h"
#include "BasicRenderer\ImageFormats.h"
#include "BasicRenderer\Vector3.h"
#include "BasicRenderer\ObjLoader.h"
#include "BasicRenderer\ImageExporter.h"

QRenderingWidget::QRenderingWidget(QWidget* parent)
{
	QOpenGLWidget::QOpenGLWidget(parent);
	bRenderer = std::make_unique<BasicRenderer>();
	setMouseTracking(false);
}

QRenderingWidget::~QRenderingWidget()
{
}

void QRenderingWidget::SetScene(const char* filename)
{
	scene = std::make_unique<World>();

	scene->sun.SetDirection({ 1.0f, -0.5f, 1.0f });

	SceneObject* bunny = new SceneObject(ObjLoader::Load(filename));
	bunny->transform.SetScale(10.f, 10.f, 10.f);
	bunny->transform.SetPosition(0.0f, -1.0f, -5.0f);
	//bunny->transform.Rotate(0.0f, 0.01f, 0.0f);
	scene.get()->hierarchy.push_back(bunny);

	Sphere* sp = new Sphere({ -0.5f, 0.0f, -3.0f }, 1.5f);
	Sphere* sp2 = new Sphere({ 0.5f, 0.0f, -1.0f }, 0.5f);

	scene.get()->hierarchy.push_back(sp);
	scene.get()->hierarchy.push_back(sp2);
}

void QRenderingWidget::SaveFrame(const char* path)
{
	ImageExporter::ExportToBMP(path, frame);
}

void QRenderingWidget::SetRenderingMode(int index)
{
	switch (index)
	{
	case 1:
		renderingMode = BasicRenderer::RenderingMode::RAYTRACER;
		break;
	default:
		renderingMode = BasicRenderer::RenderingMode::RASTERIZER;
		break;
	}
}

void QRenderingWidget::SetShadingMode(int index)
{
	switch (index)
	{
	case 1:
		shadingMode = BasicRenderer::ShadingMode::NORMAL;
		break;
	default:
		shadingMode = BasicRenderer::ShadingMode::LIT;
		break;
	}
}

void QRenderingWidget::initializeGL()
{
	img = std::make_unique<QImage>(width(), height(), QImage::Format_ARGB32);
	img->fill(QColor(211, 211, 211));

	renderingTime = clock();

	timer = std::make_unique<QTimer>(this);
	timer->setInterval(15);
	timer->start();
	connect(timer.get(), SIGNAL(timeout()), this, SLOT(RenderFrame()));

}

void QRenderingWidget::resizeGL(int w, int h)
{
	img = std::make_unique<QImage>(w, h, QImage::Format_ARGB32);
	emit RendererResized();
}

void QRenderingWidget::paintGL()
{

}

void QRenderingWidget::RenderFrame()
{
	float deltaMs = (clock() - renderingTime) * 0.001;
	renderingTime = clock();

	bRenderer->camera.transform.Rotate(cameraRot.y * deltaMs, cameraRot.x * deltaMs, 0.0f);

	Vector3 forward = bRenderer->camera.transform.right * cameraPos.z;
	Vector3 right = bRenderer->camera.transform.forward * cameraPos.x;
	Vector3 up = bRenderer->camera.transform.up * cameraPos.y;
	bRenderer->camera.transform.Translate((forward + right + up) * deltaMs);

	cameraPos = Vector3::Zero();
	cameraRot = Vector2::Zero();

	update();
}

void QRenderingWidget::paintEvent(QPaintEvent * e)
{
	QPainter painter(this) ;

	double beginClock = clock();

	frame = bRenderer->Render(width(), height(), *scene, renderingMode, shadingMode);

	QRgb* rgb = reinterpret_cast<QRgb*>(img->bits());
	int size = width() * height();

	const Color* c = frame->GetColorBuffer();

	for (int i = 0; i < size; ++i)
	{
		unsigned int ua = 255 << 24;
		ua |= static_cast<unsigned int>(c[i].x * 255) << 16;
		ua |= static_cast<unsigned int>(c[i].y * 255) << 8;
		ua |= static_cast<unsigned int>(c[i].z * 255);

		rgb[i] = ua;
	}

	painter.drawImage(0, 0, *img);

	double endClock = clock() - beginClock;

	emit RenderingCompleted(endClock);

}

void QRenderingWidget::keyPressEvent(QKeyEvent * event)
{

	if (event->type() == QKeyEvent::KeyPress)
	{
		if (event->key() == Qt::Key::Key_A)
		{
			cameraPos.x -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_D)
		{
			cameraPos.x += cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_W)
		{
			cameraPos.z += cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_S)
		{
			cameraPos.z -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_Q)
		{
			cameraPos.y -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_E)
		{
			cameraPos.y += cameraSpeed;
		}
	}

	if (event->type() == QKeyEvent::KeyRelease)
	{
		if (event->key() == Qt::Key::Key_Escape)
		{
			//TODO
		}
	}
}

void QRenderingWidget::mousePressEvent(QMouseEvent * event)
{
	lastMousePos = Vector2(event->x(), event->y());
}

void QRenderingWidget::mouseMoveEvent(QMouseEvent * event)
{
	Vector2 currentPos(event->x(), event->y());
	float ratio = 1.0 / height();
	cameraRot = cameraRot + Vector2((currentPos.x - lastMousePos.x) * ratio * cameraRotationSpeed, (currentPos.y - lastMousePos.y) * ratio * cameraRotationSpeed);
	lastMousePos = currentPos;
}

<commit_msg>improved QGLWidget render loop<commit_after>#include "QRenderingWidget.h"
#include <qpainter.h>
#include <QKeyEvent>
#include <ctime>
#include <memory>
#include "BasicRenderer\PrimitiveTypes.h"
#include "BasicRenderer\ImageFormats.h"
#include "BasicRenderer\Vector3.h"
#include "BasicRenderer\ObjLoader.h"
#include "BasicRenderer\ImageExporter.h"

QRenderingWidget::QRenderingWidget(QWidget* parent)
{
	QOpenGLWidget::QOpenGLWidget(parent);
	bRenderer = std::make_unique<BasicRenderer>();
	setMouseTracking(false);
}

QRenderingWidget::~QRenderingWidget()
{
}

void QRenderingWidget::SetScene(const char* filename)
{
	scene = std::make_unique<World>();

	scene->sun.SetDirection({ 1.0f, -0.5f, 1.0f });

	SceneObject* bunny = new SceneObject(ObjLoader::Load(filename));
	bunny->transform.SetScale(10.f, 10.f, 10.f);
	bunny->transform.SetPosition(0.0f, -1.0f, -5.0f);
	//bunny->transform.Rotate(0.0f, 0.01f, 0.0f);
	scene.get()->hierarchy.push_back(bunny);

	Sphere* sp = new Sphere({ -0.5f, 0.0f, -3.0f }, 1.5f);
	Sphere* sp2 = new Sphere({ 0.5f, 0.0f, -1.0f }, 0.5f);

	scene.get()->hierarchy.push_back(sp);
	scene.get()->hierarchy.push_back(sp2);
}

void QRenderingWidget::SaveFrame(const char* path)
{
	ImageExporter::ExportToBMP(path, frame);
}

void QRenderingWidget::SetRenderingMode(int index)
{
	switch (index)
	{
	case 1:
		renderingMode = BasicRenderer::RenderingMode::RAYTRACER;
		break;
	default:
		renderingMode = BasicRenderer::RenderingMode::RASTERIZER;
		break;
	}
}

void QRenderingWidget::SetShadingMode(int index)
{
	switch (index)
	{
	case 1:
		shadingMode = BasicRenderer::ShadingMode::NORMAL;
		break;
	default:
		shadingMode = BasicRenderer::ShadingMode::LIT;
		break;
	}
}

void QRenderingWidget::initializeGL()
{
	img = std::make_unique<QImage>(width(), height(), QImage::Format_ARGB32);
	img->fill(QColor(211, 211, 211));

	renderingTime = clock();

	connect(this, SIGNAL(RenderingCompleted(double)), this, SLOT(RenderFrame()));
}

void QRenderingWidget::resizeGL(int w, int h)
{
	img = std::make_unique<QImage>(w, h, QImage::Format_ARGB32);
	emit RendererResized();
}

void QRenderingWidget::paintGL()
{

}

void QRenderingWidget::RenderFrame()
{
	float deltaMs = (clock() - renderingTime) * 0.001f;
	renderingTime = clock();

	bRenderer->camera.transform.Rotate(cameraRot.y * deltaMs, cameraRot.x * deltaMs, 0.0f);

	Vector3 forward = bRenderer->camera.transform.right * cameraPos.z;
	Vector3 right = bRenderer->camera.transform.forward * cameraPos.x;
	Vector3 up = bRenderer->camera.transform.up * cameraPos.y;
	bRenderer->camera.transform.Translate((forward + right + up) * deltaMs);

	cameraPos = Vector3::Zero();
	cameraRot = Vector2::Zero();

	//Calls paintEvent()
	update();
}

void QRenderingWidget::paintEvent(QPaintEvent * e)
{
	QPainter painter(this) ;

	double beginClock = clock();

	frame = bRenderer->Render(width(), height(), *scene, renderingMode, shadingMode);

	QRgb* rgb = reinterpret_cast<QRgb*>(img->bits());
	int size = width() * height();

	const Color* c = frame->GetColorBuffer();

	for (int i = 0; i < size; ++i)
	{
		unsigned int ua = 255 << 24;
		ua |= static_cast<unsigned int>(c[i].x * 255) << 16;
		ua |= static_cast<unsigned int>(c[i].y * 255) << 8;
		ua |= static_cast<unsigned int>(c[i].z * 255);

		rgb[i] = ua;
	}

	painter.drawImage(0, 0, *img);

	double endClock = clock() - beginClock;

	emit RenderingCompleted(endClock);
}

void QRenderingWidget::keyPressEvent(QKeyEvent * event)
{

	if (event->type() == QKeyEvent::KeyPress)
	{
		if (event->key() == Qt::Key::Key_A)
		{
			cameraPos.x -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_D)
		{
			cameraPos.x += cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_W)
		{
			cameraPos.z += cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_S)
		{
			cameraPos.z -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_Q)
		{
			cameraPos.y -= cameraSpeed;
		}
		if (event->key() == Qt::Key::Key_E)
		{
			cameraPos.y += cameraSpeed;
		}
	}

	if (event->type() == QKeyEvent::KeyRelease)
	{
		if (event->key() == Qt::Key::Key_Escape)
		{
			//TODO
		}
	}
}

void QRenderingWidget::mousePressEvent(QMouseEvent * event)
{
	lastMousePos = Vector2(event->x(), event->y());
}

void QRenderingWidget::mouseMoveEvent(QMouseEvent * event)
{
	Vector2 currentPos(event->x(), event->y());
	float ratio = 1.0 / height();
	cameraRot = cameraRot + Vector2((currentPos.x - lastMousePos.x) * ratio * cameraRotationSpeed, (currentPos.y - lastMousePos.y) * ratio * cameraRotationSpeed);
	lastMousePos = currentPos;
}

<|endoftext|>


<commit_before>// Copyright blackw 2015-2020

#include "UnrealSandboxTerrainPrivatePCH.h"
#include "TerrainZoneComponent.h"
#include "SandboxTerrainController.h"

UTerrainZoneComponent::UTerrainZoneComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {

}

void UTerrainZoneComponent::makeTerrain() {
	if (voxel_data == NULL) {
		voxel_data = GetTerrainController()->GetTerrainVoxelDataByPos(GetComponentLocation());
	}

	if (voxel_data == NULL) {
		return;
	}

	std::shared_ptr<MeshData> md_ptr = generateMesh();

	if (IsInGameThread()) {
		applyTerrainMesh(md_ptr);
		voxel_data->resetLastMeshRegenerationTime();
	} else {
		UE_LOG(LogTemp, Warning, TEXT("non-game thread -> invoke async task"));
		if (GetTerrainController() != NULL) {
			GetTerrainController()->invokeZoneMeshAsync(this, md_ptr);
		}
	}
}

std::shared_ptr<MeshData> UTerrainZoneComponent::generateMesh() {
	double start = FPlatformTime::Seconds();

	if (voxel_data->getDensityFillState() == VoxelDataFillState::ZERO || voxel_data->getDensityFillState() == VoxelDataFillState::ALL) {
		return NULL;
	}

	bool enableLOD = GetTerrainController()->bEnableLOD;

	VoxelDataParam vdp;

	if (enableLOD) {
		vdp.bGenerateLOD = true;
		vdp.collisionLOD = 1;
	} else {
		vdp.bGenerateLOD = false;
		vdp.collisionLOD = 0;
	}

	MeshDataPtr md_ptr = sandboxVoxelGenerateMesh(*voxel_data, vdp);

	double end = FPlatformTime::Seconds();
	double time = (end - start) * 1000;

	UE_LOG(LogTemp, Warning, TEXT("ASandboxTerrainZone::generateMesh -------------> %f %f %f --> %f ms"), GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z, time);

	return md_ptr;
}

void UTerrainZoneComponent::applyTerrainMesh(std::shared_ptr<MeshData> mesh_data_ptr) {
	double start = FPlatformTime::Seconds();

	MeshData* mesh_data = mesh_data_ptr.get();

	if (mesh_data == NULL) {
		return;
	}

	MeshDataSection& MeshDataSection = mesh_data->MeshDataSectionLOD[0];
	FProcMeshSection& MeshSection = MeshDataSection.MainMesh;

	if (MeshSection.ProcVertexBuffer.Num() == 0) {
		//return;
	}

	const int section = 0;

	MainTerrainMesh->SetMobility(EComponentMobility::Movable);
	MainTerrainMesh->AddLocalRotation(FRotator(0.0f, 0.01, 0.0f));  // workaround
	MainTerrainMesh->AddLocalRotation(FRotator(0.0f, -0.01, 0.0f)); // workaround

	MainTerrainMesh->SetMeshData(mesh_data_ptr);

	MainTerrainMesh->SetMobility(EComponentMobility::Stationary);
	MainTerrainMesh->SetVisibility(false);
	MainTerrainMesh->SetCastShadow(true);
	MainTerrainMesh->bCastHiddenShadow = true;
	MainTerrainMesh->SetMaterial(0, GetTerrainController()->TerrainMaterial);

	CollisionMesh->SetMeshData(mesh_data_ptr);

	MainTerrainMesh->SetVisibility(true);
	MainTerrainMesh->SetCollisionProfileName(TEXT("BlockAll"));

	double end = FPlatformTime::Seconds();
	double time = (end - start) * 1000;
	UE_LOG(LogTemp, Warning, TEXT("ASandboxTerrainZone::applyTerrainMesh ---------> %f %f %f --> %f ms"), GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z, time);
}<commit_msg>fix ApplyTerrain issues<commit_after>// Copyright blackw 2015-2020

#include "UnrealSandboxTerrainPrivatePCH.h"
#include "TerrainZoneComponent.h"
#include "SandboxTerrainController.h"

UTerrainZoneComponent::UTerrainZoneComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {

}

void UTerrainZoneComponent::makeTerrain() {
	if (voxel_data == NULL) {
		voxel_data = GetTerrainController()->GetTerrainVoxelDataByPos(GetComponentLocation());
	}

	if (voxel_data == NULL) {
		return;
	}

	std::shared_ptr<MeshData> md_ptr = generateMesh();

	if (IsInGameThread()) {
		applyTerrainMesh(md_ptr);
		voxel_data->resetLastMeshRegenerationTime();
	} else {
		UE_LOG(LogTemp, Warning, TEXT("non-game thread -> invoke async task"));
		if (GetTerrainController() != NULL) {
			GetTerrainController()->invokeZoneMeshAsync(this, md_ptr);
		}
	}
}

std::shared_ptr<MeshData> UTerrainZoneComponent::generateMesh() {
	double start = FPlatformTime::Seconds();

	if (voxel_data->getDensityFillState() == VoxelDataFillState::ZERO || voxel_data->getDensityFillState() == VoxelDataFillState::ALL) {
		return NULL;
	}

	bool enableLOD = GetTerrainController()->bEnableLOD;

	VoxelDataParam vdp;

	if (enableLOD) {
		vdp.bGenerateLOD = true;
		vdp.collisionLOD = 1;
	} else {
		vdp.bGenerateLOD = false;
		vdp.collisionLOD = 0;
	}

	MeshDataPtr md_ptr = sandboxVoxelGenerateMesh(*voxel_data, vdp);

	double end = FPlatformTime::Seconds();
	double time = (end - start) * 1000;

	UE_LOG(LogTemp, Warning, TEXT("ASandboxTerrainZone::generateMesh -------------> %f %f %f --> %f ms"), GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z, time);

	return md_ptr;
}

void UTerrainZoneComponent::applyTerrainMesh(std::shared_ptr<MeshData> mesh_data_ptr) {
	double start = FPlatformTime::Seconds();

	MeshData* mesh_data = mesh_data_ptr.get();

	if (mesh_data == NULL) {
		return;
	}

	MeshDataSection& MeshDataSection = mesh_data->MeshDataSectionLOD[0];
	FProcMeshSection& MeshSection = MeshDataSection.MainMesh;

	MainTerrainMesh->SetMobility(EComponentMobility::Movable);

	MainTerrainMesh->AddLocalRotation(FRotator(0.0f, 0.01, 0.0f));  // workaround
	MainTerrainMesh->AddLocalRotation(FRotator(0.0f, -0.01, 0.0f)); // workaround

	MainTerrainMesh->SetMeshData(mesh_data_ptr);

	MainTerrainMesh->SetMobility(EComponentMobility::Stationary);

	MainTerrainMesh->SetCastShadow(true);
	MainTerrainMesh->bCastHiddenShadow = true;
	MainTerrainMesh->SetMaterial(0, GetTerrainController()->TerrainMaterial);
	MainTerrainMesh->SetVisibility(true);

	CollisionMesh->SetMeshData(mesh_data_ptr);
	CollisionMesh->SetCollisionProfileName(TEXT("BlockAll"));

	double end = FPlatformTime::Seconds();
	double time = (end - start) * 1000;
	UE_LOG(LogTemp, Warning, TEXT("ASandboxTerrainZone::applyTerrainMesh ---------> %f %f %f --> %f ms"), GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z, time);
}<|endoftext|>