<commit_before>/**
 * Copyright (C) 2015 Virgil Security Inc.
 *
 * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SPLIT_CLI

#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <iterator>

#include <cli/version.h>
#include <cli/util.h>

typedef int (*main_func)(int argc, char** argv);

// simple-action
int hash_main(int argc, char** argv);
int keygen_main(int argc, char** argv);
int key2pub_main(int argc, char** argv);
int encrypt_main(int argc, char** argv);
int decrypt_main(int argc, char** argv);
int sign_main(int argc, char** argv);
int verify_main(int argc, char** argv);

// module-action
int identity_verify_main(int argc, char** argv);
int identity_confirm_global_main(int argc, char** argv);
int identity_confirm_private_main(int argc, char** argv);
int identity_valid_main(int argc, char** argv);

int card_create_global_main(int argc, char** argv);
int card_create_private_main(int argc, char** argv);
int card_get_main(int argc, char** argv);
int card_search_private_main(int argc, char** argv);
int card_search_global_main(int argc, char** argv);
int card_revoke_global_main(int argc, char** argv);
int card_revoke_private_main(int argc, char** argv);

int public_key_get_main(int argc, char** argv);
int public_key_revoke_main(int argc, char** argv);

int private_key_add_main(int argc, char** argv);
int private_key_get_main(int argc, char** argv);
int private_key_del_main(int argc, char** argv);

static void print_usage(std::ostream& out, const char* programName);

int main(int argc, char** argv) {
    // Parse arguments.
    if (argc < 2) {
        std::cerr << "Error: "
                  << " Required argument is missing: "
                  << "command" << std::endl;
        print_usage(std::cerr, argv[0]);
        return EXIT_FAILURE;
    }

    std::string firstArg(argv[1]);
    if (firstArg == "-h" || firstArg == "--help") {
        print_usage(std::cout, argv[0]);
        return EXIT_SUCCESS;
    } else if (firstArg == "--version") {
        virgil::cli::printVersion(std::cout, argv[0]);
        return EXIT_SUCCESS;
    }

    std::map<std::string, main_func> commandsMap;
    // simple-action
    commandsMap["hash"] = &hash_main;
    commandsMap["keygen"] = &keygen_main;
    commandsMap["key2pub"] = &key2pub_main;
    commandsMap["encrypt"] = &encrypt_main;
    commandsMap["decrypt"] = &decrypt_main;
    commandsMap["sign"] = &sign_main;
    commandsMap["verify"] = &verify_main;

    // module-action
    commandsMap["identity-verify"] = &identity_verify_main;
    commandsMap["identity-confirm-global"] = &identity_confirm_global_main;
    commandsMap["identity-confirm-private"] = &identity_confirm_private_main;
    commandsMap["identity-valid"] = &identity_valid_main;

    commandsMap["card-create-global"] = &card_create_global_main;
    commandsMap["card-create=private"] = &card_create_private_main;
    commandsMap["card-get"] = &card_get_main;
    commandsMap["card-search-private"] = &card_search_private_main;
    commandsMap["card-search-global"] = &card_search_global_main;
    commandsMap["card-revoke-global"] = &card_revoke_global_main;
    commandsMap["card-revoke-private"] = &card_revoke_private_main;

    commandsMap["public-key-get"] = &public_key_get_main;
    commandsMap["public-key-revoke"] = &public_key_revoke_main;

    commandsMap["private-key-add"] = &private_key_add_main;
    commandsMap["private-key-get"] = &private_key_get_main;
    commandsMap["private-key-del"] = &private_key_del_main;

    auto module = commandsMap.find(firstArg);
    if (module != commandsMap.end()) {
        module->second(argc - 1, argv + 1);
    } else {
        std::cerr << "Error: "
                  << "command '" << firstArg << "' not found" << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

void print_usage(std::ostream& out, const char* programName) {
    std::string doc = "command [command_opts] [command_args]\n"
                      "DESCRIPTION:\n"
                      "The 'virgil' program is a command line tool for using Virgil Security\n"
                      "stack functionality:\n"
                      "encrypt, decrypt, sign and verify data;\n"
                      "interact with Virgil Keys Service;\n"
                      "interact with Virgil Private Keys Service.\n\n"

                      "COMMON COMMANDS:\n"
                      "hash                        Derives the obfuscated data from incoming parameters using\n"
                      "                            PBKDF function.\n\n"

                      "keygen                      Generate private key with given parameters.\n\n"

                      "key2pub                     Extract Public Key from the Private Key.\n\n"

                      "encrypt                     Encrypt data for given recipients which can be\n"
                      "                            defined by Virgil Public Keys and by passwords.\n\n"

                      "decrypt                     Decrypt data for given recipient which can be\n"
                      "                            defined by Virgil Public Key or by password.\n\n"

                      "sign                        Sign data with Private Key.\n\n"

                      "verify                      Verify data with Virgil Public Key.\n\n\n"

                      "virgil CARD COMMANDS:\n"

                      "card-create-global          Create a Global Virgil Card\n\n"

                      "card-create-private         Create a Private Virgil Card\n\n"

                      "card-revoke-global          Revoke the Global Virgil Card\n\n"

                      "card-revoke-private         Revoke the Private Virgil Card\n\n"

                      "card-search-private         Search a Private Virgil Card\n\n"

                      "card-search-global          Search a global Virgil Card\n\n"

                      "card-get                    Get user's Virgil Card/Cards\n\n"

                      "PUBCLIC KEY COMMANDS:\n"

                      "public-key-revoke           Revoke Public Key\n\n"

                      "public-key-get              Get Public Key\n\n\n"

                      "PRIVATE KEY COMMANDS:\n"

                      "public-key-revoke           Revoke Public Key\n\n"

                      "public-key-get              Get Public Key\n\n\n"

                      "IDENTITY COMMANDS:\n"

                      "identity-verify             Verify a Identity\n\n"

                      "identity-confirm-global     Confirm the Identity for the Global Virgil Card\n\n"

                      "identity-confirm-private    Confirm the Identity for the Private Virgil Card\n\n"

                      "identity-valid              Validate the Identity\n\n\n";

    out << "USAGE: " << programName << " " << doc << std::endl;
}

#endif /* SPLIT_CLI */
<commit_msg>Fix wrong name utility card-create-private<commit_after>/**
 * Copyright (C) 2015 Virgil Security Inc.
 *
 * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SPLIT_CLI

#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <iterator>

#include <cli/version.h>
#include <cli/util.h>

typedef int (*main_func)(int argc, char** argv);

// simple-action
int hash_main(int argc, char** argv);
int keygen_main(int argc, char** argv);
int key2pub_main(int argc, char** argv);
int encrypt_main(int argc, char** argv);
int decrypt_main(int argc, char** argv);
int sign_main(int argc, char** argv);
int verify_main(int argc, char** argv);

// module-action
int identity_verify_main(int argc, char** argv);
int identity_confirm_global_main(int argc, char** argv);
int identity_confirm_private_main(int argc, char** argv);
int identity_valid_main(int argc, char** argv);

int card_create_global_main(int argc, char** argv);
int card_create_private_main(int argc, char** argv);
int card_get_main(int argc, char** argv);
int card_search_private_main(int argc, char** argv);
int card_search_global_main(int argc, char** argv);
int card_revoke_global_main(int argc, char** argv);
int card_revoke_private_main(int argc, char** argv);

int public_key_get_main(int argc, char** argv);
int public_key_revoke_main(int argc, char** argv);

int private_key_add_main(int argc, char** argv);
int private_key_get_main(int argc, char** argv);
int private_key_del_main(int argc, char** argv);

static void print_usage(std::ostream& out, const char* programName);

int main(int argc, char** argv) {
    // Parse arguments.
    if (argc < 2) {
        std::cerr << "Error: "
                  << " Required argument is missing: "
                  << "command" << std::endl;
        print_usage(std::cerr, argv[0]);
        return EXIT_FAILURE;
    }

    std::string firstArg(argv[1]);
    if (firstArg == "-h" || firstArg == "--help") {
        print_usage(std::cout, argv[0]);
        return EXIT_SUCCESS;
    } else if (firstArg == "--version") {
        virgil::cli::printVersion(std::cout, argv[0]);
        return EXIT_SUCCESS;
    }

    std::map<std::string, main_func> commandsMap;
    // simple-action
    commandsMap["hash"] = &hash_main;
    commandsMap["keygen"] = &keygen_main;
    commandsMap["key2pub"] = &key2pub_main;
    commandsMap["encrypt"] = &encrypt_main;
    commandsMap["decrypt"] = &decrypt_main;
    commandsMap["sign"] = &sign_main;
    commandsMap["verify"] = &verify_main;

    // module-action
    commandsMap["identity-verify"] = &identity_verify_main;
    commandsMap["identity-confirm-global"] = &identity_confirm_global_main;
    commandsMap["identity-confirm-private"] = &identity_confirm_private_main;
    commandsMap["identity-valid"] = &identity_valid_main;

    commandsMap["card-create-global"] = &card_create_global_main;
    commandsMap["card-create-private"] = &card_create_private_main;
    commandsMap["card-get"] = &card_get_main;
    commandsMap["card-search-private"] = &card_search_private_main;
    commandsMap["card-search-global"] = &card_search_global_main;
    commandsMap["card-revoke-global"] = &card_revoke_global_main;
    commandsMap["card-revoke-private"] = &card_revoke_private_main;

    commandsMap["public-key-get"] = &public_key_get_main;
    commandsMap["public-key-revoke"] = &public_key_revoke_main;

    commandsMap["private-key-add"] = &private_key_add_main;
    commandsMap["private-key-get"] = &private_key_get_main;
    commandsMap["private-key-del"] = &private_key_del_main;

    auto module = commandsMap.find(firstArg);
    if (module != commandsMap.end()) {
        module->second(argc - 1, argv + 1);
    } else {
        std::cerr << "Error: "
                  << "command '" << firstArg << "' not found" << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

void print_usage(std::ostream& out, const char* programName) {
    std::string doc = "command [command_opts] [command_args]\n"
                      "DESCRIPTION:\n"
                      "The 'virgil' program is a command line tool for using Virgil Security\n"
                      "stack functionality:\n"
                      "encrypt, decrypt, sign and verify data;\n"
                      "interact with Virgil Keys Service;\n"
                      "interact with Virgil Private Keys Service.\n\n"

                      "COMMON COMMANDS:\n"
                      "hash                        Derives the obfuscated data from incoming parameters using\n"
                      "                            PBKDF function.\n\n"

                      "keygen                      Generate private key with given parameters.\n\n"

                      "key2pub                     Extract Public Key from the Private Key.\n\n"

                      "encrypt                     Encrypt data for given recipients which can be\n"
                      "                            defined by Virgil Public Keys and by passwords.\n\n"

                      "decrypt                     Decrypt data for given recipient which can be\n"
                      "                            defined by Virgil Public Key or by password.\n\n"

                      "sign                        Sign data with Private Key.\n\n"

                      "verify                      Verify data with Virgil Public Key.\n\n\n"

                      "virgil CARD COMMANDS:\n"

                      "card-create-global          Create a Global Virgil Card\n\n"

                      "card-create-private         Create a Private Virgil Card\n\n"

                      "card-revoke-global          Revoke the Global Virgil Card\n\n"

                      "card-revoke-private         Revoke the Private Virgil Card\n\n"

                      "card-search-private         Search a Private Virgil Card\n\n"

                      "card-search-global          Search a global Virgil Card\n\n"

                      "card-get                    Get user's Virgil Card/Cards\n\n"

                      "PUBCLIC KEY COMMANDS:\n"

                      "public-key-revoke           Revoke Public Key\n\n"

                      "public-key-get              Get Public Key\n\n\n"

                      "PRIVATE KEY COMMANDS:\n"

                      "public-key-revoke           Revoke Public Key\n\n"

                      "public-key-get              Get Public Key\n\n\n"

                      "IDENTITY COMMANDS:\n"

                      "identity-verify             Verify a Identity\n\n"

                      "identity-confirm-global     Confirm the Identity for the Global Virgil Card\n\n"

                      "identity-confirm-private    Confirm the Identity for the Private Virgil Card\n\n"

                      "identity-valid              Validate the Identity\n\n\n";

    out << "USAGE: " << programName << " " << doc << std::endl;
}

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


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * GameTime:
 *	Manages the network time.
 *      Time is stored as microseconds since the epoch.
 */

// the top dog
#include "common.h"

// interface header
#include "GameTime.h"

// system headers
#include <time.h>
#ifndef _WIN32
#  include <sys/time.h>
#endif
#include <list>

// common headers
#include "Pack.h"
#include "bzfio.h"

// type definitions
typedef uint16_t u16;
typedef uint32_t u32;
#ifndef WIN32
typedef int64_t s64;
#else
typedef __int64 s64;
#endif
typedef struct {
  s64 netTime;
  s64 localTime;
} TimeRecord;

// local constants
static const double filterTime = 10.0;
static const unsigned int maxRecords = 1024; // safety
static const unsigned int maxRecordAge = 120 * 1000000;
static const s64 maxTime = 2345678;
static const double minRate = 0.50;
static const double maxRate = 2.00;

// local variables
static std::list<TimeRecord> timeRecs;
static double stepSecs = 0.0;
static s64 stepTime = 0;
static double avgRate = 1.0;
static TimeRecord avgPoint = {0, 0};

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

static s64 getRawTime()
{
#ifndef _WIN32

  struct timeval tv;
  gettimeofday(&tv, NULL);
  return ((s64)tv.tv_sec * (s64)1000000) + (s64)tv.tv_usec;

#else //_WIN32

  // FIXME - use QPC if available? (10ms[pat] good enough?)
  //       - during rollovers, check time() against the
  //	 current value to see if a rollover was missed?

  static s64 offset = ((s64)time(NULL) * (s64)1000000) -
                      ((s64)timeGetTime() * (s64)1000);
  static u32 lasttime = (u32)timeGetTime();

  u32 nowtime = (u32)timeGetTime();

  // we've got 49.71 days to catch the rollovers
  if (nowtime < lasttime) {
    // add the rollover value
    offset += ((s64)(1 << 32));
  }
  lasttime = nowtime;
  return offset + ((s64)nowtime * (s64)1000);

#endif //_WIN32
}

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

static void calcAvgRate()
{
  // FIXME - this is weak
  const int count = timeRecs.size();
  if (count <= 0) {
    avgRate = 1.0;
    avgPoint.netTime = 0;
    avgPoint.localTime = 0;
    return;
  }
  else if (timeRecs.size() == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    avgRate = 1.0;
    avgPoint = tr;
    return;
  }
  else {
    const TimeRecord& last = *timeRecs.begin();
    const TimeRecord& first = *timeRecs.rbegin();
    const s64 netDiff = last.netTime - first.netTime;
    const s64 locDiff = last.localTime - first.localTime;
    if (locDiff != 0.0) {
      avgRate = ((double)netDiff / (double)locDiff);
      avgPoint = last;
    } else {
      // don't update
    }
  }
  return;
}

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

void GameTime::reset()
{
  stepSecs = 0.0;
  stepTime = 0;
  avgRate = 1.0;
  avgPoint.netTime = 0;
  avgPoint.localTime = 0;
  timeRecs.clear();
  return;
}

static void resetToRecord(const TimeRecord& record)
{
  avgRate = 1.0;
  avgPoint = record;
  stepTime = record.netTime;
  TimeRecord copy = record;
  timeRecs.clear();
  timeRecs.push_front(copy);
  return;
}

void GameTime::update()
{
  std::list<TimeRecord>::iterator it;
  unsigned int count = timeRecs.size();
  if (count <= 0) {
    const TimeRecord tr = {0,0};
    resetToRecord(tr);
  }
  else if (count == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    resetToRecord(tr);
  }
  else {
    calcAvgRate();
    const TimeRecord& tr = *timeRecs.begin();
    const s64 diffTime = stepTime - tr.netTime;
    if ((diffTime < -maxTime) || (diffTime > +maxTime) ||
        (avgRate < minRate) || (avgRate > maxRate)) {
      DEBUG4("GameTime: discontinuity: usecs = %lli, rate = %f\n",
             diffTime, avgRate);
      resetToRecord(tr);
    }
  }

  DEBUG4("GameTime: count = %i, rate = %f\n", timeRecs.size(), avgRate);

  return;
}

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

void GameTime::setStepTime()
{
  static s64 lastStep = 0;
  const s64 thisStep = getRawTime();
  if (timeRecs.size() <= 0) {
    stepTime = thisStep;
  } else {
    // long term prediction
    const double diffLocal = thisStep - avgPoint.localTime;
    const double longPred = (double)avgPoint.netTime + (diffLocal * avgRate);
    // short term prediction
    const double skipTime = (double)(thisStep - lastStep);
    const double shortPred = (double)stepTime + (skipTime * avgRate);
    // filtering
    const double c = (skipTime * 1.0e-6) / filterTime;
    const double a = (c > 0.0) && (c < 1.0) ? c : 0.5;
    const double b = 1.0 - a;
    stepTime = (s64)((a * longPred) + (b * (double)shortPred));
  }
  stepSecs = (double)stepTime * 1.0e-6;
  lastStep = thisStep;

  return;
}

double GameTime::getStepTime()
{
  return stepSecs;
}

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

int GameTime::packSize()
{
  return (2 * sizeof(u32));
}

void* GameTime::pack(void *buf)
{
  const s64 nowTime = getRawTime();
//  const s64 nowTime = getRawTime() + (s64)((bzfrand() - 0.5) * 2.0e6);
  buf = nboPackUInt(buf, (u32)(nowTime >> 32));		// msb's
  buf = nboPackUInt(buf, (u32)(nowTime & 0xFFFFFFFF));	// lsb's
  return buf;
}

void* GameTime::unpack(void *buf)
{
  u32 msb, lsb;
  buf = nboUnpackUInt(buf, msb);
  buf = nboUnpackUInt(buf, lsb);
  const s64 netTime = ((s64)msb << 32) + (s64)lsb;

  // store the value
  const TimeRecord tr = { netTime, getRawTime() };
  timeRecs.push_front(tr);

  // clear oversize entries
  while (timeRecs.size() > maxRecords) {
    timeRecs.pop_back();
  }

  // clear the aged entries
  if (timeRecs.size() > 0) {
    s64 nowTime = getRawTime();
    while (timeRecs.size() > 0) {
      TimeRecord back = *timeRecs.rbegin();
      if ((nowTime - back.localTime) < maxRecordAge) {
        break;
      }
      timeRecs.pop_back();
    }
  }

  return buf;
}

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

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>conversion precision warning<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * GameTime:
 *	Manages the network time.
 *      Time is stored as microseconds since the epoch.
 */

// the top dog
#include "common.h"

// interface header
#include "GameTime.h"

// system headers
#include <time.h>
#ifndef _WIN32
#  include <sys/time.h>
#endif
#include <list>

// common headers
#include "Pack.h"
#include "bzfio.h"

// type definitions
typedef uint16_t u16;
typedef uint32_t u32;
#ifndef WIN32
typedef int64_t s64;
#else
typedef __int64 s64;
#endif
typedef struct {
  s64 netTime;
  s64 localTime;
} TimeRecord;

// local constants
static const double filterTime = 10.0;
static const unsigned int maxRecords = 1024; // safety
static const unsigned int maxRecordAge = 120 * 1000000;
static const s64 maxTime = 2345678;
static const double minRate = 0.50;
static const double maxRate = 2.00;

// local variables
static std::list<TimeRecord> timeRecs;
static double stepSecs = 0.0;
static s64 stepTime = 0;
static double avgRate = 1.0;
static TimeRecord avgPoint = {0, 0};

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

static s64 getRawTime()
{
#ifndef _WIN32

  struct timeval tv;
  gettimeofday(&tv, NULL);
  return ((s64)tv.tv_sec * (s64)1000000) + (s64)tv.tv_usec;

#else //_WIN32

  // FIXME - use QPC if available? (10ms[pat] good enough?)
  //       - during rollovers, check time() against the
  //	 current value to see if a rollover was missed?

  static s64 offset = ((s64)time(NULL) * (s64)1000000) -
                      ((s64)timeGetTime() * (s64)1000);
  static u32 lasttime = (u32)timeGetTime();

  u32 nowtime = (u32)timeGetTime();

  // we've got 49.71 days to catch the rollovers
  if (nowtime < lasttime) {
    // add the rollover value
    offset += ((s64)(1 << 32));
  }
  lasttime = nowtime;
  return offset + ((s64)nowtime * (s64)1000);

#endif //_WIN32
}

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

static void calcAvgRate()
{
  // FIXME - this is weak
  const int count = timeRecs.size();
  if (count <= 0) {
    avgRate = 1.0;
    avgPoint.netTime = 0;
    avgPoint.localTime = 0;
    return;
  }
  else if (timeRecs.size() == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    avgRate = 1.0;
    avgPoint = tr;
    return;
  }
  else {
    const TimeRecord& last = *timeRecs.begin();
    const TimeRecord& first = *timeRecs.rbegin();
    const s64 netDiff = last.netTime - first.netTime;
    const s64 locDiff = last.localTime - first.localTime;
    if (locDiff != 0.0) {
      avgRate = ((double)netDiff / (double)locDiff);
      avgPoint = last;
    } else {
      // don't update
    }
  }
  return;
}

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

void GameTime::reset()
{
  stepSecs = 0.0;
  stepTime = 0;
  avgRate = 1.0;
  avgPoint.netTime = 0;
  avgPoint.localTime = 0;
  timeRecs.clear();
  return;
}

static void resetToRecord(const TimeRecord& record)
{
  avgRate = 1.0;
  avgPoint = record;
  stepTime = record.netTime;
  TimeRecord copy = record;
  timeRecs.clear();
  timeRecs.push_front(copy);
  return;
}

void GameTime::update()
{
  std::list<TimeRecord>::iterator it;
  unsigned int count = timeRecs.size();
  if (count <= 0) {
    const TimeRecord tr = {0,0};
    resetToRecord(tr);
  }
  else if (count == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    resetToRecord(tr);
  }
  else {
    calcAvgRate();
    const TimeRecord& tr = *timeRecs.begin();
    const s64 diffTime = stepTime - tr.netTime;
    if ((diffTime < -maxTime) || (diffTime > +maxTime) ||
        (avgRate < minRate) || (avgRate > maxRate)) {
      DEBUG4("GameTime: discontinuity: usecs = %lli, rate = %f\n",
             diffTime, avgRate);
      resetToRecord(tr);
    }
  }

  DEBUG4("GameTime: count = %i, rate = %f\n", timeRecs.size(), avgRate);

  return;
}

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

void GameTime::setStepTime()
{
  static s64 lastStep = 0;
  const s64 thisStep = getRawTime();
  if (timeRecs.size() <= 0) {
    stepTime = thisStep;
  } else {
    // long term prediction
    const double diffLocal = (double)(thisStep - avgPoint.localTime);
    const double longPred = (double)avgPoint.netTime + (diffLocal * avgRate);
    // short term prediction
    const double skipTime = (double)(thisStep - lastStep);
    const double shortPred = (double)stepTime + (skipTime * avgRate);
    // filtering
    const double c = (skipTime * 1.0e-6) / filterTime;
    const double a = (c > 0.0) && (c < 1.0) ? c : 0.5;
    const double b = 1.0 - a;
    stepTime = (s64)((a * longPred) + (b * (double)shortPred));
  }
  stepSecs = (double)stepTime * 1.0e-6;
  lastStep = thisStep;

  return;
}

double GameTime::getStepTime()
{
  return stepSecs;
}

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

int GameTime::packSize()
{
  return (2 * sizeof(u32));
}

void* GameTime::pack(void *buf)
{
  const s64 nowTime = getRawTime();
//  const s64 nowTime = getRawTime() + (s64)((bzfrand() - 0.5) * 2.0e6);
  buf = nboPackUInt(buf, (u32)(nowTime >> 32));		// msb's
  buf = nboPackUInt(buf, (u32)(nowTime & 0xFFFFFFFF));	// lsb's
  return buf;
}

void* GameTime::unpack(void *buf)
{
  u32 msb, lsb;
  buf = nboUnpackUInt(buf, msb);
  buf = nboUnpackUInt(buf, lsb);
  const s64 netTime = ((s64)msb << 32) + (s64)lsb;

  // store the value
  const TimeRecord tr = { netTime, getRawTime() };
  timeRecs.push_front(tr);

  // clear oversize entries
  while (timeRecs.size() > maxRecords) {
    timeRecs.pop_back();
  }

  // clear the aged entries
  if (timeRecs.size() > 0) {
    s64 nowTime = getRawTime();
    while (timeRecs.size() > 0) {
      TimeRecord back = *timeRecs.rbegin();
      if ((nowTime - back.localTime) < maxRecordAge) {
        break;
      }
      timeRecs.pop_back();
    }
  }

  return buf;
}

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

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>

#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/plugin.h>

static ThisPlugin helloworld;

static void SAMPGDK_CALL RepeatingTimer(int, void *) {
	ServerLog::Printf("RepeatingTimer");
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
	SetGameModeText("Hello, World!");

	AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);

	ServerLog::Printf("------------------------------------------\n");
	ServerLog::Printf("      HelloWorld gamemode got loaded.     \n");
	ServerLog::Printf("------------------------------------------\n");

	SetTimer(1000, true, RepeatingTimer, 0);

	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
	SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {
	SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
	SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
	SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);
	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {
	if (std::strcmp(cmdtext, "/hello") == 0) {
		char name[MAX_PLAYER_NAME];
		GetPlayerName(playerid, name, MAX_PLAYER_NAME);
		char message[128];
		std::sprintf(message, "Hello, %s!", name);
		SendClientMessage(playerid, 0x00FF00FF, message);
		return true;
	}
	if (std::strcmp(cmdtext, "/pos") == 0) {
		float x, y, z;
		GetPlayerPos(playerid, &x, &y, &z);
		char message[128];
		std::sprintf(message, "You are at (%f, %f, %f)", x, y, z);
		SendClientMessage(playerid, 0xFFFFFFFF, message);
		return true;
	}
	return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	return helloworld.Load(ppData) >= 0;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
	helloworld.Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
	helloworld.ProcessTimers();
}
<commit_msg>Insert a few blank lines for better readability<commit_after>#include <cstdio>  // for sprintf
#include <cstring> // for strcmp

#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/plugin.h>

static ThisPlugin helloworld;

static void SAMPGDK_CALL RepeatingTimer(int, void *) {
	ServerLog::Printf("RepeatingTimer");
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
	SetGameModeText("Hello, World!");

	AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);

	ServerLog::Printf("------------------------------------------\n");
	ServerLog::Printf("      HelloWorld gamemode got loaded.     \n");
	ServerLog::Printf("------------------------------------------\n");

	SetTimer(1000, true, RepeatingTimer, 0);

	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
	SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {
	SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
	SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
	SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);
	return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {
	if (std::strcmp(cmdtext, "/hello") == 0) {
		char name[MAX_PLAYER_NAME];
		GetPlayerName(playerid, name);

		char message[128];
		std::sprintf(message, "Hello, %s!", name);

		SendClientMessage(playerid, 0x00FF00FF, message);
		return true;
	}

	if (std::strcmp(cmdtext, "/pos") == 0) {
		float x, y, z;
		GetPlayerPos(playerid, &x, &y, &z);

		char message[128];
		std::sprintf(message, "You are at (%f, %f, %f)", x, y, z);

		SendClientMessage(playerid, 0xFFFFFFFF, message);
		return true;
	}

	return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	return helloworld.Load(ppData) >= 0;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
	helloworld.Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
	helloworld.ProcessTimers();
}
<|endoftext|>


<commit_before>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi, daniel-k
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/

#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include <nrf24.hpp>
#include "../../xpcc/examples/stm32f4_discovery/stm32f4_discovery.hpp"

xpcc::IODeviceWrapper< Usart2 > loggerDevice;
xpcc::log::Logger xpcc::log::error(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::debug(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

typedef LedBlue Led;

MAIN_FUNCTION
{
	defaultSystemClock::enable();

	Led::setOutput(xpcc::Gpio::Low);

	// Initialize Usart
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 115200>(10);

	XPCC_LOG_INFO << "Nrf24L01+ Test" << xpcc::endl;

	while (1)
	{
		Led::toggle();
		xpcc::delay_ms(500);
	}
}
<commit_msg>Nrf24: can act as receiver or transmitter<commit_after>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi, daniel-k
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/

#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include <nrf24.hpp>
#include "../../xpcc/examples/stm32f4_discovery/stm32f4_discovery.hpp"

xpcc::IODeviceWrapper< Usart2 > loggerDevice;
xpcc::log::Logger xpcc::log::error(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::debug(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

typedef LedBlue Led;

static constexpr bool isReceiverNotTransmitter = true;

MAIN_FUNCTION
{
	defaultSystemClock::enable();

	Led::setOutput(xpcc::Gpio::Low);

	// Initialize Usart
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 115200>(10);

	XPCC_LOG_INFO << "Nrf24L01+ Test" << xpcc::endl;

	if(isReceiverNotTransmitter) {
	///////////// Receiver /////////////////////////////////////////////////////
		XPCC_LOG_INFO << "acting as receiver" << xpcc::endl;
		while (1)
		{
			Led::toggle();
			xpcc::delay_ms(500);
		}
	} else {
	///////////// Transmitter //////////////////////////////////////////////////
		XPCC_LOG_INFO << "acting as transmitter" << xpcc::endl;
		while (1)
		{
			Led::toggle();
			xpcc::delay_ms(100);
		}
	}

}
<|endoftext|>


<commit_before>
#pragma once

#include <array>
#include <vector>

#include "base/tags.hpp"
#include "numerics/transposed_view.hpp"
#include "quantities/named_quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_fixed_arrays {

using base::uninitialized_t;
using quantities::Difference;
using quantities::Product;

template<typename Scalar, int rows, int columns>
class FixedMatrix;

template<typename Scalar, int size_>
class FixedVector final {
 public:
  constexpr FixedVector();
  explicit FixedVector(uninitialized_t);

  // TODO(egg): Figure out why we have a move-conversion for |FixedVector| but
  // not the matrices.
  constexpr FixedVector(std::array<Scalar, size_> const& data);
  constexpr FixedVector(std::array<Scalar, size_>&& data);

  TransposedView<FixedVector> Transpose() const;

  bool operator==(FixedVector const& right) const;

  constexpr Scalar& operator[](int index);
  constexpr Scalar const& operator[](int index) const;

  explicit operator std::vector<Scalar>() const;

  static constexpr int size() { return size_; }

 private:
  std::array<Scalar, size_> data_;

  template<typename L, typename R, int s>
  friend constexpr Product<L, R> operator*(
      TransposedView<FixedVector<L, s>> const& left,
      FixedVector<R, s> const& right);
  template<typename L, typename R, int r, int c>
  friend constexpr FixedVector<Product<L, R>, r> operator*(
      FixedMatrix<L, r, c> const& left,
      FixedVector<R, c> const& right);
  template<typename S, int s>
  friend std::ostream& operator<<(std::ostream& out,
                                  FixedVector<S, s> const& vector);
};

template<typename Scalar, int rows_, int columns_>
class FixedMatrix final {
 public:
  static constexpr int rows() { return rows_; }
  static constexpr int columns() { return columns_; }

  constexpr FixedMatrix();
  explicit FixedMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedMatrix(std::array<Scalar, rows_ * columns_> const& data);

  bool operator==(FixedMatrix const& right) const;

  template<int r>
  class Row {
   public:
    explicit Row(const FixedMatrix* matrix);

    constexpr Scalar const& operator[](int index) const;

    // The template deduction runs into trouble if this operator is declared at
    // namespace scope.
    template<typename S>
    Product<Scalar, S> operator*(FixedVector<S, columns_> const& right);

   private:
    const FixedMatrix* matrix_;
  };

  template<int r>
  typename FixedMatrix::template Row<r> row() const;

  // For  0 < i < rows and 0 < j < columns, the entry a_ij is accessed as
  // |a[i][j]|.  if i and j do not satisfy these conditions, the expression
  // |a[i][j]| is erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, rows() * columns()> data_;

  template<typename L, typename R, int r, int c>
  friend constexpr FixedVector<Product<L, R>, r> operator*(
      FixedMatrix<L, r, c> const& left,
      FixedVector<R, c> const& right);
};

template<typename Scalar, int rows_>
class FixedStrictlyLowerTriangularMatrix final {
 public:
  static constexpr int rows = rows_;
  static constexpr int dimension = rows_ * (rows_ - 1) / 2;

  constexpr FixedStrictlyLowerTriangularMatrix();
  explicit FixedStrictlyLowerTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedStrictlyLowerTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedStrictlyLowerTriangularMatrix const& right) const;

  // For  0 < j < i < rows, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, dimension> data_;
};

template<typename Scalar, int rows_>
class FixedLowerTriangularMatrix final {
 public:
  static constexpr int rows = rows_;
  static constexpr int dimension = rows * (rows + 1) / 2;

  constexpr FixedLowerTriangularMatrix();
  explicit FixedLowerTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedLowerTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedLowerTriangularMatrix const& right) const;

  // For  0 < j <= i < rows, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, dimension> data_;
};

template<typename Scalar, int columns_>
class FixedUpperTriangularMatrix final {
 public:
  static constexpr int columns() { return columns_; }
  static constexpr int dimension = columns_ * (columns_ + 1) / 2;

  constexpr FixedUpperTriangularMatrix();
  explicit FixedUpperTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedUpperTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedUpperTriangularMatrix const& right) const;

  // A helper class for indexing column-major data in a human-friendly manner.
  template<typename Matrix>
  class Row {
   public:
    Scalar& operator[](int column);
    Scalar const& operator[](int column) const;

   private:
    explicit Row(Matrix& matrix, int row);

    // We need to remove the const because, when this class is instantiated with
    // |FixedUpperTriangularMatrix const|, the first operator[], not the second,
    // is picked by overload resolution.
    std::remove_const_t<Matrix>& matrix_;
    int row_;

    template<typename S, int c>
    friend class FixedUpperTriangularMatrix;
  };

  // For  0 ≤ i ≤ j < columns, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Row<FixedUpperTriangularMatrix> operator[](int row);
  Row<FixedUpperTriangularMatrix const> operator[](int row) const;

 private:
  // For ease of writing matrices in tests, the input data is received in row-
  // major format.  This translates a trapezoidal slice to make it column-major.
  static std::array<Scalar, dimension> Transpose(
      std::array<Scalar, dimension> const& data);

  std::array<Scalar, dimension> data_;
};

template<typename ScalarLeft, typename ScalarRight, int size>
constexpr FixedVector<Difference<ScalarLeft, ScalarRight>, size> operator-(
    FixedVector<ScalarLeft, size> const& left,
    FixedVector<ScalarRight, size> const& right);

template<typename ScalarLeft, typename ScalarRight, int size>
constexpr Product<ScalarLeft, ScalarRight> operator*(
    TransposedView<FixedVector<ScalarLeft, size>> const& left,
    FixedVector<ScalarRight, size> const& right);

template<typename ScalarLeft, typename ScalarRight, int rows, int columns>
constexpr FixedVector<Product<ScalarLeft, ScalarRight>, rows> operator*(
    FixedMatrix<ScalarLeft, rows, columns> const& left,
    FixedVector<ScalarRight, columns> const& right);

template<typename Scalar, int size>
std::ostream& operator<<(std::ostream& out,
                         FixedVector<Scalar, size> const& vector);

template<typename Scalar, int rows, int columns>
std::ostream& operator<<(std::ostream& out,
                         FixedMatrix<Scalar, rows, columns> const& matrix);

template<typename Scalar, int rows>
std::ostream& operator<<(
    std::ostream& out,
    FixedLowerTriangularMatrix<Scalar, rows> const& matrix);

template<typename Scalar, int columns>
std::ostream& operator<<(
    std::ostream& out,
    FixedUpperTriangularMatrix<Scalar, columns> const& matrix);

}  // namespace internal_fixed_arrays

using internal_fixed_arrays::FixedLowerTriangularMatrix;
using internal_fixed_arrays::FixedMatrix;
using internal_fixed_arrays::FixedStrictlyLowerTriangularMatrix;
using internal_fixed_arrays::FixedUpperTriangularMatrix;
using internal_fixed_arrays::FixedVector;

}  // namespace numerics
}  // namespace principia

#include "numerics/fixed_arrays_body.hpp"
<commit_msg>Cleanup.<commit_after>
#pragma once

#include <array>
#include <vector>

#include "base/tags.hpp"
#include "numerics/transposed_view.hpp"
#include "quantities/named_quantities.hpp"

namespace principia {
namespace numerics {
namespace internal_fixed_arrays {

using base::uninitialized_t;
using quantities::Difference;
using quantities::Product;

template<typename Scalar, int rows, int columns>
class FixedMatrix;

template<typename Scalar, int size_>
class FixedVector final {
 public:
  constexpr FixedVector();
  explicit FixedVector(uninitialized_t);

  // TODO(egg): Figure out why we have a move-conversion for |FixedVector| but
  // not the matrices.
  constexpr FixedVector(std::array<Scalar, size_> const& data);
  constexpr FixedVector(std::array<Scalar, size_>&& data);

  TransposedView<FixedVector> Transpose() const;

  bool operator==(FixedVector const& right) const;

  constexpr Scalar& operator[](int index);
  constexpr Scalar const& operator[](int index) const;

  explicit operator std::vector<Scalar>() const;

  static constexpr int size() { return size_; }

 private:
  std::array<Scalar, size_> data_;

  template<typename L, typename R, int s>
  friend constexpr Product<L, R> operator*(
      TransposedView<FixedVector<L, s>> const& left,
      FixedVector<R, s> const& right);
  template<typename L, typename R, int r, int c>
  friend constexpr FixedVector<Product<L, R>, r> operator*(
      FixedMatrix<L, r, c> const& left,
      FixedVector<R, c> const& right);
  template<typename S, int s>
  friend std::ostream& operator<<(std::ostream& out,
                                  FixedVector<S, s> const& vector);
};

template<typename Scalar, int rows_, int columns_>
class FixedMatrix final {
 public:
  static constexpr int rows() { return rows_; }
  static constexpr int columns() { return columns_; }

  constexpr FixedMatrix();
  explicit FixedMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedMatrix(std::array<Scalar, rows_ * columns_> const& data);

  bool operator==(FixedMatrix const& right) const;

  template<int r>
  class Row {
   public:
    explicit Row(const FixedMatrix* matrix);

    constexpr Scalar const& operator[](int index) const;

    // The template deduction runs into trouble if this operator is declared at
    // namespace scope.
    template<typename S>
    Product<Scalar, S> operator*(FixedVector<S, columns_> const& right);

   private:
    const FixedMatrix* matrix_;
  };

  template<int r>
  typename FixedMatrix::template Row<r> row() const;

  // For  0 < i < rows and 0 < j < columns, the entry a_ij is accessed as
  // |a[i][j]|.  if i and j do not satisfy these conditions, the expression
  // |a[i][j]| is erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, rows_ * columns_> data_;

  template<typename L, typename R, int r, int c>
  friend constexpr FixedVector<Product<L, R>, r> operator*(
      FixedMatrix<L, r, c> const& left,
      FixedVector<R, c> const& right);
};

template<typename Scalar, int rows_>
class FixedStrictlyLowerTriangularMatrix final {
 public:
  static constexpr int rows = rows_;
  static constexpr int dimension = rows_ * (rows_ - 1) / 2;

  constexpr FixedStrictlyLowerTriangularMatrix();
  explicit FixedStrictlyLowerTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedStrictlyLowerTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedStrictlyLowerTriangularMatrix const& right) const;

  // For  0 < j < i < rows, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, dimension> data_;
};

template<typename Scalar, int rows_>
class FixedLowerTriangularMatrix final {
 public:
  static constexpr int rows = rows_;
  static constexpr int dimension = rows * (rows + 1) / 2;

  constexpr FixedLowerTriangularMatrix();
  explicit FixedLowerTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedLowerTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedLowerTriangularMatrix const& right) const;

  // For  0 < j <= i < rows, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Scalar* operator[](int index);
  constexpr Scalar const* operator[](int index) const;

 private:
  std::array<Scalar, dimension> data_;
};

template<typename Scalar, int columns_>
class FixedUpperTriangularMatrix final {
 public:
  static constexpr int columns() { return columns_; }
  static constexpr int dimension = columns_ * (columns_ + 1) / 2;

  constexpr FixedUpperTriangularMatrix();
  explicit FixedUpperTriangularMatrix(uninitialized_t);

  // The |data| must be in row-major format.
  constexpr FixedUpperTriangularMatrix(
      std::array<Scalar, dimension> const& data);

  bool operator==(FixedUpperTriangularMatrix const& right) const;

  // A helper class for indexing column-major data in a human-friendly manner.
  template<typename Matrix>
  class Row {
   public:
    Scalar& operator[](int column);
    Scalar const& operator[](int column) const;

   private:
    explicit Row(Matrix& matrix, int row);

    // We need to remove the const because, when this class is instantiated with
    // |FixedUpperTriangularMatrix const|, the first operator[], not the second,
    // is picked by overload resolution.
    std::remove_const_t<Matrix>& matrix_;
    int row_;

    template<typename S, int c>
    friend class FixedUpperTriangularMatrix;
  };

  // For  0 ≤ i ≤ j < columns, the entry a_ij is accessed as |a[i][j]|.
  // if i and j do not satisfy these conditions, the expression |a[i][j]| is
  // erroneous.
  Row<FixedUpperTriangularMatrix> operator[](int row);
  Row<FixedUpperTriangularMatrix const> operator[](int row) const;

 private:
  // For ease of writing matrices in tests, the input data is received in row-
  // major format.  This translates a trapezoidal slice to make it column-major.
  static std::array<Scalar, dimension> Transpose(
      std::array<Scalar, dimension> const& data);

  std::array<Scalar, dimension> data_;
};

template<typename ScalarLeft, typename ScalarRight, int size>
constexpr FixedVector<Difference<ScalarLeft, ScalarRight>, size> operator-(
    FixedVector<ScalarLeft, size> const& left,
    FixedVector<ScalarRight, size> const& right);

template<typename ScalarLeft, typename ScalarRight, int size>
constexpr Product<ScalarLeft, ScalarRight> operator*(
    TransposedView<FixedVector<ScalarLeft, size>> const& left,
    FixedVector<ScalarRight, size> const& right);

template<typename ScalarLeft, typename ScalarRight, int rows, int columns>
constexpr FixedVector<Product<ScalarLeft, ScalarRight>, rows> operator*(
    FixedMatrix<ScalarLeft, rows, columns> const& left,
    FixedVector<ScalarRight, columns> const& right);

template<typename Scalar, int size>
std::ostream& operator<<(std::ostream& out,
                         FixedVector<Scalar, size> const& vector);

template<typename Scalar, int rows, int columns>
std::ostream& operator<<(std::ostream& out,
                         FixedMatrix<Scalar, rows, columns> const& matrix);

template<typename Scalar, int rows>
std::ostream& operator<<(
    std::ostream& out,
    FixedLowerTriangularMatrix<Scalar, rows> const& matrix);

template<typename Scalar, int columns>
std::ostream& operator<<(
    std::ostream& out,
    FixedUpperTriangularMatrix<Scalar, columns> const& matrix);

}  // namespace internal_fixed_arrays

using internal_fixed_arrays::FixedLowerTriangularMatrix;
using internal_fixed_arrays::FixedMatrix;
using internal_fixed_arrays::FixedStrictlyLowerTriangularMatrix;
using internal_fixed_arrays::FixedUpperTriangularMatrix;
using internal_fixed_arrays::FixedVector;

}  // namespace numerics
}  // namespace principia

#include "numerics/fixed_arrays_body.hpp"
<|endoftext|>


<commit_before>/***********************************************************************
filename:   SampleData.cpp
created:    4/6/2012
author:     Lukas E Meindl
*************************************************************************/
/***************************************************************************
*   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
*   Permission is hereby granted, free of charge, to any person obtaining
*   a copy of this software and associated documentation files (the
*   "Software"), to deal in the Software without restriction, including
*   without limitation the rights to use, copy, modify, merge, publish,
*   distribute, sublicense, and/or sell copies of the Software, and to
*   permit persons to whom the Software is furnished to do so, subject to
*   the following conditions:
*
*   The above copyright notice and this permission notice shall be
*   included in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
*   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
*   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*   OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SampleData.h"
#include "Sample.h"

#include "Samples_xmlHandler.h"

#include "CEGUI/DynamicModule.h"
#include "CEGUI/Version.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/TextureTarget.h"
#include "CEGUI/BasicImage.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/Texture.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Window.h"
#include "CEGUI/Vector.h"

using namespace CEGUI;

#define S_(X) #X
#define STRINGIZE(X) S_(X)

typedef Sample& (*getSampleInstance)();
#define GetSampleInstanceFuncName "getSampleInstance"

SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary,
    CEGUI::String description, SampleType sampleTypeEnum)
    : d_name(sampleName),
    d_summary(summary),
    d_description(description),
    d_type(sampleTypeEnum),
    d_guiContext(0),
    d_textureTarget(0),
    d_textureTargetImage(0),
    d_sampleWindow(0),
    d_usedFilesString("")
{
}

SampleData::~SampleData()
{

}

CEGUI::String SampleData::getName()
{
    return d_name;
}

CEGUI::String SampleData::getSummary()
{
    return "Summary:\n" + d_summary;
}

CEGUI::String SampleData::getSampleTypeString()
{
    switch(d_type)
    {
    case ST_Module:
        return SampleDataHandler::SampleTypeCppModule;
        break;
    case ST_Lua:
        return SampleDataHandler::SampleTypeLua;
        break;
    case ST_Python:
        return SampleDataHandler::SampleTypePython;
    default:
        return "";
    }
}

CEGUI::String SampleData::getDescription()
{
    return "Description:\n" + d_description;
}

CEGUI::String SampleData::getUsedFilesString()
{
    return "Used files:\n" + d_usedFilesString;
}

void SampleData::setSampleWindow(CEGUI::Window* sampleWindow)
{
    d_sampleWindow = sampleWindow;
}

CEGUI::Window* SampleData::getSampleWindow()
{
    return d_sampleWindow;
}

void SampleData::initialise(int width, int height)
{
    CEGUI::System& system(System::getSingleton());

    CEGUI::Sizef size(static_cast<float>(width), static_cast<float>(height));

    d_textureTarget = system.getRenderer()->createTextureTarget();
    d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget);
    d_textureTarget->declareRenderSize(size);

    CEGUI::String imageName(d_textureTarget->getTexture().getName());
    d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName));
    d_textureTargetImage->setTexture(&d_textureTarget->getTexture());

    setTextureTargetImageArea(height, width);
}

void SampleData::deinitialise()
{
    CEGUI::System& system(System::getSingleton());

    if(d_guiContext)
    {
        system.destroyGUIContext(*d_guiContext);
        d_guiContext = 0;
    }

    if(d_textureTarget)
    {
        system.getRenderer()->destroyTextureTarget(d_textureTarget);
        d_textureTarget = 0;
    }
}

GUIContext* SampleData::getGuiContext()
{
    return d_guiContext;
}

void SampleData::handleNewWindowSize(float width, float height)
{
    setTextureTargetImageArea(height, width);

    CEGUI::Sizef windowSize(width, height);
    d_textureTarget->declareRenderSize(windowSize);

    d_sampleWindow->getRenderingSurface()->invalidate();
}

CEGUI::Image& SampleData::getRTTImage()
{
    return *d_textureTargetImage;
}

void SampleData::setGUIContextRTT()
{
    d_guiContext->setRenderTarget(*d_textureTarget);
}

void SampleData::clearRTTTexture()
{
    d_textureTarget->clear();
}

void SampleData::setTextureTargetImageArea(float height, float width)
{
    bool isTextureTargetVerticallyFlipped = d_textureTarget->isRenderingInverted();
    CEGUI::Rectf renderArea;
    if(isTextureTargetVerticallyFlipped)
        renderArea = CEGUI::Rectf(0.f, height, width, 0.f);
    else
        renderArea = CEGUI::Rectf(0.f, 0.f, width, height);

    d_textureTargetImage->setArea(renderArea);
}

SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary,
    CEGUI::String description, SampleType sampleTypeEnum)
    : SampleData(sampleName, summary, description ,sampleTypeEnum)
{
}

SampleDataModule::~SampleDataModule()
{
}

void SampleDataModule::initialise(int width, int height)
{
    SampleData::initialise(width, height);

    getSampleInstanceFromDLL();

    d_sample->initialise(d_guiContext);
    d_usedFilesString = d_sample->getUsedFilesString();
}

void SampleDataModule::deinitialise()
{
    SampleData::deinitialise();

    d_sample->deinitialise();
}

void SampleDataModule::getSampleInstanceFromDLL()
{
    // Version suffix for the dlls
    static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) );

    CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix);
    getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName));

    if(functionPointerGetSample == 0)
    {
        CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name;
        CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str()));
    }

    d_sample =  &(functionPointerGetSample());
}<commit_msg>FIX: Resize on samples load bugfix<commit_after>/***********************************************************************
filename:   SampleData.cpp
created:    4/6/2012
author:     Lukas E Meindl
*************************************************************************/
/***************************************************************************
*   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
*   Permission is hereby granted, free of charge, to any person obtaining
*   a copy of this software and associated documentation files (the
*   "Software"), to deal in the Software without restriction, including
*   without limitation the rights to use, copy, modify, merge, publish,
*   distribute, sublicense, and/or sell copies of the Software, and to
*   permit persons to whom the Software is furnished to do so, subject to
*   the following conditions:
*
*   The above copyright notice and this permission notice shall be
*   included in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
*   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
*   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*   OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SampleData.h"
#include "Sample.h"

#include "Samples_xmlHandler.h"

#include "CEGUI/DynamicModule.h"
#include "CEGUI/Version.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/TextureTarget.h"
#include "CEGUI/BasicImage.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/Texture.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Window.h"
#include "CEGUI/Vector.h"

using namespace CEGUI;

#define S_(X) #X
#define STRINGIZE(X) S_(X)

typedef Sample& (*getSampleInstance)();
#define GetSampleInstanceFuncName "getSampleInstance"

SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary,
    CEGUI::String description, SampleType sampleTypeEnum)
    : d_name(sampleName),
    d_summary(summary),
    d_description(description),
    d_type(sampleTypeEnum),
    d_guiContext(0),
    d_textureTarget(0),
    d_textureTargetImage(0),
    d_sampleWindow(0),
    d_usedFilesString("")
{
}

SampleData::~SampleData()
{

}

CEGUI::String SampleData::getName()
{
    return d_name;
}

CEGUI::String SampleData::getSummary()
{
    return "Summary:\n" + d_summary;
}

CEGUI::String SampleData::getSampleTypeString()
{
    switch(d_type)
    {
    case ST_Module:
        return SampleDataHandler::SampleTypeCppModule;
        break;
    case ST_Lua:
        return SampleDataHandler::SampleTypeLua;
        break;
    case ST_Python:
        return SampleDataHandler::SampleTypePython;
    default:
        return "";
    }
}

CEGUI::String SampleData::getDescription()
{
    return "Description:\n" + d_description;
}

CEGUI::String SampleData::getUsedFilesString()
{
    return "Used files:\n" + d_usedFilesString;
}

void SampleData::setSampleWindow(CEGUI::Window* sampleWindow)
{
    d_sampleWindow = sampleWindow;
}

CEGUI::Window* SampleData::getSampleWindow()
{
    return d_sampleWindow;
}

void SampleData::initialise(int width, int height)
{
    CEGUI::System& system(System::getSingleton());

    CEGUI::Sizef size(static_cast<float>(width), static_cast<float>(height));

    d_textureTarget = system.getRenderer()->createTextureTarget();
    d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget);
    d_textureTarget->declareRenderSize(size);

    CEGUI::String imageName(d_textureTarget->getTexture().getName());
    d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName));
    d_textureTargetImage->setTexture(&d_textureTarget->getTexture());

    setTextureTargetImageArea(height, width);
}

void SampleData::deinitialise()
{
    CEGUI::System& system(System::getSingleton());

    if(d_guiContext)
    {
        system.destroyGUIContext(*d_guiContext);
        d_guiContext = 0;
    }

    if(d_textureTarget)
    {
        system.getRenderer()->destroyTextureTarget(d_textureTarget);
        d_textureTarget = 0;
    }
}

GUIContext* SampleData::getGuiContext()
{
    return d_guiContext;
}

void SampleData::handleNewWindowSize(float width, float height)
{
    setTextureTargetImageArea(height, width);

    CEGUI::Sizef windowSize(width, height);
    if(d_textureTarget)
    {
        d_textureTarget->declareRenderSize(windowSize);

        d_sampleWindow->getRenderingSurface()->invalidate();
    }
}

CEGUI::Image& SampleData::getRTTImage()
{
    return *d_textureTargetImage;
}

void SampleData::setGUIContextRTT()
{
    d_guiContext->setRenderTarget(*d_textureTarget);
}

void SampleData::clearRTTTexture()
{
    d_textureTarget->clear();
}

void SampleData::setTextureTargetImageArea(float height, float width)
{
    if(d_textureTarget)
    {
        bool isTextureTargetVerticallyFlipped = d_textureTarget->isRenderingInverted();
        CEGUI::Rectf renderArea;
        if(isTextureTargetVerticallyFlipped)
            renderArea = CEGUI::Rectf(0.f, height, width, 0.f);
        else
            renderArea = CEGUI::Rectf(0.f, 0.f, width, height);

        if(d_textureTargetImage)
            d_textureTargetImage->setArea(renderArea);
    }
}

SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary,
    CEGUI::String description, SampleType sampleTypeEnum)
    : SampleData(sampleName, summary, description ,sampleTypeEnum)
{
}

SampleDataModule::~SampleDataModule()
{
}

void SampleDataModule::initialise(int width, int height)
{
    SampleData::initialise(width, height);

    getSampleInstanceFromDLL();

    d_sample->initialise(d_guiContext);
    d_usedFilesString = d_sample->getUsedFilesString();
}

void SampleDataModule::deinitialise()
{
    SampleData::deinitialise();

    d_sample->deinitialise();
}

void SampleDataModule::getSampleInstanceFromDLL()
{
    // Version suffix for the dlls
    static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) );

    CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix);
    getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName));

    if(functionPointerGetSample == 0)
    {
        CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name;
        CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str()));
    }

    d_sample =  &(functionPointerGetSample());
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 *   Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com>
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include "typedstrdata.hxx"
#include "global.hxx"

#include "unotools/transliterationwrapper.hxx"

bool ScTypedStrData::LessCaseSensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return left.meStrType < right.meStrType;

    if (left.meStrType == Value)
        return left.mfValue < right.mfValue;

    return ScGlobal::GetCaseTransliteration()->compareString(
        left.maStrValue, right.maStrValue) < 0;
}

bool ScTypedStrData::LessCaseInsensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return left.meStrType < right.meStrType;

    if (left.meStrType == Value)
        return left.mfValue < right.mfValue;

    return ScGlobal::GetpTransliteration()->compareString(
        left.maStrValue, right.maStrValue) < 0;
}

bool ScTypedStrData::EqualCaseSensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return false;

    if (left.meStrType == Value && left.mfValue != right.mfValue)
        return false;

    return ScGlobal::GetCaseTransliteration()->compareString(
        left.maStrValue, right.maStrValue) == 0;
}

bool ScTypedStrData::EqualCaseInsensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return false;

    if (left.meStrType == Value && left.mfValue != right.mfValue)
        return false;

    return ScGlobal::GetpTransliteration()->compareString(
        left.maStrValue, right.maStrValue) == 0;
}

bool ScTypedStrData::operator== (const ScTypedStrData& r) const
{
    // Case insensitive comparison by default.
    EqualCaseInsensitive aHdl;
    return aHdl(*this, r);
}

bool ScTypedStrData::operator< (const ScTypedStrData& r) const
{
    // Case insensitive comparison by default.
    LessCaseInsensitive aHdl;
    return aHdl(*this, r);
}

ScTypedStrData::ScTypedStrData(
    const rtl::OUString& rStr, double nVal, StringType nType ) :
    maStrValue(rStr),
    mfValue(nVal),
    meStrType(nType) {}

ScTypedStrData::ScTypedStrData( const ScTypedStrData& rCpy ) :
    maStrValue(rCpy.maStrValue),
    mfValue(rCpy.mfValue),
    meStrType(rCpy.meStrType) {}

bool ScTypedStrData::IsStrData() const
{
    return meStrType != Value;
}

const rtl::OUString& ScTypedStrData::GetString() const
{
    return maStrValue;
}

ScTypedStrData::StringType ScTypedStrData::GetStringType() const
{
    return meStrType;
}

FindTypedStrData::FindTypedStrData(const ScTypedStrData& rVal, bool bCaseSens) :
    maVal(rVal), mbCaseSens(bCaseSens) {}

bool FindTypedStrData::operator() (const ScTypedStrData& r) const
{
    if (mbCaseSens)
    {
        ScTypedStrData::EqualCaseSensitive aHdl;
        return aHdl(maVal, r);
    }
    else
    {
        ScTypedStrData::EqualCaseInsensitive aHdl;
        return aHdl(maVal, r);
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>bnc#492440: Sort autofilter popup items correctly.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 *   Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com>
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include "typedstrdata.hxx"
#include "global.hxx"

#include "unotools/collatorwrapper.hxx"

bool ScTypedStrData::LessCaseSensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return left.meStrType < right.meStrType;

    if (left.meStrType == Value)
        return left.mfValue < right.mfValue;

    return ScGlobal::GetCaseCollator()->compareString(
        left.maStrValue, right.maStrValue) < 0;
}

bool ScTypedStrData::LessCaseInsensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return left.meStrType < right.meStrType;

    if (left.meStrType == Value)
        return left.mfValue < right.mfValue;

    return ScGlobal::GetCollator()->compareString(
        left.maStrValue, right.maStrValue) < 0;
}

bool ScTypedStrData::EqualCaseSensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return false;

    if (left.meStrType == Value && left.mfValue != right.mfValue)
        return false;

    return ScGlobal::GetCaseCollator()->compareString(
        left.maStrValue, right.maStrValue) == 0;
}

bool ScTypedStrData::EqualCaseInsensitive::operator() (const ScTypedStrData& left, const ScTypedStrData& right) const
{
    if (left.meStrType != right.meStrType)
        return false;

    if (left.meStrType == Value && left.mfValue != right.mfValue)
        return false;

    return ScGlobal::GetCollator()->compareString(
        left.maStrValue, right.maStrValue) == 0;
}

bool ScTypedStrData::operator== (const ScTypedStrData& r) const
{
    // Case insensitive comparison by default.
    EqualCaseInsensitive aHdl;
    return aHdl(*this, r);
}

bool ScTypedStrData::operator< (const ScTypedStrData& r) const
{
    // Case insensitive comparison by default.
    LessCaseInsensitive aHdl;
    return aHdl(*this, r);
}

ScTypedStrData::ScTypedStrData(
    const rtl::OUString& rStr, double nVal, StringType nType ) :
    maStrValue(rStr),
    mfValue(nVal),
    meStrType(nType) {}

ScTypedStrData::ScTypedStrData( const ScTypedStrData& rCpy ) :
    maStrValue(rCpy.maStrValue),
    mfValue(rCpy.mfValue),
    meStrType(rCpy.meStrType) {}

bool ScTypedStrData::IsStrData() const
{
    return meStrType != Value;
}

const rtl::OUString& ScTypedStrData::GetString() const
{
    return maStrValue;
}

ScTypedStrData::StringType ScTypedStrData::GetStringType() const
{
    return meStrType;
}

FindTypedStrData::FindTypedStrData(const ScTypedStrData& rVal, bool bCaseSens) :
    maVal(rVal), mbCaseSens(bCaseSens) {}

bool FindTypedStrData::operator() (const ScTypedStrData& r) const
{
    if (mbCaseSens)
    {
        ScTypedStrData::EqualCaseSensitive aHdl;
        return aHdl(maVal, r);
    }
    else
    {
        ScTypedStrData::EqualCaseInsensitive aHdl;
        return aHdl(maVal, r);
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>