<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/customization_document.h"

#include "base/time.h"
#include "chrome/browser/chromeos/system/mock_statistics_provider.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

const char kGoodStartupManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"initial_locale\" : \"en-US\","
    "  \"initial_timezone\" : \"US/Pacific\","
    "  \"keyboard_layout\" : \"xkb:us::eng\","
    "  \"registration_url\" : \"http://www.google.com\","
    "  \"setup_content\" : {"
    "    \"en-US\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/en-US/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/en-US/eula.html\","
    "    },"
    "    \"ru-RU\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/ru-RU/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/ru-RU/eula.html\","
    "    },"
    "    \"default\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/en/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/en/eula.html\","
    "    },"
    "  },"
    "  \"hwid_map\" : ["
    "    {"
    "      \"hwid_mask\": \"ZGA*34\","
    "      \"initial_locale\" : \"ja\","
    "      \"initial_timezone\" : \"Asia/Tokyo\","
    "      \"keyboard_layout\" : \"mozc-jp\","
    "    },"
    "    {"
    "      \"hwid_mask\": \"Mario 1?3*\","
    "      \"initial_locale\" : \"ru-RU\","
    "      \"initial_timezone\" : \"Europe/Moscow\","
    "      \"keyboard_layout\" : \"xkb:ru::rus\","
    "    },"
    "  ],"
    "}";

const char kBadManifest[] = "{\"version\": \"1\"}";

const char kGoodServicesManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"app_content\" : {"
    "    \"en-US\" : {"
    "      \"initial_start_page\": \"http://mario/promo\","
    "      \"support_page\": \"http://mario/us\","
    "    },"
    "    \"ru-RU\" : {"
    "      \"initial_start_page\": \"http://mario/ru/promo\","
    "      \"support_page\": \"http://mario/ru\","
    "    },"
    "    \"default\" : {"
    "      \"initial_start_page\": \"http://mario/global/promo\","
    "      \"support_page\": \"http://mario/global\","
    "    },"
    "  },"
    "  \"carrier_deals\" : {"
    "    \"Carrier (country)\" : {"
    "      \"deal_locale\" : \"en-US\","
    "      \"top_up_url\" : \"http://www.carrier.com/\","
    "      \"notification_count\" : 1,\n"
    "      \"expire_date\" : \"31/12/12 0:00\","
    "      \"localized_content\" : {"
    "        \"en-US\" : {"
    "          \"notification_text\" : \"3G connectivity : Carrier.\","
    "        },"
    "        \"default\" : {"
    "          \"notification_text\" : \"default_text.\","
    "        },"
    "      },"
    "    },"
    "  },"
    "}";

const char kOldDealServicesManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"carrier_deals\" : {"
    "    \"Carrier (country)\" : {"
    "      \"deal_locale\" : \"en-US\","
    "      \"top_up_url\" : \"http://www.carrier.com/\","
    "      \"notification_count\" : 1,"
    "      \"expire_date\" : \"01/01/01 0:00\","
    "      \"localized_content\" : {"
    "        \"en-US\" : {"
    "          \"notification_text\" : \"en-US text.\","
    "        },"
    "        \"default\" : {"
    "          \"notification_text\" : \"default_text.\","
    "        },"
    "      },"
    "    },"
    "  },"
    "}";

}  // anonymous namespace

namespace chromeos {

using ::testing::_;
using ::testing::DoAll;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SetArgumentPointee;

TEST(StartupCustomizationDocumentTest, Basic) {
  system::MockStatisticsProvider mock_statistics_provider;
  EXPECT_CALL(mock_statistics_provider, GetMachineStatistic(_, NotNull()))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("hardware_class"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
                          Return(true)));
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kGoodStartupManifest);
  EXPECT_EQ("ru-RU", customization.initial_locale());
  EXPECT_EQ("Europe/Moscow", customization.initial_timezone());
  EXPECT_EQ("xkb:ru::rus", customization.keyboard_layout());
  EXPECT_EQ("http://www.google.com", customization.registration_url());

  EXPECT_EQ("file:///opt/oem/help/en-US/help.html",
            customization.GetHelpPage("en-US"));
  EXPECT_EQ("file:///opt/oem/help/ru-RU/help.html",
            customization.GetHelpPage("ru-RU"));
  EXPECT_EQ("file:///opt/oem/help/en/help.html",
            customization.GetHelpPage("ja"));

  EXPECT_EQ("file:///opt/oem/eula/en-US/eula.html",
            customization.GetEULAPage("en-US"));
  EXPECT_EQ("file:///opt/oem/eula/ru-RU/eula.html",
            customization.GetEULAPage("ru-RU"));
  EXPECT_EQ("file:///opt/oem/eula/en/eula.html",
            customization.GetEULAPage("ja"));
}

TEST(StartupCustomizationDocumentTest, VPD) {
  system::MockStatisticsProvider mock_statistics_provider;
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("hardware_class"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("initial_locale"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("ja")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("initial_timezone"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Asia/Tokyo")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("keyboard_layout"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("mozc-jp")),
                          Return(true)));
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kGoodStartupManifest);
  EXPECT_TRUE(customization.IsReady());
  EXPECT_EQ("ja", customization.initial_locale());
  EXPECT_EQ("Asia/Tokyo", customization.initial_timezone());
  EXPECT_EQ("mozc-jp", customization.keyboard_layout());
}

TEST(StartupCustomizationDocumentTest, BadManifest) {
  system::MockStatisticsProvider mock_statistics_provider;
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kBadManifest);
  EXPECT_FALSE(customization.IsReady());
}

TEST(ServicesCustomizationDocumentTest, Basic) {
  ServicesCustomizationDocument customization(kGoodServicesManifest, "en-US");
  EXPECT_TRUE(customization.IsReady());

  EXPECT_EQ("http://mario/promo",
            customization.GetInitialStartPage("en-US"));
  EXPECT_EQ("http://mario/ru/promo",
            customization.GetInitialStartPage("ru-RU"));
  EXPECT_EQ("http://mario/global/promo",
            customization.GetInitialStartPage("ja"));

  EXPECT_EQ("http://mario/us", customization.GetSupportPage("en-US"));
  EXPECT_EQ("http://mario/ru", customization.GetSupportPage("ru-RU"));
  EXPECT_EQ("http://mario/global", customization.GetSupportPage("ja"));

  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal != NULL);
  EXPECT_EQ("en-US", deal->deal_locale());
  EXPECT_EQ("http://www.carrier.com/", deal->top_up_url());
  EXPECT_EQ(1, deal->notification_count());
  EXPECT_EQ("3G connectivity : Carrier.",
            deal->GetLocalizedString("en-US", "notification_text"));
  EXPECT_EQ("default_text.",
            deal->GetLocalizedString("en", "notification_text"));

  base::Time reference_time;
  base::Time::FromString(L"31/12/12 0:00", &reference_time);
  EXPECT_EQ(reference_time, deal->expire_date());
}

TEST(ServicesCustomizationDocumentTest, OldDeal) {
  ServicesCustomizationDocument customization(kOldDealServicesManifest,
                                              "en-US");
  EXPECT_TRUE(customization.IsReady());

  const ServicesCustomizationDocument::CarrierDeal* deal;
  // TODO(nkostylev): Pass fixed time instead of relying on Time::Now().
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal == NULL);
}

TEST(ServicesCustomizationDocumentTest, DealOtherLocale) {
  ServicesCustomizationDocument customization(kGoodServicesManifest,
                                              "en-GB");
  EXPECT_TRUE(customization.IsReady());

  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal == NULL);
}

TEST(ServicesCustomizationDocumentTest, BadManifest) {
  ServicesCustomizationDocument customization(kBadManifest, "en-US");
  EXPECT_FALSE(customization.IsReady());
}

TEST(ServicesCustomizationDocumentTest, NoDealRestrictions) {
  ServicesCustomizationDocument customization_oth_locale(kGoodServicesManifest,
                                                         "en-GB");
  EXPECT_TRUE(customization_oth_locale.IsReady());
  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization_oth_locale.GetCarrierDeal("Carrier (country)", false);
  EXPECT_TRUE(deal != NULL);

  ServicesCustomizationDocument customization_old_deal(kOldDealServicesManifest,
                                                       "en-US");
  EXPECT_TRUE(customization_old_deal.IsReady());
  deal = customization_old_deal.GetCarrierDeal("Carrier (country)", false);
  EXPECT_TRUE(deal != NULL);
}

}  // namespace chromeos
<commit_msg>Another attempt to fix build<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/customization_document.h"

#include "base/time.h"
#include "chrome/browser/chromeos/system/mock_statistics_provider.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

const char kGoodStartupManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"initial_locale\" : \"en-US\","
    "  \"initial_timezone\" : \"US/Pacific\","
    "  \"keyboard_layout\" : \"xkb:us::eng\","
    "  \"registration_url\" : \"http://www.google.com\","
    "  \"setup_content\" : {"
    "    \"en-US\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/en-US/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/en-US/eula.html\","
    "    },"
    "    \"ru-RU\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/ru-RU/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/ru-RU/eula.html\","
    "    },"
    "    \"default\" : {"
    "      \"help_page\" : \"file:///opt/oem/help/en/help.html\","
    "      \"eula_page\" : \"file:///opt/oem/eula/en/eula.html\","
    "    },"
    "  },"
    "  \"hwid_map\" : ["
    "    {"
    "      \"hwid_mask\": \"ZGA*34\","
    "      \"initial_locale\" : \"ja\","
    "      \"initial_timezone\" : \"Asia/Tokyo\","
    "      \"keyboard_layout\" : \"mozc-jp\","
    "    },"
    "    {"
    "      \"hwid_mask\": \"Mario 1?3*\","
    "      \"initial_locale\" : \"ru-RU\","
    "      \"initial_timezone\" : \"Europe/Moscow\","
    "      \"keyboard_layout\" : \"xkb:ru::rus\","
    "    },"
    "  ],"
    "}";

const char kBadManifest[] = "{\"version\": \"1\"}";

const char kGoodServicesManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"app_content\" : {"
    "    \"en-US\" : {"
    "      \"initial_start_page\": \"http://mario/promo\","
    "      \"support_page\": \"http://mario/us\","
    "    },"
    "    \"ru-RU\" : {"
    "      \"initial_start_page\": \"http://mario/ru/promo\","
    "      \"support_page\": \"http://mario/ru\","
    "    },"
    "    \"default\" : {"
    "      \"initial_start_page\": \"http://mario/global/promo\","
    "      \"support_page\": \"http://mario/global\","
    "    },"
    "  },"
    "  \"carrier_deals\" : {"
    "    \"Carrier (country)\" : {"
    "      \"deal_locale\" : \"en-US\","
    "      \"top_up_url\" : \"http://www.carrier.com/\","
    "      \"notification_count\" : 1,\n"
    "      \"expire_date\" : \"31/12/12 0:00\","
    "      \"localized_content\" : {"
    "        \"en-US\" : {"
    "          \"notification_text\" : \"3G connectivity : Carrier.\","
    "        },"
    "        \"default\" : {"
    "          \"notification_text\" : \"default_text.\","
    "        },"
    "      },"
    "    },"
    "  },"
    "}";

const char kOldDealServicesManifest[] =
    "{"
    "  \"version\": \"1.0\","
    "  \"carrier_deals\" : {"
    "    \"Carrier (country)\" : {"
    "      \"deal_locale\" : \"en-US\","
    "      \"top_up_url\" : \"http://www.carrier.com/\","
    "      \"notification_count\" : 1,"
    "      \"expire_date\" : \"01/01/01 0:00\","
    "      \"localized_content\" : {"
    "        \"en-US\" : {"
    "          \"notification_text\" : \"en-US text.\","
    "        },"
    "        \"default\" : {"
    "          \"notification_text\" : \"default_text.\","
    "        },"
    "      },"
    "    },"
    "  },"
    "}";

}  // anonymous namespace

namespace chromeos {

using ::testing::_;
using ::testing::DoAll;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SetArgumentPointee;

TEST(StartupCustomizationDocumentTest, Basic) {
  system::MockStatisticsProvider mock_statistics_provider;
  EXPECT_CALL(mock_statistics_provider, GetMachineStatistic(_, NotNull()))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("hardware_class"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
                          Return(true)));
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kGoodStartupManifest);
  EXPECT_EQ("ru-RU", customization.initial_locale());
  EXPECT_EQ("Europe/Moscow", customization.initial_timezone());
  EXPECT_EQ("xkb:ru::rus", customization.keyboard_layout());
  EXPECT_EQ("http://www.google.com", customization.registration_url());

  EXPECT_EQ("file:///opt/oem/help/en-US/help.html",
            customization.GetHelpPage("en-US"));
  EXPECT_EQ("file:///opt/oem/help/ru-RU/help.html",
            customization.GetHelpPage("ru-RU"));
  EXPECT_EQ("file:///opt/oem/help/en/help.html",
            customization.GetHelpPage("ja"));

  EXPECT_EQ("file:///opt/oem/eula/en-US/eula.html",
            customization.GetEULAPage("en-US"));
  EXPECT_EQ("file:///opt/oem/eula/ru-RU/eula.html",
            customization.GetEULAPage("ru-RU"));
  EXPECT_EQ("file:///opt/oem/eula/en/eula.html",
            customization.GetEULAPage("ja"));
}

TEST(StartupCustomizationDocumentTest, VPD) {
  system::MockStatisticsProvider mock_statistics_provider;
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("hardware_class"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("initial_locale"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("ja")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("initial_timezone"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("Asia/Tokyo")),
                          Return(true)));
  EXPECT_CALL(mock_statistics_provider,
      GetMachineStatistic(std::string("keyboard_layout"), NotNull()))
          .WillOnce(DoAll(SetArgumentPointee<1>(std::string("mozc-jp")),
                          Return(true)));
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kGoodStartupManifest);
  EXPECT_TRUE(customization.IsReady());
  EXPECT_EQ("ja", customization.initial_locale());
  EXPECT_EQ("Asia/Tokyo", customization.initial_timezone());
  EXPECT_EQ("mozc-jp", customization.keyboard_layout());
}

TEST(StartupCustomizationDocumentTest, BadManifest) {
  system::MockStatisticsProvider mock_statistics_provider;
  StartupCustomizationDocument customization(&mock_statistics_provider,
                                             kBadManifest);
  EXPECT_FALSE(customization.IsReady());
}

TEST(ServicesCustomizationDocumentTest, Basic) {
  ServicesCustomizationDocument customization(kGoodServicesManifest, "en-US");
  EXPECT_TRUE(customization.IsReady());

  EXPECT_EQ("http://mario/promo",
            customization.GetInitialStartPage("en-US"));
  EXPECT_EQ("http://mario/ru/promo",
            customization.GetInitialStartPage("ru-RU"));
  EXPECT_EQ("http://mario/global/promo",
            customization.GetInitialStartPage("ja"));

  EXPECT_EQ("http://mario/us", customization.GetSupportPage("en-US"));
  EXPECT_EQ("http://mario/ru", customization.GetSupportPage("ru-RU"));
  EXPECT_EQ("http://mario/global", customization.GetSupportPage("ja"));

  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal != NULL);
  EXPECT_EQ("en-US", deal->deal_locale());
  EXPECT_EQ("http://www.carrier.com/", deal->top_up_url());
  EXPECT_EQ(1, deal->notification_count());
  EXPECT_EQ("3G connectivity : Carrier.",
            deal->GetLocalizedString("en-US", "notification_text"));
  EXPECT_EQ("default_text.",
            deal->GetLocalizedString("en", "notification_text"));

  base::Time reference_time;
  base::Time::FromString("31/12/12 0:00", &reference_time);
  EXPECT_EQ(reference_time, deal->expire_date());
}

TEST(ServicesCustomizationDocumentTest, OldDeal) {
  ServicesCustomizationDocument customization(kOldDealServicesManifest,
                                              "en-US");
  EXPECT_TRUE(customization.IsReady());

  const ServicesCustomizationDocument::CarrierDeal* deal;
  // TODO(nkostylev): Pass fixed time instead of relying on Time::Now().
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal == NULL);
}

TEST(ServicesCustomizationDocumentTest, DealOtherLocale) {
  ServicesCustomizationDocument customization(kGoodServicesManifest,
                                              "en-GB");
  EXPECT_TRUE(customization.IsReady());

  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization.GetCarrierDeal("Carrier (country)", true);
  EXPECT_TRUE(deal == NULL);
}

TEST(ServicesCustomizationDocumentTest, BadManifest) {
  ServicesCustomizationDocument customization(kBadManifest, "en-US");
  EXPECT_FALSE(customization.IsReady());
}

TEST(ServicesCustomizationDocumentTest, NoDealRestrictions) {
  ServicesCustomizationDocument customization_oth_locale(kGoodServicesManifest,
                                                         "en-GB");
  EXPECT_TRUE(customization_oth_locale.IsReady());
  const ServicesCustomizationDocument::CarrierDeal* deal;
  deal = customization_oth_locale.GetCarrierDeal("Carrier (country)", false);
  EXPECT_TRUE(deal != NULL);

  ServicesCustomizationDocument customization_old_deal(kOldDealServicesManifest,
                                                       "en-US");
  EXPECT_TRUE(customization_old_deal.IsReady());
  deal = customization_old_deal.GetCarrierDeal("Carrier (country)", false);
  EXPECT_TRUE(deal != NULL);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*
Copyright (c) 2014-2018 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Management/TaxiMgr.h"
#include "Storage/MySQLDataStore.hpp"
#include "Server/Packets/CmsgTaxiQueryAvailableNodes.h"
#include "Server/Packets/CmsgEnabletaxi.h"
#include "Server/Packets/SmsgTaxinodeStatus.h"
#include "Server/Packets/CmsgTaxinodeStatusQuery.h"

using namespace AscEmu::Packets;

void WorldSession::handleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgTaxinodeStatusQuery recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_TAXINODE_STATUS_QUERY");

    const auto nearestNode = sTaxiMgr.getNearestNodeForPlayer(_player);

    const auto field = static_cast<uint8_t>((nearestNode - 1) / 32);
    const uint32_t submask = 1 << ((nearestNode - 1) % 32);

    // Check known nodes
    uint8_t status = 1;
    if ((GetPlayer()->GetTaximask(field) & submask) != submask)
        status = 0;

    SendPacket(SmsgTaxinodeStatus(recv_packet.guid, status).serialise().get());
}

void WorldSession::handleTaxiQueryAvaibleNodesOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgTaxiQueryAvailableNodes recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_TAXIQUERYAVAILABLENODES");

    if (const auto creature = _player->GetMapMgr()->GetCreature(recv_packet.creatureGuid.getGuidLowPart()))
        SendTaxiList(creature);
}

void WorldSession::handleEnabletaxiOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgEnabletaxi recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_ENABLETAXI");

    if (const auto creature = _player->GetMapMgr()->GetCreature(recv_packet.creatureGuid.getGuidLowPart()))
        SendTaxiList(creature);
}
<commit_msg>Refactoring extract method to check known taximasks.<commit_after>/*
Copyright (c) 2014-2018 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Management/TaxiMgr.h"
#include "Storage/MySQLDataStore.hpp"
#include "Server/Packets/CmsgTaxiQueryAvailableNodes.h"
#include "Server/Packets/CmsgEnabletaxi.h"
#include "Server/Packets/SmsgTaxinodeStatus.h"
#include "Server/Packets/CmsgTaxinodeStatusQuery.h"

using namespace AscEmu::Packets;

uint8_t isTaximaskKnown(Player* player, uint32_t nearestNode)
{
    const auto field = static_cast<uint8_t>((nearestNode - 1) / 32);
    const uint32_t submask = 1 << ((nearestNode - 1) % 32);

    if ((player->GetTaximask(field) & submask) != submask)
        return 0;

    return 1;
}

void WorldSession::handleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgTaxinodeStatusQuery recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_TAXINODE_STATUS_QUERY");

    const auto nearestNode = sTaxiMgr.getNearestNodeForPlayer(_player);
    if (!nearestNode)
        return;

    uint8_t status = isTaximaskKnown(_player, nearestNode);
    SendPacket(SmsgTaxinodeStatus(recv_packet.guid, status).serialise().get());
}

void WorldSession::handleTaxiQueryAvaibleNodesOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgTaxiQueryAvailableNodes recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_TAXIQUERYAVAILABLENODES");

    if (const auto creature = _player->GetMapMgr()->GetCreature(recv_packet.creatureGuid.getGuidLowPart()))
        SendTaxiList(creature);
}

void WorldSession::handleEnabletaxiOpcode(WorldPacket& recvPacket)
{
    CHECK_INWORLD_RETURN

    CmsgEnabletaxi recv_packet;
    if (!recv_packet.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "WORLD: Received CMSG_ENABLETAXI");

    if (const auto creature = _player->GetMapMgr()->GetCreature(recv_packet.creatureGuid.getGuidLowPart()))
        SendTaxiList(creature);
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/common/AllContentModel.hpp>
#include <xercesc/validators/schema/SubstitutionGroupComparator.hpp>
#include <xercesc/validators/schema/XercesElementWildcard.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  AllContentModel: Constructors and Destructor
// ---------------------------------------------------------------------------
AllContentModel::AllContentModel( ContentSpecNode* const parentContentSpec
                                , const bool             isMixed
                                , MemoryManager* const   manager) :
   fMemoryManager(manager)
 , fCount(0)
 , fChildren(0)
 , fChildOptional(0)
 , fNumRequired(0)
 , fIsMixed(isMixed)
 , fHasOptionalContent(false)
{
    //
    //  Create a vector of unsigned ints that will be filled in with the
    //  ids of the child nodes. It will be expanded as needed but we give
    //  it an initial capacity of 64 which should be more than enough for
    //  99% of the scenarios.
    //

    ValueVectorOf<QName*> children(64, fMemoryManager);
    ValueVectorOf<bool> childOptional(64, fMemoryManager);

    //
    //  Get the parent element's content spec. This is the head of the tree
    //  of nodes that describes the content model. We will iterate this
    //  tree.
    //
    ContentSpecNode* curNode = parentContentSpec;
    if (!curNode)
        ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_NoParentCSN, fMemoryManager);

    // And now call the private recursive method that iterates the tree
    if (curNode->getType() == ContentSpecNode::All
        && curNode->getMinOccurs() == 0) {
        fHasOptionalContent = true;
    }
    buildChildList(curNode, children, childOptional);

    //
    //  And now we know how many elements we need in our member list. So
    //  fill them in.
    //
    fCount = children.size();
    fChildren = (QName**) fMemoryManager->allocate(fCount * sizeof(QName*)); //new QName*[fCount];
    fChildOptional = (bool*) fMemoryManager->allocate(fCount * sizeof(bool)); //new bool[fCount];
    for (unsigned int index = 0; index < fCount; index++) {
        fChildren[index] = new (fMemoryManager) QName(*(children.elementAt(index)));
        fChildOptional[index] = childOptional.elementAt(index);
    }
}

AllContentModel::~AllContentModel()
{
    for (unsigned int index = 0; index < fCount; index++)
        delete fChildren[index];
    fMemoryManager->deallocate(fChildren); //delete [] fChildren;
    fMemoryManager->deallocate(fChildOptional); //delete [] fChildOptional;
}

// ---------------------------------------------------------------------------
//  AllContentModel: Implementation of the ContentModel virtual interface
// ---------------------------------------------------------------------------
//
//Under the XML Schema mixed model,
//the order and number of child elements appearing in an instance
//must agree with
//the order and number of child elements specified in the model.
//
int
AllContentModel::validateContent( QName** const         children
                                , const unsigned int    childCount
                                , const unsigned int) const
{
    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (childCount == 0 && (fHasOptionalContent || !fNumRequired))
        return -1;

    MemoryManager* const    localMemoryManager =
        children[0]->getMemoryManager();

    // Check for duplicate element
    bool* elementSeen = (bool*) localMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    const ArrayJanitor<bool> jan(elementSeen, localMemoryManager);

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        const QName* curChild = children[outIndex];

        // If it's PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            const QName* inChild = fChildren[inIndex];
            if ((inChild->getURI() == curChild->getURI()) &&
                (XMLString::equals(inChild->getLocalPart(), curChild->getLocalPart()))) {
                // found it
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            return outIndex;
        }

    }

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    return -1;
}

int AllContentModel::validateContentSpecial(QName** const           children
                                          , const unsigned int      childCount
                                          , const unsigned int
                                          , GrammarResolver*  const pGrammarResolver
                                          , XMLStringPool*    const pStringPool) const
{

    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (childCount == 0 && (fHasOptionalContent || !fNumRequired))
        return -1;

    MemoryManager* const    localMemoryManager =
        children[0]->getMemoryManager();

    // Check for duplicate element
    bool* elementSeen = (bool*) localMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

    const ArrayJanitor<bool> jan(elementSeen, localMemoryManager);

    // initialize the array
    for (unsigned int i = 0; i < fCount; i++)
        elementSeen[i] = false;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
        // Get the current child out of the source index
        QName* const curChild = children[outIndex];

        // If it's PCDATA, then we just accept that
        if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
            continue;

        // And try to find it in our list
        unsigned int inIndex = 0;
        for (; inIndex < fCount; inIndex++)
        {
            QName* const inChild = fChildren[inIndex];
            if ( comparator.isEquivalentTo(curChild, inChild)) {
                // match
                // If this element was seen already, indicate an error was
                // found at the duplicate index.
                if (elementSeen[inIndex]) {
                    return outIndex;
                }
                else
                    elementSeen[inIndex] = true;

                if (!fChildOptional[inIndex])
                    numRequiredSeen++;

                break;
            }
        }

        // We did not find this one, so the validation failed
        if (inIndex == fCount) {
            return outIndex;
        }

    }

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    return -1;

}

void AllContentModel::checkUniqueParticleAttribution
    (
        SchemaGrammar*    const pGrammar
      , GrammarResolver*  const pGrammarResolver
      , XMLStringPool*    const pStringPool
      , XMLValidator*     const pValidator
      , unsigned int*     const pContentSpecOrgURI
      , const XMLCh*            pComplexTypeName /*= 0*/
    )
{
    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    unsigned int i, j;

    // rename back
    for (i = 0; i < fCount; i++) {
        unsigned int orgURIIndex = fChildren[i]->getURI();
        fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]);
    }

    // check whether there is conflict between any two leaves
    for (i = 0; i < fCount; i++) {
        for (j = i+1; j < fCount; j++) {
            // If this is text in a Schema mixed content model, skip it.
            if ( fIsMixed &&
                 (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) ||
                  ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId)))
                continue;

            if (XercesElementWildcard::conflict(pGrammar,
                                                ContentSpecNode::Leaf,
                                                fChildren[i],
                                                ContentSpecNode::Leaf,
                                                fChildren[j],
                                                &comparator)) {
                pValidator->emitError(XMLValid::UniqueParticleAttributionFail,
                                      pComplexTypeName,
                                      fChildren[i]->getRawName(),
                                      fChildren[j]->getRawName());
             }
         }
    }
}

// ---------------------------------------------------------------------------
//  AllContentModel: Private helper methods
// ---------------------------------------------------------------------------
void
AllContentModel::buildChildList(ContentSpecNode* const       curNode
                              , ValueVectorOf<QName*>&       toFill
                              , ValueVectorOf<bool>&         toOptional)
{
    // Get the type of spec node our current node is
    const ContentSpecNode::NodeTypes curType = curNode->getType();

    if (curType == ContentSpecNode::All)
    {
        // Get both the child node pointers
        ContentSpecNode* leftNode = curNode->getFirst();
        ContentSpecNode* rightNode = curNode->getSecond();

        // Recurse on the left and right nodes
        buildChildList(leftNode, toFill, toOptional);
        buildChildList(rightNode, toFill, toOptional);
    }
    else if (curType == ContentSpecNode::Leaf)
    {
        // At leaf, add the element to list of elements permitted in the all
        toFill.addElement(curNode->getElement());
        toOptional.addElement(false);
        fNumRequired++;
    }
    else if (curType == ContentSpecNode::ZeroOrOne)
    {
        // At ZERO_OR_ONE node, subtree must be an element
        // that was specified with minOccurs=0, maxOccurs=1
        ContentSpecNode* leftNode = curNode->getFirst();
        if (leftNode->getType() != ContentSpecNode::Leaf)
            ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_UnknownCMSpecType, fMemoryManager);

        toFill.addElement(leftNode->getElement());
        toOptional.addElement(true);
    }
    else
        ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_UnknownCMSpecType, fMemoryManager);
}

XERCES_CPP_NAMESPACE_END
<commit_msg>Before using a local memory manager, check that we have a valid pointer<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/common/AllContentModel.hpp>
#include <xercesc/validators/schema/SubstitutionGroupComparator.hpp>
#include <xercesc/validators/schema/XercesElementWildcard.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  AllContentModel: Constructors and Destructor
// ---------------------------------------------------------------------------
AllContentModel::AllContentModel( ContentSpecNode* const parentContentSpec
                                , const bool             isMixed
                                , MemoryManager* const   manager) :
   fMemoryManager(manager)
 , fCount(0)
 , fChildren(0)
 , fChildOptional(0)
 , fNumRequired(0)
 , fIsMixed(isMixed)
 , fHasOptionalContent(false)
{
    //
    //  Create a vector of unsigned ints that will be filled in with the
    //  ids of the child nodes. It will be expanded as needed but we give
    //  it an initial capacity of 64 which should be more than enough for
    //  99% of the scenarios.
    //

    ValueVectorOf<QName*> children(64, fMemoryManager);
    ValueVectorOf<bool> childOptional(64, fMemoryManager);

    //
    //  Get the parent element's content spec. This is the head of the tree
    //  of nodes that describes the content model. We will iterate this
    //  tree.
    //
    ContentSpecNode* curNode = parentContentSpec;
    if (!curNode)
        ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_NoParentCSN, fMemoryManager);

    // And now call the private recursive method that iterates the tree
    if (curNode->getType() == ContentSpecNode::All
        && curNode->getMinOccurs() == 0) {
        fHasOptionalContent = true;
    }
    buildChildList(curNode, children, childOptional);

    //
    //  And now we know how many elements we need in our member list. So
    //  fill them in.
    //
    fCount = children.size();
    fChildren = (QName**) fMemoryManager->allocate(fCount * sizeof(QName*)); //new QName*[fCount];
    fChildOptional = (bool*) fMemoryManager->allocate(fCount * sizeof(bool)); //new bool[fCount];
    for (unsigned int index = 0; index < fCount; index++) {
        fChildren[index] = new (fMemoryManager) QName(*(children.elementAt(index)));
        fChildOptional[index] = childOptional.elementAt(index);
    }
}

AllContentModel::~AllContentModel()
{
    for (unsigned int index = 0; index < fCount; index++)
        delete fChildren[index];
    fMemoryManager->deallocate(fChildren); //delete [] fChildren;
    fMemoryManager->deallocate(fChildOptional); //delete [] fChildOptional;
}

// ---------------------------------------------------------------------------
//  AllContentModel: Implementation of the ContentModel virtual interface
// ---------------------------------------------------------------------------
//
//Under the XML Schema mixed model,
//the order and number of child elements appearing in an instance
//must agree with
//the order and number of child elements specified in the model.
//
int
AllContentModel::validateContent( QName** const         children
                                , const unsigned int    childCount
                                , const unsigned int) const
{
    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (childCount == 0 && (fHasOptionalContent || !fNumRequired))
        return -1;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    if(childCount > 0)
    {
        MemoryManager* const localMemoryManager = children[0]->getMemoryManager();

        // Check for duplicate element
        bool* elementSeen = (bool*) localMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

        const ArrayJanitor<bool> jan(elementSeen, localMemoryManager);

        // initialize the array
        for (unsigned int i = 0; i < fCount; i++)
            elementSeen[i] = false;

        for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
            // Get the current child out of the source index
            const QName* curChild = children[outIndex];

            // If it's PCDATA, then we just accept that
            if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
                continue;

            // And try to find it in our list
            unsigned int inIndex = 0;
            for (; inIndex < fCount; inIndex++)
            {
                const QName* inChild = fChildren[inIndex];
                if ((inChild->getURI() == curChild->getURI()) &&
                    (XMLString::equals(inChild->getLocalPart(), curChild->getLocalPart()))) {
                    // found it
                    // If this element was seen already, indicate an error was
                    // found at the duplicate index.
                    if (elementSeen[inIndex]) {
                        return outIndex;
                    }
                    else
                        elementSeen[inIndex] = true;

                    if (!fChildOptional[inIndex])
                        numRequiredSeen++;

                    break;
                }
            }

            // We did not find this one, so the validation failed
            if (inIndex == fCount) {
                return outIndex;
            }

        }
    }

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    return -1;
}

int AllContentModel::validateContentSpecial(QName** const           children
                                          , const unsigned int      childCount
                                          , const unsigned int
                                          , GrammarResolver*  const pGrammarResolver
                                          , XMLStringPool*    const pStringPool) const
{
    // If <all> had minOccurs of zero and there are
    // no children to validate, trivially validate
    if (childCount == 0 && (fHasOptionalContent || !fNumRequired))
        return -1;

    // keep track of the required element seen
    unsigned int numRequiredSeen = 0;

    if(childCount > 0)
    {
        SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

        MemoryManager* const localMemoryManager = children[0]->getMemoryManager();

        // Check for duplicate element
        bool* elementSeen = (bool*) localMemoryManager->allocate(fCount*sizeof(bool)); //new bool[fCount];

        const ArrayJanitor<bool> jan(elementSeen, localMemoryManager);

        // initialize the array
        for (unsigned int i = 0; i < fCount; i++)
            elementSeen[i] = false;

        for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) {
            // Get the current child out of the source index
            QName* const curChild = children[outIndex];

            // If it's PCDATA, then we just accept that
            if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId)
                continue;

            // And try to find it in our list
            unsigned int inIndex = 0;
            for (; inIndex < fCount; inIndex++)
            {
                QName* const inChild = fChildren[inIndex];
                if ( comparator.isEquivalentTo(curChild, inChild)) {
                    // match
                    // If this element was seen already, indicate an error was
                    // found at the duplicate index.
                    if (elementSeen[inIndex]) {
                        return outIndex;
                    }
                    else
                        elementSeen[inIndex] = true;

                    if (!fChildOptional[inIndex])
                        numRequiredSeen++;

                    break;
                }
            }

            // We did not find this one, so the validation failed
            if (inIndex == fCount) {
                return outIndex;
            }

        }
    }

    // Were all the required elements of the <all> encountered?
    if (numRequiredSeen != fNumRequired) {
        return childCount;
    }

    // Everything seems to be ok, so return success
    return -1;

}

void AllContentModel::checkUniqueParticleAttribution
    (
        SchemaGrammar*    const pGrammar
      , GrammarResolver*  const pGrammarResolver
      , XMLStringPool*    const pStringPool
      , XMLValidator*     const pValidator
      , unsigned int*     const pContentSpecOrgURI
      , const XMLCh*            pComplexTypeName /*= 0*/
    )
{
    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    unsigned int i, j;

    // rename back
    for (i = 0; i < fCount; i++) {
        unsigned int orgURIIndex = fChildren[i]->getURI();
        fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]);
    }

    // check whether there is conflict between any two leaves
    for (i = 0; i < fCount; i++) {
        for (j = i+1; j < fCount; j++) {
            // If this is text in a Schema mixed content model, skip it.
            if ( fIsMixed &&
                 (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) ||
                  ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId)))
                continue;

            if (XercesElementWildcard::conflict(pGrammar,
                                                ContentSpecNode::Leaf,
                                                fChildren[i],
                                                ContentSpecNode::Leaf,
                                                fChildren[j],
                                                &comparator)) {
                pValidator->emitError(XMLValid::UniqueParticleAttributionFail,
                                      pComplexTypeName,
                                      fChildren[i]->getRawName(),
                                      fChildren[j]->getRawName());
             }
         }
    }
}

// ---------------------------------------------------------------------------
//  AllContentModel: Private helper methods
// ---------------------------------------------------------------------------
void
AllContentModel::buildChildList(ContentSpecNode* const       curNode
                              , ValueVectorOf<QName*>&       toFill
                              , ValueVectorOf<bool>&         toOptional)
{
    // Get the type of spec node our current node is
    const ContentSpecNode::NodeTypes curType = curNode->getType();

    if (curType == ContentSpecNode::All)
    {
        // Get both the child node pointers
        ContentSpecNode* leftNode = curNode->getFirst();
        ContentSpecNode* rightNode = curNode->getSecond();

        // Recurse on the left and right nodes
        buildChildList(leftNode, toFill, toOptional);
        buildChildList(rightNode, toFill, toOptional);
    }
    else if (curType == ContentSpecNode::Leaf)
    {
        // At leaf, add the element to list of elements permitted in the all
        toFill.addElement(curNode->getElement());
        toOptional.addElement(false);
        fNumRequired++;
    }
    else if (curType == ContentSpecNode::ZeroOrOne)
    {
        // At ZERO_OR_ONE node, subtree must be an element
        // that was specified with minOccurs=0, maxOccurs=1
        ContentSpecNode* leftNode = curNode->getFirst();
        if (leftNode->getType() != ContentSpecNode::Leaf)
            ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_UnknownCMSpecType, fMemoryManager);

        toFill.addElement(leftNode->getElement());
        toOptional.addElement(true);
    }
    else
        ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::CM_UnknownCMSpecType, fMemoryManager);
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Id$
 */

#if !defined(GRAMMARRESOLVER_HPP)
#define GRAMMARRESOLVER_HPP

#include <xercesc/util/RefHashTableOf.hpp>
#include <xercesc/util/StringPool.hpp>
#include <xercesc/validators/common/Grammar.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class DatatypeValidator;
class DatatypeValidatorFactory;

/**
 * This class embodies the representation of a Grammar pool Resolver.
 * This class is called from the validator.
 *
 */

class GrammarResolver {
public:

    /** @name Constructor and Destructor */
    //@{
    /**
     *
     * Default Constructor
     */
    GrammarResolver();

    /**
      * Destructor
      */
    ~GrammarResolver();

    //@}

    /** @name Getter methods */
    //@{
    /**
     * Retrieve the DatatypeValidator
     *
     * @param uriStr the namespace URI
     * @param typeName the type name
     * @return the DatatypeValidator associated with namespace & type name
     */
    DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr,
                                            const XMLCh* const typeName);

    /**
     * Retrieve the grammar that is associated with the specified namespace key
     *
     * @param  nameSpaceKey   Namespace key into Grammar pool
     * @return Grammar abstraction associated with the NameSpace key.
     */
    Grammar* getGrammar( const XMLCh* const nameSpaceKey ) ;

    /**
     * Get an enumeration of Grammar in the Grammar pool
     *
     * @return enumeration of Grammar in Grammar pool
     */
    RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const;

    /**
     * Get a string pool of schema grammar element/attribute names/prefixes
     * (used by TraverseSchema)
     *
     * @return a string pool of schema grammar element/attribute names/prefixes
     */
    XMLStringPool* getStringPool();

    /**
     * Is the specified Namespace key in Grammar pool?
     *
     * @param  nameSpaceKey    Namespace key
     * @return True if Namespace key association is in the Grammar pool.
     */
    bool containsNameSpace( const XMLCh* const nameSpaceKey );

    //@}

    /** @name Setter methods */
    //@{

    /**
      * Set the 'Grammar caching' flag
      */
    void cacheGrammarFromParse(const bool newState);

    /**
      * Set the 'Use cached grammar' flag
      */
    void useCachedGrammarInParse(const bool newState);

    //@}

    /** @name GrammarResolver methods */
    //@{
    /**
     * Add the Grammar with Namespace Key associated to the Grammar Pool.
     * The Grammar will be owned by the Grammar Pool.
     *
     * @param  nameSpaceKey    Key to associate with Grammar abstraction
     * @param  grammarToAdopt  Grammar abstraction used by validator.
     */
    void putGrammar(const XMLCh* const nameSpaceKey, Grammar* const grammarToAdopt );

    /**
     * Returns the Grammar with Namespace Key associated from the Grammar Pool
     * The Key entry is removed from the table (grammar is not deleted if
     * adopted - now owned by caller).
     *
     * @param  nameSpaceKey    Key to associate with Grammar abstraction
     */
    Grammar* orphanGrammar(const XMLCh* const nameSpaceKey);

    /**
     * Cache the grammars in fGrammarRegistry to fCachedGrammarRegistry.
     * If a grammar with the same key is already cached, an exception is
     * thrown and none of the grammars will be cached.
     */
    void cacheGrammars();

    /**
     * Reset internal Namespace/Grammar registry.
     */
    void reset();
    void resetCachedGrammar();

    //@}

private:
    // -----------------------------------------------------------------------
    //  Private data members
    //
    //  fStringPool            The string pool used by TraverseSchema to store
    //                         element/attribute names and prefixes.
    //
    //  fGrammarRegistry       The parsed Grammar Pool, if no caching option.
    //
    //  fCachedGrammarRegistry The cached Grammar Pool.  It represents a
    //                         mapping between Namespace and a Grammar
    //
    //  fDataTypeReg           DatatypeValidatorFactory registery
    //
    // -----------------------------------------------------------------------
    bool                       fCacheGrammar;
    bool                       fUseCachedGrammar;
    XMLStringPool              fStringPool;
    RefHashTableOf<Grammar>*   fGrammarRegistry;
    RefHashTableOf<Grammar>*   fCachedGrammarRegistry;
    DatatypeValidatorFactory*  fDataTypeReg;
};

inline XMLStringPool* GrammarResolver::getStringPool() {

    return &fStringPool;
}

inline void GrammarResolver::useCachedGrammarInParse(const bool aValue)
{
    fUseCachedGrammar = aValue;
}

inline Grammar*
GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) {

    if (fCacheGrammar)
        return fCachedGrammarRegistry->orphanKey(nameSpaceKey);

    return fGrammarRegistry->orphanKey(nameSpaceKey);
}

XERCES_CPP_NAMESPACE_END

#endif
<commit_msg>[Bug 9697] Make GrammarResolver to be exportable<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Id$
 */

#if !defined(GRAMMARRESOLVER_HPP)
#define GRAMMARRESOLVER_HPP

#include <xercesc/util/RefHashTableOf.hpp>
#include <xercesc/util/StringPool.hpp>
#include <xercesc/validators/common/Grammar.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class DatatypeValidator;
class DatatypeValidatorFactory;

/**
 * This class embodies the representation of a Grammar pool Resolver.
 * This class is called from the validator.
 *
 */

class VALIDATORS_EXPORT GrammarResolver {
public:

    /** @name Constructor and Destructor */
    //@{
    /**
     *
     * Default Constructor
     */
    GrammarResolver();

    /**
      * Destructor
      */
    ~GrammarResolver();

    //@}

    /** @name Getter methods */
    //@{
    /**
     * Retrieve the DatatypeValidator
     *
     * @param uriStr the namespace URI
     * @param typeName the type name
     * @return the DatatypeValidator associated with namespace & type name
     */
    DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr,
                                            const XMLCh* const typeName);

    /**
     * Retrieve the grammar that is associated with the specified namespace key
     *
     * @param  nameSpaceKey   Namespace key into Grammar pool
     * @return Grammar abstraction associated with the NameSpace key.
     */
    Grammar* getGrammar( const XMLCh* const nameSpaceKey ) ;

    /**
     * Get an enumeration of Grammar in the Grammar pool
     *
     * @return enumeration of Grammar in Grammar pool
     */
    RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const;

    /**
     * Get a string pool of schema grammar element/attribute names/prefixes
     * (used by TraverseSchema)
     *
     * @return a string pool of schema grammar element/attribute names/prefixes
     */
    XMLStringPool* getStringPool();

    /**
     * Is the specified Namespace key in Grammar pool?
     *
     * @param  nameSpaceKey    Namespace key
     * @return True if Namespace key association is in the Grammar pool.
     */
    bool containsNameSpace( const XMLCh* const nameSpaceKey );

    //@}

    /** @name Setter methods */
    //@{

    /**
      * Set the 'Grammar caching' flag
      */
    void cacheGrammarFromParse(const bool newState);

    /**
      * Set the 'Use cached grammar' flag
      */
    void useCachedGrammarInParse(const bool newState);

    //@}

    /** @name GrammarResolver methods */
    //@{
    /**
     * Add the Grammar with Namespace Key associated to the Grammar Pool.
     * The Grammar will be owned by the Grammar Pool.
     *
     * @param  nameSpaceKey    Key to associate with Grammar abstraction
     * @param  grammarToAdopt  Grammar abstraction used by validator.
     */
    void putGrammar(const XMLCh* const nameSpaceKey, Grammar* const grammarToAdopt );

    /**
     * Returns the Grammar with Namespace Key associated from the Grammar Pool
     * The Key entry is removed from the table (grammar is not deleted if
     * adopted - now owned by caller).
     *
     * @param  nameSpaceKey    Key to associate with Grammar abstraction
     */
    Grammar* orphanGrammar(const XMLCh* const nameSpaceKey);

    /**
     * Cache the grammars in fGrammarRegistry to fCachedGrammarRegistry.
     * If a grammar with the same key is already cached, an exception is
     * thrown and none of the grammars will be cached.
     */
    void cacheGrammars();

    /**
     * Reset internal Namespace/Grammar registry.
     */
    void reset();
    void resetCachedGrammar();

    //@}

private:
    // -----------------------------------------------------------------------
    //  Private data members
    //
    //  fStringPool            The string pool used by TraverseSchema to store
    //                         element/attribute names and prefixes.
    //
    //  fGrammarRegistry       The parsed Grammar Pool, if no caching option.
    //
    //  fCachedGrammarRegistry The cached Grammar Pool.  It represents a
    //                         mapping between Namespace and a Grammar
    //
    //  fDataTypeReg           DatatypeValidatorFactory registery
    //
    // -----------------------------------------------------------------------
    bool                       fCacheGrammar;
    bool                       fUseCachedGrammar;
    XMLStringPool              fStringPool;
    RefHashTableOf<Grammar>*   fGrammarRegistry;
    RefHashTableOf<Grammar>*   fCachedGrammarRegistry;
    DatatypeValidatorFactory*  fDataTypeReg;
};

inline XMLStringPool* GrammarResolver::getStringPool() {

    return &fStringPool;
}

inline void GrammarResolver::useCachedGrammarInParse(const bool aValue)
{
    fUseCachedGrammar = aValue;
}

inline Grammar*
GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) {

    if (fCacheGrammar)
        return fCachedGrammarRegistry->orphanKey(nameSpaceKey);

    return fGrammarRegistry->orphanKey(nameSpaceKey);
}

XERCES_CPP_NAMESPACE_END

#endif
<|endoftext|>


<commit_before>#include "MenuState.h"
#include "InputManager.h"
#include "TitleState.h"
#include "BattleState.h"
#include "Game.h"

#define OPTION_OFFSET 50

MenuState::MenuState() : current_option(0) {
	background = Sprite("menu/background.png");

	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "START", {255, 255, 255, 255}, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "CONTINUE", {255, 255, 255, 255}, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "OPTIONS", {255, 255, 255, 255}, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "EXIT", {255, 255, 255, 255}, 640, 640));
}

void MenuState::update(float delta){
	printf("CURRENT OPTION: %d\n", current_option);

	InputManager input_manager = InputManager::get_instance();

	// handling general inputs
	if(input_manager.key_press(SDLK_ESCAPE) or input_manager.quit_requested()){
		m_quit_requested = true;
		Game::get_instance().push(new TitleState());
		return;
	}

	if(input_manager.key_press(SDLK_SPACE)){
		m_quit_requested = true;
		Game::get_instance().push(new BattleState("1"));
		return;
	}

	// handling options input
	if(input_manager.key_press(SDLK_LEFT)){
		current_option = (current_option - 1) % options.size();
	}

	if(input_manager.key_press(SDLK_RIGHT)){
		current_option = (current_option + 1) % options.size();
	}

	// TODO when press space switch case in options

	// handling options positioning
	options[current_option]->set_pos(640, 640, true, true);
	options[current_option]->set_color({ 255, 0, 0, 1 });

	int idx = (current_option + 1) % options.size();

	for(int counter = 0; counter < options.size() - 1; counter++){
		int prev_idx = (idx - 1) % options.size();
		Text* prev_option = options[prev_idx];

		// printf("PREV: (x: %f, y: %f, w: %f, h: %f)")

		int new_x = prev_option->get_x() + prev_option->get_width() + OPTION_OFFSET;
		options[idx]->set_pos(new_x, 640, false, true);
		options[idx]->set_color({ 255, 255, 255, 255 });

		idx = (idx + 1) % options.size();
	}
}

void MenuState::render(){
	background.render(0, 0);

	for(auto option_text : options){
		option_text->render(0, 0);
	}
}

void MenuState::pause(){

}

void MenuState::resume(){

}
<commit_msg>Make menu options display correctly<commit_after>#include "MenuState.h"
#include "InputManager.h"
#include "TitleState.h"
#include "BattleState.h"
#include "Game.h"

#define OPTION_OFFSET 50
#define RED { 255, 0, 0, 1 }
#define WHITE { 255, 255, 255, 255 }

MenuState::MenuState() : current_option(0) {
	background = Sprite("menu/background.png");

	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "START", RED, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "CONTINUE", RED, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "OPTIONS", RED, 640, 640));
	options.push_back(new Text("font/8-BIT WONDER.ttf", 45, Text::TextStyle::SOLID, "EXIT", RED, 640, 640));
}

void MenuState::update(float delta){
	InputManager input_manager = InputManager::get_instance();

	// handling general inputs
	if(input_manager.key_press(SDLK_ESCAPE) or input_manager.quit_requested()){
		m_quit_requested = true;
		Game::get_instance().push(new TitleState());
		return;
	}

	if(input_manager.key_press(SDLK_SPACE)){
		m_quit_requested = true;
		Game::get_instance().push(new BattleState("1"));
		return;
	}

	// handling options input
	if(input_manager.key_press(SDLK_LEFT) && current_option != 0){
		current_option--;
	}

	if(input_manager.key_press(SDLK_RIGHT) && current_option != (int)options.size() - 1){
		current_option++;
	}

	// TODO when press space switch case in options

	// handling options positioning
	options[current_option]->set_pos(640, 640, true, true);
	options[current_option]->set_color(WHITE);

	// positioning options before current option
	for(int idx = 0; idx < current_option; idx++){
		Text* next_option = options[idx + 1];

		int new_x = next_option->get_x() - options[idx]->get_width() - OPTION_OFFSET;
		options[idx]->set_pos(new_x, 640, false, true);
		options[idx]->set_color(RED);
	}

	// positioning options after current option
	for(unsigned int idx = current_option + 1; idx < options.size(); idx++){
		Text* prev_option = options[idx - 1];

		int new_x = prev_option->get_x() + prev_option->get_width() + OPTION_OFFSET;
		options[idx]->set_pos(new_x, 640, false, true);
		options[idx]->set_color(RED);
	}
}

void MenuState::render(){
	background.render(0, 0);

	for(auto option_text : options){
		option_text->render(0, 0);
	}
}

void MenuState::pause(){

}

void MenuState::resume(){

}
<|endoftext|>


<commit_before>// commands.cxx - encapsulated commands.
// Started Spring 2001 by David Megginson, david@megginson.com
// This code is released into the Public Domain.
//
// $Id$

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include <memory>
#include <simgear/props/props_io.hxx>

#include "commands.hxx"

#include <simgear/structure/exception.hxx>
#include <simgear/threads/SGThread.hxx>
#include <simgear/threads/SGGuard.hxx>
#include <simgear/debug/logstream.hxx>

////////////////////////////////////////////////////////////////////////
// Implementation of SGCommandMgr class.
////////////////////////////////////////////////////////////////////////

SGCommandMgr::SGCommandMgr ()
{
  // no-op
}

SGCommandMgr::~SGCommandMgr ()
{
  // no-op
}

SGMutex SGCommandMgr::_instanceMutex;

SGCommandMgr*
SGCommandMgr::instance()
{
  static std::auto_ptr<SGCommandMgr> mgr;
  if (mgr.get())
    return mgr.get();

  SGGuard<SGMutex> lock(_instanceMutex);
  if (mgr.get())
    return mgr.get();

  mgr = std::auto_ptr<SGCommandMgr>(new SGCommandMgr);
  return mgr.get();
}

void
SGCommandMgr::addCommandObject (const std::string &name, Command* command)
{
    if (_commands.find(name) != _commands.end())
        throw sg_exception("duplicate command name:" + name);

  _commands[name] = command;
}

SGCommandMgr::Command*
SGCommandMgr::getCommand (const std::string &name) const
{
  const command_map::const_iterator it = _commands.find(name);
  return (it != _commands.end() ? it->second : 0);
}

string_list
SGCommandMgr::getCommandNames () const
{
  string_list names;
  command_map::const_iterator it = _commands.begin();
  command_map::const_iterator last = _commands.end();
  while (it != last) {
    names.push_back(it->first);
    ++it;
  }
  return names;
}

bool
SGCommandMgr::execute (const std::string &name, const SGPropertyNode * arg) const
{
  Command* command = getCommand(name);
  if (command == 0)
    return false;

  try {
    return (*command)(arg);
  } catch (sg_exception& e) {
    SG_LOG(SG_GENERAL, SG_ALERT, "command '" << name << "' failed with exception\n"
      << "\tmessage:" << e.getMessage() << " (from " << e.getOrigin() << ")");
    return false;
  }
}

// end of commands.cxx
<commit_msg>Don't let exceptions escape from commands.<commit_after>// commands.cxx - encapsulated commands.
// Started Spring 2001 by David Megginson, david@megginson.com
// This code is released into the Public Domain.
//
// $Id$

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include <memory>
#include <simgear/props/props_io.hxx>

#include "commands.hxx"

#include <simgear/structure/exception.hxx>
#include <simgear/threads/SGThread.hxx>
#include <simgear/threads/SGGuard.hxx>
#include <simgear/debug/logstream.hxx>

////////////////////////////////////////////////////////////////////////
// Implementation of SGCommandMgr class.
////////////////////////////////////////////////////////////////////////

SGCommandMgr::SGCommandMgr ()
{
  // no-op
}

SGCommandMgr::~SGCommandMgr ()
{
  // no-op
}

SGMutex SGCommandMgr::_instanceMutex;

SGCommandMgr*
SGCommandMgr::instance()
{
  static std::auto_ptr<SGCommandMgr> mgr;
  if (mgr.get())
    return mgr.get();

  SGGuard<SGMutex> lock(_instanceMutex);
  if (mgr.get())
    return mgr.get();

  mgr = std::auto_ptr<SGCommandMgr>(new SGCommandMgr);
  return mgr.get();
}

void
SGCommandMgr::addCommandObject (const std::string &name, Command* command)
{
    if (_commands.find(name) != _commands.end())
        throw sg_exception("duplicate command name:" + name);

  _commands[name] = command;
}

SGCommandMgr::Command*
SGCommandMgr::getCommand (const std::string &name) const
{
  const command_map::const_iterator it = _commands.find(name);
  return (it != _commands.end() ? it->second : 0);
}

string_list
SGCommandMgr::getCommandNames () const
{
  string_list names;
  command_map::const_iterator it = _commands.begin();
  command_map::const_iterator last = _commands.end();
  while (it != last) {
    names.push_back(it->first);
    ++it;
  }
  return names;
}

bool
SGCommandMgr::execute (const std::string &name, const SGPropertyNode * arg) const
{
  Command* command = getCommand(name);
  if (command == 0)
  {
    SG_LOG(SG_GENERAL, SG_WARN, "command not found: '" << name << "'");
    return false;
  }

  try
  {
    return (*command)(arg);
  }
  catch(sg_exception& e)
  {
    SG_LOG
    (
      SG_GENERAL,
      SG_ALERT,
      "command '" << name << "' failed with exception\n"
      "\tmessage:" << e.getMessage() << " (from " << e.getOrigin() << ")"
    );
  }
  catch(std::exception& ex)
  {
    SG_LOG
    (
      SG_GENERAL,
      SG_ALERT,
      "command '" << name << "' failed with exception: " << ex.what()
    );
  }
  catch(...)
  {
    SG_LOG
    (
      SG_GENERAL,
      SG_ALERT,
      "command '" << name << "' failed with unknown exception."
    );
  }

  return false;
}

// end of commands.cxx
<|endoftext|>


<commit_before>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef PARAMETER_H
#define PARAMETER_H

namespace galgo {

//=================================================================================================

// end of recursion for computing the sum of a parameter pack of integral numbers
int sum(int first)
{
   return first;
}

// recursion for computing the sum of a parameter pack of integral numbers
template <typename...Args>
int sum(int first, Args...args)
{
   return first + sum(args...);
}

/*-------------------------------------------------------------------------------------------------*/

template <typename T, int N = 16>
class Parameter
{
   template <typename K, int...S>
   friend class Chromosome;

public:
   std::vector<T> data; // contains lower bound, upper bound and initial value (optional)
   // nullary constructor
   Parameter() {}
   // constructor
   Parameter(const std::vector<T>& data) {
      if (data.size() < 2) {
         throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, std::vector argument must contain at least 2 elements of type T, the lower bound and the upper bound, please adjust.");
      }
      if (data[0] >= data[1]) {
         throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, first std::vector argument (lower bound) cannot be equal or greater than second argument (upper bound), please amend.");
      }
      this->data = data;
   }
private:
   // encoding random unsigned integer
   std::string encode() const {
      // generating and encoding a random unsigned integer
      std::string str = GetBinary(Randomize<N>::generate());
      // truncating string to desired number of bits N
      return str.substr(str.size() - N, N);
   }
   // encoding known unsigned integer
   std::string encode(T z) const {
      // converting known value to unsigned integer
      uint64_t value = Randomize<N>::MAXVAL * (z - data[0]) / (data[1] - data[0]);
      // encoding it into a string
      std::string str = GetBinary(value);
      // truncating string to desired number of bits N
      return str.substr(str.size() - N, N);
   }
   // decoding string to real value
   T decode(const std::string& str) const {
      return data[0] + (GetValue(str) / (double)Randomize<N>::MAXVAL) * (data[1] - data[0]);
   }
   // return encoded parameter size in number of bits
   T size() const {
      return N;
   }
};

//=================================================================================================

}

#endif
<commit_msg>Update Parameter.hpp<commit_after>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef PARAMETER_H
#define PARAMETER_H

namespace galgo {

//=================================================================================================

// end of recursion for computing the sum of a parameter pack of integral numbers
int sum(int first)
{
   return first;
}

// recursion for computing the sum of a parameter pack of integral numbers
template <typename...Args>
int sum(int first, Args...args)
{
   return first + sum(args...);
}

/*-------------------------------------------------------------------------------------------------*/

template <typename T, int N = 16>
class Parameter
{
   template <typename K, int...S>
   friend class Chromosome;

public:
   std::vector<T> data; // contains lower bound, upper bound and initial value (optional)
   // nullary constructor
   Parameter() {}
   // constructor
   Parameter(const std::vector<T>& data) {
      if (data.size() < 2) {
         throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, std::vector argument must contain at least 2 elements of type T, the lower bound and the upper bound, please adjust.");
      }
      if (data[0] >= data[1]) {
         throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, first std::vector argument (lower bound) cannot be equal or greater than second argument (upper bound), please amend.");
      }
      this->data = data;
   }
private:
   // encoding random unsigned integer
   std::string encode() const {
      // generating and encoding a random unsigned integer
      std::string str = GetBinary(Randomize<N>::generate());
      // truncating string to desired number of bits N
      return str.substr(str.size() - N, N);
   }
   // encoding known unsigned integer
   std::string encode(T z) const {
      // converting known value to unsigned integer
      uint64_t value = Randomize<N>::MAXVAL * (z - data[0]) / (data[1] - data[0]);
      // encoding it into a string
      std::string str = GetBinary(value);
      // truncating string to desired number of bits N
      return str.substr(str.size() - N, N);
   }
   // decoding string to real value
   T decode(const std::string& str) const {
      return data[0] + (GetValue(str) / static_cast<double>(Randomize<N>::MAXVAL)) * (data[1] - data[0]);
   }
   // return encoded parameter size in number of bits
   T size() const {
      return N;
   }
};

//=================================================================================================

}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``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
 * FOUNDATION OR CONTRIBUTORS 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.
 */

#pragma once

#include "io/FileDescriptor.hxx"

#include <utility>

class Stock;
class StockItem;

class PipeLease {
    Stock *stock;
    StockItem *item = nullptr;
    FileDescriptor fds[2]{FileDescriptor::Undefined(), FileDescriptor::Undefined()};

public:
    explicit PipeLease(Stock *_stock) noexcept
        :stock(_stock) {}

    PipeLease(PipeLease &&src) noexcept
        :stock(src.stock), item(std::exchange(src.item, nullptr)),
         fds(src.fds) {
        for (auto &fd : src.fds)
            fd.SetUndefined();
    }

    PipeLease &operator=(PipeLease &&src) noexcept {
        std::swap(stock, src.stock);
        std::swap(item, src.item);
        std::swap(fds, src.fds);
        return *this;
    }

    bool IsDefined() const noexcept {
        return fds[0].IsDefined();
    }

    /**
     * Throws on error.
     */
    void Create(struct pool &pool);

    /**
     * Ensure that there is a pipe.
     *
     * Throws on error.
     */
    void EnsureCreated(struct pool &pool) {
        if (!IsDefined())
            Create(pool);
    }

    void Release(bool reuse) noexcept;

    void ReleaseIfStock() noexcept {
        if (item != nullptr)
            Release(true);
    }

    void CloseWriteIfNotStock() noexcept {
        if (item == nullptr && fds[1].IsDefined())
            fds[1].Close();
    }

    FileDescriptor GetReadFd() noexcept {
        return fds[0];
    }

    FileDescriptor GetWriteFd() noexcept {
        return fds[1];
    }
};
<commit_msg>PipeLease: fix class/struct mismatch (`-Wmismatched-tags`)<commit_after>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``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
 * FOUNDATION OR CONTRIBUTORS 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.
 */

#pragma once

#include "io/FileDescriptor.hxx"

#include <utility>

class Stock;
struct StockItem;

class PipeLease {
    Stock *stock;
    StockItem *item = nullptr;
    FileDescriptor fds[2]{FileDescriptor::Undefined(), FileDescriptor::Undefined()};

public:
    explicit PipeLease(Stock *_stock) noexcept
        :stock(_stock) {}

    PipeLease(PipeLease &&src) noexcept
        :stock(src.stock), item(std::exchange(src.item, nullptr)),
         fds(src.fds) {
        for (auto &fd : src.fds)
            fd.SetUndefined();
    }

    PipeLease &operator=(PipeLease &&src) noexcept {
        std::swap(stock, src.stock);
        std::swap(item, src.item);
        std::swap(fds, src.fds);
        return *this;
    }

    bool IsDefined() const noexcept {
        return fds[0].IsDefined();
    }

    /**
     * Throws on error.
     */
    void Create(struct pool &pool);

    /**
     * Ensure that there is a pipe.
     *
     * Throws on error.
     */
    void EnsureCreated(struct pool &pool) {
        if (!IsDefined())
            Create(pool);
    }

    void Release(bool reuse) noexcept;

    void ReleaseIfStock() noexcept {
        if (item != nullptr)
            Release(true);
    }

    void CloseWriteIfNotStock() noexcept {
        if (item == nullptr && fds[1].IsDefined())
            fds[1].Close();
    }

    FileDescriptor GetReadFd() noexcept {
        return fds[0];
    }

    FileDescriptor GetWriteFd() noexcept {
        return fds[1];
    }
};
<|endoftext|>


<commit_before>/*
 Filename: RenderGL2.cpp
 Purpose:  OpenGL 2.x Rendering Interface

 Part of Engine2D

 Copyright (C) 2014 Vbitz

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#define GLEW_STATIC
#include "vendor/GL/glew.h"

#include "RenderGL2.hpp"
#include "RenderGL3.hpp"

#include "GL3Buffer.hpp"
#include "TextureLoader.hpp"

#include "Config.hpp"

#include "Application.hpp"

// TODO: define GLM_FORCE_RADIANS, I need to make sure that Draw2D.rotateCamera does this
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#define BUFFER_SIZE 4096

namespace Engine {
    class RenderGL2 : public RenderDriver {
    public:
        RendererType GetRendererType() override {
            return RendererType_OpenGL2;
        }

        OpenGLVersion GetOpenGLVersion() override {
            return GetAppSingilton()->GetWindow()->GetGlVersion();
        }

        EffectShaderTypes::Type GetBestEffectShaderType() override {
            return EffectShaderTypes::GLSL_150;
        }

        bool CheckError(const char* source) override {
            GLenum err;
            bool oneError = false;
            while ((err = glGetError()) != GL_NO_ERROR) {
                Logger::begin("OpenGL", Logger::LogLevel_Error) << "GLError in " << source << " : " << GLErrorString(err) << Logger::end();
                throw new RenderDriverError(source, err, GLErrorString(err));
            }
            return oneError;
        }

        bool HasExtention(std::string extentionName) override {
            bool has = glewGetExtension(extentionName.c_str());

            CheckError("RenderGL2::HasExtention::PostGlewGetExtention");

            return has;
        }

        std::vector<std::string> GetExtentions() override {
            std::vector<std::string> ret;

            std::string extentionList = std::string((const char*) glGetString(GL_EXTENSIONS));
            size_t currentPos = 0;
            int currentIndex = 0;
            while (currentPos < extentionList.length() && currentPos != std::string::npos) {
                size_t nextPos = extentionList.find(' ', currentPos);
                if (nextPos == std::string::npos) {
                    break;
                }
                ret.push_back(extentionList.substr(currentPos, nextPos - currentPos));
                currentPos = extentionList.find(' ', currentPos) + 1;
            }

            CheckError("RenderGL2::GetExtentions");

            return ret;
        }

        void ResetMatrix() override {
            //glPushMatrix();
            glDisable(GL_DEPTH_TEST);
            glLoadIdentity();
            Application* app = GetAppSingilton();
            glm::vec2 windowSize = app->GetWindow()->GetWindowSize();
            glOrtho(0, windowSize.x, windowSize.y, 0, 1, -1);
            if (Config::GetBoolean("core.render.halfPix")) {
                glTranslatef(0.5f, 0.5f, 0.0f);
            }
        }

        void BeginRendering(int mode) override {
            glBegin(mode);
        }

        void EndRendering() override {
            glEnd();
        }

        void EnableTexture(Texture* texId) override {
            glEnable(GL_TEXTURE_2D);

            texId->Begin();
        }

        void DisableTexture() override {
            glBindTexture(GL_TEXTURE_2D, 0);

            glDisable(GL_TEXTURE_2D);
        }

        void EnableSmooth() override {
            glEnable(GL_LINE_SMOOTH);
            glEnable(GL_POLYGON_SMOOTH);
            glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
            glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
        }

        void DisableSmooth() override {
            glDisable(GL_LINE_SMOOTH);
            glDisable(GL_POLYGON_SMOOTH);
        }

        void FlushAll() override { }

        void Init2d() override { }

		void Begin2d() override {
            EnableSmooth();

            glDisable(GL_TEXTURE_2D);

            ResetMatrix();

            CheckError("RenderGL2::Begin2d");
        }

		void End2d() override {
            CheckError("RenderGL2::End2d");
        }

        void Reset() override {
            End2d();
            Begin2d();
        }

        void SetCenter(float x, float y) override {
            this->_centerX = x;
            this->_centerY = y;
        }

        void CameraPan(float x, float y) override {
            glTranslatef(x, y, 0.0f);
        }

        void CameraZoom(float f) override {
            glScalef(f, f, 0.0f);
        }

        void CameraRotate(float r) override {
            glRotatef(r, 0.0f, 0.0f, 1.0f);
        }
    protected:
        void _clearColor(Color4f col) override {
            glClearColor(col.r, col.g, col.b, col.a);
        }

        void _addVert(float x, float y, float z, Color4f col, float s, float t) override {
            glColor4f(col.r, col.g, col.b, col.a);
            glTexCoord2f(s, t);
            glVertex3f(x - _centerX, y - _centerY, z);
        }

        void _printFT(float x, float y, const char* string) override {
            glEnable(GL_TEXTURE_2D);

            glColor4f(_currentColor.r, _currentColor.g, _currentColor.b, _currentColor.a);

            GLFT_Font* drawingFont = GetAppSingilton()->GetFont(_currentFontName, _currentFontSize);

            drawingFont->drawText(x - _centerX, y - _centerY, string);

            glDisable(GL_TEXTURE_2D);

            CheckError("RenderGL2::Print::PostGL2Print");
        }

    private:
        int _centerX = 0;
        int _centerY = 0;

        int _currentVerts = 0;

        GLenum _currentMode = 0;

        EffectParameters* _currentEffect;

        Texture* _defaultTexture;

        Texture* _currentTexture = NULL;
    };

    RenderDriver* CreateRenderGL2() {
        return new RenderGL2();
    }
}<commit_msg>Removed leftover members from RenderGL2<commit_after>/*
 Filename: RenderGL2.cpp
 Purpose:  OpenGL 2.x Rendering Interface

 Part of Engine2D

 Copyright (C) 2014 Vbitz

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#define GLEW_STATIC
#include "vendor/GL/glew.h"

#include "RenderGL2.hpp"
#include "RenderGL3.hpp"

#include "GL3Buffer.hpp"
#include "TextureLoader.hpp"

#include "Config.hpp"

#include "Application.hpp"

// TODO: define GLM_FORCE_RADIANS, I need to make sure that Draw2D.rotateCamera does this
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#define BUFFER_SIZE 4096

namespace Engine {
    class RenderGL2 : public RenderDriver {
    public:
        RendererType GetRendererType() override {
            return RendererType_OpenGL2;
        }

        OpenGLVersion GetOpenGLVersion() override {
            return GetAppSingilton()->GetWindow()->GetGlVersion();
        }

        EffectShaderTypes::Type GetBestEffectShaderType() override {
            return EffectShaderTypes::GLSL_150;
        }

        bool CheckError(const char* source) override {
            GLenum err;
            bool oneError = false;
            while ((err = glGetError()) != GL_NO_ERROR) {
                Logger::begin("OpenGL", Logger::LogLevel_Error) << "GLError in " << source << " : " << GLErrorString(err) << Logger::end();
                throw new RenderDriverError(source, err, GLErrorString(err));
            }
            return oneError;
        }

        bool HasExtention(std::string extentionName) override {
            bool has = glewGetExtension(extentionName.c_str());

            CheckError("RenderGL2::HasExtention::PostGlewGetExtention");

            return has;
        }

        std::vector<std::string> GetExtentions() override {
            std::vector<std::string> ret;

            std::string extentionList = std::string((const char*) glGetString(GL_EXTENSIONS));
            size_t currentPos = 0;
            int currentIndex = 0;
            while (currentPos < extentionList.length() && currentPos != std::string::npos) {
                size_t nextPos = extentionList.find(' ', currentPos);
                if (nextPos == std::string::npos) {
                    break;
                }
                ret.push_back(extentionList.substr(currentPos, nextPos - currentPos));
                currentPos = extentionList.find(' ', currentPos) + 1;
            }

            CheckError("RenderGL2::GetExtentions");

            return ret;
        }

        void ResetMatrix() override {
            //glPushMatrix();
            glDisable(GL_DEPTH_TEST);
            glLoadIdentity();
            Application* app = GetAppSingilton();
            glm::vec2 windowSize = app->GetWindow()->GetWindowSize();
            glOrtho(0, windowSize.x, windowSize.y, 0, 1, -1);
            if (Config::GetBoolean("core.render.halfPix")) {
                glTranslatef(0.5f, 0.5f, 0.0f);
            }
        }

        void BeginRendering(int mode) override {
            glBegin(mode);
        }

        void EndRendering() override {
            glEnd();
        }

        void EnableTexture(Texture* texId) override {
            glEnable(GL_TEXTURE_2D);

            texId->Begin();
        }

        void DisableTexture() override {
            glBindTexture(GL_TEXTURE_2D, 0);

            glDisable(GL_TEXTURE_2D);
        }

        void EnableSmooth() override {
            glEnable(GL_LINE_SMOOTH);
            glEnable(GL_POLYGON_SMOOTH);
            glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
            glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
        }

        void DisableSmooth() override {
            glDisable(GL_LINE_SMOOTH);
            glDisable(GL_POLYGON_SMOOTH);
        }

        void FlushAll() override { }

        void Init2d() override { }

		void Begin2d() override {
            EnableSmooth();

            glDisable(GL_TEXTURE_2D);

            ResetMatrix();

            CheckError("RenderGL2::Begin2d");
        }

		void End2d() override {
            CheckError("RenderGL2::End2d");
        }

        void Reset() override {
            End2d();
            Begin2d();
        }

        void SetCenter(float x, float y) override {
            this->_centerX = x;
            this->_centerY = y;
        }

        void CameraPan(float x, float y) override {
            glTranslatef(x, y, 0.0f);
        }

        void CameraZoom(float f) override {
            glScalef(f, f, 0.0f);
        }

        void CameraRotate(float r) override {
            glRotatef(r, 0.0f, 0.0f, 1.0f);
        }
    protected:
        void _clearColor(Color4f col) override {
            glClearColor(col.r, col.g, col.b, col.a);
        }

        void _addVert(float x, float y, float z, Color4f col, float s, float t) override {
            glColor4f(col.r, col.g, col.b, col.a);
            glTexCoord2f(s, t);
            glVertex3f(x - _centerX, y - _centerY, z);
        }

        void _printFT(float x, float y, const char* string) override {
            glEnable(GL_TEXTURE_2D);

            glColor4f(_currentColor.r, _currentColor.g, _currentColor.b, _currentColor.a);

            GLFT_Font* drawingFont = GetAppSingilton()->GetFont(_currentFontName, _currentFontSize);

            drawingFont->drawText(x - _centerX, y - _centerY, string);

            glDisable(GL_TEXTURE_2D);

            CheckError("RenderGL2::Print::PostGL2Print");
        }

    private:
        int _centerX = 0;
        int _centerY = 0;

        int _currentVerts = 0;
    };

    RenderDriver* CreateRenderGL2() {
        return new RenderGL2();
    }
}<|endoftext|>