<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: arealink.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 12:29:21 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif

class ScDocShell;
class SfxObjectShell;
class AbstractScLinkedAreaDlg;
struct AreaLink_Impl;

class ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer
{
private:
    AreaLink_Impl*  pImpl;
    String          aFileName;
    String          aFilterName;
    String          aOptions;
    String          aSourceArea;
    ScRange         aDestArea;
    BOOL            bAddUndo;
    BOOL            bInCreate;
    BOOL            bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

    BOOL        FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual void    Edit( Window*, const Link& rEndEditHdl );

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );
    DECL_LINK( AreaEndEditHdl, void* );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.11.240); FILE MERGED 2008/04/01 15:29:16 thb 1.11.240.3: #i85898# Stripping all external header guards 2008/04/01 12:35:49 thb 1.11.240.2: #i85898# Stripping all external header guards 2008/03/31 17:13:25 rt 1.11.240.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: arealink.hxx,v $
 * $Revision: 1.12 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX

#include "global.hxx"
#include "refreshtimer.hxx"
#include "address.hxx"
#include <sfx2/lnkbase.hxx>

class ScDocShell;
class SfxObjectShell;
class AbstractScLinkedAreaDlg;
struct AreaLink_Impl;

class ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer
{
private:
    AreaLink_Impl*  pImpl;
    String          aFileName;
    String          aFilterName;
    String          aOptions;
    String          aSourceArea;
    ScRange         aDestArea;
    BOOL            bAddUndo;
    BOOL            bInCreate;
    BOOL            bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

    BOOL        FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual void    Edit( Window*, const Link& rEndEditHdl );

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );
    DECL_LINK( AreaEndEditHdl, void* );
};

#endif

<|endoftext|>


<commit_before>/**
 * @file
 * @author Jason Lingle
 * @date 2012.02.25
 * @brief Implementation of the AIM_VetoFire AI module
 */

#include <cmath>
#include <cstdlib>
#include <list>

#include <libconfig.h++>

#include "aim_veto_fire.hxx"
#include "src/control/ai/aictrl.hxx"
#include "src/ship/ship.hxx"
#include "src/ship/insignia.hxx"
#include "src/sim/game_field.hxx"
#include "src/sim/blast.hxx"

using namespace libconfig;
using namespace std;

AIM_VetoFire::AIM_VetoFire(AIControl* c, const Setting& s)
: AIModule(c),
  trials(s.exists("trials")? s["trials"] : 64)
{
}

static bool compareObjects(const GameObject* a, const GameObject* b) {
  return a->getX() < b->getX();
}

void AIM_VetoFire::action() {
  if (!ship->target.ref) return;
  if (controller.gstat("no_appropriate_weapon", false)) return;

  float dx = ship->target.ref->getX() - ship->getX();
  float dy = ship->target.ref->getY() - ship->getY();
  float maxdist = sqrt(dx*dx + dy*dy);

  float angle = atan2(dy,dx) + controller.gstat("suggest_angle_offset", 0);
  float startx = ship->getX();
  float starty = ship->getY();
  float c = cos(angle), s = sin(angle);
  float radius = ship->getRadius();

  //Get a list of ships within the maximum distance, including dead ones
  list<Ship*> potential;

  {
    GameField::iterator it = ship->getField()->begin(),
                      end = ship->getField()->end();
    //Create dummy blast object
    Blast dummy(ship->getField(), 0, ship->getX()-maxdist,
                0, 0, 0, false, 0, false);
    it = lower_bound(it, end, &dummy, compareObjects);

    //Find ships that aren't us and put them into the list
    while (it != end) {
      if ((*it)->getClassification() == GameObject::ClassShip
      &&  (*it) != ship) {
        float xo = ship->getX() - (*it)->getX();
        float yo = ship->getY() - (*it)->getY();
        float distsq = xo*xo + yo*yo;
        float mdist = maxdist + (*it)->getRadius();
        if (distsq < mdist*mdist) {
          //It's a ship that isn't us, and it's close enough
          potential.push_back((Ship*)(*it));
        }
      }
      ++it;
    }
  }

  //Perform trials
  for (unsigned t = 0; t < trials; ++t) {
    float portion = rand()/(float)RAND_MAX;
    float px = startx + c*portion*maxdist;
    float py = starty + s*portion*maxdist;

    //Scan objects for collisions
    for (list<Ship*>::const_iterator it = potential.begin();
         it != potential.end(); ++it) {
      float xo = px - (*it)->getX();
      float yo = py - (*it)->getY();
      float distsq = xo*xo + yo*yo;
      float rad = (*it)->getRadius();
      if (distsq < rad*rad) {
        //Collision.
        //If within our own radius (portion*maxdist < ship->getRadius())
        //or if this is a friend, veto
        if (portion*maxdist < radius
        ||  (Allies == getAlliance(ship->insignia, (*it)->insignia)
             && (*it)->hasPower())) {
          controller.sstat("veto_fire", true);
          return;
        }
      }
    }
  }

  //No objection
  controller.sstat("veto_fire", false);
}

static AIModuleRegistrar<AIM_VetoFire> registrar("attack/veto_fire");
<commit_msg>Reduce default trial count to 16 in AIM_VetoFire.<commit_after>/**
 * @file
 * @author Jason Lingle
 * @date 2012.02.25
 * @brief Implementation of the AIM_VetoFire AI module
 */

#include <cmath>
#include <cstdlib>
#include <list>

#include <libconfig.h++>

#include "aim_veto_fire.hxx"
#include "src/control/ai/aictrl.hxx"
#include "src/ship/ship.hxx"
#include "src/ship/insignia.hxx"
#include "src/sim/game_field.hxx"
#include "src/sim/blast.hxx"

using namespace libconfig;
using namespace std;

AIM_VetoFire::AIM_VetoFire(AIControl* c, const Setting& s)
: AIModule(c),
  trials(s.exists("trials")? s["trials"] : 16)
{
}

static bool compareObjects(const GameObject* a, const GameObject* b) {
  return a->getX() < b->getX();
}

void AIM_VetoFire::action() {
  if (!ship->target.ref) return;
  if (controller.gstat("no_appropriate_weapon", false)) return;

  float dx = ship->target.ref->getX() - ship->getX();
  float dy = ship->target.ref->getY() - ship->getY();
  float maxdist = sqrt(dx*dx + dy*dy);

  float angle = atan2(dy,dx) + controller.gstat("suggest_angle_offset", 0);
  float startx = ship->getX();
  float starty = ship->getY();
  float c = cos(angle), s = sin(angle);
  float radius = ship->getRadius();

  //Get a list of ships within the maximum distance, including dead ones
  list<Ship*> potential;

  {
    GameField::iterator it = ship->getField()->begin(),
                      end = ship->getField()->end();
    //Create dummy blast object
    Blast dummy(ship->getField(), 0, ship->getX()-maxdist,
                0, 0, 0, false, 0, false);
    it = lower_bound(it, end, &dummy, compareObjects);

    //Find ships that aren't us and put them into the list
    while (it != end) {
      if ((*it)->getClassification() == GameObject::ClassShip
      &&  (*it) != ship) {
        float xo = ship->getX() - (*it)->getX();
        float yo = ship->getY() - (*it)->getY();
        float distsq = xo*xo + yo*yo;
        float mdist = maxdist + (*it)->getRadius();
        if (distsq < mdist*mdist) {
          //It's a ship that isn't us, and it's close enough
          potential.push_back((Ship*)(*it));
        }
      }
      ++it;
    }
  }

  //Perform trials
  for (unsigned t = 0; t < trials; ++t) {
    float portion = rand()/(float)RAND_MAX;
    float px = startx + c*portion*maxdist;
    float py = starty + s*portion*maxdist;

    //Scan objects for collisions
    for (list<Ship*>::const_iterator it = potential.begin();
         it != potential.end(); ++it) {
      float xo = px - (*it)->getX();
      float yo = py - (*it)->getY();
      float distsq = xo*xo + yo*yo;
      float rad = (*it)->getRadius();
      if (distsq < rad*rad) {
        //Collision.
        //If within our own radius (portion*maxdist < ship->getRadius())
        //or if this is a friend, veto
        if (portion*maxdist < radius
        ||  (Allies == getAlliance(ship->insignia, (*it)->insignia)
             && (*it)->hasPower())) {
          controller.sstat("veto_fire", true);
          return;
        }
      }
    }
  }

  //No objection
  controller.sstat("veto_fire", false);
}

static AIModuleRegistrar<AIM_VetoFire> registrar("attack/veto_fire");
<|endoftext|>


<commit_before>#include <QDebug>
#include <cmath>

#include "MAVLinkSimulationMAV.h"

MAVLinkSimulationMAV::MAVLinkSimulationMAV(MAVLinkSimulationLink *parent, int systemid, double lat, double lon) :
        QObject(parent),
        link(parent),
        planner(parent, systemid),
        systemid(systemid),
        timer25Hz(0),
        timer10Hz(0),
        timer1Hz(0),
        latitude(lat),
        longitude(lon),
        altitude(0.0),
        x(lon),
        y(lat),
        z(550),
        roll(0.0),
        pitch(0.0),
        yaw(0.0),
        globalNavigation(true),
        firstWP(false),
        previousSPX(8.548056),
        previousSPY(47.376389),
        previousSPZ(550),
        previousSPYaw(0.0),
        nextSPX(8.548056),
        nextSPY(47.376389),
        nextSPZ(550),
        nextSPYaw(0.0),
        sys_mode(MAV_MODE_READY),
        sys_state(MAV_STATE_STANDBY),
        nav_mode(MAV_NAV_GROUNDED),
        flying(false)
{
    // Please note: The waypoint planner is running
    connect(&mainloopTimer, SIGNAL(timeout()), this, SLOT(mainloop()));
    connect(&planner, SIGNAL(messageSent(mavlink_message_t)), this, SLOT(handleMessage(mavlink_message_t)));
    connect(link, SIGNAL(messageReceived(mavlink_message_t)), this, SLOT(handleMessage(mavlink_message_t)));
    mainloopTimer.start(20);
    mainloop();
}

void MAVLinkSimulationMAV::mainloop()
{
    // Calculate new simulator values
    //    double maxSpeed = 0.0001; // rad/s in earth coordinate frame

    //        double xNew = // (nextSPX - previousSPX)

    if (flying)
    {
        sys_state = MAV_STATE_ACTIVE;
        sys_mode = MAV_MODE_AUTO;
        nav_mode = MAV_NAV_WAYPOINT;
    }

    // 1 Hz execution
    if (timer1Hz <= 0)
    {
        mavlink_message_t msg;
        mavlink_msg_heartbeat_pack(systemid, MAV_COMP_ID_IMU, &msg, MAV_FIXED_WING, MAV_AUTOPILOT_PIXHAWK);
        link->sendMAVLinkMessage(&msg);
        planner.handleMessage(msg);

        mavlink_servo_output_raw_t servos;
        servos.servo1_raw = 1000;
        servos.servo2_raw = 1250;
        servos.servo3_raw = 1400;
        servos.servo4_raw = 1500;
        servos.servo5_raw = 1800;
        servos.servo6_raw = 1500;
        servos.servo7_raw = 1500;
        servos.servo8_raw = 2000;

        mavlink_msg_servo_output_raw_encode(systemid, MAV_COMP_ID_IMU, &msg, &servos);
        link->sendMAVLinkMessage(&msg);
        timer1Hz = 50;
    }

    // 10 Hz execution
    if (timer10Hz <= 0)
    {
        double radPer100ms = 0.00006;
        double altPer100ms = 0.4;
        double xm = (nextSPX - x);
        double ym = (nextSPY - y);
        double zm = (nextSPZ - z);

        float zsign = (zm < 0) ? -1.0f : 1.0f;

        if (!firstWP)
        {
            //float trueyaw = atan2f(xm, ym);

            float newYaw = atan2f(xm, ym);

            if (fabs(yaw - newYaw) < 90)
            {
                yaw = yaw*0.7 + 0.3*newYaw;
            }
            else
            {
                yaw = newYaw;
            }

            //qDebug() << "SIMULATION MAV: x:" << xm << "y:" << ym << "z:" << zm << "yaw:" << yaw;

            //if (sqrt(xm*xm+ym*ym) > 0.0000001)
            if (flying)
            {
                x += sin(yaw)*radPer100ms;
                y += cos(yaw)*radPer100ms;
                z += altPer100ms*zsign;
            }

            //if (xm < 0.001) xm
        }
        else
        {
            x = nextSPX;
            y = nextSPY;
            z = nextSPZ;
            firstWP = false;
            qDebug() << "INIT STEP";
        }

        // GLOBAL POSITION
        mavlink_message_t msg;
        mavlink_global_position_int_t pos;
        pos.alt = z*1000.0;
        pos.lat = y*1E7;
        pos.lon = x*1E7;
        pos.vx = 10.0f*100.0f;
        pos.vy = 0;
        pos.vz = altPer100ms*10.0f*100.0f*zsign*-1.0f;
        mavlink_msg_global_position_int_encode(systemid, MAV_COMP_ID_IMU, &msg, &pos);
        link->sendMAVLinkMessage(&msg);
        planner.handleMessage(msg);

        // ATTITUDE
        mavlink_attitude_t attitude;
        attitude.roll = 0.0f;
        attitude.pitch = 0.0f;
        attitude.yaw = yaw;

        mavlink_msg_attitude_encode(systemid, MAV_COMP_ID_IMU, &msg, &attitude);
        link->sendMAVLinkMessage(&msg);

        // SYSTEM STATUS
        mavlink_sys_status_t status;
        status.load = 300;
        status.mode = sys_mode;
        status.nav_mode = nav_mode;
        status.packet_drop = 0;
        status.vbat = 10500;
        status.status = sys_state;

        mavlink_msg_sys_status_encode(systemid, MAV_COMP_ID_IMU, &msg, &status);
        link->sendMAVLinkMessage(&msg);
        timer10Hz = 5;

        // VFR HUD
        mavlink_vfr_hud_t hud;
        hud.airspeed = pos.vx;
        hud.groundspeed = pos.vx;
        hud.alt = pos.alt;
        hud.heading = static_cast<int>((yaw/M_PI)*180.0f+180.0f) % 360;
        hud.climb = pos.vz;
        hud.throttle = 90;
        mavlink_msg_vfr_hud_encode(systemid, MAV_COMP_ID_IMU, &msg, &hud);
        link->sendMAVLinkMessage(&msg);

        // NAV CONTROLLER
        mavlink_nav_controller_output_t nav;
        nav.nav_roll = roll;
        nav.nav_pitch = pitch;
        nav.nav_bearing = yaw;
        nav.target_bearing = yaw;
        nav.wp_dist = 2.0f;
        nav.alt_error = 0.5f;
        nav.xtrack_error = 0.2f;
        mavlink_msg_nav_controller_output_encode(systemid, MAV_COMP_ID_IMU, &msg, &nav);
        link->sendMAVLinkMessage(&msg);
    }

    // 25 Hz execution
    if (timer25Hz <= 0)
    {
        // The message container to be used for sending
        mavlink_message_t ret;

        #ifdef MAVLINK_ENABLED_PIXHAWK
        // Send which controllers are active
        mavlink_control_status_t control_status;
        control_status.control_att = 1;
        control_status.control_pos_xy = 1;
        control_status.control_pos_yaw = 1;
        control_status.control_pos_z = 1;
        control_status.gps_fix = 2;        // 2D GPS fix
        control_status.position_fix = 3;   // 3D fix from GPS + barometric pressure
        control_status.vision_fix = 0;     // no fix from vision system
        mavlink_msg_control_status_encode(systemid, MAV_COMP_ID_IMU, &ret, &control_status);
        link->sendMAVLinkMessage(&ret);
        #endif //MAVLINK_ENABLED_PIXHAWK

        // Send actual controller outputs
        // This message just shows the direction
        // and magnitude of the control output
//        mavlink_position_controller_output_t pos;
//        pos.x = sin(yaw)*127.0f;
//        pos.y = cos(yaw)*127.0f;
//        pos.z = 0;
//        mavlink_msg_position_controller_output_encode(systemid, MAV_COMP_ID_IMU, &ret, &pos);
//        link->sendMAVLinkMessage(&ret);

        // Send a named value with name "FLOAT" and 0.5f as value

        // The message container to be used for sending
        //mavlink_message_t ret;
        // The C-struct holding the data to be sent
        mavlink_named_value_float_t val;

        // Fill in the data
        // Name of the value, maximum 10 characters
        // see full message specs at:
        // http://pixhawk.ethz.ch/wiki/mavlink/
        strcpy((char *)val.name, "FLOAT");
        // Value, in this case 0.5
        val.value = 0.5f;

        // Encode the data (adding header and checksums, etc.)
        mavlink_msg_named_value_float_encode(systemid, MAV_COMP_ID_IMU, &ret, &val);
        // And send it
        link->sendMAVLinkMessage(&ret);

        // MICROCONTROLLER SEND CODE:

        // uint8_t buf[MAVLINK_MAX_PACKET_LEN];
        // int16_t len = mavlink_msg_to_send_buffer(buf, &ret);
        // uart0_transmit(buf, len);

        // SEND INTEGER VALUE

        // We are reusing the "mavlink_message_t ret"
        // message buffer

        // The C-struct holding the data to be sent
        mavlink_named_value_int_t valint;

        // Fill in the data
        // Name of the value, maximum 10 characters
        // see full message specs at:
        // http://pixhawk.ethz.ch/wiki/mavlink/
        strcpy((char *)valint.name, "INTEGER");
        // Value, in this case 18000
        valint.value = 18000;

        // Encode the data (adding header and checksums, etc.)
        mavlink_msg_named_value_int_encode(systemid, MAV_COMP_ID_IMU, &ret, &valint);
        // And send it
        link->sendMAVLinkMessage(&ret);

        // MICROCONTROLLER SEND CODE:

        // uint8_t buf[MAVLINK_MAX_PACKET_LEN];
        // int16_t len = mavlink_msg_to_send_buffer(buf, &ret);
        // uart0_transmit(buf, len);

        timer25Hz = 2;
    }

    timer1Hz--;
    timer10Hz--;
    timer25Hz--;
}

void MAVLinkSimulationMAV::handleMessage(const mavlink_message_t& msg)
{
    //qDebug() << "MAV:" << systemid << "RECEIVED MESSAGE FROM" << msg.sysid << "COMP" << msg.compid;

    switch(msg.msgid)
    {
    case MAVLINK_MSG_ID_ATTITUDE:
        break;
    case MAVLINK_MSG_ID_SET_MODE:
        {
            mavlink_set_mode_t mode;
            mavlink_msg_set_mode_decode(&msg, &mode);
            if (systemid == mode.target) sys_mode = mode.mode;
        }
        break;
    case MAVLINK_MSG_ID_ACTION:
        {
            mavlink_action_t action;
            mavlink_msg_action_decode(&msg, &action);
            if (systemid == action.target && (action.target_component == 0 || action.target_component == MAV_COMP_ID_IMU))
            {
                switch (action.action)
                {
                case MAV_ACTION_TAKEOFF:
                    flying = true;
                    break;
                default:
                    {
                        mavlink_statustext_t text;
                        mavlink_message_t r_msg;
                        sprintf((char*)text.text, "MAV%d ignored unknown action %d", systemid, action.action);
                        mavlink_msg_statustext_encode(systemid, MAV_COMP_ID_IMU, &r_msg, &text);
                        link->sendMAVLinkMessage(&r_msg);
                    }
                    break;
                }
            }
        }
        break;
    case MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT_SET:
        {
            mavlink_local_position_setpoint_set_t sp;
            mavlink_msg_local_position_setpoint_set_decode(&msg, &sp);
            if (sp.target_system == this->systemid)
            {
                previousSPX = nextSPX;
                previousSPY = nextSPY;
                previousSPZ = nextSPZ;
                nextSPX = sp.x;
                nextSPY = sp.y;
                nextSPZ = sp.z;

                // Rotary wing
                //nextSPYaw = sp.yaw;

                // Airplane
                //yaw = atan2(previousSPX-nextSPX, previousSPY-nextSPY);

                //if (!firstWP) firstWP = true;
            }
            //qDebug() << "UPDATED SP:" << "X" << nextSPX << "Y" << nextSPY << "Z" << nextSPZ;
        }
        break;
    }
}
<commit_msg>Fixed win compile error<commit_after>#include <QDebug>
#include <cmath>
#include <qmath.h>

#include "MAVLinkSimulationMAV.h"

MAVLinkSimulationMAV::MAVLinkSimulationMAV(MAVLinkSimulationLink *parent, int systemid, double lat, double lon) :
        QObject(parent),
        link(parent),
        planner(parent, systemid),
        systemid(systemid),
        timer25Hz(0),
        timer10Hz(0),
        timer1Hz(0),
        latitude(lat),
        longitude(lon),
        altitude(0.0),
        x(lon),
        y(lat),
        z(550),
        roll(0.0),
        pitch(0.0),
        yaw(0.0),
        globalNavigation(true),
        firstWP(false),
        previousSPX(8.548056),
        previousSPY(47.376389),
        previousSPZ(550),
        previousSPYaw(0.0),
        nextSPX(8.548056),
        nextSPY(47.376389),
        nextSPZ(550),
        nextSPYaw(0.0),
        sys_mode(MAV_MODE_READY),
        sys_state(MAV_STATE_STANDBY),
        nav_mode(MAV_NAV_GROUNDED),
        flying(false)
{
    // Please note: The waypoint planner is running
    connect(&mainloopTimer, SIGNAL(timeout()), this, SLOT(mainloop()));
    connect(&planner, SIGNAL(messageSent(mavlink_message_t)), this, SLOT(handleMessage(mavlink_message_t)));
    connect(link, SIGNAL(messageReceived(mavlink_message_t)), this, SLOT(handleMessage(mavlink_message_t)));
    mainloopTimer.start(20);
    mainloop();
}

void MAVLinkSimulationMAV::mainloop()
{
    // Calculate new simulator values
    //    double maxSpeed = 0.0001; // rad/s in earth coordinate frame

    //        double xNew = // (nextSPX - previousSPX)

    if (flying)
    {
        sys_state = MAV_STATE_ACTIVE;
        sys_mode = MAV_MODE_AUTO;
        nav_mode = MAV_NAV_WAYPOINT;
    }

    // 1 Hz execution
    if (timer1Hz <= 0)
    {
        mavlink_message_t msg;
        mavlink_msg_heartbeat_pack(systemid, MAV_COMP_ID_IMU, &msg, MAV_FIXED_WING, MAV_AUTOPILOT_PIXHAWK);
        link->sendMAVLinkMessage(&msg);
        planner.handleMessage(msg);

        mavlink_servo_output_raw_t servos;
        servos.servo1_raw = 1000;
        servos.servo2_raw = 1250;
        servos.servo3_raw = 1400;
        servos.servo4_raw = 1500;
        servos.servo5_raw = 1800;
        servos.servo6_raw = 1500;
        servos.servo7_raw = 1500;
        servos.servo8_raw = 2000;

        mavlink_msg_servo_output_raw_encode(systemid, MAV_COMP_ID_IMU, &msg, &servos);
        link->sendMAVLinkMessage(&msg);
        timer1Hz = 50;
    }

    // 10 Hz execution
    if (timer10Hz <= 0)
    {
        double radPer100ms = 0.00006;
        double altPer100ms = 0.4;
        double xm = (nextSPX - x);
        double ym = (nextSPY - y);
        double zm = (nextSPZ - z);

        float zsign = (zm < 0) ? -1.0f : 1.0f;

        if (!firstWP)
        {
            //float trueyaw = atan2f(xm, ym);

            float newYaw = atan2f(xm, ym);

            if (fabs(yaw - newYaw) < 90)
            {
                yaw = yaw*0.7 + 0.3*newYaw;
            }
            else
            {
                yaw = newYaw;
            }

            //qDebug() << "SIMULATION MAV: x:" << xm << "y:" << ym << "z:" << zm << "yaw:" << yaw;

            //if (sqrt(xm*xm+ym*ym) > 0.0000001)
            if (flying)
            {
                x += sin(yaw)*radPer100ms;
                y += cos(yaw)*radPer100ms;
                z += altPer100ms*zsign;
            }

            //if (xm < 0.001) xm
        }
        else
        {
            x = nextSPX;
            y = nextSPY;
            z = nextSPZ;
            firstWP = false;
            qDebug() << "INIT STEP";
        }

        // GLOBAL POSITION
        mavlink_message_t msg;
        mavlink_global_position_int_t pos;
        pos.alt = z*1000.0;
        pos.lat = y*1E7;
        pos.lon = x*1E7;
        pos.vx = 10.0f*100.0f;
        pos.vy = 0;
        pos.vz = altPer100ms*10.0f*100.0f*zsign*-1.0f;
        mavlink_msg_global_position_int_encode(systemid, MAV_COMP_ID_IMU, &msg, &pos);
        link->sendMAVLinkMessage(&msg);
        planner.handleMessage(msg);

        // ATTITUDE
        mavlink_attitude_t attitude;
        attitude.roll = 0.0f;
        attitude.pitch = 0.0f;
        attitude.yaw = yaw;

        mavlink_msg_attitude_encode(systemid, MAV_COMP_ID_IMU, &msg, &attitude);
        link->sendMAVLinkMessage(&msg);

        // SYSTEM STATUS
        mavlink_sys_status_t status;
        status.load = 300;
        status.mode = sys_mode;
        status.nav_mode = nav_mode;
        status.packet_drop = 0;
        status.vbat = 10500;
        status.status = sys_state;

        mavlink_msg_sys_status_encode(systemid, MAV_COMP_ID_IMU, &msg, &status);
        link->sendMAVLinkMessage(&msg);
        timer10Hz = 5;

        // VFR HUD
        mavlink_vfr_hud_t hud;
        hud.airspeed = pos.vx;
        hud.groundspeed = pos.vx;
        hud.alt = pos.alt;
        hud.heading = static_cast<int>((yaw/M_PI)*180.0f+180.0f) % 360;
        hud.climb = pos.vz;
        hud.throttle = 90;
        mavlink_msg_vfr_hud_encode(systemid, MAV_COMP_ID_IMU, &msg, &hud);
        link->sendMAVLinkMessage(&msg);

        // NAV CONTROLLER
        mavlink_nav_controller_output_t nav;
        nav.nav_roll = roll;
        nav.nav_pitch = pitch;
        nav.nav_bearing = yaw;
        nav.target_bearing = yaw;
        nav.wp_dist = 2.0f;
        nav.alt_error = 0.5f;
        nav.xtrack_error = 0.2f;
        mavlink_msg_nav_controller_output_encode(systemid, MAV_COMP_ID_IMU, &msg, &nav);
        link->sendMAVLinkMessage(&msg);
    }

    // 25 Hz execution
    if (timer25Hz <= 0)
    {
        // The message container to be used for sending
        mavlink_message_t ret;

        #ifdef MAVLINK_ENABLED_PIXHAWK
        // Send which controllers are active
        mavlink_control_status_t control_status;
        control_status.control_att = 1;
        control_status.control_pos_xy = 1;
        control_status.control_pos_yaw = 1;
        control_status.control_pos_z = 1;
        control_status.gps_fix = 2;        // 2D GPS fix
        control_status.position_fix = 3;   // 3D fix from GPS + barometric pressure
        control_status.vision_fix = 0;     // no fix from vision system
        mavlink_msg_control_status_encode(systemid, MAV_COMP_ID_IMU, &ret, &control_status);
        link->sendMAVLinkMessage(&ret);
        #endif //MAVLINK_ENABLED_PIXHAWK

        // Send actual controller outputs
        // This message just shows the direction
        // and magnitude of the control output
//        mavlink_position_controller_output_t pos;
//        pos.x = sin(yaw)*127.0f;
//        pos.y = cos(yaw)*127.0f;
//        pos.z = 0;
//        mavlink_msg_position_controller_output_encode(systemid, MAV_COMP_ID_IMU, &ret, &pos);
//        link->sendMAVLinkMessage(&ret);

        // Send a named value with name "FLOAT" and 0.5f as value

        // The message container to be used for sending
        //mavlink_message_t ret;
        // The C-struct holding the data to be sent
        mavlink_named_value_float_t val;

        // Fill in the data
        // Name of the value, maximum 10 characters
        // see full message specs at:
        // http://pixhawk.ethz.ch/wiki/mavlink/
        strcpy((char *)val.name, "FLOAT");
        // Value, in this case 0.5
        val.value = 0.5f;

        // Encode the data (adding header and checksums, etc.)
        mavlink_msg_named_value_float_encode(systemid, MAV_COMP_ID_IMU, &ret, &val);
        // And send it
        link->sendMAVLinkMessage(&ret);

        // MICROCONTROLLER SEND CODE:

        // uint8_t buf[MAVLINK_MAX_PACKET_LEN];
        // int16_t len = mavlink_msg_to_send_buffer(buf, &ret);
        // uart0_transmit(buf, len);

        // SEND INTEGER VALUE

        // We are reusing the "mavlink_message_t ret"
        // message buffer

        // The C-struct holding the data to be sent
        mavlink_named_value_int_t valint;

        // Fill in the data
        // Name of the value, maximum 10 characters
        // see full message specs at:
        // http://pixhawk.ethz.ch/wiki/mavlink/
        strcpy((char *)valint.name, "INTEGER");
        // Value, in this case 18000
        valint.value = 18000;

        // Encode the data (adding header and checksums, etc.)
        mavlink_msg_named_value_int_encode(systemid, MAV_COMP_ID_IMU, &ret, &valint);
        // And send it
        link->sendMAVLinkMessage(&ret);

        // MICROCONTROLLER SEND CODE:

        // uint8_t buf[MAVLINK_MAX_PACKET_LEN];
        // int16_t len = mavlink_msg_to_send_buffer(buf, &ret);
        // uart0_transmit(buf, len);

        timer25Hz = 2;
    }

    timer1Hz--;
    timer10Hz--;
    timer25Hz--;
}

void MAVLinkSimulationMAV::handleMessage(const mavlink_message_t& msg)
{
    //qDebug() << "MAV:" << systemid << "RECEIVED MESSAGE FROM" << msg.sysid << "COMP" << msg.compid;

    switch(msg.msgid)
    {
    case MAVLINK_MSG_ID_ATTITUDE:
        break;
    case MAVLINK_MSG_ID_SET_MODE:
        {
            mavlink_set_mode_t mode;
            mavlink_msg_set_mode_decode(&msg, &mode);
            if (systemid == mode.target) sys_mode = mode.mode;
        }
        break;
    case MAVLINK_MSG_ID_ACTION:
        {
            mavlink_action_t action;
            mavlink_msg_action_decode(&msg, &action);
            if (systemid == action.target && (action.target_component == 0 || action.target_component == MAV_COMP_ID_IMU))
            {
                switch (action.action)
                {
                case MAV_ACTION_TAKEOFF:
                    flying = true;
                    break;
                default:
                    {
                        mavlink_statustext_t text;
                        mavlink_message_t r_msg;
                        sprintf((char*)text.text, "MAV%d ignored unknown action %d", systemid, action.action);
                        mavlink_msg_statustext_encode(systemid, MAV_COMP_ID_IMU, &r_msg, &text);
                        link->sendMAVLinkMessage(&r_msg);
                    }
                    break;
                }
            }
        }
        break;
    case MAVLINK_MSG_ID_LOCAL_POSITION_SETPOINT_SET:
        {
            mavlink_local_position_setpoint_set_t sp;
            mavlink_msg_local_position_setpoint_set_decode(&msg, &sp);
            if (sp.target_system == this->systemid)
            {
                previousSPX = nextSPX;
                previousSPY = nextSPY;
                previousSPZ = nextSPZ;
                nextSPX = sp.x;
                nextSPY = sp.y;
                nextSPZ = sp.z;

                // Rotary wing
                //nextSPYaw = sp.yaw;

                // Airplane
                //yaw = atan2(previousSPX-nextSPX, previousSPY-nextSPY);

                //if (!firstWP) firstWP = true;
            }
            //qDebug() << "UPDATED SP:" << "X" << nextSPX << "Y" << nextSPY << "Z" << nextSPZ;
        }
        break;
    }
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <signal.h>

#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

inline void check_dnsservice_errors(DNSServiceErrorType& e, const std::string& func_name) {
    std::string error(func_name);
    error += ": ";

    switch (e) {
        case kDNSServiceErr_NoError:
            return;
        case kDNSServiceErr_NameConflict:
            error += "Name in use, please choose another";
            break;
        case kDNSServiceErr_Invalid:
            error += "An invalid index or character was passed";
            break;
        case kDNSServiceErr_BadReference:
            error += "Bad reference";
            break;
        case kDNSServiceErr_BadParam:
            error += "Bad parameter value passed to function.";
            break;
        default:
            error += "Unknown error code... ";
            error += std::to_string(e);
    }

    throw std::runtime_error(error.c_str());
}

inline void signal_int(ev::sig& sig, int) {
    std::cerr << std::endl << "Caught SIGINT..." << std::endl;

    sig.loop.break_loop();
}

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }

    std::vector<std::string> _domains;

    DNSServiceRef serviceRef = 0;
    int dns_sd_fd = -1;

    try {
        std::ifstream f(argv[1], std::ios::in | std::ios::binary);

        if (!f.is_open()) {
            std::cerr << "Unable to open file: " << argv[1] << std::endl;
            return -2;
        }

        for (std::string line; std::getline(f, line); /**/) {
            if (line.length() != 0) _domains.push_back(line);
        }

        DNSServiceErrorType error = kDNSServiceErr_NoError;

        // Setup the mDNS context...
        error = DNSServiceCreateConnection(&serviceRef);
        check_dnsservice_errors(error, "DNSServiceCreateConnection");

        for (auto &d : _domains) {
            std::cout << "Registering Domain: " << d << std::endl;

        }

        // Add event for catching SIGINT, so we can do proper cleanup
        ev::sig sio;
        sio.set<signal_int>();
        sio.start(SIGINT);

        // Ignore SIGPIPE
        struct sigaction act;
        act.sa_handler = SIG_IGN;
        sigemptyset(&act.sa_mask);
        act.sa_flags = 0;
        sigaction(SIGPIPE, &act, 0);

        // start the libev loop
        ev::default_loop loop;
        loop.run(0);
    } catch (std::exception const& e) {
        std::cerr << "Caught an exception: " << e.what() << std::endl;
    }

    DNSServiceRefDeallocate(serviceRef);

    return 0;
}
<commit_msg>Actually register the CNAME records...<commit_after>#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <signal.h>

#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

inline void check_dnsservice_errors(DNSServiceErrorType& e, const std::string& func_name) {
    std::string error(func_name);
    error += ": ";

    switch (e) {
        case kDNSServiceErr_NoError:
            return;
        case kDNSServiceErr_NameConflict:
            error += "Name in use, please choose another";
            break;
        case kDNSServiceErr_Invalid:
            error += "An invalid index or character was passed";
            break;
        case kDNSServiceErr_BadReference:
            error += "Bad reference";
            break;
        case kDNSServiceErr_BadParam:
            error += "Bad parameter value passed to function.";
            break;
        default:
            error += "Unknown error code... ";
            error += std::to_string(e);
    }

    throw std::runtime_error(error.c_str());
}

inline void signal_int(ev::sig& sig, int) {
    std::cerr << std::endl << "Caught SIGINT..." << std::endl;

    sig.loop.break_loop();
}

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }

    std::vector<std::string> _domains;
    std::vector<DNSRecordRef> _records;

    DNSServiceRef serviceRef = 0;
    int dns_sd_fd = -1;

    try {
        std::ifstream f(argv[1], std::ios::in | std::ios::binary);

        if (!f.is_open()) {
            std::cerr << "Unable to open file: " << argv[1] << std::endl;
            return -2;
        }

        for (std::string line; std::getline(f, line); /**/) {
            if (line.length() != 0) _domains.push_back(line);
        }

        DNSServiceErrorType error = kDNSServiceErr_NoError;

        // Setup the mDNS context...
        error = DNSServiceCreateConnection(&serviceRef);
        check_dnsservice_errors(error, "DNSServiceCreateConnection");

        for (auto &d : _domains) {
            std::cout << "Registering Domain: " << d << std::endl;
            DNSRecordRef record = 0;

            const char cname[] = { 9, 'a', 'l', 'e', 'x', 'a', 'n', 'd', 'r', 'a', 5, 'l', 'o', 'c', 'a', 'l', 0 };

            error = DNSServiceRegisterRecord(
                    serviceRef,                     // DNSServiceRef
                    &record,                        // DNSRecordRef
                    kDNSServiceFlagsShareConnection | kDNSServiceFlagsUnique,         // DNSServiceFlags
                    kDNSServiceInterfaceIndexAny,   // uint32_t interfaceIndex
                    d.c_str(),                      // fullname
                    kDNSServiceType_CNAME,          // rrtype
                    kDNSServiceClass_IN,            // rrclass
                    sizeof(cname),                  // rdlen
                    cname,                          // rdata (const void)
                    0,                              // uint32_t ttl
                    CallBack,                       // Callback
                    reinterpret_cast<void*>(&d)     // Context
                    );

            check_dnsservice_errors(error, "DNSServiceRegisterRecord");
            _records.push_back(record);

        }

        // Add event for catching SIGINT, so we can do proper cleanup
        ev::sig sio;
        sio.set<signal_int>();
        sio.start(SIGINT);

        // Ignore SIGPIPE
        struct sigaction act;
        act.sa_handler = SIG_IGN;
        sigemptyset(&act.sa_mask);
        act.sa_flags = 0;
        sigaction(SIGPIPE, &act, 0);

        // start the libev loop
        ev::default_loop loop;
        loop.run(0);
    } catch (std::exception const& e) {
        std::cerr << "Caught an exception: " << e.what() << std::endl;
    }

    DNSServiceRefDeallocate(serviceRef);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "mainwindow.h"
#include "version.h"
#include <QApplication>
#include <QCommandLineParser>

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}
<commit_msg>Use an ini file to store GUI settings in windows<commit_after>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "mainwindow.h"
#include "version.h"
#include <QApplication>
#include <QCommandLineParser>
#include <QSettings>

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

#ifdef Q_OS_WIN
    // Use an ini file instead of the registry to store GUI settings.
    //
    // The `window_state` QSettings key is ~5.3KB (as of December 2019) and
    // Microsoft's documentation recommends that we do not store values > 2048 bytes in the registry.
    // https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
    QSettings::setDefaultFormat(QSettings::IniFormat);
#endif

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}
<|endoftext|>


<commit_before>#include "OGLPlotter.hpp"

namespace hpl {
OGLPlotter::OGLPlotter() : AbstractPlotter(), Window()
{
}

OGLPlotter::~OGLPlotter()
{
}

void OGLPlotter::init()
{
    if (plots != 0) {
        for (auto it = plots->cbegin(); it != plots->cend(); ++it) {
            if (revision.find(it->first) == revision.end()) {
                Lines* l = dynamic_cast<Lines*>(it->second);
                if (l != 0) {
                    lineCollection[it->first] = LineCollection();
                }
                revision[it->first] = 0;
            }
        }
    }

    glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1.0);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    //font.init(fontFile);

    programsDatabase.init();

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        unsigned int ar = actualRevision->at(it->first);
        if (ar != revision[it->first]) {
            const Lines* l = static_cast<const Lines*>(&plots->lookup(it->first));

            float* interleave = new float[2 * l->n];
            for (int i = 0; i < l->n; i++) {
                interleave[(i << 1)] = (l->x[i] - l->getXmin()) / (l->getXmax() - l->getXmin());
                interleave[(i << 1) + 1] = (l->y[i] - l->getYmin()) / (l->getYmax() - l->getYmin());
            }

            glGenBuffers(1, &it->second.lineBuffer);
            glBindBuffer(GL_ARRAY_BUFFER, it->second.lineBuffer);
            glBufferData(GL_ARRAY_BUFFER, 2 * l->n * sizeof(float), interleave, GL_STATIC_DRAW);
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            it->second.pos = glGetAttribLocation(programsDatabase.getLineProgram(), "Position");
            it->second.rect = glGetUniformLocation(programsDatabase.getLineProgram(), "Rect");
            it->second.color = glGetUniformLocation(programsDatabase.getLineProgram(), "Color");
            it->second.linemvp = glGetUniformLocation(programsDatabase.getLineProgram(), "MVP");

            revision[it->first] = ar;
        }
    }
}

void OGLPlotter::destroy()
{
    /*pthread_mutex_lock(&mutex);
    for (auto it = csystems.cbegin(); it != csystems.cend(); ++it) {
        it->second->destroy();
    }
    pthread_mutex_unlock(&mutex);*/

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        glDeleteBuffers(1, &it->second.lineBuffer);
    }

    programsDatabase.destroy();
}

void OGLPlotter::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /*pthread_mutex_lock(&mutex);
    while (!csInit.empty()) {
        CoordinateSystem::ID id = csInit.front();
        csInit.pop();
        if (csystems.has(id)) {
            csystems.lookup(id).init(programsDatabase.getLineProgram(), programsDatabase.getTextProgram(), programsDatabase.getMapProgram());
        }
    }

    for (auto it = csystems.cbegin(); it != csystems.cend(); ++it) {
        it->second->draw(mvp);
    }
    pthread_mutex_unlock(&mutex);*/

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        const Lines* l = static_cast<const Lines*>(&plots->lookup(it->first));
        Geometry g = l->getGeometry();
        Color c = l->getColor();

        glUseProgram(programsDatabase.getLineProgram());
        glBindBuffer(GL_ARRAY_BUFFER, it->second.lineBuffer);
        glVertexAttribPointer(
            it->second.pos,
            2,
            GL_FLOAT,
            GL_FALSE,
            0,
            (GLvoid const*) 0
        );
        glEnableVertexAttribArray(it->second.pos);
        glUniform4f(it->second.rect, g.leftOffset, g.topOffset, g.width, g.height);
        glUniform3f(it->second.color, c.r, c.g, c.b);
        glUniformMatrix3fv(it->second.linemvp, 1, GL_FALSE, mvp);

        glDrawArrays((l->separate ? GL_LINES : GL_LINE_STRIP), 0, l->n);
        glDisableVertexAttribArray(it->second.pos);
    }
}

void OGLPlotter::resetEvent()
{
    mvp[0] = 1.0;
    mvp[4] = 1.0;
    mvp[6] = 0.0;
    mvp[7] = 0.0;
}

void OGLPlotter::moveEvent(int deltax, int deltay)
{
    mvp[6] += deltax / static_cast<double>(width);
    mvp[7] += -deltay / static_cast<double>(height);
}

void OGLPlotter::mouseWheelEvent(int x, int y, double delta)
{
    delta *= 0.2f;
    double old = mvp[0];
    mvp[0] += delta;
    mvp[4] += delta;
    if (mvp[0] < 0.5f) {
        mvp[0] = 0.5f;
    }
    if (mvp[4] < 0.5f) {
        mvp[4] = 0.5f;
    }
    double xs = (x / static_cast<double>(width) - mvp[6]) / old;
    double ys = (1.0 - y / static_cast<double>(height) - mvp[7]) / old;
    mvp[6] += (old-mvp[0]) * xs;
    mvp[7] += (old-mvp[4]) * ys;
}

void OGLPlotter::checkAndCleanCollections()
{
    for (auto it = lineCollection.begin(); it != lineCollection.end();) {
        if (!plots->has(it->first)) {
            lineCollection.erase(it++);
        } else {
            ++it;
        }
    }
}
}
<commit_msg>Resolved that issue, forgot to recall init. Think about if this is the right place for this call<commit_after>#include "OGLPlotter.hpp"

namespace hpl {
OGLPlotter::OGLPlotter() : AbstractPlotter(), Window()
{
}

OGLPlotter::~OGLPlotter()
{
}

void OGLPlotter::init()
{
    if (plots != 0) {
        for (auto it = plots->cbegin(); it != plots->cend(); ++it) {
            if (revision.find(it->first) == revision.end()) {
                Lines* l = dynamic_cast<Lines*>(it->second);
                if (l != 0) {
                    lineCollection[it->first] = LineCollection();
                }
                revision[it->first] = 0;
            }
        }
    }

    glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1.0);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    //font.init(fontFile);

    programsDatabase.init();

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        unsigned int ar = actualRevision->at(it->first);
        if (ar != revision[it->first]) {
            const Lines* l = static_cast<const Lines*>(&plots->lookup(it->first));

            float* interleave = new float[2 * l->n];
            for (int i = 0; i < l->n; i++) {
                interleave[(i << 1)] = (l->x[i] - l->getXmin()) / (l->getXmax() - l->getXmin());
                interleave[(i << 1) + 1] = (l->y[i] - l->getYmin()) / (l->getYmax() - l->getYmin());
            }

            glGenBuffers(1, &it->second.lineBuffer);
            glBindBuffer(GL_ARRAY_BUFFER, it->second.lineBuffer);
            glBufferData(GL_ARRAY_BUFFER, 2 * l->n * sizeof(float), interleave, GL_STATIC_DRAW);
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            it->second.pos = glGetAttribLocation(programsDatabase.getLineProgram(), "Position");
            it->second.rect = glGetUniformLocation(programsDatabase.getLineProgram(), "Rect");
            it->second.color = glGetUniformLocation(programsDatabase.getLineProgram(), "Color");
            it->second.linemvp = glGetUniformLocation(programsDatabase.getLineProgram(), "MVP");

            revision[it->first] = ar;
        }
    }
}

void OGLPlotter::destroy()
{
    /*pthread_mutex_lock(&mutex);
    for (auto it = csystems.cbegin(); it != csystems.cend(); ++it) {
        it->second->destroy();
    }
    pthread_mutex_unlock(&mutex);*/

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        glDeleteBuffers(1, &it->second.lineBuffer);
    }

    programsDatabase.destroy();
}

void OGLPlotter::draw()
{
    init();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /*pthread_mutex_lock(&mutex);
    while (!csInit.empty()) {
        CoordinateSystem::ID id = csInit.front();
        csInit.pop();
        if (csystems.has(id)) {
            csystems.lookup(id).init(programsDatabase.getLineProgram(), programsDatabase.getTextProgram(), programsDatabase.getMapProgram());
        }
    }

    for (auto it = csystems.cbegin(); it != csystems.cend(); ++it) {
        it->second->draw(mvp);
    }
    pthread_mutex_unlock(&mutex);*/

    for (auto it = lineCollection.begin(); it != lineCollection.end(); ++it) {
        const Lines* l = static_cast<const Lines*>(&plots->lookup(it->first));
        Geometry g = l->getGeometry();
        Color c = l->getColor();

        glUseProgram(programsDatabase.getLineProgram());
        glBindBuffer(GL_ARRAY_BUFFER, it->second.lineBuffer);
        glVertexAttribPointer(
            it->second.pos,
            2,
            GL_FLOAT,
            GL_FALSE,
            0,
            (GLvoid const*) 0
        );
        glEnableVertexAttribArray(it->second.pos);
        glUniform4f(it->second.rect, g.leftOffset, g.topOffset, g.width, g.height);
        glUniform3f(it->second.color, c.r, c.g, c.b);
        glUniformMatrix3fv(it->second.linemvp, 1, GL_FALSE, mvp);

        glDrawArrays((l->separate ? GL_LINES : GL_LINE_STRIP), 0, l->n);
        glDisableVertexAttribArray(it->second.pos);
    }
}

void OGLPlotter::resetEvent()
{
    mvp[0] = 1.0;
    mvp[4] = 1.0;
    mvp[6] = 0.0;
    mvp[7] = 0.0;
}

void OGLPlotter::moveEvent(int deltax, int deltay)
{
    mvp[6] += deltax / static_cast<double>(width);
    mvp[7] += -deltay / static_cast<double>(height);
}

void OGLPlotter::mouseWheelEvent(int x, int y, double delta)
{
    delta *= 0.2f;
    double old = mvp[0];
    mvp[0] += delta;
    mvp[4] += delta;
    if (mvp[0] < 0.5f) {
        mvp[0] = 0.5f;
    }
    if (mvp[4] < 0.5f) {
        mvp[4] = 0.5f;
    }
    double xs = (x / static_cast<double>(width) - mvp[6]) / old;
    double ys = (1.0 - y / static_cast<double>(height) - mvp[7]) / old;
    mvp[6] += (old-mvp[0]) * xs;
    mvp[7] += (old-mvp[4]) * ys;
}

void OGLPlotter::checkAndCleanCollections()
{
    for (auto it = lineCollection.begin(); it != lineCollection.end();) {
        if (!plots->has(it->first)) {
            lineCollection.erase(it++);
        } else {
            ++it;
        }
    }
}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018 Sven Willner <sven.willner@pik-potsdam.de>
 * Free software under GNU Affero General Public License v3, see LICENSE
 */

#include "Observable.h"
#include <algorithm>
#include <limits>
#include "imodel_component.hpp"
#include "core.hpp"

namespace hector = Hector;
namespace py = pybind11;

namespace pyhector {

Observable::Observable(
    hector::Core* hcore, std::string component_name_p, std::string name_p, bool needs_date_p, bool in_spinup_p, std::size_t expected_run_size_p)
    : component_name(std::move(component_name_p)),
      name(std::move(name_p)),
      needs_date(needs_date_p),
      in_spinup(in_spinup_p),
      expected_run_size(expected_run_size_p) {
    reset(hcore);
}

void Observable::read_data(hector::Core* hcore, double current_date, std::size_t time_index, std::size_t spinup_index) {
    if (in_spinup == hcore->inSpinup()) {
        hector::message_data info;
        if (needs_date) {
            info.date = current_date;
        }

        std::size_t index;
        if (in_spinup) {
            index = spinup_index;
        } else {
            index = time_index;
        }

        double value;
        if (component) {
            value = component->sendMessage(M_GETDATA, name, info);
        } else {
            value = hcore->sendMessage(M_GETDATA, name, info);
        }

        if (index >= values.size()) {
            values.resize(index + 1, std::numeric_limits<double>::quiet_NaN());
        }
        values[index] = value;
        array.reset();
    }
}

void Observable::reset(hector::Core* hcore) {
    if (component_name == CORE_COMPONENT_NAME) {
        component = nullptr;
    } else {
        component = hcore->getComponentByName(component_name);
    }
    values.clear();
    if (!in_spinup) {
        values.reserve(expected_run_size);
    }
    array.reset();
}

bool Observable::matches(const std::string& component_name_p, const std::string& name_p, bool in_spinup_p) const {
    return in_spinup == in_spinup_p
           && ((component == nullptr && component_name_p == CORE_COMPONENT_NAME) || (component != nullptr && component_name_p == component->getComponentName()))
           && name == name_p;
}

py::array_t<double> Observable::get_array() const {
    if (array) {
        return *array.get();
    }
    double* data = new double[values.size()];
    std::copy(std::begin(values), std::end(values), data);

    py::capsule handle(data, [](void* d) {
        double* data = reinterpret_cast<double*>(d);
        delete[] data;
    });

    array.reset(new py::array_t<double>{{values.size()}, data, handle});
    return *array.get();
}

}  // namespace pyhector
<commit_msg>Add explicit cast to ssize_t (and use more appropriate array_t constructor)<commit_after>/*
 * Copyright (c) 2018 Sven Willner <sven.willner@pik-potsdam.de>
 * Free software under GNU Affero General Public License v3, see LICENSE
 */

#include "Observable.h"
#include <algorithm>
#include <limits>
#include "imodel_component.hpp"
#include "core.hpp"

namespace hector = Hector;
namespace py = pybind11;

namespace pyhector {

Observable::Observable(
    hector::Core* hcore, std::string component_name_p, std::string name_p, bool needs_date_p, bool in_spinup_p, std::size_t expected_run_size_p)
    : component_name(std::move(component_name_p)),
      name(std::move(name_p)),
      needs_date(needs_date_p),
      in_spinup(in_spinup_p),
      expected_run_size(expected_run_size_p) {
    reset(hcore);
}

void Observable::read_data(hector::Core* hcore, double current_date, std::size_t time_index, std::size_t spinup_index) {
    if (in_spinup == hcore->inSpinup()) {
        hector::message_data info;
        if (needs_date) {
            info.date = current_date;
        }

        std::size_t index;
        if (in_spinup) {
            index = spinup_index;
        } else {
            index = time_index;
        }

        double value;
        if (component) {
            value = component->sendMessage(M_GETDATA, name, info);
        } else {
            value = hcore->sendMessage(M_GETDATA, name, info);
        }

        if (index >= values.size()) {
            values.resize(index + 1, std::numeric_limits<double>::quiet_NaN());
        }
        values[index] = value;
        array.reset();
    }
}

void Observable::reset(hector::Core* hcore) {
    if (component_name == CORE_COMPONENT_NAME) {
        component = nullptr;
    } else {
        component = hcore->getComponentByName(component_name);
    }
    values.clear();
    if (!in_spinup) {
        values.reserve(expected_run_size);
    }
    array.reset();
}

bool Observable::matches(const std::string& component_name_p, const std::string& name_p, bool in_spinup_p) const {
    return in_spinup == in_spinup_p
           && ((component == nullptr && component_name_p == CORE_COMPONENT_NAME) || (component != nullptr && component_name_p == component->getComponentName()))
           && name == name_p;
}

py::array_t<double> Observable::get_array() const {
    if (array) {
        return *array.get();
    }
    double* data = new double[values.size()];
    std::copy(std::begin(values), std::end(values), data);

    py::capsule handle(data, [](void* d) {
        double* data = reinterpret_cast<double*>(d);
        delete[] data;
    });

    array.reset(new py::array_t<double>{static_cast<ssize_t>(values.size()), data, handle});
    return *array.get();
}

}  // namespace pyhector
<|endoftext|>


<commit_before><commit_msg>Add a basic test for main frame swap.<commit_after><|endoftext|>


<commit_before>#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP

#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>

namespace cdm
{
	struct boost_paths
	{
		Si::absolute_path root;
	};

	inline boost_paths install_boost(
		Si::absolute_path const &source,
		Si::absolute_path const &temporary,
		Si::absolute_path const &install_root,
		Si::absolute_path const &cmake_exe,
		unsigned make_parallelism,
		Si::Sink<char, Si::success>::interface &output)
	{
		boost::ignore_unused(cmake_exe);

		Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
		if (!Si::file_exists(module_in_cache, Si::throw_))
		{
			Si::absolute_path const copy_of_boost = temporary / Si::relative_path("boost-copy");
			Si::copy_recursively(source, copy_of_boost, &output, Si::throw_);

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
				arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache));
				int const rc = Si::run_process(*Si::absolute_path::create("/usr/bin/env"), arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("bootstrap failed");
				}
			}

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
				int const rc = Si::run_process(copy_of_boost / "b2", arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("b2 failed");
				}
			}
		}
		boost_paths result;
		result.root = module_in_cache;
		return result;
	}
}

#endif
<commit_msg>avoid boost::ignore_unused because it is too new<commit_after>#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP

#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>

namespace cdm
{
	struct boost_paths
	{
		Si::absolute_path root;
	};

	inline boost_paths install_boost(
		Si::absolute_path const &source,
		Si::absolute_path const &temporary,
		Si::absolute_path const &install_root,
		Si::absolute_path const &cmake_exe,
		unsigned make_parallelism,
		Si::Sink<char, Si::success>::interface &output)
	{
		boost::ignore_unused_variable_warning(cmake_exe);

		Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
		if (!Si::file_exists(module_in_cache, Si::throw_))
		{
			Si::absolute_path const copy_of_boost = temporary / Si::relative_path("boost-copy");
			Si::copy_recursively(source, copy_of_boost, &output, Si::throw_);

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
				arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache));
				int const rc = Si::run_process(*Si::absolute_path::create("/usr/bin/env"), arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("bootstrap failed");
				}
			}

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
				int const rc = Si::run_process(copy_of_boost / "b2", arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("b2 failed");
				}
			}
		}
		boost_paths result;
		result.root = module_in_cache;
		return result;
	}
}

#endif
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <errno.h>
#include <QtWidgets>

#include "p6vxapp.h"

#ifndef NOJOYSTICK
//SDL使用時にビルドを通すのに必要
#undef main
#endif

///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
#ifdef PANDORA
	//VALGRIND実行時用の環境変数
	setenv("DISPLAY", ":0.0", 1);
	//GlibのOSと開発環境のバージョン不一致に対する暫定対応
	//setenv("QT_NO_GLIB", "0", 1);
	//EGLFS対応
	setenv("EGLFS_X11_SIZE", "800x480", 1);
	setenv("EGLFS_X11_FULLSCREEN", "1", 1);
	setenv("QT_QPA_EGLFS_DEPTH", "16", 1);
	setenv("QT_QPA_EGLFS_PHYSICAL_WIDTH", "200", 1);
	setenv("QT_QPA_EGLFS_PHYSICAL_HEIGHT", "150", 1);
#endif

	//X11の場合用
	QCoreApplication::setAttribute(Qt::AA_X11InitThreads);

	P6VXApp app(argc, argv);

	QCommandLineParser parser;
	QCommandLineOption safeModeOption(QStringList() << "s" << "safemode", "Safe Mode");
	parser.addOption(safeModeOption);
	parser.process(app);
	bool safeMode = parser.isSet(safeModeOption);
	app.enableSafeMode(safeMode);

#ifdef ANDROID
	app.setCustomRomPath(CUSTOMROMPATH);
#endif

	QLocale locale;
    QString lang = locale.uiLanguages()[0];
    QTranslator myappTranslator;

    //表示言語が日本語でない場合は英語リソースを読み込む
	if(lang != "ja-JP" && lang != "ja"){
		qDebug() << "LANG = " << lang;
        myappTranslator.load(":/translation/PC6001VX_en");
        app.installTranslator(&myappTranslator);
    }

	//イベントループが始まったらp6vxapp::startup()を実行
    QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection);

    //イベントループを開始
	return app.exec();
}
<commit_msg>Androidで日本語フォントがちゃんと表示されるようにした。<commit_after>#include <stdlib.h>
#include <errno.h>
#include <QtWidgets>

#include "p6vxapp.h"

#ifndef NOJOYSTICK
//SDL使用時にビルドを通すのに必要
#undef main
#endif

///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
#ifdef PANDORA
	//VALGRIND実行時用の環境変数
	setenv("DISPLAY", ":0.0", 1);
	//GlibのOSと開発環境のバージョン不一致に対する暫定対応
	//setenv("QT_NO_GLIB", "0", 1);
	//EGLFS対応
	setenv("EGLFS_X11_SIZE", "800x480", 1);
	setenv("EGLFS_X11_FULLSCREEN", "1", 1);
	setenv("QT_QPA_EGLFS_DEPTH", "16", 1);
	setenv("QT_QPA_EGLFS_PHYSICAL_WIDTH", "200", 1);
	setenv("QT_QPA_EGLFS_PHYSICAL_HEIGHT", "150", 1);
#endif

	//X11の場合用
	QCoreApplication::setAttribute(Qt::AA_X11InitThreads);

	P6VXApp app(argc, argv);

	QCommandLineParser parser;
	QCommandLineOption safeModeOption(QStringList() << "s" << "safemode", "Safe Mode");
	parser.addOption(safeModeOption);
	parser.process(app);
	bool safeMode = parser.isSet(safeModeOption);
	app.enableSafeMode(safeMode);

#ifdef ANDROID
	app.setCustomRomPath(CUSTOMROMPATH);
#endif

	QLocale locale;
    QString lang = locale.uiLanguages()[0];
    QTranslator myappTranslator;

    //表示言語が日本語でない場合は英語リソースを読み込む
	if(lang != "ja-JP" && lang != "ja"){
		qDebug() << "LANG = " << lang;
        myappTranslator.load(":/translation/PC6001VX_en");
        app.installTranslator(&myappTranslator);
	} else {
#ifdef ANDROID
		app.setFont(QFont("MotoyaLMaru"));
#endif
	}

	//イベントループが始まったらp6vxapp::startup()を実行
    QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection);

    //イベントループを開始
	return app.exec();
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <errno.h>
#include <QtWidgets>

#include "qtp6vxapplication.h"

#ifndef NOJOYSTICK
//リンクエラー解消のために入れておく必要がある
#include <SDL2/SDL.h>
#undef main
#endif

///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
    //X11の場合
    if (QGuiApplication::platformName() == QLatin1String("xcb")){
        QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
    }

    QtP6VXApplication app(argc, argv);

    QLocale locale;
    QString lang = locale.uiLanguages()[0];
    QTranslator myappTranslator;

    //表示言語が日本語でない場合は英語リソースを読み込む
    if(lang != "ja_JP"){
        myappTranslator.load(":/translation/PC6001VX_en");
        app.installTranslator(&myappTranslator);
    }
    //setlocale(LC_ALL,"Japanese");

    //イベントループが始まったらQtP6VXApplication::startup()を実行
    QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection);

    //イベントループを開始
    app.exec();

	return true;
}
<commit_msg>言語の識別子が間違っていたので修正<commit_after>#include <stdlib.h>
#include <errno.h>
#include <QtWidgets>

#include "qtp6vxapplication.h"

#ifndef NOJOYSTICK
//リンクエラー解消のために入れておく必要がある
#include <SDL2/SDL.h>
#undef main
#endif

///////////////////////////////////////////////////////////
// メイン
///////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
    //X11の場合
    if (QGuiApplication::platformName() == QLatin1String("xcb")){
        QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
    }

    QtP6VXApplication app(argc, argv);

    QLocale locale;
    QString lang = locale.uiLanguages()[0];
    QTranslator myappTranslator;

    //表示言語が日本語でない場合は英語リソースを読み込む
    if(lang != "ja-JP"){
        myappTranslator.load(":/translation/PC6001VX_en");
        app.installTranslator(&myappTranslator);
    }
    //setlocale(LC_ALL,"Japanese");

    //イベントループが始まったらQtP6VXApplication::startup()を実行
    QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection);

    //イベントループを開始
    app.exec();

	return true;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2005 by Andrei Alexandrescu
// Copyright (c) 2006 Peter Kmmel
// Permission to use, copy, modify, distribute, and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author makes no representations about the suitability of this software
//     for any purpose. It is provided "as is" without express or implied
//     warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header$

#include <loki/SafeFormat.h>

namespace Loki
{

    // Crude writing method: writes straight to the file, unbuffered
    // Must be combined with a buffer to work properly (and efficiently)

    void write(std::FILE* f, const char* from, const char* to) {
        assert(from <= to);
        ::std::fwrite(from, 1, to - from, f);
    }

    // Write to a string

    void write(std::string& s, const char* from, const char* to) {
        assert(from <= to);
        s.append(from, to);
    }

    // Write to a stream

    void write(std::ostream& f, const char* from, const char* to) {
        assert(from <= to);
        f.write(from, to - from);
    }

    ////////////////////////////////////////////////////////////////////////////////
    // PrintfState class template
    // Holds the formatting state, and implements operator() to format stuff
    // Todo: make sure errors are handled properly
    ////////////////////////////////////////////////////////////////////////////////

    PrintfState<std::FILE*, char> Printf(const char* format) {
        return PrintfState<std::FILE*, char>(stdout, format);
    }

    PrintfState<std::FILE*, char> Printf(const std::string& format) {
        return PrintfState<std::FILE*, char>(stdout, format.c_str());
    }

    PrintfState<std::FILE*, char> FPrintf(std::FILE* f, const char* format) {
        return PrintfState<std::FILE*, char>(f, format);
    }

    PrintfState<std::FILE*, char> FPrintf(std::FILE* f, const std::string& format) {
        return PrintfState<std::FILE*, char>(f, format.c_str());
    }

    PrintfState<std::ostream&, char> FPrintf(std::ostream& f, const char* format) {
        return PrintfState<std::ostream&, char>(f, format);
    }

    PrintfState<std::ostream&, char> FPrintf(std::ostream& f, const std::string& format) {
        return PrintfState<std::ostream&, char>(f, format.c_str());
    }

    PrintfState<std::string&, char> SPrintf(std::string& s, const char* format) {
        return PrintfState<std::string&, char>(s, format);
    }

    PrintfState<std::string&, char> SPrintf(std::string& s, const std::string& format) {
        return PrintfState<std::string&, char>(s, format.c_str());
    }

}// namespace Loki

// $Log$
// Revision 1.4  2006/07/06 18:25:28  syntheticpp
// add writing to ostream, by Tom Browder
//
// Revision 1.3  2006/06/28 08:04:21  syntheticpp
// use standard conforming naming, SUN's compiler needs it
//
// Revision 1.2  2006/01/16 20:59:53  rich_sposato
// Added cvs keywords.
//
<commit_msg>remove 64 bit warning<commit_after>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2005 by Andrei Alexandrescu
// Copyright (c) 2006 Peter Kmmel
// Permission to use, copy, modify, distribute, and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author makes no representations about the suitability of this software
//     for any purpose. It is provided "as is" without express or implied
//     warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header$

#include <loki/SafeFormat.h>

namespace Loki
{

    // Crude writing method: writes straight to the file, unbuffered
    // Must be combined with a buffer to work properly (and efficiently)

    void write(std::FILE* f, const char* from, const char* to) {
        assert(from <= to);
        ::std::fwrite(from, 1, to - from, f);
    }

    // Write to a string

    void write(std::string& s, const char* from, const char* to) {
        assert(from <= to);
        s.append(from, to);
    }

    // Write to a stream

    void write(std::ostream& f, const char* from, const char* to) {
        assert(from <= to);
        f.write(from, std::streamsize(to - from));
    }

    ////////////////////////////////////////////////////////////////////////////////
    // PrintfState class template
    // Holds the formatting state, and implements operator() to format stuff
    // Todo: make sure errors are handled properly
    ////////////////////////////////////////////////////////////////////////////////

    PrintfState<std::FILE*, char> Printf(const char* format) {
        return PrintfState<std::FILE*, char>(stdout, format);
    }

    PrintfState<std::FILE*, char> Printf(const std::string& format) {
        return PrintfState<std::FILE*, char>(stdout, format.c_str());
    }

    PrintfState<std::FILE*, char> FPrintf(std::FILE* f, const char* format) {
        return PrintfState<std::FILE*, char>(f, format);
    }

    PrintfState<std::FILE*, char> FPrintf(std::FILE* f, const std::string& format) {
        return PrintfState<std::FILE*, char>(f, format.c_str());
    }

    PrintfState<std::ostream&, char> FPrintf(std::ostream& f, const char* format) {
        return PrintfState<std::ostream&, char>(f, format);
    }

    PrintfState<std::ostream&, char> FPrintf(std::ostream& f, const std::string& format) {
        return PrintfState<std::ostream&, char>(f, format.c_str());
    }

    PrintfState<std::string&, char> SPrintf(std::string& s, const char* format) {
        return PrintfState<std::string&, char>(s, format);
    }

    PrintfState<std::string&, char> SPrintf(std::string& s, const std::string& format) {
        return PrintfState<std::string&, char>(s, format.c_str());
    }

}// namespace Loki

// $Log$
// Revision 1.5  2006/07/07 09:30:48  syntheticpp
// remove 64 bit warning
//
// Revision 1.4  2006/07/06 18:25:28  syntheticpp
// add writing to ostream, by Tom Browder
//
// Revision 1.3  2006/06/28 08:04:21  syntheticpp
// use standard conforming naming, SUN's compiler needs it
//
// Revision 1.2  2006/01/16 20:59:53  rich_sposato
// Added cvs keywords.
//
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2015 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "repo_dialog_manager_connect.h"
#include "ui_repoabstractmanagerdialog.h"

repo::gui::RepoDialogManagerConnect::RepoDialogManagerConnect(
        repo::RepoController *controller,
        QWidget *parent)
    : RepoAbstractManagerDialog(0, parent)
    , controller(controller)
{
    setWindowTitle("Connection Manager");
    setWindowIcon(RepoFontAwesome::getConnectIcon());

    //--------------------------------------------------------------------------
    // Connections table
    model->setColumnCount(5);
    model->setHeaderData(
                (int) Columns::ALIAS,
                Qt::Horizontal,
                tr("Alias"));
    model->setHeaderData(
                (int) Columns::HOST_PORT,
                Qt::Horizontal,
                tr("Address"));
    model->setHeaderData(
                (int) Columns::AUTHENTICATION,
                Qt::Horizontal,
                tr("Authentication"));
    model->setHeaderData(
                (int) Columns::SSL,
                Qt::Horizontal,
                tr("SSL"));
    model->setHeaderData(
                (int) Columns::SSH,
                Qt::Horizontal,
                tr("SSH"));

    //    ui->treeView->sortByColumn((int) Columns::ALIAS, Qt::SortOrder::AscendingOrder);

    ui->hostComboBox->hide();
    ui->databaseComboBox->hide();

    ui->buttonBox->addButton("Connect", QDialogButtonBox::AcceptRole);
}

void repo::gui::RepoDialogManagerConnect::addCredentials(const RepoCredentials &credentials)
{
    QList<QStandardItem *> row;
    row.append(getAliasItem(credentials));
    row.append(getAddressItem(credentials));
    row.append(getAuthenticationItem(credentials));

    // TODO: add support for SSL and SSH
    row.append(getSSLItem(credentials));
    row.append(getSSHItem(credentials));

    model->invisibleRootItem()->appendRow(row);
}

void repo::gui::RepoDialogManagerConnect::edit()
{
    showEditDialog(getConnection(), ui->treeView->selectionModel()->currentIndex());
}

void repo::gui::RepoDialogManagerConnect::edit(const QModelIndex &index)
{
    showEditDialog(getConnection(index), index);
}

repo::RepoCredentials repo::gui::RepoDialogManagerConnect::getConnection()
{
    return getConnection(ui->treeView->selectionModel()->currentIndex());
}

repo::RepoCredentials repo::gui::RepoDialogManagerConnect::getConnection(const QModelIndex &index)
{
    repo::RepoCredentials credentials;
    if (index.isValid())
    {
        QModelIndex credentialsIndex = index.sibling(index.row(), (int) Columns::ALIAS);
        credentials = credentialsIndex.data(Qt::UserRole + 1).value<repo::RepoCredentials>();
    }
    return credentials;
}

void repo::gui::RepoDialogManagerConnect::refresh()
{
    if (cancelAllThreads())
    {
        ui->progressBar->show(); // TODO: delete line
        //----------------------------------------------------------------------
        clear(); // Clear any previous entries

        // TODO: new worker here
        repo::settings::RepoSettingsCredentials settings;
        QList<repo::RepoCredentials> credentialsList = settings.readCredentials();
        for (int i = 0; i < credentialsList.size(); ++i)
        {
            addCredentials(credentialsList[i]);
        }

        //----------------------------------------------------------------------
        ui->progressBar->hide(); // TODO: show
    }
}

void repo::gui::RepoDialogManagerConnect::removeItem()
{
    QModelIndex index = ui->treeView->selectionModel()->currentIndex();
    int row = proxy->mapToSource(index).row();
    model->removeRow(row);
    sync();
    updateCountLabel();
}

void repo::gui::RepoDialogManagerConnect::showEditDialog(
        const repo::RepoCredentials &credentials,
        const QModelIndex &index)
{
    RepoDialogConnect connectionSettingsDialog(controller, credentials, this);
    if (QDialog::Rejected == connectionSettingsDialog.exec())
        repoLog("Connection Settings Dialog cancelled by user.\n");
    else // QDialog::Accepted
    {
        repoLog("Create or update connection settings...\n");

        RepoCredentials credentials = connectionSettingsDialog.getConnectionSettings();
        if (!index.isValid())
        {
            addCredentials(credentials);
        }
        else
        {
            int row = proxy->mapToSource(index).row();
            model->setItem(row, (int) Columns::ALIAS, getAliasItem(credentials));
            model->setItem(row, (int) Columns::HOST_PORT, getAddressItem(credentials));
            model->setItem(row, (int) Columns::AUTHENTICATION, getAuthenticationItem(credentials));
            model->setItem(row, (int) Columns::SSL, getSSLItem(credentials));
            model->setItem(row, (int) Columns::SSH, getSSHItem(credentials));
        }
        sync();
    }
}

void repo::gui::RepoDialogManagerConnect::sync()
{
    // TODO: put into async worker
    QList<repo::RepoCredentials> list;
    for (int i = 0; i < model->invisibleRootItem()->rowCount(); ++i)
    {
        QModelIndex index = model->indexFromItem(model->invisibleRootItem()->child(i, (int) Columns::ALIAS));
        list.append(index.data(Qt::UserRole + 1).value<repo::RepoCredentials>());
    }
    settings::RepoSettingsCredentials credentialsSettings;
    credentialsSettings.writeCredentials(list);
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAliasItem(
        const RepoCredentials &credentials)
{
    QVariant var;
    var.setValue(credentials);
    QStandardItem *item = createItem(QString::fromStdString(credentials.getAlias()));
    item->setData(var);
    item->setEnabled(true);
    item->setIcon(RepoFontAwesome::getHostIcon());
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAddressItem(
        const RepoCredentials &credentials)
{
    return createItem(QString::fromStdString(credentials.getHostAndPort()));
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAuthenticationItem(
        const RepoCredentials &credentials)
{
    QString label;
    QStandardItem *item = 0;
    if (!credentials.getAuthenticationDatabase().empty() &&
            !credentials.getUsername().empty())
    {
        label = QString::fromStdString(
                    credentials.getAuthenticationDatabase() +
                    " / " +
                    credentials.getUsername());
        item = createItem(label);
        item->setIcon(RepoFontAwesome::getDatabaseIcon());
    }
    else
        item = createItem(label);
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getSSLItem(
        const RepoCredentials &credentials)
{
    QStandardItem *item = createItem(QVariant());
    item->setEnabled(false);
    item->setIcon(RepoFontAwesome::getInstance().getIcon(
                      RepoFontAwesome::fa_unlock_alt));
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getSSHItem(
        const RepoCredentials &credentials)
{
    QStandardItem *item = createItem(QVariant());
    item->setEnabled(false);
    item->setIcon(RepoFontAwesome::getInstance().getIcon(
                      RepoFontAwesome::fa_unlock_alt));
    return item;
}
<commit_msg>Changed Connect Managed Dialog double click from edit to immediate connect as requested by carmenfan.<commit_after>/**
 *  Copyright (C) 2015 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "repo_dialog_manager_connect.h"
#include "ui_repoabstractmanagerdialog.h"

repo::gui::RepoDialogManagerConnect::RepoDialogManagerConnect(
        repo::RepoController *controller,
        QWidget *parent)
    : RepoAbstractManagerDialog(0, parent)
    , controller(controller)
{
    setWindowTitle("Connection Manager");
    setWindowIcon(RepoFontAwesome::getConnectIcon());

    //--------------------------------------------------------------------------
    // Connections table
    model->setColumnCount(5);
    model->setHeaderData(
                (int) Columns::ALIAS,
                Qt::Horizontal,
                tr("Alias"));
    model->setHeaderData(
                (int) Columns::HOST_PORT,
                Qt::Horizontal,
                tr("Address"));
    model->setHeaderData(
                (int) Columns::AUTHENTICATION,
                Qt::Horizontal,
                tr("Authentication"));
    model->setHeaderData(
                (int) Columns::SSL,
                Qt::Horizontal,
                tr("SSL"));
    model->setHeaderData(
                (int) Columns::SSH,
                Qt::Horizontal,
                tr("SSH"));

    //    ui->treeView->sortByColumn((int) Columns::ALIAS, Qt::SortOrder::AscendingOrder);

    ui->hostComboBox->hide();
    ui->databaseComboBox->hide();

    ui->buttonBox->addButton("Connect", QDialogButtonBox::AcceptRole);

    QObject::disconnect(ui->treeView, SIGNAL(doubleClicked(const QModelIndex &)),
                     this, SLOT(edit(const QModelIndex &)));

    QObject::connect(ui->treeView, &QTreeView::doubleClicked,
                     this, &QDialog::accept);
}

void repo::gui::RepoDialogManagerConnect::addCredentials(const RepoCredentials &credentials)
{
    QList<QStandardItem *> row;
    row.append(getAliasItem(credentials));
    row.append(getAddressItem(credentials));
    row.append(getAuthenticationItem(credentials));

    // TODO: add support for SSL and SSH
    row.append(getSSLItem(credentials));
    row.append(getSSHItem(credentials));

    model->invisibleRootItem()->appendRow(row);
}

void repo::gui::RepoDialogManagerConnect::edit()
{
    showEditDialog(getConnection(), ui->treeView->selectionModel()->currentIndex());
}

void repo::gui::RepoDialogManagerConnect::edit(const QModelIndex &index)
{
    showEditDialog(getConnection(index), index);
}

repo::RepoCredentials repo::gui::RepoDialogManagerConnect::getConnection()
{
    return getConnection(ui->treeView->selectionModel()->currentIndex());
}

repo::RepoCredentials repo::gui::RepoDialogManagerConnect::getConnection(const QModelIndex &index)
{
    repo::RepoCredentials credentials;
    if (index.isValid())
    {
        QModelIndex credentialsIndex = index.sibling(index.row(), (int) Columns::ALIAS);
        credentials = credentialsIndex.data(Qt::UserRole + 1).value<repo::RepoCredentials>();
    }
    return credentials;
}

void repo::gui::RepoDialogManagerConnect::refresh()
{
    if (cancelAllThreads())
    {
        ui->progressBar->show(); // TODO: delete line
        //----------------------------------------------------------------------
        clear(); // Clear any previous entries

        // TODO: new worker here
        repo::settings::RepoSettingsCredentials settings;
        QList<repo::RepoCredentials> credentialsList = settings.readCredentials();
        for (int i = 0; i < credentialsList.size(); ++i)
        {
            addCredentials(credentialsList[i]);
        }

        //----------------------------------------------------------------------
        ui->progressBar->hide(); // TODO: show
    }
}

void repo::gui::RepoDialogManagerConnect::removeItem()
{
    QModelIndex index = ui->treeView->selectionModel()->currentIndex();
    int row = proxy->mapToSource(index).row();
    model->removeRow(row);
    sync();
    updateCountLabel();
}

void repo::gui::RepoDialogManagerConnect::showEditDialog(
        const repo::RepoCredentials &credentials,
        const QModelIndex &index)
{
    RepoDialogConnect connectionSettingsDialog(controller, credentials, this);
    if (QDialog::Rejected == connectionSettingsDialog.exec())
        repoLog("Connection Settings Dialog cancelled by user.\n");
    else // QDialog::Accepted
    {
        repoLog("Create or update connection settings...\n");

        RepoCredentials credentials = connectionSettingsDialog.getConnectionSettings();
        if (!index.isValid())
        {
            addCredentials(credentials);
        }
        else
        {
            int row = proxy->mapToSource(index).row();
            model->setItem(row, (int) Columns::ALIAS, getAliasItem(credentials));
            model->setItem(row, (int) Columns::HOST_PORT, getAddressItem(credentials));
            model->setItem(row, (int) Columns::AUTHENTICATION, getAuthenticationItem(credentials));
            model->setItem(row, (int) Columns::SSL, getSSLItem(credentials));
            model->setItem(row, (int) Columns::SSH, getSSHItem(credentials));
        }
        sync();
    }
}

void repo::gui::RepoDialogManagerConnect::sync()
{
    // TODO: put into async worker
    QList<repo::RepoCredentials> list;
    for (int i = 0; i < model->invisibleRootItem()->rowCount(); ++i)
    {
        QModelIndex index = model->indexFromItem(model->invisibleRootItem()->child(i, (int) Columns::ALIAS));
        list.append(index.data(Qt::UserRole + 1).value<repo::RepoCredentials>());
    }
    settings::RepoSettingsCredentials credentialsSettings;
    credentialsSettings.writeCredentials(list);
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAliasItem(
        const RepoCredentials &credentials)
{
    QVariant var;
    var.setValue(credentials);
    QStandardItem *item = createItem(QString::fromStdString(credentials.getAlias()));
    item->setData(var);
    item->setEnabled(true);
    item->setIcon(RepoFontAwesome::getHostIcon());
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAddressItem(
        const RepoCredentials &credentials)
{
    return createItem(QString::fromStdString(credentials.getHostAndPort()));
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getAuthenticationItem(
        const RepoCredentials &credentials)
{
    QString label;
    QStandardItem *item = 0;
    if (!credentials.getAuthenticationDatabase().empty() &&
            !credentials.getUsername().empty())
    {
        label = QString::fromStdString(
                    credentials.getAuthenticationDatabase() +
                    " / " +
                    credentials.getUsername());
        item = createItem(label);
        item->setIcon(RepoFontAwesome::getDatabaseIcon());
    }
    else
        item = createItem(label);
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getSSLItem(
        const RepoCredentials &credentials)
{
    QStandardItem *item = createItem(QVariant());
    item->setEnabled(true);
    item->setIcon(RepoFontAwesome::getInstance().getIcon(
                      RepoFontAwesome::fa_unlock_alt));
    return item;
}

QStandardItem *repo::gui::RepoDialogManagerConnect::getSSHItem(
        const RepoCredentials &credentials)
{
    QStandardItem *item = createItem(QVariant());
    item->setEnabled(true);
    item->setIcon(RepoFontAwesome::getInstance().getIcon(
                      RepoFontAwesome::fa_unlock_alt));
    return item;
}
<|endoftext|>