<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

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 COPYRIGHT HOLDER 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.
*/

#include "sphere_user.h"

static fclaw2d_vtable_t fclaw2d_vt;
static fc2d_clawpack46_vtable_t classic_claw46;
static fc2d_clawpack5_vtable_t classic_claw5;

void sphere_link_solvers(fclaw2d_domain_t *domain)
{
    const user_options_t *user =  sphere_user_get_options(domain);

    if (user->claw_version == 4)
    {
        fclaw2d_init_vtable(&fclaw2d_vt);
        fc2d_clawpack46_set_vtable_defaults(&fclaw2d_vt, &classic_claw46);

        fclaw2d_vt.problem_setup    = &sphere_problem_setup;
        fclaw2d_vt.patch_setup   = &sphere_patch_setup;

        /* Needed to avoid triggering refinement around block corners */
        fclaw2d_vt.fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;
        fclaw2d_vt.fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;

        classic_claw46.qinit     = &CLAWPACK46_QINIT;
        classic_claw46.rpn2      = &CLAWPACK46_RPN2ADV_MANIFOLD;
        classic_claw46.rpt2      = &CLAWPACK46_RPT2ADV_MANIFOLD;

        fc2d_clawpack46_set_vtable(classic_claw46);

    }
    else if (user->claw_version == 5)
    {
        fclaw2d_init_vtable(&fclaw2d_vt);
        fc2d_clawpack5_set_vtable_defaults(&fclaw2d_vt, &classic_claw5);

        fclaw2d_vt.problem_setup     = &sphere_problem_setup;
        fclaw2d_vt.patch_setup    = &sphere_patch_setup;

        /* Needed to avoid triggering refinement around block corners */
        fclaw2d_vt.fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;
        fclaw2d_vt.fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;

        classic_claw5.qinit       = &CLAWPACK5_QINIT;
        classic_claw5.rpn2        = &CLAWPACK5_RPN2ADV_MANIFOLD;
        classic_claw5.rpt2        = &CLAWPACK5_RPT2ADV_MANIFOLD;

        fc2d_clawpack5_set_vtable(classic_claw5);
    }
    fclaw2d_set_vtable(domain,&fclaw2d_vt);
}

void sphere_problem_setup(fclaw2d_domain_t* domain)
{
    const user_options_t *user = sphere_user_get_options(domain);

    SPHERE_SETPROB(&user->revs_per_second);
}

void sphere_patch_setup(fclaw2d_domain_t *domain,
                        fclaw2d_patch_t *this_patch,
                        int this_block_idx,
                        int this_patch_idx)
{
    int mx,my,mbc,maux;
    double xlower,ylower,dx,dy;
    double *aux,*xd,*yd,*zd,*area;
    double *xp,*yp,*zp;
    const user_options_t* user = sphere_user_get_options(domain);

    if (fclaw2d_patch_is_ghost(this_patch))
    {
        return;
    }

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,
                                  &xd,&yd,&zd,&area);

    if (user->claw_version == 4)
    {
        fc2d_clawpack46_define_auxarray(domain,this_patch);
        fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);

        USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,
                               &maux,aux,&this_block_idx,xd,yd,zd,area);
    }
    else if(user->claw_version == 5)
    {
        fc2d_clawpack5_define_auxarray(domain,this_patch);
        fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);

        USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,
                              &maux,aux,&this_block_idx,xd,yd,zd,area);
    }
}
<commit_msg>(sphere) Clean up problem setup<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

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 COPYRIGHT HOLDER 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.
*/

#include "sphere_user.h"

static fclaw2d_vtable_t fclaw2d_vt;
static fc2d_clawpack46_vtable_t classic_claw46;
static fc2d_clawpack5_vtable_t classic_claw5;

void sphere_link_solvers(fclaw2d_domain_t *domain)
{
    const user_options_t *user =  sphere_user_get_options(domain);

    fclaw2d_init_vtable(&fclaw2d_vt);
    fclaw2d_vt.problem_setup = &sphere_problem_setup;

    if (user->claw_version == 4)
    {
        fc2d_clawpack46_set_vtable_defaults(&fclaw2d_vt, &classic_claw46);

        fclaw2d_vt.patch_setup   = &sphere_patch_setup;

        /* Needed to avoid triggering refinement around block corners */
        fclaw2d_vt.fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;
        fclaw2d_vt.fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;

        classic_claw46.qinit = &CLAWPACK46_QINIT;
        classic_claw46.rpn2  = &CLAWPACK46_RPN2ADV_MANIFOLD;
        classic_claw46.rpt2  = &CLAWPACK46_RPT2ADV_MANIFOLD;

        fc2d_clawpack46_set_vtable(classic_claw46);

    }
    else if (user->claw_version == 5)
    {
        fc2d_clawpack5_set_vtable_defaults(&fclaw2d_vt, &classic_claw5);

        fclaw2d_vt.patch_setup    = &sphere_patch_setup;

        /* Avoid triggering refinement around block corners */
        fclaw2d_vt.fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;
        fclaw2d_vt.fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;

        classic_claw5.qinit = &CLAWPACK5_QINIT;
        classic_claw5.rpn2  = &CLAWPACK5_RPN2ADV_MANIFOLD;
        classic_claw5.rpt2  = &CLAWPACK5_RPT2ADV_MANIFOLD;

        fc2d_clawpack5_set_vtable(classic_claw5);
    }
    fclaw2d_set_vtable(domain,&fclaw2d_vt);
}

void sphere_problem_setup(fclaw2d_domain_t* domain)
{
    const user_options_t *user = sphere_user_get_options(domain);

    SPHERE_SETPROB(&user->revs_per_second);
}

void sphere_patch_setup(fclaw2d_domain_t *domain,
                        fclaw2d_patch_t *this_patch,
                        int this_block_idx,
                        int this_patch_idx)
{
    int mx,my,mbc,maux;
    double xlower,ylower,dx,dy;
    double *aux,*xd,*yd,*zd,*area;
    double *xp,*yp,*zp;
    const user_options_t* user = sphere_user_get_options(domain);

    if (fclaw2d_patch_is_ghost(this_patch))
    {
        return;
    }

    fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
                                &xlower,&ylower,&dx,&dy);

    fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,
                                  &xd,&yd,&zd,&area);

    if (user->claw_version == 4)
    {
        fc2d_clawpack46_define_auxarray(domain,this_patch);
        fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);

        USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,
                               &maux,aux,&this_block_idx,xd,yd,zd,area);
    }
    else if(user->claw_version == 5)
    {
        fc2d_clawpack5_define_auxarray(domain,this_patch);
        fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);

        USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,
                              &maux,aux,&this_block_idx,xd,yd,zd,area);
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *   - Laura Schlimmer <laura@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */

#include <assert.h>
#include <eventql/sql/table_schema.h>

namespace csql {

TableSchema::TableSchema(const TableSchema& other) {
  HashMap<ColumnDefinition const*, ColumnDefinition const*> ptr_map;

  for (auto col : other.columns_) {
    auto new_col = new ColumnDefinition(*col);
    ptr_map.emplace(col, new_col);
    columns_.emplace_back(new_col);

    for (auto subcol : col->column_schema) {
      auto new_subcol = ptr_map[subcol];

      /**
       * N.B. we require the column list to be built up so that a given column
       * Ci is only ever referenced by another column Cj where j > i.
       */
      assert(new_subcol != nullptr); // invalid reference order
      new_col->column_schema.emplace_back(new_subcol);
    }
  }

  for (auto col : other.root_columns_) {
    auto new_col = ptr_map[col];
    assert(new_col != nullptr); // invalid reference
    root_columns_.emplace_back(new_col);
  }
}

TableSchema::TableSchema(
    TableSchema&& other) :
    columns_(other.columns_),
    root_columns_(other.root_columns_) {
  other.columns_.clear();
  other.root_columns_.clear();
}

TableSchema::~TableSchema() {
  for (auto c : columns_) {
    delete c;
  }
}

TableSchema::ColumnList TableSchema::getColumns() const {
  return root_columns_;
}

TableSchema::ColumnList TableSchema::getFlatColumnList() const {
  return columns_;
}

void TableSchemaBuilder::addScalarColumn(
    const String& column_name,
    const String& column_type,
    Vector<TableSchema::ColumnOptions> column_options) {
  auto col_def = new TableSchema::ColumnDefinition();
  col_def->column_class = TableSchema::ColumnClass::SCALAR;
  col_def->column_name = column_name;
  col_def->column_type = column_type;
  col_def->column_options = column_options;
  schema_.columns_.emplace_back(col_def);
  schema_.root_columns_.emplace_back(col_def);
}

void TableSchemaBuilder::addRecordColumn(
    const String& column_name,
    Vector<TableSchema::ColumnOptions> column_options,
    TableSchema&& column_schema) {
  auto col_def = new TableSchema::ColumnDefinition();
  col_def->column_class = TableSchema::ColumnClass::RECORD;
  col_def->column_name = column_name;
  col_def->column_type = "RECORD";
  col_def->column_options = column_options;
  col_def->column_schema = column_schema.root_columns_;

  schema_.columns_.insert(
      schema_.columns_.end(),
      column_schema.columns_.begin(),
      column_schema.columns_.end());

  schema_.columns_.emplace_back(col_def);
  schema_.root_columns_.emplace_back(col_def);

  column_schema.columns_.clear();
  column_schema.root_columns_.clear();
}

TableSchema&& TableSchemaBuilder::getTableSchema() {
  return std::move(schema_);
}

} // namespace csql

<commit_msg>reverse nested column order<commit_after>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *   - Laura Schlimmer <laura@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */

#include <assert.h>
#include <eventql/sql/table_schema.h>

namespace csql {

TableSchema::TableSchema(const TableSchema& other) {
  HashMap<ColumnDefinition const*, ColumnDefinition const*> ptr_map;

  for (auto col = other.columns_.rbegin(); col != other.columns_.rend(); ++col) {
    auto new_col = new ColumnDefinition(**col);
    ptr_map.emplace(*col, new_col);
    columns_.emplace_back(new_col);

    for (auto subcol : (*col)->column_schema) {
      auto new_subcol = ptr_map[subcol];

      /**
       * N.B. we require the column list to be built up so that a given column
       * Ci is only ever referenced by another column Cj where j < i.
       */
      assert(new_subcol != nullptr); // invalid reference order
      new_col->column_schema.emplace_back(new_subcol);
    }
  }

  for (auto col : other.root_columns_) {
    auto new_col = ptr_map[col];
    assert(new_col != nullptr); // invalid reference
    root_columns_.emplace_back(new_col);
  }
}

TableSchema::TableSchema(
    TableSchema&& other) :
    columns_(other.columns_),
    root_columns_(other.root_columns_) {
  other.columns_.clear();
  other.root_columns_.clear();
}

TableSchema::~TableSchema() {
  for (auto c : columns_) {
    delete c;
  }
}

TableSchema::ColumnList TableSchema::getColumns() const {
  return root_columns_;
}

TableSchema::ColumnList TableSchema::getFlatColumnList() const {
  return columns_;
}

void TableSchemaBuilder::addScalarColumn(
    const String& column_name,
    const String& column_type,
    Vector<TableSchema::ColumnOptions> column_options) {
  auto col_def = new TableSchema::ColumnDefinition();
  col_def->column_class = TableSchema::ColumnClass::SCALAR;
  col_def->column_name = column_name;
  col_def->column_type = column_type;
  col_def->column_options = column_options;
  schema_.columns_.emplace_back(col_def);
  schema_.root_columns_.emplace_back(col_def);
}

void TableSchemaBuilder::addRecordColumn(
    const String& column_name,
    Vector<TableSchema::ColumnOptions> column_options,
    TableSchema&& column_schema) {
  auto col_def = new TableSchema::ColumnDefinition();
  col_def->column_class = TableSchema::ColumnClass::RECORD;
  col_def->column_name = column_name;
  col_def->column_type = "RECORD";
  col_def->column_options = column_options;
  col_def->column_schema = column_schema.root_columns_;

  schema_.columns_.emplace_back(col_def);
  schema_.root_columns_.emplace_back(col_def);
  schema_.columns_.insert(
      schema_.columns_.end(),
      column_schema.columns_.begin(),
      column_schema.columns_.end());

  column_schema.columns_.clear();
  column_schema.root_columns_.clear();
}

TableSchema&& TableSchemaBuilder::getTableSchema() {
  return std::move(schema_);
}

} // namespace csql

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *   - Laura Schlimmer <laura@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/eventql.h>
#include <eventql/util/stdtypes.h>
#include <eventql/util/application.h>
#include <eventql/util/cli/flagparser.h>
#include <eventql/util/csv/BinaryCSVOutputStream.h>
#include <eventql/util/http/httpclient.h>
#include <eventql/util/json/jsonoutputstream.h>
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/util/SimpleRateLimit.h"
#include <eventql/util/mysql/MySQL.h>
#include <eventql/util/mysql/MySQLConnection.h>

using namespace eventql;

struct UploadShard {
  Buffer data;
  size_t nrows;
};

bool run(const cli::FlagParser& flags) {
  auto source_table = flags.getString("source_table");
  auto destination_table = flags.getString("destination_table");
  auto shard_size = flags.getInt("shard_size");
  auto num_upload_threads = flags.getInt("upload_threads");
  auto mysql_addr = flags.getString("mysql");
  auto host = flags.getString("host");
  auto port = flags.getInt("port");
  auto db = flags.getString("database");
  auto max_retries = flags.getInt("max_retries");

  logInfo("mysql2evql", "Connecting to MySQL Server...");

  util::mysql::mysqlInit();
  auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));

  logInfo(
      "mysql2evql",
      "Analyzing the input table. This might take a few minutes...");

  auto schema = mysql_conn->getTableSchema(source_table);
  logDebug("mysql2evql", "Table Schema:\n$0", schema->toString());
  Vector<String> column_names;
  for (const auto& field : schema->fields()) {
    column_names.emplace_back(field.name);
  }

  /* status line */
  std::atomic<size_t> num_rows_uploaded(0);
  util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
    logInfo(
        "mysql2evql",
        "Uploading... $0 rows",
        num_rows_uploaded.load());
  });

  /* start upload threads */
  http::HTTPMessage::HeaderList auth_headers;
  if (flags.isSet("auth_token")) {
    auth_headers.emplace_back(
        "Authorization",
        StringUtil::format("Token $0", flags.getString("auth_token")));
  //} else if (!cfg_.getPassword().isEmpty()) {
  //  auth_headers.emplace_back(
  //      "Authorization",
  //      StringUtil::format("Basic $0",
  //          util::Base64::encode(
  //              cfg_.getUser() + ":" + cfg_.getPassword().get())));
  }

  auto insert_uri = StringUtil::format(
      "http://$0:$1/api/v1/tables/insert",
      host,
      port);

  bool upload_done = false;
  bool upload_error = false;
  thread::Queue<UploadShard> upload_queue(1);
  Vector<std::thread> upload_threads(num_upload_threads);
  for (size_t i = 0; i < num_upload_threads; ++i) {
    upload_threads[i] = std::thread([&] {
      while (!upload_done) {
        auto shard = upload_queue.interruptiblePop();
        if (shard.isEmpty()) {
          continue;
        }

        auto retry = 0;
        size_t status_code;

        for (; ;) {
          logDebug(
              "mysql2evql",
              "Uploading batch; target=$0:$1 size=$2MB",
              host,
              port,
              shard.get().data.size() / 1000000.0);

          try {

            http::HTTPClient http_client;
            auto upload_res = http_client.executeRequest(
                http::HTTPRequest::mkPost(
                    insert_uri,
                    "[" + shard.get().data.toString() + "]",
                    auth_headers));

            if (upload_res.statusCode() != 201) {
              status_code = upload_res.statusCode();
              logError(
                  "mysql2evql", "[FATAL ERROR]: HTTP Status Code $0 $1",
                  upload_res.statusCode(),
                  upload_res.body().toString());
              RAISE(kRuntimeError, upload_res.body().toString());
            }

            num_rows_uploaded += shard.get().nrows;
            status_line.runMaybe();
            break;

          } catch (const std::exception& e) {
            logError("mysql2evql", e, "error while uploading table data");

            /* retry upload kMaxRetries times unless an authentication failure occurs */
            if (++retry < max_retries && status_code != 403) {
              auto base_wait = 2;
              auto increased_wait = base_wait * (pow(base_wait, retry));
              sleep(increased_wait);
              continue;
            } else {
              upload_error = true;
              break;
            }
          }
        }
      }
    });
  }

  /* fetch rows from mysql */
  UploadShard shard;
  shard.nrows = 0;
  json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));

  String where_expr;
  if (flags.isSet("filter")) {
    where_expr = "WHERE " + flags.getString("filter");
  }

  auto get_rows_qry = StringUtil::format(
      "SELECT * FROM `$0` $1;",
     source_table,
     where_expr);

  mysql_conn->executeQuery(
      get_rows_qry,
      [&] (const Vector<String>& column_values) -> bool {
    ++shard.nrows;

    if (shard.nrows > 1) {
      json.addComma();
    }

    json.beginObject();
    json.addObjectEntry("database");
    json.addString(db);
    json.addComma();
    json.addObjectEntry("table");
    json.addString(destination_table);
    json.addComma();
    json.addObjectEntry("data");
    json.beginObject();

    for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {
      if (i > 0 ){
        json.addComma();
      }

      json.addObjectEntry(column_names[i]);
      json.addString(column_values[i]);
    }

    json.endObject();
    json.endObject();

    if (shard.nrows == shard_size) {
      upload_queue.insert(shard, true);
      shard.data.clear();
      shard.nrows = 0;
    }

    status_line.runMaybe();
    return true;
  });

  if (shard.nrows > 0) {
    upload_queue.insert(shard, true);
  }

  upload_queue.waitUntilEmpty();
  upload_done = true;
  upload_queue.wakeup();
  for (auto& t : upload_threads) {
    t.join();
  }

  status_line.runForce();

  if (upload_error) {
    logInfo("mysql2evql", "Upload finished with errors");
    return false;
  } else {
    logInfo("mysql2evql", "Upload finished successfully :)");
    return true;
  }
}

int main(int argc, const char** argv) {
  Application::init();
  Application::logToStderr("mysql2evql");

  cli::FlagParser flags;

  flags.defineFlag(
      "loglevel",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.defineFlag(
      "source_table",
      cli::FlagParser::T_STRING,
      true,
      "t",
      NULL,
      "table name",
      "<name>");

  flags.defineFlag(
      "destination_table",
      cli::FlagParser::T_STRING,
      true,
      "t",
      NULL,
      "table name",
      "<name>");

  flags.defineFlag(
      "host",
      cli::FlagParser::T_STRING,
      true,
      "h",
      NULL,
      "eventql server hostname",
      "<host>");

  flags.defineFlag(
      "port",
      cli::FlagParser::T_INTEGER,
      true,
      "p",
      NULL,
      "eventql server port",
      "<port>");

  flags.defineFlag(
      "database",
      cli::FlagParser::T_STRING,
      true,
      "db",
      "",
      "eventql database",
      "<database>");

  flags.defineFlag(
      "auth_token",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "auth token",
      "<token>");

  flags.defineFlag(
      "mysql",
      cli::FlagParser::T_STRING,
      true,
      "x",
      "mysql://localhost:3306/mydb?user=root",
      "MySQL connection string",
      "<url>");

  flags.defineFlag(
      "filter",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "boolean sql expression",
      "<sql_expr>");

  flags.defineFlag(
      "shard_size",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "128",
      "shard size",
      "<num>");

  flags.defineFlag(
      "upload_threads",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8",
      "concurrent uploads",
      "<num>");

  flags.defineFlag(
      "max_retries",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "20",
      "max number of upload retries",
      "<num>");

  try {
    flags.parseArgv(argc, argv);
  } catch (const StandardException& e) {
    logError("mysql2evql", "$0", e.what());
    auto stdout_os = OutputStream::getStdout();
    flags.printUsage(stdout_os.get());
    return 0;
  }

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  try {
    if (run(flags)) {
      return 0;
    } else {
      return 1;
    }
  } catch (const StandardException& e) {
    logFatal("mysql2evql", "$0", e.what());
    return 1;
  }
}
<commit_msg>formatting<commit_after>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *   - Laura Schlimmer <laura@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/eventql.h>
#include <eventql/util/stdtypes.h>
#include <eventql/util/application.h>
#include <eventql/util/cli/flagparser.h>
#include <eventql/util/csv/BinaryCSVOutputStream.h>
#include <eventql/util/http/httpclient.h>
#include <eventql/util/json/jsonoutputstream.h>
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/util/SimpleRateLimit.h"
#include <eventql/util/mysql/MySQL.h>
#include <eventql/util/mysql/MySQLConnection.h>

using namespace eventql;

struct UploadShard {
  Buffer data;
  size_t nrows;
};

bool run(const cli::FlagParser& flags) {
  auto source_table = flags.getString("source_table");
  auto destination_table = flags.getString("destination_table");
  auto shard_size = flags.getInt("shard_size");
  auto num_upload_threads = flags.getInt("upload_threads");
  auto mysql_addr = flags.getString("mysql");
  auto host = flags.getString("host");
  auto port = flags.getInt("port");
  auto db = flags.getString("database");
  auto max_retries = flags.getInt("max_retries");

  logInfo("mysql2evql", "Connecting to MySQL Server...");

  util::mysql::mysqlInit();
  auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));

  logInfo(
      "mysql2evql",
      "Analyzing the input table. This might take a few minutes...");

  auto schema = mysql_conn->getTableSchema(source_table);
  logDebug("mysql2evql", "Table Schema:\n$0", schema->toString());
  Vector<String> column_names;
  for (const auto& field : schema->fields()) {
    column_names.emplace_back(field.name);
  }

  /* status line */
  std::atomic<size_t> num_rows_uploaded(0);
  util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
    logInfo(
        "mysql2evql",
        "Uploading... $0 rows",
        num_rows_uploaded.load());
  });

  /* start upload threads */
  http::HTTPMessage::HeaderList auth_headers;
  if (flags.isSet("auth_token")) {
    auth_headers.emplace_back(
        "Authorization",
        StringUtil::format("Token $0", flags.getString("auth_token")));
  //} else if (!cfg_.getPassword().isEmpty()) {
  //  auth_headers.emplace_back(
  //      "Authorization",
  //      StringUtil::format("Basic $0",
  //          util::Base64::encode(
  //              cfg_.getUser() + ":" + cfg_.getPassword().get())));
  }

  auto insert_uri = StringUtil::format(
      "http://$0:$1/api/v1/tables/insert",
      host,
      port);

  bool upload_done = false;
  bool upload_error = false;
  thread::Queue<UploadShard> upload_queue(1);
  Vector<std::thread> upload_threads(num_upload_threads);
  for (size_t i = 0; i < num_upload_threads; ++i) {
    upload_threads[i] = std::thread([&] {
      while (!upload_done) {
        auto shard = upload_queue.interruptiblePop();
        if (shard.isEmpty()) {
          continue;
        }

        auto retry = 0;
        size_t status_code;
        for (; ;) {
          logDebug(
              "mysql2evql",
              "Uploading batch; target=$0:$1 size=$2MB",
              host,
              port,
              shard.get().data.size() / 1000000.0);

          try {

            http::HTTPClient http_client;
            auto upload_res = http_client.executeRequest(
                http::HTTPRequest::mkPost(
                    insert_uri,
                    "[" + shard.get().data.toString() + "]",
                    auth_headers));

            if (upload_res.statusCode() != 201) {
              status_code = upload_res.statusCode();
              logError(
                  "mysql2evql", "[FATAL ERROR]: HTTP Status Code $0 $1",
                  upload_res.statusCode(),
                  upload_res.body().toString());
              RAISE(kRuntimeError, upload_res.body().toString());
            }

            num_rows_uploaded += shard.get().nrows;
            status_line.runMaybe();
            break;

          } catch (const std::exception& e) {
            logError("mysql2evql", e, "error while uploading table data");
            /* retry upload kMaxRetries times unless an authentication failure occurs */
            if (++retry < max_retries && status_code != 403) {
              auto base_wait = 2;
              sleep(base_wait * (pow(base_wait, retry));
              continue;
            } else {
              upload_error = true;
              break;
            }
          }
        }
      }
    });
  }

  /* fetch rows from mysql */
  UploadShard shard;
  shard.nrows = 0;
  json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));

  String where_expr;
  if (flags.isSet("filter")) {
    where_expr = "WHERE " + flags.getString("filter");
  }

  auto get_rows_qry = StringUtil::format(
      "SELECT * FROM `$0` $1;",
     source_table,
     where_expr);

  mysql_conn->executeQuery(
      get_rows_qry,
      [&] (const Vector<String>& column_values) -> bool {
    ++shard.nrows;

    if (shard.nrows > 1) {
      json.addComma();
    }

    json.beginObject();
    json.addObjectEntry("database");
    json.addString(db);
    json.addComma();
    json.addObjectEntry("table");
    json.addString(destination_table);
    json.addComma();
    json.addObjectEntry("data");
    json.beginObject();

    for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {
      if (i > 0 ){
        json.addComma();
      }

      json.addObjectEntry(column_names[i]);
      json.addString(column_values[i]);
    }

    json.endObject();
    json.endObject();

    if (shard.nrows == shard_size) {
      upload_queue.insert(shard, true);
      shard.data.clear();
      shard.nrows = 0;
    }

    status_line.runMaybe();
    return true;
  });

  if (shard.nrows > 0) {
    upload_queue.insert(shard, true);
  }

  upload_queue.waitUntilEmpty();
  upload_done = true;
  upload_queue.wakeup();
  for (auto& t : upload_threads) {
    t.join();
  }

  status_line.runForce();

  if (upload_error) {
    logInfo("mysql2evql", "Upload finished with errors");
    return false;
  } else {
    logInfo("mysql2evql", "Upload finished successfully :)");
    return true;
  }
}

int main(int argc, const char** argv) {
  Application::init();
  Application::logToStderr("mysql2evql");

  cli::FlagParser flags;

  flags.defineFlag(
      "loglevel",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.defineFlag(
      "source_table",
      cli::FlagParser::T_STRING,
      true,
      "t",
      NULL,
      "table name",
      "<name>");

  flags.defineFlag(
      "destination_table",
      cli::FlagParser::T_STRING,
      true,
      "t",
      NULL,
      "table name",
      "<name>");

  flags.defineFlag(
      "host",
      cli::FlagParser::T_STRING,
      true,
      "h",
      NULL,
      "eventql server hostname",
      "<host>");

  flags.defineFlag(
      "port",
      cli::FlagParser::T_INTEGER,
      true,
      "p",
      NULL,
      "eventql server port",
      "<port>");

  flags.defineFlag(
      "database",
      cli::FlagParser::T_STRING,
      true,
      "db",
      "",
      "eventql database",
      "<database>");

  flags.defineFlag(
      "auth_token",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "auth token",
      "<token>");

  flags.defineFlag(
      "mysql",
      cli::FlagParser::T_STRING,
      true,
      "x",
      "mysql://localhost:3306/mydb?user=root",
      "MySQL connection string",
      "<url>");

  flags.defineFlag(
      "filter",
      cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "boolean sql expression",
      "<sql_expr>");

  flags.defineFlag(
      "shard_size",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "128",
      "shard size",
      "<num>");

  flags.defineFlag(
      "upload_threads",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8",
      "concurrent uploads",
      "<num>");

  flags.defineFlag(
      "max_retries",
      cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "20",
      "max number of upload retries",
      "<num>");

  try {
    flags.parseArgv(argc, argv);
  } catch (const StandardException& e) {
    logError("mysql2evql", "$0", e.what());
    auto stdout_os = OutputStream::getStdout();
    flags.printUsage(stdout_os.get());
    return 0;
  }

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  try {
    if (run(flags)) {
      return 0;
    } else {
      return 1;
    }
  } catch (const StandardException& e) {
    logFatal("mysql2evql", "$0", e.what());
    return 1;
  }
}
<|endoftext|>


<commit_before>AliAnalysisTask *AddTask_miweber_LMEE_pp(){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_miweber_LMEE_pp", "No analysis manager found.");
    return 0;
  }

  Bool_t bESDANA=kFALSE; //Autodetect via InputHandler

  TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
  TString configFile("Config_miweber_LMEE_pp.C");
  TString configLMEECutLib("LMEECutLib_miweber.C");
  TString configFilePath(configBasePath+configFile);
  TString configLMEECutLibPath(configBasePath+configLMEECutLib);

  //load dielectron configuration files
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))
    gROOT->LoadMacro(configLMEECutLibPath.Data());
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
    gROOT->LoadMacro(configFilePath.Data());

  // cut lib
  LMEECutLib* cutlib = new LMEECutLib();

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //AOD Usage currently tested with Input handler
  if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
    ::Info("AddTaskLMEEPbPb2011", "no dedicated AOD configuration");
  }
  else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
    ::Info("AddTaskLMEEPbPb2011AOD","switching on ESD specific code");
    bESDANA=kTRUE;
  }

  //create task and add it to the manager
  AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_pp");
  if (!hasMC) task->UsePhysicsSelection();

  //Add event filter
  Int_t triggerNames=(AliVEvent::kINT7+AliVEvent::kMB+AliVEvent::kINT8);//pp 2010/2011 Min Bias?
  task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kpp2010All));
  task->SetRejectPileup();
  // Note: event cuts are identical for all analysis 'cutDefinition's that run together!

  // Add the task to the manager
  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    //MB
    AliDielectron *diel_low = Config_miweber_pp(i,hasMC,bESDANA);
    if(!diel_low)continue;
    task->AddDielectron(diel_low);
    printf("successfully added AliDielectron: %s\n",diel_low->GetName());
  }//loop

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("miweber_LMEE_pp_tree",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         "AnalysisResults.root");

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("miweber_LMEE_pp_out",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         "AnalysisResults.root");

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("miweber_LMEE_pp_CF",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         "AnalysisResults.root");
  //                         "miweber_LMEE_pp_CF.root");

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("miweber_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         "AnalysisResults.root");

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

  return task;
}
<commit_msg>o updated macro (Michael Weber)<commit_after>AliAnalysisTask *AddTask_miweber_LMEE_pp(TString outputFileName = "AnalysisResult.root"){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_miweber_LMEE_pp", "No analysis manager found.");
    return 0;
  }

  Bool_t bESDANA=kFALSE; //Autodetect via InputHandler

  TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/");
  TString configFile("Config_miweber_LMEE_pp.C");
  TString configLMEECutLib("LMEECutLib_miweber.C");
  TString configFilePath(configBasePath+configFile);
  TString configLMEECutLibPath(configBasePath+configLMEECutLib);

  //load dielectron configuration files
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))
    gROOT->LoadMacro(configLMEECutLibPath.Data());
  if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
    gROOT->LoadMacro(configFilePath.Data());

  // cut lib
  LMEECutLib* cutlib = new LMEECutLib();

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //AOD Usage currently tested with Input handler
  if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
    ::Info("AddTaskLMEEPbPb2011", "no dedicated AOD configuration");
  }
  else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
    ::Info("AddTaskLMEEPbPb2011AOD","switching on ESD specific code");
    bESDANA=kTRUE;
  }

  //create task and add it to the manager
  AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData_miweber_pp");
  if (!hasMC) task->UsePhysicsSelection();

  //Add event filter
  Int_t triggerNames=(AliVEvent::kINT7+AliVEvent::kMB+AliVEvent::kINT8);//pp 2010/2011 Min Bias?
  task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kpp2010All));
  task->SetRejectPileup();
  // Note: event cuts are identical for all analysis 'cutDefinition's that run together!

  // Add the task to the manager
  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    //MB
    AliDielectron *diel_low = Config_miweber_pp(i,hasMC,bESDANA);
    if(!diel_low)continue;
    task->AddDielectron(diel_low);
    printf("successfully added AliDielectron: %s\n",diel_low->GetName());
  }//loop

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("miweber_LMEE_pp_tree",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("miweber_LMEE_pp_out",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("miweber_LMEE_pp_CF",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());
  //                         "miweber_LMEE_pp_CF.root");

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("miweber_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

  return task;
}
<|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.
 */
#include <activemq/connector/openwire/marshal/V2/MarshallerFactory.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQBytesMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQMapMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQObjectMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQQueueMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQStreamMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTempQueueMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTempTopicMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTextMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTopicMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/BrokerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/BrokerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionControlMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionErrorMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerControlMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ControlCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DataArrayResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DataResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DestinationInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DiscoveryEventMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ExceptionResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/FlushCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/IntegerResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalQueueAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTopicAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTraceMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTransactionMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/KeepAliveInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/LastPartialCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/LocalTransactionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageDispatchMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageDispatchNotificationMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessagePullMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/NetworkBridgeFilterMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/PartialCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ProducerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ProducerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/RemoveInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/RemoveSubscriptionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ReplayCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SessionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SessionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ShutdownInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SubscriptionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/TransactionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/WireFormatInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/XATransactionIdMarshaller.h>

/*
 *
 *  Command and marshalling code for OpenWire format for MarshallerFactory
 *
 *
 *  NOTE!: This file is autogenerated - do not modify!
 *         if you need to make a change, please see the Java Classes
 *         in the activemq-openwire-generator module
 *
 */

using namespace activemq;
using namespace activemq::connector;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::marshal;
using namespace activemq::connector::openwire::marshal::v2;

///////////////////////////////////////////////////////////////////////////////
void MarshallerFactory::configure( OpenWireFormat* format ) {
    format->addMarshaller( new ActiveMQBytesMessageMarshaller());
    format->addMarshaller( new ActiveMQMapMessageMarshaller());
    format->addMarshaller( new ActiveMQMessageMarshaller());
    format->addMarshaller( new ActiveMQObjectMessageMarshaller());
    format->addMarshaller( new ActiveMQQueueMarshaller());
    format->addMarshaller( new ActiveMQStreamMessageMarshaller());
    format->addMarshaller( new ActiveMQTempQueueMarshaller());
    format->addMarshaller( new ActiveMQTempTopicMarshaller());
    format->addMarshaller( new ActiveMQTextMessageMarshaller());
    format->addMarshaller( new ActiveMQTopicMarshaller());
    format->addMarshaller( new BrokerIdMarshaller());
    format->addMarshaller( new BrokerInfoMarshaller());
    format->addMarshaller( new ConnectionControlMarshaller());
    format->addMarshaller( new ConnectionErrorMarshaller());
    format->addMarshaller( new ConnectionIdMarshaller());
    format->addMarshaller( new ConnectionInfoMarshaller());
    format->addMarshaller( new ConsumerControlMarshaller());
    format->addMarshaller( new ConsumerIdMarshaller());
    format->addMarshaller( new ConsumerInfoMarshaller());
    format->addMarshaller( new ControlCommandMarshaller());
    format->addMarshaller( new DataArrayResponseMarshaller());
    format->addMarshaller( new DataResponseMarshaller());
    format->addMarshaller( new DestinationInfoMarshaller());
    format->addMarshaller( new DiscoveryEventMarshaller());
    format->addMarshaller( new ExceptionResponseMarshaller());
    format->addMarshaller( new FlushCommandMarshaller());
    format->addMarshaller( new IntegerResponseMarshaller());
    format->addMarshaller( new JournalQueueAckMarshaller());
    format->addMarshaller( new JournalTopicAckMarshaller());
    format->addMarshaller( new JournalTraceMarshaller());
    format->addMarshaller( new JournalTransactionMarshaller());
    format->addMarshaller( new KeepAliveInfoMarshaller());
    format->addMarshaller( new LastPartialCommandMarshaller());
    format->addMarshaller( new LocalTransactionIdMarshaller());
    format->addMarshaller( new MessageAckMarshaller());
    format->addMarshaller( new MessageDispatchMarshaller());
    format->addMarshaller( new MessageDispatchNotificationMarshaller());
    format->addMarshaller( new MessageIdMarshaller());
    format->addMarshaller( new MessagePullMarshaller());
    format->addMarshaller( new NetworkBridgeFilterMarshaller());
    format->addMarshaller( new PartialCommandMarshaller());
    format->addMarshaller( new ProducerIdMarshaller());
    format->addMarshaller( new ProducerInfoMarshaller());
    format->addMarshaller( new RemoveInfoMarshaller());
    format->addMarshaller( new RemoveSubscriptionInfoMarshaller());
    format->addMarshaller( new ReplayCommandMarshaller());
    format->addMarshaller( new ResponseMarshaller());
    format->addMarshaller( new SessionIdMarshaller());
    format->addMarshaller( new SessionInfoMarshaller());
    format->addMarshaller( new ShutdownInfoMarshaller());
    format->addMarshaller( new SubscriptionInfoMarshaller());
    format->addMarshaller( new TransactionInfoMarshaller());
    format->addMarshaller( new WireFormatInfoMarshaller());
    format->addMarshaller( new XATransactionIdMarshaller());
}

<commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-21<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.
 */
#include <activemq/connector/openwire/marshal/v2/MarshallerFactory.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQBytesMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQMapMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQObjectMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQQueueMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQStreamMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTempQueueMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTempTopicMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTextMessageMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ActiveMQTopicMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/BrokerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/BrokerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionControlMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionErrorMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConnectionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerControlMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ConsumerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ControlCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DataArrayResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DataResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DestinationInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/DiscoveryEventMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ExceptionResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/FlushCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/IntegerResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalQueueAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTopicAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTraceMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/JournalTransactionMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/KeepAliveInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/LastPartialCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/LocalTransactionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageAckMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageDispatchMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageDispatchNotificationMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessageIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/MessagePullMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/NetworkBridgeFilterMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/PartialCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ProducerIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ProducerInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/RemoveInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/RemoveSubscriptionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ReplayCommandMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ResponseMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SessionIdMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SessionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/ShutdownInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/SubscriptionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/TransactionInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/WireFormatInfoMarshaller.h>
#include <activemq/connector/openwire/marshal/v2/XATransactionIdMarshaller.h>

/*
 *
 *  Command and marshalling code for OpenWire format for MarshallerFactory
 *
 *
 *  NOTE!: This file is autogenerated - do not modify!
 *         if you need to make a change, please see the Java Classes
 *         in the activemq-openwire-generator module
 *
 */

using namespace activemq;
using namespace activemq::connector;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::marshal;
using namespace activemq::connector::openwire::marshal::v2;

///////////////////////////////////////////////////////////////////////////////
void MarshallerFactory::configure( OpenWireFormat* format ) {
    format->addMarshaller( new ActiveMQBytesMessageMarshaller());
    format->addMarshaller( new ActiveMQMapMessageMarshaller());
    format->addMarshaller( new ActiveMQMessageMarshaller());
    format->addMarshaller( new ActiveMQObjectMessageMarshaller());
    format->addMarshaller( new ActiveMQQueueMarshaller());
    format->addMarshaller( new ActiveMQStreamMessageMarshaller());
    format->addMarshaller( new ActiveMQTempQueueMarshaller());
    format->addMarshaller( new ActiveMQTempTopicMarshaller());
    format->addMarshaller( new ActiveMQTextMessageMarshaller());
    format->addMarshaller( new ActiveMQTopicMarshaller());
    format->addMarshaller( new BrokerIdMarshaller());
    format->addMarshaller( new BrokerInfoMarshaller());
    format->addMarshaller( new ConnectionControlMarshaller());
    format->addMarshaller( new ConnectionErrorMarshaller());
    format->addMarshaller( new ConnectionIdMarshaller());
    format->addMarshaller( new ConnectionInfoMarshaller());
    format->addMarshaller( new ConsumerControlMarshaller());
    format->addMarshaller( new ConsumerIdMarshaller());
    format->addMarshaller( new ConsumerInfoMarshaller());
    format->addMarshaller( new ControlCommandMarshaller());
    format->addMarshaller( new DataArrayResponseMarshaller());
    format->addMarshaller( new DataResponseMarshaller());
    format->addMarshaller( new DestinationInfoMarshaller());
    format->addMarshaller( new DiscoveryEventMarshaller());
    format->addMarshaller( new ExceptionResponseMarshaller());
    format->addMarshaller( new FlushCommandMarshaller());
    format->addMarshaller( new IntegerResponseMarshaller());
    format->addMarshaller( new JournalQueueAckMarshaller());
    format->addMarshaller( new JournalTopicAckMarshaller());
    format->addMarshaller( new JournalTraceMarshaller());
    format->addMarshaller( new JournalTransactionMarshaller());
    format->addMarshaller( new KeepAliveInfoMarshaller());
    format->addMarshaller( new LastPartialCommandMarshaller());
    format->addMarshaller( new LocalTransactionIdMarshaller());
    format->addMarshaller( new MessageAckMarshaller());
    format->addMarshaller( new MessageDispatchMarshaller());
    format->addMarshaller( new MessageDispatchNotificationMarshaller());
    format->addMarshaller( new MessageIdMarshaller());
    format->addMarshaller( new MessagePullMarshaller());
    format->addMarshaller( new NetworkBridgeFilterMarshaller());
    format->addMarshaller( new PartialCommandMarshaller());
    format->addMarshaller( new ProducerIdMarshaller());
    format->addMarshaller( new ProducerInfoMarshaller());
    format->addMarshaller( new RemoveInfoMarshaller());
    format->addMarshaller( new RemoveSubscriptionInfoMarshaller());
    format->addMarshaller( new ReplayCommandMarshaller());
    format->addMarshaller( new ResponseMarshaller());
    format->addMarshaller( new SessionIdMarshaller());
    format->addMarshaller( new SessionInfoMarshaller());
    format->addMarshaller( new ShutdownInfoMarshaller());
    format->addMarshaller( new SubscriptionInfoMarshaller());
    format->addMarshaller( new TransactionInfoMarshaller());
    format->addMarshaller( new WireFormatInfoMarshaller());
    format->addMarshaller( new XATransactionIdMarshaller());
}

<|endoftext|>


<commit_before><commit_msg>Streamlined sun update changes. Added night/day detection<commit_after><|endoftext|>


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

// bzflag common header
#include "common.h"

// interface header
#include "LaserSceneNode.h"

// system headers
#include <math.h>

// common implementation headers
#include "StateDatabase.h"
#include "BZDBCache.h"

// FIXME (SceneRenderer.cxx is in src/bzflag)
#include "SceneRenderer.h"

const GLfloat		LaserRadius = 0.1f;

LaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) :
				texturing(false),
				renderNode(this)
{
  // prepare rendering info
  azimuth = (float)(180.0 / M_PI*atan2f(forward[1], forward[0]));
  elevation = (float)(-180.0 / M_PI*atan2f(forward[2], hypotf(forward[0],forward[1])));
  length = hypotf(forward[0], hypotf(forward[1], forward[2]));

  // setup sphere
  setCenter(pos);
  setRadius(length * length);

  OpenGLGStateBuilder builder(gstate);
  builder.setCulling(GL_NONE);
  gstate = builder.getState();
}

LaserSceneNode::~LaserSceneNode()
{
  // do nothing
}

void			LaserSceneNode::setTexture(const int texture)
{
  OpenGLGStateBuilder builder(gstate);
  builder.setTexture(texture);
  builder.enableTexture(texture>=0);
  gstate = builder.getState();
}

bool			LaserSceneNode::cull(const ViewFrustum&) const
{
  // no culling
  return false;
}

void			LaserSceneNode::notifyStyleChange()
{
  texturing = BZDBCache::texture && BZDBCache::blend;
  OpenGLGStateBuilder builder(gstate);
  builder.enableTexture(texturing);
  if (BZDBCache::blend) {
    // add in contribution from laser
    builder.setBlending(GL_SRC_ALPHA, GL_ONE);
    builder.setSmoothing(BZDB.isTrue("smooth"));
  }
  else {
    builder.resetBlending();
    builder.setSmoothing(false);
  }
  gstate = builder.getState();
}

void			LaserSceneNode::addRenderNodes(
				SceneRenderer& renderer)
{
  renderer.addRenderNode(&renderNode, &gstate);
}

//
// LaserSceneNode::LaserRenderNode
//

GLfloat			LaserSceneNode::LaserRenderNode::geom[6][2];

LaserSceneNode::LaserRenderNode::LaserRenderNode(
				const LaserSceneNode* _sceneNode) :
				sceneNode(_sceneNode)
{
  // initialize geometry if first instance
  static bool init = false;
  if (!init) {
    init = true;
    for (int i = 0; i < 6; i++) {
      geom[i][0] = (float)(-LaserRadius * cosf(2.0 * M_PI * float(i) / 6.0));
      geom[i][1] =  (float)(LaserRadius * sinf(2.0 * M_PI * float(i) / 6.0));
    }
  }
}

LaserSceneNode::LaserRenderNode::~LaserRenderNode()
{
  // do nothing
}

void			LaserSceneNode::LaserRenderNode::render()
{
  const GLfloat length = sceneNode->length;
  const GLfloat* sphere = sceneNode->getSphere();
  glPushMatrix();
    glTranslatef(sphere[0], sphere[1], sphere[2]);
    glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f);
    glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f);

    if (sceneNode->texturing) {
      myColor3f(1.0f, 1.0f, 1.0f);
      glBegin(GL_TRIANGLE_FAN);
	glTexCoord2f(0.5f,  0.5f);
	glVertex3f(  0.0f,  0.0f,  0.0f);
	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
	glVertex3f(  0.0f,  1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f, -1.0f);
	glVertex3f(  0.0f, -1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
      glEnd();

      glBegin(GL_QUADS);
	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
	glTexCoord2f(0.0f,  1.0f);
	glVertex3f(length,  0.0f,  1.0f);
	glTexCoord2f(1.0f,  1.0f);
	glVertex3f(length,  0.0f, -1.0f);
	glTexCoord2f(1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f, -1.0f);

	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  1.0f,  0.0f);
	glTexCoord2f(0.0f,  1.0f);
	glVertex3f(length,  1.0f,  0.0f);
	glTexCoord2f(1.0f,  1.0f);
	glVertex3f(length, -1.0f,  0.0f);
	glTexCoord2f(1.0f,  0.0f);
	glVertex3f(  0.0f, -1.0f,  0.0f);
      glEnd();
    }

    else {
      // draw beam
      myColor4f(1.0f, 0.25f, 0.0f, 0.85f);
      glBegin(GL_QUAD_STRIP);
	glVertex3f(  0.0f, geom[0][0], geom[0][1]);
	glVertex3f(length, geom[0][0], geom[0][1]);
	glVertex3f(  0.0f, geom[1][0], geom[1][1]);
	glVertex3f(length, geom[1][0], geom[1][1]);
	glVertex3f(  0.0f, geom[2][0], geom[2][1]);
	glVertex3f(length, geom[2][0], geom[2][1]);
	glVertex3f(  0.0f, geom[3][0], geom[3][1]);
	glVertex3f(length, geom[3][0], geom[3][1]);
	glVertex3f(  0.0f, geom[4][0], geom[4][1]);
	glVertex3f(length, geom[4][0], geom[4][1]);
	glVertex3f(  0.0f, geom[5][0], geom[5][1]);
	glVertex3f(length, geom[5][0], geom[5][1]);
	glVertex3f(  0.0f, geom[0][0], geom[0][1]);
	glVertex3f(length, geom[0][0], geom[0][1]);
      glEnd();

      // also draw a line down the middle (so the beam is visible even
      // if very far away).  this will also give the beam an extra bright
      // center.
      glBegin(GL_LINES);
	glVertex3f(  0.0f, 0.0f, 0.0f);
	glVertex3f(length, 0.0f, 0.0f);
      glEnd();
    }

  glPopMatrix();
}

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

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

// bzflag common header
#include "common.h"

// interface header
#include "LaserSceneNode.h"

// system headers
#include <math.h>

// common implementation headers
#include "StateDatabase.h"
#include "BZDBCache.h"

// FIXME (SceneRenderer.cxx is in src/bzflag)
#include "SceneRenderer.h"

const GLfloat		LaserRadius = 0.1f;

LaserSceneNode::LaserSceneNode(const GLfloat pos[3], const GLfloat forward[3]) :
				texturing(false),
				renderNode(this)
{
  // prepare rendering info
  azimuth = (float)(180.0 / M_PI*atan2f(forward[1], forward[0]));
  elevation = (float)(-180.0 / M_PI*atan2f(forward[2], hypotf(forward[0],forward[1])));
  length = hypotf(forward[0], hypotf(forward[1], forward[2]));

  // setup sphere
  setCenter(pos);
  setRadius(length * length);

  OpenGLGStateBuilder builder(gstate);
  builder.setCulling(GL_NONE);
  gstate = builder.getState();
}

LaserSceneNode::~LaserSceneNode()
{
  // do nothing
}

void			LaserSceneNode::setTexture(const int texture)
{
  OpenGLGStateBuilder builder(gstate);
  builder.setTexture(texture);
  builder.enableTexture(texture>=0);
  gstate = builder.getState();
}

bool			LaserSceneNode::cull(const ViewFrustum&) const
{
  // no culling
  return false;
}

void			LaserSceneNode::notifyStyleChange()
{
  texturing = BZDBCache::texture && BZDBCache::blend;
  OpenGLGStateBuilder builder(gstate);
  builder.enableTexture(texturing);
  if (BZDBCache::blend) {
    // add in contribution from laser
    builder.setBlending(GL_SRC_ALPHA, GL_ONE);
    builder.setSmoothing(BZDB.isTrue("smooth"));
  }
  else {
    builder.resetBlending();
    builder.setSmoothing(false);
  }
  gstate = builder.getState();
}

void			LaserSceneNode::addRenderNodes(
				SceneRenderer& renderer)
{
  renderer.addRenderNode(&renderNode, &gstate);
}

//
// LaserSceneNode::LaserRenderNode
//

GLfloat			LaserSceneNode::LaserRenderNode::geom[6][2];

LaserSceneNode::LaserRenderNode::LaserRenderNode(
				const LaserSceneNode* _sceneNode) :
				sceneNode(_sceneNode)
{
  // initialize geometry if first instance
  static bool init = false;
  if (!init) {
    init = true;
    for (int i = 0; i < 6; i++) {
      geom[i][0] = -LaserRadius * cosf((float)(2.0 * M_PI * double(i) / 6.0));
      geom[i][1] =  LaserRadius * sinf((float)(2.0 * M_PI * double(i) / 6.0));
    }
  }
}

LaserSceneNode::LaserRenderNode::~LaserRenderNode()
{
  // do nothing
}

void			LaserSceneNode::LaserRenderNode::render()
{
  const GLfloat length = sceneNode->length;
  const GLfloat* sphere = sceneNode->getSphere();
  glPushMatrix();
    glTranslatef(sphere[0], sphere[1], sphere[2]);
    glRotatef(sceneNode->azimuth, 0.0f, 0.0f, 1.0f);
    glRotatef(sceneNode->elevation, 0.0f, 1.0f, 0.0f);

    if (sceneNode->texturing) {
      myColor3f(1.0f, 1.0f, 1.0f);
      glBegin(GL_TRIANGLE_FAN);
	glTexCoord2f(0.5f,  0.5f);
	glVertex3f(  0.0f,  0.0f,  0.0f);
	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
	glVertex3f(  0.0f,  1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f, -1.0f);
	glVertex3f(  0.0f, -1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
      glEnd();

      glBegin(GL_QUADS);
	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f,  1.0f);
	glTexCoord2f(0.0f,  1.0f);
	glVertex3f(length,  0.0f,  1.0f);
	glTexCoord2f(1.0f,  1.0f);
	glVertex3f(length,  0.0f, -1.0f);
	glTexCoord2f(1.0f,  0.0f);
	glVertex3f(  0.0f,  0.0f, -1.0f);

	glTexCoord2f(0.0f,  0.0f);
	glVertex3f(  0.0f,  1.0f,  0.0f);
	glTexCoord2f(0.0f,  1.0f);
	glVertex3f(length,  1.0f,  0.0f);
	glTexCoord2f(1.0f,  1.0f);
	glVertex3f(length, -1.0f,  0.0f);
	glTexCoord2f(1.0f,  0.0f);
	glVertex3f(  0.0f, -1.0f,  0.0f);
      glEnd();
    }

    else {
      // draw beam
      myColor4f(1.0f, 0.25f, 0.0f, 0.85f);
      glBegin(GL_QUAD_STRIP);
	glVertex3f(  0.0f, geom[0][0], geom[0][1]);
	glVertex3f(length, geom[0][0], geom[0][1]);
	glVertex3f(  0.0f, geom[1][0], geom[1][1]);
	glVertex3f(length, geom[1][0], geom[1][1]);
	glVertex3f(  0.0f, geom[2][0], geom[2][1]);
	glVertex3f(length, geom[2][0], geom[2][1]);
	glVertex3f(  0.0f, geom[3][0], geom[3][1]);
	glVertex3f(length, geom[3][0], geom[3][1]);
	glVertex3f(  0.0f, geom[4][0], geom[4][1]);
	glVertex3f(length, geom[4][0], geom[4][1]);
	glVertex3f(  0.0f, geom[5][0], geom[5][1]);
	glVertex3f(length, geom[5][0], geom[5][1]);
	glVertex3f(  0.0f, geom[0][0], geom[0][1]);
	glVertex3f(length, geom[0][0], geom[0][1]);
      glEnd();

      // also draw a line down the middle (so the beam is visible even
      // if very far away).  this will also give the beam an extra bright
      // center.
      glBegin(GL_LINES);
	glVertex3f(  0.0f, 0.0f, 0.0f);
	glVertex3f(length, 0.0f, 0.0f);
      glEnd();
    }

  glPopMatrix();
}

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

<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*! @file
	@brief  Emulator Tools クラス @n
			Copyright 2017 Kunihito Hiramatsu
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "widgets/widget_terminal.hpp"

#include "emu/cpu/nes6502.h"

#include "emu/cpu/dis6502.hpp"

namespace emu {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	エミュレーター Tools クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class tools {

		static gui::widget_terminal*	terminal_;

		cpu::dis6502	dis_;

		uint16_t	disasm_org_;
		uint16_t	dump_org_;

		uint16_t	adr_;
		uint16_t 	ncnt_;

		bool		enable_;

		void dump_() {
			if(ncnt_ > 0) { dump_org_ = adr_; adr_ = 0; ncnt_ = 0; }
			std::string list = dis_.dump(dump_org_);
			terminal_->output(list + "\n");
			++dump_org_;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		tools() : disasm_org_(0), dump_org_(0), adr_(0), ncnt_(0), enable_(false) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  ターミナル・コンテキストを設定
			@param[in]	term	ターミナル・コンテキスト
		*/
		//-----------------------------------------------------------------//
		static void set_terminal(gui::widget_terminal* t) {
			terminal_ = t;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  出力
		*/
		//-----------------------------------------------------------------//
		static void put(const char* text) {
			if(terminal_ == nullptr) return;
			terminal_->output(text);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  初期化
		*/
		//-----------------------------------------------------------------//
		void init()
		{
			dis_.at_getbyte() = nes6502_getbyte;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  許可
			@param[in]	f	不許可なら「false」
		*/
		//-----------------------------------------------------------------//
		void enable(bool f = true) { enable_ = f; }

		//-----------------------------------------------------------------//
		/*!
			@brief  コマンド
			@param[in]	cmd	コマンド
		*/
		//-----------------------------------------------------------------//
		void command(const std::string& cmd)
		{
			if(cmd == "state") {
				if(enable_) {
					terminal_->output("ROM active\n");
				} else {
					terminal_->output("ROM not active\n");
				}
				return;
			}

			if(!enable_) return;

			adr_ = 0;
			ncnt_ = 0;
			bool dump = true;
			for(char ch : cmd) {
				if(ch == ' ') {
					dump_();
				} else if(ch >= '0' && ch <= '9') {
					adr_ <<= 4;
					adr_ += ch - '0';
					++ncnt_;
				} else if(ch >= 'A' && ch <= 'F') {
					adr_ <<= 4;
					adr_ += ch - 'A' + 10;
					++ncnt_;
				} else if(ch >= 'a' && ch <= 'f') {
					adr_ <<= 4;
					adr_ += ch - 'a' + 10;
					++ncnt_;
				} else {
					if(ch == 'l' || ch == 'L') {
						if(ncnt_ > 0) { disasm_org_ = adr_; adr_ = 0; ncnt_ = 0; }
						for(int i = 0; i < 16; ++i) {
							std::string list = dis_.disasm(disasm_org_);
							terminal_->output(list + "\n");
							disasm_org_ = dis_.get_pc();
						}
					} else {
						std::string s;
						s = "Command error: '";
						terminal_->output(s + ch + "'\n");
					}
					dump = false;
				}
			}
			if(dump) {
				dump_();
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ツール・サービス
		*/
		//-----------------------------------------------------------------//
		void service()
		{
		}
	};
}
<commit_msg>update<commit_after>#pragma once
//=====================================================================//
/*! @file
	@brief  Emulator Tools クラス @n
			Copyright 2017 Kunihito Hiramatsu
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "widgets/widget_terminal.hpp"

#include "emu/cpu/nes6502.h"

#include "emu/cpu/dis6502.hpp"
#include "emu/cpu/nes6502.hpp"

namespace emu {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	エミュレーター Tools クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class tools {

		static gui::widget_terminal*	terminal_;

		cpu::dis6502	dis_;

		uint16_t	disasm_org_;
		uint16_t	dump_org_;

		uint16_t	adr_;
		uint16_t 	ncnt_;

		bool		enable_;

		void dump_() {
			if(ncnt_ > 0) { dump_org_ = adr_; adr_ = 0; ncnt_ = 0; }
			std::string list = dis_.dump(dump_org_);
			terminal_->output(list + "\n");
			++dump_org_;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		tools() : disasm_org_(0), dump_org_(0), adr_(0), ncnt_(0), enable_(false) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  ターミナル・コンテキストを設定
			@param[in]	term	ターミナル・コンテキスト
		*/
		//-----------------------------------------------------------------//
		static void set_terminal(gui::widget_terminal* t) {
			terminal_ = t;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  出力
		*/
		//-----------------------------------------------------------------//
		static void put(const char* text) {
			if(terminal_ == nullptr) return;
			terminal_->output(text);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  初期化
		*/
		//-----------------------------------------------------------------//
		void init()
		{
			dis_.at_getbyte() = nes6502_getbyte;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  許可
			@param[in]	f	不許可なら「false」
		*/
		//-----------------------------------------------------------------//
		void enable(bool f = true) { enable_ = f; }

		//-----------------------------------------------------------------//
		/*!
			@brief  コマンド
			@param[in]	cmd	コマンド
		*/
		//-----------------------------------------------------------------//
		void command(const std::string& cmd)
		{
			if(cmd == "state") {
				if(enable_) {
					terminal_->output("ROM active\n");
				} else {
					terminal_->output("ROM not active\n");
				}
				return;
			}

			if(!enable_) return;

			adr_ = 0;
			ncnt_ = 0;
			bool dump = true;
			for(char ch : cmd) {
				if(ch == ' ') {
					dump_();
				} else if(ch >= '0' && ch <= '9') {
					adr_ <<= 4;
					adr_ += ch - '0';
					++ncnt_;
				} else if(ch >= 'A' && ch <= 'F') {
					adr_ <<= 4;
					adr_ += ch - 'A' + 10;
					++ncnt_;
				} else if(ch >= 'a' && ch <= 'f') {
					adr_ <<= 4;
					adr_ += ch - 'a' + 10;
					++ncnt_;
				} else {
					if(ch == 'l' || ch == 'L') {
						if(ncnt_ > 0) { disasm_org_ = adr_; adr_ = 0; ncnt_ = 0; }
						for(int i = 0; i < 16; ++i) {
							std::string list = dis_.disasm(disasm_org_);
							terminal_->output(list + "\n");
							disasm_org_ = dis_.get_pc();
						}
					} else {
						std::string s;
						s = "Command error: '";
						terminal_->output(s + ch + "'\n");
					}
					dump = false;
				}
			}
			if(dump) {
				dump_();
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ツール・サービス
		*/
		//-----------------------------------------------------------------//
		void service()
		{
		}
	};
}
<|endoftext|>