<commit_before>#include <cmath>

#include "ingameelements/weapons/peacemaker.h"
#include "renderer.h"
#include "ingameelements/projectiles/peacemakerbullet.h"
#include "ingameelements/heroes/mccree.h"
#include "ingameelements/explosion.h"
#include "ingameelements/trail.h"
#include "engine.h"

Peacemaker::Peacemaker(uint64_t id_, Gamestate *state, EntityPtr owner_) : Weapon(id_, state, owner_, constructparameters(state)),
                        fthanim("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::firesecondary, this, state)), isfthing(false)
{
    fthanim.active(false);
}

Peacemaker::~Peacemaker()
{
    //dtor
}

void Peacemaker::render(Renderer *renderer, Gamestate *state)
{
    std::string mainsprite;
    double dir = aimdirection;
    Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
    if (firinganim.active())
    {
        mainsprite = firinganim.getframepath();
    }
    else if (reloadanim.active())
    {
        mainsprite = reloadanim.getframepath();
        dir = 3.1415*c->isflipped;
    }
    else if (fthanim.active())
    {
        mainsprite = fthanim.getframepath();
    }
    else
    {
        mainsprite = "heroes/"+c->getcharacterfolder()+"arm/1";
    }
    ALLEGRO_BITMAP *sprite = renderer->spriteloader.requestsprite(mainsprite);
    int spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite);
    int spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite);
    Rect spritedimensions = renderer->spriteloader.get_rect(mainsprite);

    al_set_target_bitmap(renderer->midground);
    if (c->weaponvisible(state))
    {
        if (c->isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, 1, -1, dir, 0);
        }
        else
        {
            al_draw_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, dir, 0);
        }
    }
}

void Peacemaker::midstep(Gamestate *state, double frametime)
{
    Weapon::midstep(state, frametime);

    if (isfthing)
    {
        fthanim.active(true);
    }
    fthanim.update(state, frametime);
}

void Peacemaker::reload(Gamestate *state)
{
    if (clip < getclipsize() and not firinganim.active() and not reloadanim.active() and not isfthing)
    {
        // We need to reload
        reloadanim.reset();
        reloadanim.active(true);
    }
}

void Peacemaker::wantfireprimary(Gamestate *state)
{
    if (state->engine->isserver)
    {
        Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
        if (c->ulting.active)
        {
            // TODO: Deadeye active
        }
        else if (clip > 0 and not firinganim.active() and not reloadanim.active())
        {
            fireprimary(state);
            state->engine->sendbuffer->write<uint8_t>(PRIMARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
    }
}

void Peacemaker::fireprimary(Gamestate *state)
{
    double cosa = std::cos(aimdirection), sina = std::sin(aimdirection);
    double collisionptx, collisionpty;
    double d = std::hypot(state->currentmap->width(), state->currentmap->height());
    EntityPtr target = state->collidelinedamageable(x, y, x+cosa*d, y+sina*d, team, &collisionptx, &collisionpty);
    if (target.id != 0)
    {
        double distance = std::hypot(collisionptx-x, collisionpty-y);
        double falloff = 1.0;
        if (distance > FALLOFF_BEGIN)
        {
            falloff = std::max(0.0, 1 - (distance-FALLOFF_BEGIN)/(FALLOFF_END-FALLOFF_BEGIN));
        }
        MovingEntity *m = state->get<MovingEntity>(target);
        if (m->entitytype == CHARACTER)
        {
            Character *c = reinterpret_cast<Character*>(m);
            c->damage(state, MAX_DAMAGE*falloff);
        }
    }

    state->make_entity<Trail>(state, al_premul_rgba(133, 238, 238, 150), x+cosa*24, y+sina*24, collisionptx, collisionpty, 0.1);
    Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection));
    e->x = x+cosa*24;
    e->y = y+sina*24;

    --clip;
    firinganim.reset();
    firinganim.active(true);
}

void Peacemaker::wantfiresecondary(Gamestate *state)
{
    if (clip > 0)
    {
        if (not isfthing and state->engine->isserver and not reloadanim.active())
        {
            firesecondary(state);
            state->engine->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
        else if (isfthing and fthanim.getpercent() >= 1)
        {
            firesecondary(state);
            state->engine->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
    }
    else
    {
        isfthing = false;
        fthanim.active(false);
    }
}

void Peacemaker::firesecondary(Gamestate *state)
{
    double spread = (2*(rand()/(RAND_MAX+1.0)) - 1)*25*3.1415/180.0;
    double cosa = std::cos(aimdirection+spread), sina = std::sin(aimdirection+spread);
    double collisionptx, collisionpty;
    EntityPtr target = state->collidelinedamageable(x, y, x+cosa*FALLOFF_END, y+sina*FALLOFF_END, team, &collisionptx, &collisionpty);
    if (target.id != 0)
    {
        double distance = std::hypot(collisionptx-x, collisionpty-y);
        double falloff = 1.0;
        if (distance > FALLOFF_BEGIN)
        {
            falloff = std::max(0.0, (distance-FALLOFF_BEGIN) / (FALLOFF_END-FALLOFF_BEGIN));
        }
        MovingEntity *m = state->get<MovingEntity>(target);
        if (m->entitytype == CHARACTER)
        {
            Character *c = reinterpret_cast<Character*>(m);
            c->damage(state, MAX_FTH_DAMAGE*falloff);
        }
    }

    state->make_entity<Trail>(state, al_premul_rgba(133, 238, 238, 150), x+cosa*24, y+sina*24, collisionptx, collisionpty, 0.1);
    Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection+spread));
    e->x = x+cosa*24;
    e->y = y+sina*24;

    --clip;

    if (clip > 0 and state->engine->isserver)
    {
        if (isfthing)
        {
            fthanim = Animation("heroes/mccree/fanthehammerloop/", std::bind(&Peacemaker::wantfiresecondary, this, state));
        }
        else
        {
            fthanim = Animation("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::wantfiresecondary, this, state));
            isfthing = true;
        }
    }
}

WeaponChildParameters Peacemaker::constructparameters(Gamestate *state)
{
    WeaponChildParameters p;
    p.clipsize = 6;
    p.characterfolder = "heroes/mccree/";
    p.reloadfunction = std::bind(&Peacemaker::restoreclip, this, state);
    return p;
}
<commit_msg>Removed useless variable containing sprite size.<commit_after>#include <cmath>

#include "ingameelements/weapons/peacemaker.h"
#include "renderer.h"
#include "ingameelements/projectiles/peacemakerbullet.h"
#include "ingameelements/heroes/mccree.h"
#include "ingameelements/explosion.h"
#include "ingameelements/trail.h"
#include "engine.h"

Peacemaker::Peacemaker(uint64_t id_, Gamestate *state, EntityPtr owner_) : Weapon(id_, state, owner_, constructparameters(state)),
                        fthanim("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::firesecondary, this, state)), isfthing(false)
{
    fthanim.active(false);
}

Peacemaker::~Peacemaker()
{
    //dtor
}

void Peacemaker::render(Renderer *renderer, Gamestate *state)
{
    std::string mainsprite;
    double dir = aimdirection;
    Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
    if (firinganim.active())
    {
        mainsprite = firinganim.getframepath();
    }
    else if (reloadanim.active())
    {
        mainsprite = reloadanim.getframepath();
        dir = 3.1415*c->isflipped;
    }
    else if (fthanim.active())
    {
        mainsprite = fthanim.getframepath();
    }
    else
    {
        mainsprite = "heroes/"+c->getcharacterfolder()+"arm/1";
    }
    ALLEGRO_BITMAP *sprite = renderer->spriteloader.requestsprite(mainsprite);
    int spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite);
    int spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite);

    al_set_target_bitmap(renderer->midground);
    if (c->weaponvisible(state))
    {
        if (c->isflipped)
        {
            al_draw_scaled_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, 1, -1, dir, 0);
        }
        else
        {
            al_draw_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, dir, 0);
        }
    }
}

void Peacemaker::midstep(Gamestate *state, double frametime)
{
    Weapon::midstep(state, frametime);

    if (isfthing)
    {
        fthanim.active(true);
    }
    fthanim.update(state, frametime);
}

void Peacemaker::reload(Gamestate *state)
{
    if (clip < getclipsize() and not firinganim.active() and not reloadanim.active() and not isfthing)
    {
        // We need to reload
        reloadanim.reset();
        reloadanim.active(true);
    }
}

void Peacemaker::wantfireprimary(Gamestate *state)
{
    if (state->engine->isserver)
    {
        Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
        if (c->ulting.active)
        {
            // TODO: Deadeye active
        }
        else if (clip > 0 and not firinganim.active() and not reloadanim.active())
        {
            fireprimary(state);
            state->engine->sendbuffer->write<uint8_t>(PRIMARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
    }
}

void Peacemaker::fireprimary(Gamestate *state)
{
    double cosa = std::cos(aimdirection), sina = std::sin(aimdirection);
    double collisionptx, collisionpty;
    double d = std::hypot(state->currentmap->width(), state->currentmap->height());
    EntityPtr target = state->collidelinedamageable(x, y, x+cosa*d, y+sina*d, team, &collisionptx, &collisionpty);
    if (target.id != 0)
    {
        double distance = std::hypot(collisionptx-x, collisionpty-y);
        double falloff = 1.0;
        if (distance > FALLOFF_BEGIN)
        {
            falloff = std::max(0.0, 1 - (distance-FALLOFF_BEGIN)/(FALLOFF_END-FALLOFF_BEGIN));
        }
        MovingEntity *m = state->get<MovingEntity>(target);
        if (m->entitytype == CHARACTER)
        {
            Character *c = reinterpret_cast<Character*>(m);
            c->damage(state, MAX_DAMAGE*falloff);
        }
    }

    state->make_entity<Trail>(state, al_premul_rgba(133, 238, 238, 150), x+cosa*24, y+sina*24, collisionptx, collisionpty, 0.1);
    Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection));
    e->x = x+cosa*24;
    e->y = y+sina*24;

    --clip;
    firinganim.reset();
    firinganim.active(true);
}

void Peacemaker::wantfiresecondary(Gamestate *state)
{
    if (clip > 0)
    {
        if (not isfthing and state->engine->isserver and not reloadanim.active())
        {
            firesecondary(state);
            state->engine->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
        else if (isfthing and fthanim.getpercent() >= 1)
        {
            firesecondary(state);
            state->engine->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
            state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner));
        }
    }
    else
    {
        isfthing = false;
        fthanim.active(false);
    }
}

void Peacemaker::firesecondary(Gamestate *state)
{
    double spread = (2*(rand()/(RAND_MAX+1.0)) - 1)*25*3.1415/180.0;
    double cosa = std::cos(aimdirection+spread), sina = std::sin(aimdirection+spread);
    double collisionptx, collisionpty;
    EntityPtr target = state->collidelinedamageable(x, y, x+cosa*FALLOFF_END, y+sina*FALLOFF_END, team, &collisionptx, &collisionpty);
    if (target.id != 0)
    {
        double distance = std::hypot(collisionptx-x, collisionpty-y);
        double falloff = 1.0;
        if (distance > FALLOFF_BEGIN)
        {
            falloff = std::max(0.0, (distance-FALLOFF_BEGIN) / (FALLOFF_END-FALLOFF_BEGIN));
        }
        MovingEntity *m = state->get<MovingEntity>(target);
        if (m->entitytype == CHARACTER)
        {
            Character *c = reinterpret_cast<Character*>(m);
            c->damage(state, MAX_FTH_DAMAGE*falloff);
        }
    }

    state->make_entity<Trail>(state, al_premul_rgba(133, 238, 238, 150), x+cosa*24, y+sina*24, collisionptx, collisionpty, 0.1);
    Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection+spread));
    e->x = x+cosa*24;
    e->y = y+sina*24;

    --clip;

    if (clip > 0 and state->engine->isserver)
    {
        if (isfthing)
        {
            fthanim = Animation("heroes/mccree/fanthehammerloop/", std::bind(&Peacemaker::wantfiresecondary, this, state));
        }
        else
        {
            fthanim = Animation("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::wantfiresecondary, this, state));
            isfthing = true;
        }
    }
}

WeaponChildParameters Peacemaker::constructparameters(Gamestate *state)
{
    WeaponChildParameters p;
    p.clipsize = 6;
    p.characterfolder = "heroes/mccree/";
    p.reloadfunction = std::bind(&Peacemaker::restoreclip, this, state);
    return p;
}
<|endoftext|>


<commit_before>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;

ifstream inFile;     // define ifstream to inFile command
ofstream outFile;    // define outfile2

int main()
{
	// variables

	char guess = ' '; // guess from user
	string dictionary[20]; // 20 words to load from file
	int random20 = 0; // random number
	string word = ""; // word to be read from file (the solution)
	int wordLength = 0; // length of word
	string solution = ""; // solution (guessed by user)

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary

	cout << "Random word: -------- " << word << endl; // test

	wordLength = word.length();
	cout << "Word length: " << wordLength << endl; // test

	for (int i = 0; i < wordLength; i++) // fill solution with * length of word
	{
		solution[i] = '*';
	}

	cout << "Solution: " << solution << endl;

	return 0;
}<commit_msg>switch type of string length var<commit_after>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;

ifstream inFile;     // define ifstream to inFile command
ofstream outFile;    // define outfile2

int main()
{
	// variables

	//char guess = ' '; // guess from user
	string dictionary[20]; // 20 words to load from file
	int random20 = 0; // random number
	string word = ""; // word to be read from file (the solution)
	unsigned long wordLength = 0; // length of word
	string solution = ""; // solution (guessed by user)

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary

	cout << "Random word: -------- " << word << endl; // test

	wordLength = word.size();
	cout << "Word length: " << wordLength << endl; // test

	for (int i = 0; i < wordLength; i++) // fill solution with * length of word
	{
		solution[i] = '*';
	}

	cout << "Solution: " << solution << endl;

	return 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: share.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-03-26 13:15:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "uno/mapping.h"

#include <typeinfo>
#include <exception>
#include <cstddef>

namespace CPPU_CURRENT_NAMESPACE
{

void dummy_can_throw_anything( char const * );

// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h

struct _Unwind_Exception
{
    unsigned exception_class __attribute__((__mode__(__DI__)));
    void * exception_cleanup;
    unsigned private_1 __attribute__((__mode__(__word__)));
    unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));

struct __cxa_exception
{
    ::std::type_info *exceptionType;
    void (*exceptionDestructor)(void *);

    ::std::unexpected_handler unexpectedHandler;
    ::std::terminate_handler terminateHandler;

    __cxa_exception *nextException;

    int handlerCount;

    int handlerSwitchValue;
    const unsigned char *actionRecord;
    const unsigned char *languageSpecificData;
    void *catchTemp;
    void *adjustedPtr;

    _Unwind_Exception unwindHeader;
};

extern "C" void *__cxa_allocate_exception(
    std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
    void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));

struct __cxa_eh_globals
{
    __cxa_exception *caughtExceptions;
    unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();

// -----

//==================================================================================================
void raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
    __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.2.60); FILE MERGED 2008/03/28 16:30:37 rt 1.2.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: share.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "uno/mapping.h"

#include <typeinfo>
#include <exception>
#include <cstddef>

namespace CPPU_CURRENT_NAMESPACE
{

void dummy_can_throw_anything( char const * );

// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h

struct _Unwind_Exception
{
    unsigned exception_class __attribute__((__mode__(__DI__)));
    void * exception_cleanup;
    unsigned private_1 __attribute__((__mode__(__word__)));
    unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));

struct __cxa_exception
{
    ::std::type_info *exceptionType;
    void (*exceptionDestructor)(void *);

    ::std::unexpected_handler unexpectedHandler;
    ::std::terminate_handler terminateHandler;

    __cxa_exception *nextException;

    int handlerCount;

    int handlerSwitchValue;
    const unsigned char *actionRecord;
    const unsigned char *languageSpecificData;
    void *catchTemp;
    void *adjustedPtr;

    _Unwind_Exception unwindHeader;
};

extern "C" void *__cxa_allocate_exception(
    std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
    void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));

struct __cxa_eh_globals
{
    __cxa_exception *caughtExceptions;
    unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();

// -----

//==================================================================================================
void raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
    __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.18.130); FILE MERGED 2005/09/05 15:00:34 rt 1.18.130.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>


<commit_before>#include "ajp_server.hxx"
#include "tio.hxx"
#include "pool.hxx"
#include "strmap.hxx"

#include <string.h>
#include <stdlib.h>

static char *
read_string_n(struct pool *pool, size_t length, size_t *remaining_r)
{
    if (length == 0xffff)
        return nullptr;

    if (*remaining_r < length + 1)
        exit(EXIT_FAILURE);

    char *value = (char *)p_malloc(pool, length + 1);
    read_full(value, length + 1);
    if (value[length] != 0)
        exit(EXIT_FAILURE);

    *remaining_r -= length + 1;
    return value;
}

static char *
read_string(struct pool *pool, size_t *remaining_r)
{
    const size_t length = read_short(remaining_r);
    return read_string_n(pool, length, remaining_r);
}

void
read_ajp_header(struct ajp_header *header)
{
    read_full(header, sizeof(*header));
    if (header->a != 0x12 || header->b != 0x34)
        exit(EXIT_FAILURE);
}

static void
write_string(const char *value)
{
    if (value != nullptr) {
        size_t length = strlen(value);
        if (length > 0xfffe)
            length = 0xfffe;

        write_short(length);
        write_full(value, length);
        write_byte(0);
    } else
        write_short(0xffff);
}

static void
write_get_body_chunk(size_t length)
{
    assert(length <= 0xffff);

    static constexpr struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(3),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_GET_BODY_CHUNK);
    write_short(length);
}

void
read_ajp_request(struct pool *pool, struct ajp_request *r)
{
    struct ajp_header header;
    read_ajp_header(&header);

    size_t remaining = FromBE16(header.length);

    r->code = (ajp_code)read_byte(&remaining);
    if (r->code != AJP_CODE_FORWARD_REQUEST) {
        discard(remaining);
        return;
    }

    r->method = (ajp_method)read_byte(&remaining);

    read_string(pool, &remaining); /* protocol */
    r->uri = read_string(pool, &remaining);
    read_string(pool, &remaining); /* remote_address */
    read_string(pool, &remaining); /* remote_host */
    read_string(pool, &remaining); /* server_name */
    read_short(&remaining); /* server_port */
    read_byte(&remaining); /* is_ssl */

    r->headers = strmap_new(pool);

    unsigned n_headers = read_short(&remaining);
    while (n_headers-- > 0) {
        unsigned name_length = read_short(&remaining);
        const ajp_header_code code = (ajp_header_code)name_length;
        const char *name = ajp_decode_header_name(code);
        if (name == nullptr) {
            char *name2 = read_string_n(pool, name_length, &remaining);
            if (name2 == nullptr)
                exit(EXIT_FAILURE);

            name = p_strndup_lower(pool, name2, name_length);
        }

        const char *value = read_string(pool, &remaining);
        r->headers->Add(name, value);
    }

    // ...

    discard(remaining);

    const char *length_string = r->headers->Get("content-length");
    r->length = length_string != nullptr
        ? strtoul(length_string, nullptr, 10)
        : 0;
    r->body = r->length > 0
        ? (uint8_t *)p_malloc(pool, r->length)
        : nullptr;
    r->requested = 0;
    r->received = 0;
}

void
read_ajp_request_body_chunk(struct ajp_request *r)
{
    assert(r->length > 0);
    assert(r->received < r->length);
    assert(r->body != nullptr);

    const size_t remaining = r->length - r->received;

    while (r->requested <= r->received) {
        size_t nbytes = remaining;
        if (nbytes > 8192)
            nbytes = 8192;

        write_get_body_chunk(nbytes);
        r->requested += nbytes;
    }

    struct ajp_header header;
    read_ajp_header(&header);

    size_t packet_length = FromBE16(header.length);
    size_t chunk_length = read_short(&packet_length);
    if (chunk_length == 0 || chunk_length > packet_length ||
        chunk_length > remaining)
        exit(EXIT_FAILURE);

    read_full(r->body + r->received, chunk_length);
    r->received += chunk_length;

    size_t junk_length = packet_length - chunk_length;
    discard(junk_length);
}

void
read_ajp_end_request_body_chunk(struct ajp_request *r)
{
    assert(r->length > 0);
    assert(r->received == r->length);
    assert(r->body != nullptr);

    struct ajp_header header;
    read_ajp_header(&header);
    size_t packet_length = FromBE16(header.length);
    if (packet_length == 0)
        return;

    size_t chunk_length = read_short(&packet_length);
    if (chunk_length != 0)
        exit(EXIT_FAILURE);
}

void
discard_ajp_request_body(struct ajp_request *r)
{
    if (r->length == 0)
        return;

    while (r->received < r->length)
        read_ajp_request_body_chunk(r);

    read_ajp_end_request_body_chunk(r);
}

void
write_headers(http_status_t status, const StringMap *headers)
{
    unsigned n = 0;
    size_t length = 7;

    if (headers != nullptr) {
        for (const auto &i : *headers) {
            ++n;
            length += 4;

            enum ajp_response_header_code code =
                ajp_encode_response_header_name(i.key);
            if (code == AJP_RESPONSE_HEADER_NONE)
                length += strlen(i.key) + 1;

            length += strlen(i.value) + 1;
        }
    }

    const struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(length),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_SEND_HEADERS);
    write_short(status);
    write_string(nullptr);

    write_short(n);

    if (headers != nullptr) {
        for (const auto &i : *headers) {
            enum ajp_response_header_code code =
                ajp_encode_response_header_name(i.key);
            if (code == AJP_RESPONSE_HEADER_NONE)
                write_string(i.key);
            else
                write_short(code);

            write_string(i.value);
        }
    }
}

void
write_body_chunk(const void *value, size_t length, size_t junk)
{
    assert(length + junk <= 0xffff);

    const struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(3 + length + junk),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_SEND_BODY_CHUNK);
    write_short(length);
    write_full(value, length);
    fill(junk);
}

void
write_end()
{
    static constexpr struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(1),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_END_RESPONSE);
}
<commit_msg>test/ajp_server: fix -Wunused<commit_after>#include "ajp_server.hxx"
#include "tio.hxx"
#include "pool.hxx"
#include "strmap.hxx"

#include <string.h>
#include <stdlib.h>

static char *
read_string_n(struct pool *pool, size_t length, size_t *remaining_r)
{
    if (length == 0xffff)
        return nullptr;

    if (*remaining_r < length + 1)
        exit(EXIT_FAILURE);

    char *value = (char *)p_malloc(pool, length + 1);
    read_full(value, length + 1);
    if (value[length] != 0)
        exit(EXIT_FAILURE);

    *remaining_r -= length + 1;
    return value;
}

static char *
read_string(struct pool *pool, size_t *remaining_r)
{
    const size_t length = read_short(remaining_r);
    return read_string_n(pool, length, remaining_r);
}

void
read_ajp_header(struct ajp_header *header)
{
    read_full(header, sizeof(*header));
    if (header->a != 0x12 || header->b != 0x34)
        exit(EXIT_FAILURE);
}

static void
write_string(const char *value)
{
    if (value != nullptr) {
        size_t length = strlen(value);
        if (length > 0xfffe)
            length = 0xfffe;

        write_short(length);
        write_full(value, length);
        write_byte(0);
    } else
        write_short(0xffff);
}

static void
write_get_body_chunk(size_t length)
{
    assert(length <= 0xffff);

    static constexpr struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(3),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_GET_BODY_CHUNK);
    write_short(length);
}

void
read_ajp_request(struct pool *pool, struct ajp_request *r)
{
    struct ajp_header header;
    read_ajp_header(&header);

    size_t remaining = FromBE16(header.length);

    r->code = (ajp_code)read_byte(&remaining);
    if (r->code != AJP_CODE_FORWARD_REQUEST) {
        discard(remaining);
        return;
    }

    r->method = (ajp_method)read_byte(&remaining);

    read_string(pool, &remaining); /* protocol */
    r->uri = read_string(pool, &remaining);
    read_string(pool, &remaining); /* remote_address */
    read_string(pool, &remaining); /* remote_host */
    read_string(pool, &remaining); /* server_name */
    read_short(&remaining); /* server_port */
    read_byte(&remaining); /* is_ssl */

    r->headers = strmap_new(pool);

    unsigned n_headers = read_short(&remaining);
    while (n_headers-- > 0) {
        unsigned name_length = read_short(&remaining);
        const ajp_header_code code = (ajp_header_code)name_length;
        const char *name = ajp_decode_header_name(code);
        if (name == nullptr) {
            char *name2 = read_string_n(pool, name_length, &remaining);
            if (name2 == nullptr)
                exit(EXIT_FAILURE);

            name = p_strndup_lower(pool, name2, name_length);
        }

        const char *value = read_string(pool, &remaining);
        r->headers->Add(name, value);
    }

    // ...

    discard(remaining);

    const char *length_string = r->headers->Get("content-length");
    r->length = length_string != nullptr
        ? strtoul(length_string, nullptr, 10)
        : 0;
    r->body = r->length > 0
        ? (uint8_t *)p_malloc(pool, r->length)
        : nullptr;
    r->requested = 0;
    r->received = 0;
}

void
read_ajp_request_body_chunk(struct ajp_request *r)
{
    assert(r->length > 0);
    assert(r->received < r->length);
    assert(r->body != nullptr);

    const size_t remaining = r->length - r->received;

    while (r->requested <= r->received) {
        size_t nbytes = remaining;
        if (nbytes > 8192)
            nbytes = 8192;

        write_get_body_chunk(nbytes);
        r->requested += nbytes;
    }

    struct ajp_header header;
    read_ajp_header(&header);

    size_t packet_length = FromBE16(header.length);
    size_t chunk_length = read_short(&packet_length);
    if (chunk_length == 0 || chunk_length > packet_length ||
        chunk_length > remaining)
        exit(EXIT_FAILURE);

    read_full(r->body + r->received, chunk_length);
    r->received += chunk_length;

    size_t junk_length = packet_length - chunk_length;
    discard(junk_length);
}

void
read_ajp_end_request_body_chunk(gcc_unused struct ajp_request *r)
{
    assert(r->length > 0);
    assert(r->received == r->length);
    assert(r->body != nullptr);

    struct ajp_header header;
    read_ajp_header(&header);
    size_t packet_length = FromBE16(header.length);
    if (packet_length == 0)
        return;

    size_t chunk_length = read_short(&packet_length);
    if (chunk_length != 0)
        exit(EXIT_FAILURE);
}

void
discard_ajp_request_body(struct ajp_request *r)
{
    if (r->length == 0)
        return;

    while (r->received < r->length)
        read_ajp_request_body_chunk(r);

    read_ajp_end_request_body_chunk(r);
}

void
write_headers(http_status_t status, const StringMap *headers)
{
    unsigned n = 0;
    size_t length = 7;

    if (headers != nullptr) {
        for (const auto &i : *headers) {
            ++n;
            length += 4;

            enum ajp_response_header_code code =
                ajp_encode_response_header_name(i.key);
            if (code == AJP_RESPONSE_HEADER_NONE)
                length += strlen(i.key) + 1;

            length += strlen(i.value) + 1;
        }
    }

    const struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(length),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_SEND_HEADERS);
    write_short(status);
    write_string(nullptr);

    write_short(n);

    if (headers != nullptr) {
        for (const auto &i : *headers) {
            enum ajp_response_header_code code =
                ajp_encode_response_header_name(i.key);
            if (code == AJP_RESPONSE_HEADER_NONE)
                write_string(i.key);
            else
                write_short(code);

            write_string(i.value);
        }
    }
}

void
write_body_chunk(const void *value, size_t length, size_t junk)
{
    assert(length + junk <= 0xffff);

    const struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(3 + length + junk),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_SEND_BODY_CHUNK);
    write_short(length);
    write_full(value, length);
    fill(junk);
}

void
write_end()
{
    static constexpr struct ajp_header header = {
        .a = 'A',
        .b = 'B',
        .length = ToBE16(1),
    };

    write_full(&header, sizeof(header));
    write_byte(AJP_CODE_END_RESPONSE);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004  Justin Karneges
 * Copyright (C) 2004  Brad Hards <bradh@frogmouth.net>
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "qcaprovider.h"
#include <qstringlist.h>
#include <openssl/sha.h>
#include <openssl/md2.h>
#include <openssl/md4.h>
#include <openssl/md5.h>
#include <openssl/ripemd.h>
#include <openssl/hmac.h>

class MD2Context : public QCA::HashContext
{
public:
	MD2Context(QCA::Provider *p) : HashContext(p, "md2")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD2Context(*this);
	}

	void clear()
	{
		MD2_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD2_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD2_DIGEST_LENGTH);
		MD2_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD2_CTX c;
};

class MD4Context : public QCA::HashContext
{
public:
	MD4Context(QCA::Provider *p) : HashContext(p, "md4")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD4Context(*this);
	}

	void clear()
	{
		MD4_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD4_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD4_DIGEST_LENGTH);
		MD4_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD4_CTX c;
};

class MD5Context : public QCA::HashContext
{
public:
	MD5Context(QCA::Provider *p) : HashContext(p, "md5")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD5Context(*this);
	}

	void clear()
	{
		MD5_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD5_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD5_DIGEST_LENGTH);
		MD5_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD5_CTX c;
};

class SHA0Context : public QCA::HashContext
{
public:
	SHA0Context(QCA::Provider *p) : HashContext(p, "sha0")
	{
		clear();
	}

	Context *clone() const
	{
		return new SHA0Context(*this);
	}

	void clear()
	{
		SHA_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		SHA_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(SHA_DIGEST_LENGTH);
		SHA_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	SHA_CTX c;
};

class SHA1Context : public QCA::HashContext
{
public:
	SHA1Context(QCA::Provider *p) : HashContext(p, "sha1")
	{
		clear();
	}

	Context *clone() const
	{
		return new SHA1Context(*this);
	}

	void clear()
	{
		SHA1_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		SHA1_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(SHA_DIGEST_LENGTH);
		SHA1_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	SHA_CTX c;
};

class RIPEMD160Context : public QCA::HashContext
{
public:
	RIPEMD160Context(QCA::Provider *p) : HashContext(p, "ripemd160")
	{
		clear();
	}

	Context *clone() const
	{
		return new RIPEMD160Context(*this);
	}

	void clear()
	{
		RIPEMD160_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		RIPEMD160_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray result(RIPEMD160_DIGEST_LENGTH);
		RIPEMD160_Final((unsigned char *)result.data(), &c);
		return result;
	}

protected:
	RIPEMD160_CTX c;
};

class HMACMD5Context : public QCA::MACContext
{
public:
	HMACMD5Context(QCA::Provider *p) : MACContext( p, "hmac(md5)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACMD5Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( MD5_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class HMACSHA1Context : public QCA::MACContext
{
public:
	HMACSHA1Context(QCA::Provider *p) : MACContext( p, "hmac(sha1)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACSHA1Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( SHA_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class HMACRIPEMD160Context : public QCA::MACContext
{
public:
	HMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, "hmac(ripemd160)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACRIPEMD160Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( RIPEMD160_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class opensslProvider : public QCA::Provider
{
public:
	void init()
	{
	}

	QString name() const
	{
		return "qca-openssl";
	}

	QStringList features() const
	{
		QStringList list;
		list += "sha0";
		list += "sha1";
		list += "ripemd160";
		list += "md2";
		list += "md4";
		list += "md5";
		list += "hmac(md5)";
		list += "hmac(sha1)";
		list += "hmac(ripemd160)";
		list += "aes128";
		return list;
	}

	Context *createContext(const QString &type)
	{
		if ( type == "sha0" )
			return new SHA0Context( this );
		else if ( type == "sha1" )
			return new SHA1Context( this );
		else if ( type == "ripemd160" )
			return new RIPEMD160Context( this );
		else if ( type == "md2" )
			return new MD2Context( this );
		else if ( type == "md4" )
			return new MD4Context( this );
		else if ( type == "md5" )
			return new MD5Context( this );
		else if ( type == "hmac(md5)" )
			return new HMACMD5Context( this );
		else if ( type == "hmac(sha1)" )
			return new HMACSHA1Context( this );
		else if ( type == "hmac(ripemd160)" )
			return new HMACRIPEMD160Context( this );
		else
			return 0;
	}
};

QCA_EXPORT_PLUGIN(opensslProvider);
<commit_msg>This built, but segfaulted. It'd be nice if we could avoid it building at all, but not seeing any way to do that yet.<commit_after>/*
 * Copyright (C) 2004  Justin Karneges
 * Copyright (C) 2004  Brad Hards <bradh@frogmouth.net>
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "qcaprovider.h"
#include <qstringlist.h>
#include <openssl/sha.h>
#include <openssl/md2.h>
#include <openssl/md4.h>
#include <openssl/md5.h>
#include <openssl/ripemd.h>
#include <openssl/hmac.h>

class MD2Context : public QCA::HashContext
{
public:
	MD2Context(QCA::Provider *p) : HashContext(p, "md2")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD2Context(*this);
	}

	void clear()
	{
		MD2_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD2_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD2_DIGEST_LENGTH);
		MD2_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD2_CTX c;
};

class MD4Context : public QCA::HashContext
{
public:
	MD4Context(QCA::Provider *p) : HashContext(p, "md4")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD4Context(*this);
	}

	void clear()
	{
		MD4_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD4_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD4_DIGEST_LENGTH);
		MD4_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD4_CTX c;
};

class MD5Context : public QCA::HashContext
{
public:
	MD5Context(QCA::Provider *p) : HashContext(p, "md5")
	{
		clear();
	}

	Context *clone() const
	{
		return new MD5Context(*this);
	}

	void clear()
	{
		MD5_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		MD5_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(MD5_DIGEST_LENGTH);
		MD5_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	MD5_CTX c;
};

class SHA0Context : public QCA::HashContext
{
public:
	SHA0Context(QCA::Provider *p) : HashContext(p, "sha0")
	{
		clear();
	}

	Context *clone() const
	{
		return new SHA0Context(*this);
	}

	void clear()
	{
		SHA_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		SHA_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(SHA_DIGEST_LENGTH);
		SHA_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	SHA_CTX c;
};

class SHA1Context : public QCA::HashContext
{
public:
	SHA1Context(QCA::Provider *p) : HashContext(p, "sha1")
	{
		clear();
	}

	Context *clone() const
	{
		return new SHA1Context(*this);
	}

	void clear()
	{
		SHA1_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		SHA1_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray a(SHA_DIGEST_LENGTH);
		SHA1_Final((unsigned char *)a.data(), &c);
		return a;
	}

protected:
	SHA_CTX c;
};

class RIPEMD160Context : public QCA::HashContext
{
public:
	RIPEMD160Context(QCA::Provider *p) : HashContext(p, "ripemd160")
	{
		clear();
	}

	Context *clone() const
	{
		return new RIPEMD160Context(*this);
	}

	void clear()
	{
		RIPEMD160_Init(&c);
	}

	void update(const QSecureArray &a)
	{
		RIPEMD160_Update(&c, (unsigned char *)a.data(), a.size());
	}

	QSecureArray final()
	{
		QSecureArray result(RIPEMD160_DIGEST_LENGTH);
		RIPEMD160_Final((unsigned char *)result.data(), &c);
		return result;
	}

protected:
	RIPEMD160_CTX c;
};

class HMACMD5Context : public QCA::MACContext
{
public:
	HMACMD5Context(QCA::Provider *p) : MACContext( p, "hmac(md5)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACMD5Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( MD5_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class HMACSHA1Context : public QCA::MACContext
{
public:
	HMACSHA1Context(QCA::Provider *p) : MACContext( p, "hmac(sha1)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACSHA1Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( SHA_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class HMACRIPEMD160Context : public QCA::MACContext
{
public:
	HMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, "hmac(ripemd160)" )
	{
		HMAC_CTX_init( &c );
	}

	Context *clone() const
	{
		return new HMACRIPEMD160Context(*this);
	}

	void setup(const QCA::SymmetricKey &key)
	{
		HMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 );
	}

	QCA::KeyLength keyLength() const
	{
		return anyKeyLength();
	}

	void update(const QSecureArray &a)
	{
		HMAC_Update( &c, (unsigned char *)a.data(), a.size() );
	}

	void final( QSecureArray *out)
	{
		unsigned int outSize;
		out->resize( RIPEMD160_DIGEST_LENGTH );
		HMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );
		HMAC_CTX_cleanup(&c);
	}

protected:
	HMAC_CTX c;
};

class opensslProvider : public QCA::Provider
{
public:
	void init()
	{
	}

	QString name() const
	{
		return "qca-openssl";
	}

	QStringList features() const
	{
		QStringList list;
		list += "sha0";
		list += "sha1";
		list += "ripemd160";
		list += "md2";
		list += "md4";
		list += "md5";
		list += "hmac(md5)";
		list += "hmac(sha1)";
		list += "hmac(ripemd160)";
		return list;
	}

	Context *createContext(const QString &type)
	{
		if ( type == "sha0" )
			return new SHA0Context( this );
		else if ( type == "sha1" )
			return new SHA1Context( this );
		else if ( type == "ripemd160" )
			return new RIPEMD160Context( this );
		else if ( type == "md2" )
			return new MD2Context( this );
		else if ( type == "md4" )
			return new MD4Context( this );
		else if ( type == "md5" )
			return new MD5Context( this );
		else if ( type == "hmac(md5)" )
			return new HMACMD5Context( this );
		else if ( type == "hmac(sha1)" )
			return new HMACSHA1Context( this );
		else if ( type == "hmac(ripemd160)" )
			return new HMACRIPEMD160Context( this );
		else
			return 0;
	}
};

QCA_EXPORT_PLUGIN(opensslProvider);
<|endoftext|>


<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 Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 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, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_VisualModel.h"
#include "Binding_BaseState.h"
#include <fstream>

using namespace sofa::component::visualmodel;
using namespace sofa::core::objectmodel;
using namespace sofa::core::visual;

extern "C" PyObject * VisualModelImpl_setColor(PyObject *self, PyObject * args)
{
    VisualModelImpl* obj=down_cast<VisualModelImpl>(((PySPtr<Base>*)self)->object->toVisualModel());
    double r,g,b,a;
    if (!PyArg_ParseTuple(args, "dddd",&r,&g,&b,&a))
    {
        int ir,ig,ib,ia; // helper: you can set integer values
        if (!PyArg_ParseTuple(args, "iiii",&ir,&ig,&ib,&ia))
        {
            PyErr_BadArgument();
            return NULL;
        }
        r = (double)ir;
        g = (double)ig;
        b = (double)ib;
        a = (double)ia;
    }
    obj->setColor((float)r,(float)g,(float)b,(float)a);
    Py_RETURN_NONE;
}

extern "C" PyObject * VisualModel_exportOBJ(PyObject *self, PyObject * args)
{
    VisualModel* obj=((PySPtr<Base>*)self)->object->toVisualModel();

    char* filename;
    if (!PyArg_ParseTuple(args, "s",&filename))
    {
        PyErr_BadArgument();
        return NULL;
    }

    std::ofstream outfile(filename);

    int vindex = 0;
    int nindex = 0;
    int tindex = 0;
    int count = 0;

    obj->exportOBJ(obj->getName(),&outfile,NULL,vindex,nindex,tindex,count);

    outfile.close();

    Py_RETURN_NONE;
}

extern "C" PyObject * VisualModel_updateVisual(PyObject *self, PyObject * /*args*/)
{
    VisualModel* obj=((PySPtr<Base>*)self)->object->toVisualModel();
    obj->updateVisual();
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(VisualModel)
SP_CLASS_METHOD(VisualModel,exportOBJ)
SP_CLASS_METHOD(VisualModel,updateVisual)
SP_CLASS_METHODS_END

SP_CLASS_METHODS_BEGIN(VisualModelImpl)
SP_CLASS_METHOD(VisualModelImpl,setColor)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(VisualModel,VisualModel,BaseState)
SP_CLASS_TYPE_SPTR(VisualModelImpl,VisualModelImpl,VisualModel)

<commit_msg>[SofaPython] binding VisualModel::initVisual<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 Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 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, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Binding_VisualModel.h"
#include "Binding_BaseState.h"
#include <fstream>

using namespace sofa::component::visualmodel;
using namespace sofa::core::objectmodel;
using namespace sofa::core::visual;

extern "C" PyObject * VisualModelImpl_setColor(PyObject *self, PyObject * args)
{
    VisualModelImpl* obj=down_cast<VisualModelImpl>(((PySPtr<Base>*)self)->object->toVisualModel());
    double r,g,b,a;
    if (!PyArg_ParseTuple(args, "dddd",&r,&g,&b,&a))
    {
        int ir,ig,ib,ia; // helper: you can set integer values
        if (!PyArg_ParseTuple(args, "iiii",&ir,&ig,&ib,&ia))
        {
            PyErr_BadArgument();
            return NULL;
        }
        r = (double)ir;
        g = (double)ig;
        b = (double)ib;
        a = (double)ia;
    }
    obj->setColor((float)r,(float)g,(float)b,(float)a);
    Py_RETURN_NONE;
}

extern "C" PyObject * VisualModel_exportOBJ(PyObject *self, PyObject * args)
{
    VisualModel* obj=((PySPtr<Base>*)self)->object->toVisualModel();

    char* filename;
    if (!PyArg_ParseTuple(args, "s",&filename))
    {
        PyErr_BadArgument();
        return NULL;
    }

    std::ofstream outfile(filename);

    int vindex = 0;
    int nindex = 0;
    int tindex = 0;
    int count = 0;

    obj->exportOBJ(obj->getName(),&outfile,NULL,vindex,nindex,tindex,count);

    outfile.close();

    Py_RETURN_NONE;
}

extern "C" PyObject * VisualModel_updateVisual(PyObject *self, PyObject * /*args*/)
{
    VisualModel* obj=((PySPtr<Base>*)self)->object->toVisualModel();
    obj->updateVisual();
    Py_RETURN_NONE;
}

extern "C" PyObject * VisualModel_initVisual(PyObject *self, PyObject * /*args*/)
{
    VisualModel* obj=((PySPtr<Base>*)self)->object->toVisualModel();
    obj->initVisual();
    Py_RETURN_NONE;
}

SP_CLASS_METHODS_BEGIN(VisualModel)
SP_CLASS_METHOD(VisualModel,exportOBJ)
SP_CLASS_METHOD(VisualModel,updateVisual)
SP_CLASS_METHOD(VisualModel,initVisual)
SP_CLASS_METHODS_END

SP_CLASS_METHODS_BEGIN(VisualModelImpl)
SP_CLASS_METHOD(VisualModelImpl,setColor)
SP_CLASS_METHODS_END

SP_CLASS_TYPE_SPTR(VisualModel,VisualModel,BaseState)
SP_CLASS_TYPE_SPTR(VisualModelImpl,VisualModelImpl,VisualModel)

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadLandmark.cxx
  Language:  C++
  Date: $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMLoadLandmark.h"

namespace itk {
namespace fem {

/**
 * Read a LoadLandmark object from the input stream
 */
void LoadLandmark::Read( std::istream& f, void*)
{
  int n1, n2;
  vnl_vector<Float> pu;
  vnl_vector<Float> pd;

  // first call the parent's read function
  //Superclass::Read(f,info);

  // read the dimensions of the undeformed point and set the size of the point accordingly
  SkipWhiteSpace(f); f>>n1; if(!f) goto out;
  pu.set_size(n1);
  this->m_pt.set_size(n1);

  // read the undeformed point in global coordinates
  SkipWhiteSpace(f); f>>pu; if(!f) goto out;

  // Read the dimensions of the deformed point and set the size of the point accordingly
  SkipWhiteSpace(f); f>>n2; if(!f) goto out;
  pd.set_size(n2);
  m_force.set_size(n2);

  // read the deformed point in global coordinates
  SkipWhiteSpace(f); f>>pd; if(!f) goto out;

  m_source = pd;
  m_pt = pd;
  m_target = pu;
  m_force  = pu-pd;

  //std::cout << m_source << std::endl << m_pt << std::endl << m_target << std::endl << m_force << std::endl;

  // read the square root of the variance associated with this landmark
  SkipWhiteSpace(f); f>>eta; if(!f) goto out;

  // Verify that the undeformed and deformed points are of the same size.
  if (n1 != n2) { goto out; }

  this->el.resize(1);

out:

  if( !f )
  {
    throw FEMExceptionIO(__FILE__,__LINE__,"LoadLandmark::Read()","Error reading landmark load!");
  }
}

/**
 * Find the Element to which the LoadLandmark belongs
 */

void LoadLandmark::AssignToElement(Element::ArrayType::Pointer elements)
{
  bool isFound = false;

  // Compute & store the local coordinates of the undeformed point and
  // the pointer to the element

  for (Element::ArrayType::const_iterator n = elements->begin(); n!=elements->end() && !isFound; n++) {
    if ( (*n)->GetLocalFromGlobalCoordinates(m_source, this->m_pt) ) {
      isFound = true;
      std::cout << "Found: " << (&**n) << std::endl;
      this->el[0] = *n;
    }
  }

  if (!isFound) {
      throw FEMException(__FILE__,__LINE__,"LoadLandmark::Read() - could not find element containing landmark!");
  }
}

/**
 * Write the LoadLandmark object to the output stream
 */
void LoadLandmark::Write( std::ostream& f ) const
{

  /** first call the parent's write function */
  Superclass::Write(f);

  /**
   * Write the actual LoadLandmark data
   */

  /** Information */
  f<<"\t"<<"Each vector below is preceded by its size"<<"\n";

  /** Write the point coordinates in the undeformed state */
  f<<"\t"<<m_pt.size()<<" "<<m_pt<<"\t%Point (local) coordinates, undeformed state"<<"\n";

  /** check for errors */
  if (!f)
  {
    throw FEMExceptionIO(__FILE__,__LINE__,"LoadBCMFC::Write()","Error writing FEM load!");
  }

}

FEM_CLASS_REGISTER(LoadLandmark)

}} // end namespace itk::fem
<commit_msg>FIX: Bug # 522. Write method was missing the "%" in a comment sent to the      output stream.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadLandmark.cxx
  Language:  C++
  Date: $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMLoadLandmark.h"

namespace itk {
namespace fem {

/**
 * Read a LoadLandmark object from the input stream
 */
void LoadLandmark::Read( std::istream& f, void*)
{
  int n1, n2;
  vnl_vector<Float> pu;
  vnl_vector<Float> pd;

  // first call the parent's read function
  //Superclass::Read(f,info);

  // read the dimensions of the undeformed point and set the size of the point accordingly
  SkipWhiteSpace(f); f>>n1; if(!f) goto out;
  pu.set_size(n1);
  this->m_pt.set_size(n1);

  // read the undeformed point in global coordinates
  SkipWhiteSpace(f); f>>pu; if(!f) goto out;

  // Read the dimensions of the deformed point and set the size of the point accordingly
  SkipWhiteSpace(f); f>>n2; if(!f) goto out;
  pd.set_size(n2);
  m_force.set_size(n2);

  // read the deformed point in global coordinates
  SkipWhiteSpace(f); f>>pd; if(!f) goto out;

  m_source = pd;
  m_pt = pd;
  m_target = pu;
  m_force  = pu-pd;

  //std::cout << m_source << std::endl << m_pt << std::endl << m_target << std::endl << m_force << std::endl;

  // read the square root of the variance associated with this landmark
  SkipWhiteSpace(f); f>>eta; if(!f) goto out;

  // Verify that the undeformed and deformed points are of the same size.
  if (n1 != n2) { goto out; }

  this->el.resize(1);

out:

  if( !f )
  {
    throw FEMExceptionIO(__FILE__,__LINE__,"LoadLandmark::Read()","Error reading landmark load!");
  }
}

/**
 * Find the Element to which the LoadLandmark belongs
 */

void LoadLandmark::AssignToElement(Element::ArrayType::Pointer elements)
{
  bool isFound = false;

  // Compute & store the local coordinates of the undeformed point and
  // the pointer to the element

  for (Element::ArrayType::const_iterator n = elements->begin(); n!=elements->end() && !isFound; n++) {
    if ( (*n)->GetLocalFromGlobalCoordinates(m_source, this->m_pt) ) {
      isFound = true;
      std::cout << "Found: " << (&**n) << std::endl;
      this->el[0] = *n;
    }
  }

  if (!isFound) {
      throw FEMException(__FILE__,__LINE__,"LoadLandmark::Read() - could not find element containing landmark!");
  }
}

/**
 * Write the LoadLandmark object to the output stream
 */
void LoadLandmark::Write( std::ostream& f ) const
{

  /** first call the parent's write function */
  Superclass::Write(f);

  /**
   * Write the actual LoadLandmark data
   */

  /** Information */
  f << "\t% Each vector below is preceded by its size" << std::endl;

  /** Write the point coordinates in the undeformed state */
  f<<"\t"<<m_pt.size()<<" "<<m_pt<<"\t%Point (local) coordinates, undeformed state"<<"\n";

  /** check for errors */
  if (!f)
  {
    throw FEMExceptionIO(__FILE__,__LINE__,"LoadBCMFC::Write()","Error writing FEM load!");
  }

}

FEM_CLASS_REGISTER(LoadLandmark)

}} // end namespace itk::fem
<|endoftext|>


<commit_before>#include <iostream>
#include "player.hpp"

player::player(std::string name, std::string area, std::string weapon, int level = 1, int EXP = 0)
{
	setName(name);
	setArea(area);
	setWeapon(weapon);
	setLevel(level);
	setEXP(EXP);
	setMaxHealth();
	setHealth(playerMaxHealth);
	setDamage();
	setEXPReq();

}
//set values
void player::setName(std::string name)
{
	playerName = name;
}
void player::setArea(std::string area)
{
	playerArea = area;
}
void player::setWeapon(std::string weapon)
{
	playerWeapon = weapon;
}
void player::setLevel(int level)
{
	playerLevel = level
}
void player::setHealth(int health)
{
	playerHealth = health;
}
void player::setMaxHealth()
{
	playerMaxHealth = (100 * getLevel());
}
void player::setDamage()
{
	playerDamage = (30 * getLevel());
}
void player::setEXP(int _EXP)
{
	EXP = _EXP;
}
void player::setEXPReq()
{
	EXPReq = 70 + ((getLevel() * getLevel() * 35));
}

//get values
std::string player::getName()
{
	return playerName;
}
std::string player::getArea()
{
	return playerArea;
}
std::string player::getWeapon()
{
	return playerWeapon;
}
int player::getLevel()
{
	return playerLevel;
}
int player::getHealth()
{
	return playerHealth;
}
int player::getMaxHealth()
{
	return playerMaxHealth;
}
int player::getDamage()
{
	return playerDamage;
}
int player::getEXP()
{
	return playerEXP;
}
int player::getEXPReq()
{
	return EXPReq;
}
<commit_msg>Update player.cpp<commit_after>#include "player.hpp"

player::player(std::string name, std::string area, std::string weapon, int level = 1, int EXP = 0)
{
	setName(name);
	setArea(area);
	setWeapon(weapon);
	setLevel(level);
	setEXP(EXP);
	setMaxHealth();
	setHealth(playerMaxHealth);
	setDamage();
	setEXPReq();

}
//Member function definitions
void player::setName(std::string name)
{
	playerName = name;
}
void player::setArea(std::string area)
{
	playerArea = area;
}
void player::setWeapon(std::string weapon)
{
	playerWeapon = weapon;
}
void player::setLevel(int level)
{
	playerLevel = level
}
void player::setHealth(int health)
{
	playerHealth = health;
}
void player::setMaxHealth()
{
	playerMaxHealth = (100 * getLevel());
}
void player::setDamage()
{
	playerDamage = (30 * getLevel());
}
void player::setEXP(int _EXP)
{
	EXP = _EXP;
}
void player::setEXPReq()
{
	EXPReq = 70 + ((getLevel() * getLevel() * 35));
}

//Member function constructors
std::string player::getName()
{
	return playerName;
}
std::string player::getArea()
{
	return playerArea;
}
std::string player::getWeapon()
{
	return playerWeapon;
}
int player::getLevel()
{
	return playerLevel;
}
int player::getHealth()
{
	return playerHealth;
}
int player::getMaxHealth()
{
	return playerMaxHealth;
}
int player::getDamage()
{
	return playerDamage;
}
int player::getEXP()
{
	return playerEXP;
}
int player::getEXPReq()
{
	return EXPReq;
}
<|endoftext|>


<commit_before><commit_msg>removed erroneous file<commit_after><|endoftext|>


<commit_before>/*=====================================================================

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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 3 of the License, or
 (at your option) any later version.

 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "MultiVehicleManager.h"
#include "AutoPilotPlugin.h"
#include "MAVLinkProtocol.h"
#include "UAS.h"
#include "QGCApplication.h"
#include "FollowMe.h"

#ifdef __mobile__
#include "MobileScreenMgr.h"
#endif

#include <QQmlEngine>

QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog")

const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled";

MultiVehicleManager::MultiVehicleManager(QGCApplication* app)
    : QGCTool(app)
    , _activeVehicleAvailable(false)
    , _parameterReadyVehicleAvailable(false)
    , _activeVehicle(NULL)
    , _disconnectedVehicle(NULL)
    , _firmwarePluginManager(NULL)
    , _autopilotPluginManager(NULL)
    , _joystickManager(NULL)
    , _mavlinkProtocol(NULL)
    , _gcsHeartbeatEnabled(true)
{
    QSettings settings;

    _gcsHeartbeatEnabled = settings.value(_gcsHeartbeatEnabledKey, true).toBool();

    _gcsHeartbeatTimer.setInterval(_gcsHeartbeatRateMSecs);
    _gcsHeartbeatTimer.setSingleShot(false);
    connect(&_gcsHeartbeatTimer, &QTimer::timeout, this, &MultiVehicleManager::_sendGCSHeartbeat);
    if (_gcsHeartbeatEnabled) {
        _gcsHeartbeatTimer.start();
    }

    _disconnectedVehicle = new Vehicle(this);
}

void MultiVehicleManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

   _firmwarePluginManager =     _toolbox->firmwarePluginManager();
   _autopilotPluginManager =    _toolbox->autopilotPluginManager();
   _joystickManager =           _toolbox->joystickManager();
   _mavlinkProtocol =           _toolbox->mavlinkProtocol();

   QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
   qmlRegisterUncreatableType<MultiVehicleManager>("QGroundControl.MultiVehicleManager", 1, 0, "MultiVehicleManager", "Reference only");

   connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo);
}

void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType)
{
    if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId)) {
        return;
    }

    qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType "
                                      << link->getName()
                                      << vehicleId
                                      << vehicleMavlinkVersion
                                      << vehicleFirmwareType
                                      << vehicleType;

    if (vehicleId == _mavlinkProtocol->getSystemId()) {
        _app->showMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId));
    }

    QSettings settings;
    bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool();
    if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) {
        _ignoreVehicleIds += vehicleId;
        _app->showMessage(QString("The MAVLink protocol version on vehicle #%1 and QGroundControl differ! "
                                  "It is unsafe to use different MAVLink versions. "
                                  "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION));
        return;
    }

    Vehicle* vehicle = new Vehicle(link, vehicleId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _autopilotPluginManager, _joystickManager);
    connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1);
    connect(vehicle->autopilotPlugin(), &AutoPilotPlugin::parametersReadyChanged, this, &MultiVehicleManager::_autopilotParametersReadyChanged);

    _vehicles.append(vehicle);

    emit vehicleAdded(vehicle);

    setActiveVehicle(vehicle);

    // Mark link as active
    link->setActive(true);

#ifdef __mobile__
    if(_vehicles.count() == 1) {
        //-- Once a vehicle is connected, keep screen from going off
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn";
        MobileScreenMgr::setKeepScreenOn(true);
    }
#endif

}

/// This slot is connected to the Vehicle::allLinksDestroyed signal such that the Vehicle is deleted
/// and all other right things happen when the Vehicle goes away.
void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle)
{
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle;

    _vehiclesBeingDeleted << vehicle;

    // Remove from map
    bool found = false;
    for (int i=0; i<_vehicles.count(); i++) {
        if (_vehicles[i] == vehicle) {
            _vehicles.removeAt(i);
            found = true;
            break;
        }
    }
    if (!found) {
        qWarning() << "Vehicle not found in map!";
    }

    vehicle->setActive(false);
    vehicle->uas()->shutdownVehicle();

    // First we must signal that a vehicle is no longer available.
    _activeVehicleAvailable = false;
    _parameterReadyVehicleAvailable = false;
    emit activeVehicleAvailableChanged(false);
    emit parameterReadyVehicleAvailableChanged(false);
    emit vehicleRemoved(vehicle);

#ifdef __mobile__
    if(_vehicles.count() == 0) {
        //-- Once no vehicles are connected, we no longer need to keep screen from going off
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn";
        MobileScreenMgr::setKeepScreenOn(false);
    }
#endif

    // We must let the above signals flow through the system as well as get back to the main loop event queue
    // before we can actually delete the Vehicle. The reason is that Qml may be holding on the references to it.
    // Even though the above signals should unload any Qml which has references, that Qml will not be destroyed
    // until we get back to the main loop. So we set a short timer which will then fire after Qt has finished
    // doing all of its internal nastiness to clean up the Qml. This works for both the normal running case
    // as well as the unit testing case whichof course has a different signal flow!
    QTimer::singleShot(20, this, &MultiVehicleManager::_deleteVehiclePhase2);
}

void MultiVehicleManager::_deleteVehiclePhase2(void)
{
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0];

    /// Qml has been notified of vehicle about to go away and should be disconnected from it by now.
    /// This means we can now clear the active vehicle property and delete the Vehicle for real.

    Vehicle* newActiveVehicle = NULL;
    if (_vehicles.count()) {
        newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]);
    }

    _activeVehicle = newActiveVehicle;
    emit activeVehicleChanged(newActiveVehicle);

    if (_activeVehicle) {
        _activeVehicle->setActive(true);
        emit activeVehicleAvailableChanged(true);
        if (_activeVehicle->autopilotPlugin()->parametersReady()) {
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }

    delete _vehiclesBeingDeleted[0];
    _vehiclesBeingDeleted.removeAt(0);
}

void MultiVehicleManager::setActiveVehicle(Vehicle* vehicle)
{
    qCDebug(MultiVehicleManagerLog) << "setActiveVehicle" << vehicle;

    if (vehicle != _activeVehicle) {
        if (_activeVehicle) {
            _activeVehicle->setActive(false);

            // The sequence of signals is very important in order to not leave Qml elements connected
            // to a non-existent vehicle.

            // First we must signal that there is no active vehicle available. This will disconnect
            // any existing ui from the currently active vehicle.
            _activeVehicleAvailable = false;
            _parameterReadyVehicleAvailable = false;
            emit activeVehicleAvailableChanged(false);
            emit parameterReadyVehicleAvailableChanged(false);
        }

        // See explanation in _deleteVehiclePhase1
        _vehicleBeingSetActive = vehicle;
        QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2);
    }
}

void MultiVehicleManager::_setActiveVehiclePhase2(void)
{
    qCDebug(MultiVehicleManagerLog) << "_setActiveVehiclePhase2 _vehicleBeingSetActive" << _vehicleBeingSetActive;

    // Now we signal the new active vehicle
    _activeVehicle = _vehicleBeingSetActive;
    emit activeVehicleChanged(_activeVehicle);

    // And finally vehicle availability
    if (_activeVehicle) {
        _activeVehicle->setActive(true);
        _activeVehicleAvailable = true;
        emit activeVehicleAvailableChanged(true);

        if (_activeVehicle->autopilotPlugin()->parametersReady()) {
            _parameterReadyVehicleAvailable = true;
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
}

void MultiVehicleManager::_autopilotParametersReadyChanged(bool parametersReady)
{
    AutoPilotPlugin* autopilot = dynamic_cast<AutoPilotPlugin*>(sender());

    if (!autopilot) {
        qWarning() << "Dynamic cast failed!";
        return;
    }

    if (autopilot->vehicle() == _activeVehicle) {
        _parameterReadyVehicleAvailable = parametersReady;
        emit parameterReadyVehicleAvailableChanged(parametersReady);
    }
}

void MultiVehicleManager::saveSetting(const QString &name, const QString& value)
{
    QSettings settings;
    settings.setValue(name, value);
}

QString MultiVehicleManager::loadSetting(const QString &name, const QString& defaultValue)
{
    QSettings settings;
    return settings.value(name, defaultValue).toString();
}

Vehicle* MultiVehicleManager::getVehicleById(int vehicleId)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);
        if (vehicle->id() == vehicleId) {
            return vehicle;
        }
    }

    return NULL;
}

void MultiVehicleManager::setGcsHeartbeatEnabled(bool gcsHeartBeatEnabled)
{
    if (gcsHeartBeatEnabled != _gcsHeartbeatEnabled) {
        _gcsHeartbeatEnabled = gcsHeartBeatEnabled;
        emit gcsHeartBeatEnabledChanged(gcsHeartBeatEnabled);

        QSettings settings;
        settings.setValue(_gcsHeartbeatEnabledKey, gcsHeartBeatEnabled);

        if (gcsHeartBeatEnabled) {
            _gcsHeartbeatTimer.start();
        } else {
            _gcsHeartbeatTimer.stop();
        }
    }
}

void MultiVehicleManager::_sendGCSHeartbeat(void)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);

        mavlink_message_t message;
        mavlink_msg_heartbeat_pack(_mavlinkProtocol->getSystemId(),
                                   _mavlinkProtocol->getComponentId(),
                                   &message,
                                   MAV_TYPE_GCS,                // MAV_TYPE
                                   MAV_AUTOPILOT_INVALID,   // MAV_AUTOPILOT
                                   MAV_MODE_MANUAL_ARMED,   // MAV_MODE
                                   0,                       // custom mode
                                   MAV_STATE_ACTIVE);       // MAV_STATE
        vehicle->sendMessage(message);
    }
}

bool MultiVehicleManager::linkInUse(LinkInterface* link, Vehicle* skipVehicle)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);

        if (vehicle != skipVehicle) {
            if (vehicle->containsLink(link)) {
                return true;
            }
        }
    }

    return false;
}
<commit_msg>Ignore vehicle with system ID zero<commit_after>/*=====================================================================

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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 3 of the License, or
 (at your option) any later version.

 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "MultiVehicleManager.h"
#include "AutoPilotPlugin.h"
#include "MAVLinkProtocol.h"
#include "UAS.h"
#include "QGCApplication.h"
#include "FollowMe.h"

#ifdef __mobile__
#include "MobileScreenMgr.h"
#endif

#include <QQmlEngine>

QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog")

const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled";

MultiVehicleManager::MultiVehicleManager(QGCApplication* app)
    : QGCTool(app)
    , _activeVehicleAvailable(false)
    , _parameterReadyVehicleAvailable(false)
    , _activeVehicle(NULL)
    , _disconnectedVehicle(NULL)
    , _firmwarePluginManager(NULL)
    , _autopilotPluginManager(NULL)
    , _joystickManager(NULL)
    , _mavlinkProtocol(NULL)
    , _gcsHeartbeatEnabled(true)
{
    QSettings settings;

    _gcsHeartbeatEnabled = settings.value(_gcsHeartbeatEnabledKey, true).toBool();

    _gcsHeartbeatTimer.setInterval(_gcsHeartbeatRateMSecs);
    _gcsHeartbeatTimer.setSingleShot(false);
    connect(&_gcsHeartbeatTimer, &QTimer::timeout, this, &MultiVehicleManager::_sendGCSHeartbeat);
    if (_gcsHeartbeatEnabled) {
        _gcsHeartbeatTimer.start();
    }

    _disconnectedVehicle = new Vehicle(this);
}

void MultiVehicleManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

   _firmwarePluginManager =     _toolbox->firmwarePluginManager();
   _autopilotPluginManager =    _toolbox->autopilotPluginManager();
   _joystickManager =           _toolbox->joystickManager();
   _mavlinkProtocol =           _toolbox->mavlinkProtocol();

   QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
   qmlRegisterUncreatableType<MultiVehicleManager>("QGroundControl.MultiVehicleManager", 1, 0, "MultiVehicleManager", "Reference only");

   connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo);
}

void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType)
{
    if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId)
            || vehicleId == 0) {
        return;
    }

    qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType "
                                      << link->getName()
                                      << vehicleId
                                      << vehicleMavlinkVersion
                                      << vehicleFirmwareType
                                      << vehicleType;

    if (vehicleId == _mavlinkProtocol->getSystemId()) {
        _app->showMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId));
    }

    QSettings settings;
    bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool();
    if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) {
        _ignoreVehicleIds += vehicleId;
        _app->showMessage(QString("The MAVLink protocol version on vehicle #%1 and QGroundControl differ! "
                                  "It is unsafe to use different MAVLink versions. "
                                  "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION));
        return;
    }

    Vehicle* vehicle = new Vehicle(link, vehicleId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _autopilotPluginManager, _joystickManager);
    connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1);
    connect(vehicle->autopilotPlugin(), &AutoPilotPlugin::parametersReadyChanged, this, &MultiVehicleManager::_autopilotParametersReadyChanged);

    _vehicles.append(vehicle);

    emit vehicleAdded(vehicle);

    setActiveVehicle(vehicle);

    // Mark link as active
    link->setActive(true);

#ifdef __mobile__
    if(_vehicles.count() == 1) {
        //-- Once a vehicle is connected, keep screen from going off
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn";
        MobileScreenMgr::setKeepScreenOn(true);
    }
#endif

}

/// This slot is connected to the Vehicle::allLinksDestroyed signal such that the Vehicle is deleted
/// and all other right things happen when the Vehicle goes away.
void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle)
{
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle;

    _vehiclesBeingDeleted << vehicle;

    // Remove from map
    bool found = false;
    for (int i=0; i<_vehicles.count(); i++) {
        if (_vehicles[i] == vehicle) {
            _vehicles.removeAt(i);
            found = true;
            break;
        }
    }
    if (!found) {
        qWarning() << "Vehicle not found in map!";
    }

    vehicle->setActive(false);
    vehicle->uas()->shutdownVehicle();

    // First we must signal that a vehicle is no longer available.
    _activeVehicleAvailable = false;
    _parameterReadyVehicleAvailable = false;
    emit activeVehicleAvailableChanged(false);
    emit parameterReadyVehicleAvailableChanged(false);
    emit vehicleRemoved(vehicle);

#ifdef __mobile__
    if(_vehicles.count() == 0) {
        //-- Once no vehicles are connected, we no longer need to keep screen from going off
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn";
        MobileScreenMgr::setKeepScreenOn(false);
    }
#endif

    // We must let the above signals flow through the system as well as get back to the main loop event queue
    // before we can actually delete the Vehicle. The reason is that Qml may be holding on the references to it.
    // Even though the above signals should unload any Qml which has references, that Qml will not be destroyed
    // until we get back to the main loop. So we set a short timer which will then fire after Qt has finished
    // doing all of its internal nastiness to clean up the Qml. This works for both the normal running case
    // as well as the unit testing case whichof course has a different signal flow!
    QTimer::singleShot(20, this, &MultiVehicleManager::_deleteVehiclePhase2);
}

void MultiVehicleManager::_deleteVehiclePhase2(void)
{
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0];

    /// Qml has been notified of vehicle about to go away and should be disconnected from it by now.
    /// This means we can now clear the active vehicle property and delete the Vehicle for real.

    Vehicle* newActiveVehicle = NULL;
    if (_vehicles.count()) {
        newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]);
    }

    _activeVehicle = newActiveVehicle;
    emit activeVehicleChanged(newActiveVehicle);

    if (_activeVehicle) {
        _activeVehicle->setActive(true);
        emit activeVehicleAvailableChanged(true);
        if (_activeVehicle->autopilotPlugin()->parametersReady()) {
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }

    delete _vehiclesBeingDeleted[0];
    _vehiclesBeingDeleted.removeAt(0);
}

void MultiVehicleManager::setActiveVehicle(Vehicle* vehicle)
{
    qCDebug(MultiVehicleManagerLog) << "setActiveVehicle" << vehicle;

    if (vehicle != _activeVehicle) {
        if (_activeVehicle) {
            _activeVehicle->setActive(false);

            // The sequence of signals is very important in order to not leave Qml elements connected
            // to a non-existent vehicle.

            // First we must signal that there is no active vehicle available. This will disconnect
            // any existing ui from the currently active vehicle.
            _activeVehicleAvailable = false;
            _parameterReadyVehicleAvailable = false;
            emit activeVehicleAvailableChanged(false);
            emit parameterReadyVehicleAvailableChanged(false);
        }

        // See explanation in _deleteVehiclePhase1
        _vehicleBeingSetActive = vehicle;
        QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2);
    }
}

void MultiVehicleManager::_setActiveVehiclePhase2(void)
{
    qCDebug(MultiVehicleManagerLog) << "_setActiveVehiclePhase2 _vehicleBeingSetActive" << _vehicleBeingSetActive;

    // Now we signal the new active vehicle
    _activeVehicle = _vehicleBeingSetActive;
    emit activeVehicleChanged(_activeVehicle);

    // And finally vehicle availability
    if (_activeVehicle) {
        _activeVehicle->setActive(true);
        _activeVehicleAvailable = true;
        emit activeVehicleAvailableChanged(true);

        if (_activeVehicle->autopilotPlugin()->parametersReady()) {
            _parameterReadyVehicleAvailable = true;
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
}

void MultiVehicleManager::_autopilotParametersReadyChanged(bool parametersReady)
{
    AutoPilotPlugin* autopilot = dynamic_cast<AutoPilotPlugin*>(sender());

    if (!autopilot) {
        qWarning() << "Dynamic cast failed!";
        return;
    }

    if (autopilot->vehicle() == _activeVehicle) {
        _parameterReadyVehicleAvailable = parametersReady;
        emit parameterReadyVehicleAvailableChanged(parametersReady);
    }
}

void MultiVehicleManager::saveSetting(const QString &name, const QString& value)
{
    QSettings settings;
    settings.setValue(name, value);
}

QString MultiVehicleManager::loadSetting(const QString &name, const QString& defaultValue)
{
    QSettings settings;
    return settings.value(name, defaultValue).toString();
}

Vehicle* MultiVehicleManager::getVehicleById(int vehicleId)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);
        if (vehicle->id() == vehicleId) {
            return vehicle;
        }
    }

    return NULL;
}

void MultiVehicleManager::setGcsHeartbeatEnabled(bool gcsHeartBeatEnabled)
{
    if (gcsHeartBeatEnabled != _gcsHeartbeatEnabled) {
        _gcsHeartbeatEnabled = gcsHeartBeatEnabled;
        emit gcsHeartBeatEnabledChanged(gcsHeartBeatEnabled);

        QSettings settings;
        settings.setValue(_gcsHeartbeatEnabledKey, gcsHeartBeatEnabled);

        if (gcsHeartBeatEnabled) {
            _gcsHeartbeatTimer.start();
        } else {
            _gcsHeartbeatTimer.stop();
        }
    }
}

void MultiVehicleManager::_sendGCSHeartbeat(void)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);

        mavlink_message_t message;
        mavlink_msg_heartbeat_pack(_mavlinkProtocol->getSystemId(),
                                   _mavlinkProtocol->getComponentId(),
                                   &message,
                                   MAV_TYPE_GCS,                // MAV_TYPE
                                   MAV_AUTOPILOT_INVALID,   // MAV_AUTOPILOT
                                   MAV_MODE_MANUAL_ARMED,   // MAV_MODE
                                   0,                       // custom mode
                                   MAV_STATE_ACTIVE);       // MAV_STATE
        vehicle->sendMessage(message);
    }
}

bool MultiVehicleManager::linkInUse(LinkInterface* link, Vehicle* skipVehicle)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);

        if (vehicle != skipVehicle) {
            if (vehicle->containsLink(link)) {
                return true;
            }
        }
    }

    return false;
}
<|endoftext|>