text stringlengths 54 60.6k |
|---|
<commit_before>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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.
*/
#include "Properties.h"
#include "logging.h"
#include "utils.h" // tcam_xioctl
#include <algorithm> // find_if
#include <cstring>
using namespace tcam;
PropertyString::PropertyString (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyString::~PropertyString ()
{}
std::string PropertyString::get_default () const
{
return prop.value.s.default_value;
}
bool PropertyString::set_value (const std::string& new_value)
{
if (is_read_only())
{
return false;
}
if (new_value.size() > sizeof(this->prop.value.s.value))
return false;
memcpy(this->prop.value.s.value, new_value.c_str(), sizeof(this->prop.value.s.value));
notify_impl();
return true;
}
std::string PropertyString::get_value () const
{
return prop.value.s.value;
}
PropertyEnumeration::PropertyEnumeration (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
const std::map<std::string, int>& values,
VALUE_TYPE t)
: Property(prop, values, t)
{
impl = prop_impl;
}
PropertyEnumeration::~PropertyEnumeration ()
{}
std::vector<std::string> PropertyEnumeration::get_values () const
{
std::vector<std::string> vec;
for (auto m : string_map)
{
vec.push_back(std::get<0>(m));
}
return vec;
}
std::string PropertyEnumeration::get_default () const
{
return "";
}
bool PropertyEnumeration::set_value (const std::string& new_value)
{
if (is_read_only())
{
return false;
}
auto element = string_map.find(new_value);
if (element == string_map.end())
{
return false;
}
prop.value.i.value = element->second;
notify_impl();
return false;
}
std::string PropertyEnumeration::get_value () const
{
for (const auto& s : string_map)
{
if (prop.value.i.value == s.second)
{
return s.first;
}
}
return "";
}
std::map<std::string, int> PropertyEnumeration::get_mapping () const
{
return string_map;
}
PropertyBoolean::PropertyBoolean (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyBoolean::~PropertyBoolean ()
{}
bool PropertyBoolean::get_default () const
{
return prop.value.b.default_value;
}
bool PropertyBoolean::set_value (bool value)
{
if (is_read_only())
{
return false;
}
prop.value.b.value = value;
notify_impl();
return true;
}
bool PropertyBoolean::get_value () const
{
return prop.value.b.value;
}
PropertyInteger::PropertyInteger (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property (prop, t)
{
impl = prop_impl;
}
PropertyInteger::~PropertyInteger ()
{}
int64_t PropertyInteger::get_default () const
{
return prop.value.i.default_value;
}
int64_t PropertyInteger::get_min () const
{
return this->prop.value.i.min;
}
int64_t PropertyInteger::get_max () const
{
return this->prop.value.i.max;
}
int64_t PropertyInteger::get_step () const
{
return this->prop.value.i.step;
}
int64_t PropertyInteger::get_value () const
{
return this->prop.value.i.value;
}
bool PropertyInteger::set_value (int64_t new_value)
{
// if (is_read_only())
// return false;
tcam_value_int& i = this->prop.value.i;
if (i.min > new_value || i.max < new_value)
return false;
if (i.step > 0 && new_value % i.step != 0)
{
return false;
}
i.value = new_value;
notify_impl();
return true;
}
PropertyDouble::PropertyDouble (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyDouble::~PropertyDouble ()
{}
double PropertyDouble::get_default () const
{
return prop.value.d.default_value;
}
double PropertyDouble::get_min () const
{
return this->prop.value.d.min;
}
double PropertyDouble::get_max () const
{
return this->prop.value.d.max;
}
double PropertyDouble::get_step () const
{
return this->prop.value.d.step;
}
double PropertyDouble::get_value () const
{
return this->prop.value.d.value;
}
bool PropertyDouble::set_value (double new_value)
{
if (is_read_only())
{
return false;
}
tcam_value_double& d = this->prop.value.d;
if (d.min > new_value || d.max < new_value)
{
return false;
}
d.value = new_value;
notify_impl();
return false;
}
PropertyButton::PropertyButton (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyButton::~PropertyButton ()
{}
bool PropertyButton::activate ()
{
if (is_read_only())
return false;
notify_impl();
return true;
}
<commit_msg>Add default value retrieval for enumerations<commit_after>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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.
*/
#include "Properties.h"
#include "logging.h"
#include "utils.h" // tcam_xioctl
#include <algorithm> // find_if
#include <cstring>
using namespace tcam;
PropertyString::PropertyString (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyString::~PropertyString ()
{}
std::string PropertyString::get_default () const
{
return prop.value.s.default_value;
}
bool PropertyString::set_value (const std::string& new_value)
{
if (is_read_only())
{
return false;
}
if (new_value.size() > sizeof(this->prop.value.s.value))
return false;
memcpy(this->prop.value.s.value, new_value.c_str(), sizeof(this->prop.value.s.value));
notify_impl();
return true;
}
std::string PropertyString::get_value () const
{
return prop.value.s.value;
}
PropertyEnumeration::PropertyEnumeration (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
const std::map<std::string, int>& values,
VALUE_TYPE t)
: Property(prop, values, t)
{
impl = prop_impl;
}
PropertyEnumeration::~PropertyEnumeration ()
{}
std::vector<std::string> PropertyEnumeration::get_values () const
{
std::vector<std::string> vec;
for (auto m : string_map)
{
vec.push_back(std::get<0>(m));
}
return vec;
}
std::string PropertyEnumeration::get_default () const
{
for (const auto& s : string_map)
{
if (prop.value.i.default_value == s.second)
{
return s.first;
}
}
return "";
}
bool PropertyEnumeration::set_value (const std::string& new_value)
{
if (is_read_only())
{
return false;
}
auto element = string_map.find(new_value);
if (element == string_map.end())
{
return false;
}
prop.value.i.value = element->second;
notify_impl();
return false;
}
std::string PropertyEnumeration::get_value () const
{
for (const auto& s : string_map)
{
if (prop.value.i.value == s.second)
{
return s.first;
}
}
return "";
}
std::map<std::string, int> PropertyEnumeration::get_mapping () const
{
return string_map;
}
PropertyBoolean::PropertyBoolean (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyBoolean::~PropertyBoolean ()
{}
bool PropertyBoolean::get_default () const
{
return prop.value.b.default_value;
}
bool PropertyBoolean::set_value (bool value)
{
if (is_read_only())
{
return false;
}
prop.value.b.value = value;
notify_impl();
return true;
}
bool PropertyBoolean::get_value () const
{
return prop.value.b.value;
}
PropertyInteger::PropertyInteger (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property (prop, t)
{
impl = prop_impl;
}
PropertyInteger::~PropertyInteger ()
{}
int64_t PropertyInteger::get_default () const
{
return prop.value.i.default_value;
}
int64_t PropertyInteger::get_min () const
{
return this->prop.value.i.min;
}
int64_t PropertyInteger::get_max () const
{
return this->prop.value.i.max;
}
int64_t PropertyInteger::get_step () const
{
return this->prop.value.i.step;
}
int64_t PropertyInteger::get_value () const
{
return this->prop.value.i.value;
}
bool PropertyInteger::set_value (int64_t new_value)
{
// if (is_read_only())
// return false;
tcam_value_int& i = this->prop.value.i;
if (i.min > new_value || i.max < new_value)
return false;
if (i.step > 0 && new_value % i.step != 0)
{
return false;
}
i.value = new_value;
notify_impl();
return true;
}
PropertyDouble::PropertyDouble (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyDouble::~PropertyDouble ()
{}
double PropertyDouble::get_default () const
{
return prop.value.d.default_value;
}
double PropertyDouble::get_min () const
{
return this->prop.value.d.min;
}
double PropertyDouble::get_max () const
{
return this->prop.value.d.max;
}
double PropertyDouble::get_step () const
{
return this->prop.value.d.step;
}
double PropertyDouble::get_value () const
{
return this->prop.value.d.value;
}
bool PropertyDouble::set_value (double new_value)
{
if (is_read_only())
{
return false;
}
tcam_value_double& d = this->prop.value.d;
if (d.min > new_value || d.max < new_value)
{
return false;
}
d.value = new_value;
notify_impl();
return false;
}
PropertyButton::PropertyButton (std::shared_ptr<PropertyImpl> prop_impl,
const tcam_device_property& prop,
VALUE_TYPE t)
: Property(prop, t)
{
impl = prop_impl;
}
PropertyButton::~PropertyButton ()
{}
bool PropertyButton::activate ()
{
if (is_read_only())
return false;
notify_impl();
return true;
}
<|endoftext|> |
<commit_before>#include <array>
#include "core/image.h"
#include "core/io.h"
#include "core/raytracer.h"
#include "core/argparse.h"
using namespace euphoria::core;
int
main(int argc, char* argv[])
{
auto image_width = 200;
auto image_height = 100;
int number_of_samples = 100;
auto parser = argparse::Parser {"euphoria raytracer"};
parser.AddSimple("-width", &image_width).Help("image width");
parser.AddSimple("-height", &image_height).Help("image height");
parser.AddSimple("-samples", &number_of_samples).Help("number of samples (anitaliasing)");
if(parser.Parse(argc, argv) != argparse::ParseResult::Ok)
{
return -1;
}
Image image;
image.SetupNoAlphaSupport(image_width, image_height);
raytracer::Scene scene;
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(0.0f, 0.0f, -1.0f),
raytracer::CreateDiffuseMaterial
(
Rgb(0.8f, 0.3f, 0.3f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{100.0f},
vec3f(0.0f, -100.5f, -1.0f),
raytracer::CreateDiffuseMaterial
(
Rgb(0.8f, 0.8f, 0.0f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(1.0f, 0.0f, -1.0f),
raytracer::CreateMetalMaterial
(
Rgb(0.8f, 0.6f, 0.2f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(-1.0f, 0.0f, -1.0f),
raytracer::CreateMetalMaterial
(
Rgb(0.8f, 0.8f, 0.8f)
)
)
);
raytracer::Raytrace(&image, scene, number_of_samples);
io::ChunkToFile(image.Write(ImageWriteFormat::PNG), "raytracer.png");
return 0;
}
<commit_msg>printing raytracing time<commit_after>#include <array>
#include "core/image.h"
#include "core/io.h"
#include "core/raytracer.h"
#include "core/argparse.h"
#include "core/timepoint.h"
using namespace euphoria::core;
int
main(int argc, char* argv[])
{
auto image_width = 200;
auto image_height = 100;
int number_of_samples = 100;
auto parser = argparse::Parser {"euphoria raytracer"};
parser.AddSimple("-width", &image_width).Help("image width");
parser.AddSimple("-height", &image_height).Help("image height");
parser.AddSimple("-samples", &number_of_samples).Help("number of samples (anitaliasing)");
if(parser.Parse(argc, argv) != argparse::ParseResult::Ok)
{
return -1;
}
Image image;
image.SetupNoAlphaSupport(image_width, image_height);
raytracer::Scene scene;
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(0.0f, 0.0f, -1.0f),
raytracer::CreateDiffuseMaterial
(
Rgb(0.8f, 0.3f, 0.3f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{100.0f},
vec3f(0.0f, -100.5f, -1.0f),
raytracer::CreateDiffuseMaterial
(
Rgb(0.8f, 0.8f, 0.0f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(1.0f, 0.0f, -1.0f),
raytracer::CreateMetalMaterial
(
Rgb(0.8f, 0.6f, 0.2f)
)
)
);
scene.objects.push_back
(
raytracer::CreateSphere
(
Sphere{0.5f},
vec3f(-1.0f, 0.0f, -1.0f),
raytracer::CreateMetalMaterial
(
Rgb(0.8f, 0.8f, 0.8f)
)
)
);
const auto start = Now();
raytracer::Raytrace(&image, scene, number_of_samples);
const auto end = Now();
const auto seconds = SecondsBetween(start, end);
std::cout << "Rendering took " << seconds << " seconds.\n";
io::ChunkToFile(image.Write(ImageWriteFormat::PNG), "raytracer.png");
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc.
// 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.
// * Neither the name of Google Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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
// OWNER 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 "utils/logging/operations.hpp"
extern "C" {
#include <unistd.h>
}
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "utils/datetime.hpp"
#include "utils/format/macros.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/stream.hpp"
namespace datetime = utils::datetime;
namespace fs = utils::fs;
namespace logging = utils::logging;
using utils::none;
using utils::optional;
/// The general idea for the application-wide logging goes like this:
///
/// 1. The application starts. Logging is initialized to capture _all_ log
/// messages into memory regardless of their level by issuing a call to the
/// set_inmemory() function.
///
/// 2. The application offers the user a way to select the logging level and a
/// file into which to store the log.
///
/// 3. The application calls set_persistency providing a new log level and a log
/// file. This must be done as early as possible, to minimize the chances of an
/// early crash not capturing any logs.
///
/// 4. At this point, any log messages stored into memory are flushed to disk
/// respecting the provided log level.
///
/// 5. The internal state of the logging module is updated to only capture
/// messages that are of the provided log level (or below) and is configured to
/// directly send messages to disk.
///
/// 6. The user may choose to call set_inmemory() again at a later stage, which
/// will cause the log to be flushed and messages to be recorded in memory
/// again. This is useful in case the logs are being sent to either stdout or
/// stderr and the process forks and wants to keep those child channels
/// unpolluted.
///
/// The call to set_inmemory() should only be performed by the user-facing
/// application. Tests should skip this call so that the logging messages go to
/// stderr by default, thus generating a useful log to debug the tests.
namespace {
/// Current log level.
static logging::level log_level = logging::level_debug;
/// Indicates whether set_persistency() will be called automatically or not.
static bool auto_set_persistency = true;
/// First time recorded by the logging module.
static optional< datetime::timestamp > first_timestamp = none;
/// In-memory record of log entries before persistency is enabled.
static std::vector< std::pair< logging::level, std::string > > backlog;
/// Stream to the currently open log file.
static std::auto_ptr< std::ostream > logfile;
/// Constant string to strftime to format timestamps.
static const char* timestamp_format = "%Y%m%d-%H%M%S";
/// Converts a level to a printable character.
///
/// \param level The level to convert.
///
/// \return The printable character, to be used in log messages.
static char
level_to_char(const logging::level level)
{
switch (level) {
case logging::level_error: return 'E';
case logging::level_warning: return 'W';
case logging::level_info: return 'I';
case logging::level_debug: return 'D';
default: UNREACHABLE;
}
}
} // anonymous namespace
/// Generates a standard log name.
///
/// This always adds the same timestamp to the log name for a particular run.
/// Also, the timestamp added to the file name corresponds to the first
/// timestamp recorded by the module; it does not necessarily contain the
/// current value of "now".
///
/// \param logdir The path to the directory in which to place the log.
/// \param progname The name of the program that is generating the log.
fs::path
logging::generate_log_name(const fs::path& logdir, const std::string& progname)
{
if (!first_timestamp)
first_timestamp = datetime::timestamp::now();
// Update doc/troubleshooting.texi if you change the name format.
return logdir / (F("%s.%s.log") % progname %
first_timestamp.get().strftime(timestamp_format));
}
/// Logs an entry to the log file.
///
/// If the log is not yet set to persistent mode, the entry is recorded in the
/// in-memory backlog. Otherwise, it is just written to disk.
///
/// \param message_level The level of the entry.
/// \param file The file from which the log message is generated.
/// \param line The line from which the log message is generated.
/// \param user_message The raw message to store.
void
logging::log(const level message_level, const char* file, const int line,
const std::string& user_message)
{
const datetime::timestamp now = datetime::timestamp::now();
if (!first_timestamp)
first_timestamp = now;
if (auto_set_persistency) {
// These values are hardcoded here for testing purposes. The
// application should call set_inmemory() by itself during
// initialization to avoid this, so that it has explicit control on how
// the call to set_persistency() happens.
set_persistency("debug", fs::path("/dev/stderr"));
auto_set_persistency = false;
}
if (message_level > log_level)
return;
// Update doc/troubleshooting.texi if you change the log format.
const std::string message = F("%s %s %s %s:%s: %s") %
now.strftime(timestamp_format) % level_to_char(message_level) %
::getpid() % file % line % user_message;
if (logfile.get() == NULL)
backlog.push_back(std::make_pair(message_level, message));
else {
INV(backlog.empty());
(*logfile) << message << '\n';
(*logfile).flush();
}
}
/// Sets the logging to record messages in memory for later flushing.
///
/// Can be called after set_persistency to flush logs and set recording to be
/// in-memory again.
void
logging::set_inmemory(void)
{
auto_set_persistency = false;
if (logfile.get() != NULL) {
INV(backlog.empty());
(*logfile).flush();
logfile.reset(NULL);
}
}
/// Makes the log persistent.
///
/// Calling this function flushes the in-memory log, if any, to disk and sets
/// the logging module to send log entries to disk from this point onwards.
/// There is no way back, and the caller program should execute this function as
/// early as possible to ensure that a crash at startup does not discard too
/// many useful log entries.
///
/// Any log entries above the provided new_level are discarded.
///
/// \param new_level The new log level.
/// \param path The file to write the logs to.
///
/// \throw std::range_error If the given log level is invalid.
/// \throw std::runtime_error If the given file cannot be created.
void
logging::set_persistency(const std::string& new_level, const fs::path& path)
{
auto_set_persistency = false;
PRE(logfile.get() == NULL);
// Update doc/troubleshooting.info if you change the log levels.
if (new_level == "debug")
log_level = level_debug;
else if (new_level == "error")
log_level = level_error;
else if (new_level == "info")
log_level = level_info;
else if (new_level == "warning")
log_level = level_warning;
else
throw std::range_error(F("Unrecognized log level '%s'") % new_level);
try {
logfile = utils::open_ostream(path);
} catch (const std::runtime_error& unused_error) {
throw std::runtime_error(F("Failed to create log file %s") % path);
}
for (std::vector< std::pair< logging::level, std::string > >::const_iterator
iter = backlog.begin(); iter != backlog.end(); iter++) {
if ((*iter).first <= log_level)
(*logfile) << (*iter).second << '\n';
}
(*logfile).flush();
backlog.clear();
}
<commit_msg>Allow log calls to be made from destructors<commit_after>// Copyright 2011 Google Inc.
// 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.
// * Neither the name of Google Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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
// OWNER 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 "utils/logging/operations.hpp"
extern "C" {
#include <unistd.h>
}
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "utils/datetime.hpp"
#include "utils/format/macros.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/stream.hpp"
namespace datetime = utils::datetime;
namespace fs = utils::fs;
namespace logging = utils::logging;
using utils::none;
using utils::optional;
/// The general idea for the application-wide logging goes like this:
///
/// 1. The application starts. Logging is initialized to capture _all_ log
/// messages into memory regardless of their level by issuing a call to the
/// set_inmemory() function.
///
/// 2. The application offers the user a way to select the logging level and a
/// file into which to store the log.
///
/// 3. The application calls set_persistency providing a new log level and a log
/// file. This must be done as early as possible, to minimize the chances of an
/// early crash not capturing any logs.
///
/// 4. At this point, any log messages stored into memory are flushed to disk
/// respecting the provided log level.
///
/// 5. The internal state of the logging module is updated to only capture
/// messages that are of the provided log level (or below) and is configured to
/// directly send messages to disk.
///
/// 6. The user may choose to call set_inmemory() again at a later stage, which
/// will cause the log to be flushed and messages to be recorded in memory
/// again. This is useful in case the logs are being sent to either stdout or
/// stderr and the process forks and wants to keep those child channels
/// unpolluted.
///
/// The call to set_inmemory() should only be performed by the user-facing
/// application. Tests should skip this call so that the logging messages go to
/// stderr by default, thus generating a useful log to debug the tests.
namespace {
/// Constant string to strftime to format timestamps.
static const char* timestamp_format = "%Y%m%d-%H%M%S";
/// Mutable global state.
struct global_state {
/// Current log level.
logging::level log_level;
/// Indicates whether set_persistency() will be called automatically or not.
bool auto_set_persistency;
/// First time recorded by the logging module.
optional< datetime::timestamp > first_timestamp;
/// In-memory record of log entries before persistency is enabled.
std::vector< std::pair< logging::level, std::string > > backlog;
/// Stream to the currently open log file.
std::auto_ptr< std::ostream > logfile;
global_state() :
log_level(logging::level_debug),
auto_set_persistency(true)
{
}
};
/// Single instance of the mutable global state.
///
/// Note that this is a raw pointer that we intentionally leak. We must do
/// this, instead of making all of the singleton's members static values,
/// because we want other destructors in the program to be able to log critical
/// conditions. If we use complex types in this translation unit, they may be
/// destroyed before the logging methods in the destructors get a chance to run
/// thus resulting in a premature crash. By using a plain pointer, we ensure
/// this state never gets cleaned up.
static struct global_state* globals_singleton = NULL;
/// Gets the singleton instance of global_state.
///
/// \return A pointer to the unique global_state instance.
static struct global_state*
get_globals(void)
{
if (globals_singleton == NULL) {
globals_singleton = new global_state();
}
return globals_singleton;
}
/// Converts a level to a printable character.
///
/// \param level The level to convert.
///
/// \return The printable character, to be used in log messages.
static char
level_to_char(const logging::level level)
{
switch (level) {
case logging::level_error: return 'E';
case logging::level_warning: return 'W';
case logging::level_info: return 'I';
case logging::level_debug: return 'D';
default: UNREACHABLE;
}
}
} // anonymous namespace
/// Generates a standard log name.
///
/// This always adds the same timestamp to the log name for a particular run.
/// Also, the timestamp added to the file name corresponds to the first
/// timestamp recorded by the module; it does not necessarily contain the
/// current value of "now".
///
/// \param logdir The path to the directory in which to place the log.
/// \param progname The name of the program that is generating the log.
fs::path
logging::generate_log_name(const fs::path& logdir, const std::string& progname)
{
struct global_state* globals = get_globals();
if (!globals->first_timestamp)
globals->first_timestamp = datetime::timestamp::now();
// Update kyua(1) if you change the name format.
return logdir / (F("%s.%s.log") % progname %
globals->first_timestamp.get().strftime(timestamp_format));
}
/// Logs an entry to the log file.
///
/// If the log is not yet set to persistent mode, the entry is recorded in the
/// in-memory backlog. Otherwise, it is just written to disk.
///
/// \param message_level The level of the entry.
/// \param file The file from which the log message is generated.
/// \param line The line from which the log message is generated.
/// \param user_message The raw message to store.
void
logging::log(const level message_level, const char* file, const int line,
const std::string& user_message)
{
struct global_state* globals = get_globals();
const datetime::timestamp now = datetime::timestamp::now();
if (!globals->first_timestamp)
globals->first_timestamp = now;
if (globals->auto_set_persistency) {
// These values are hardcoded here for testing purposes. The
// application should call set_inmemory() by itself during
// initialization to avoid this, so that it has explicit control on how
// the call to set_persistency() happens.
set_persistency("debug", fs::path("/dev/stderr"));
globals->auto_set_persistency = false;
}
if (message_level > globals->log_level)
return;
// Update doc/troubleshooting.texi if you change the log format.
const std::string message = F("%s %s %s %s:%s: %s") %
now.strftime(timestamp_format) % level_to_char(message_level) %
::getpid() % file % line % user_message;
if (globals->logfile.get() == NULL)
globals->backlog.push_back(std::make_pair(message_level, message));
else {
INV(globals->backlog.empty());
(*globals->logfile) << message << '\n';
globals->logfile->flush();
}
}
/// Sets the logging to record messages in memory for later flushing.
///
/// Can be called after set_persistency to flush logs and set recording to be
/// in-memory again.
void
logging::set_inmemory(void)
{
struct global_state* globals = get_globals();
globals->auto_set_persistency = false;
if (globals->logfile.get() != NULL) {
INV(globals->backlog.empty());
globals->logfile->flush();
globals->logfile.reset(NULL);
}
}
/// Makes the log persistent.
///
/// Calling this function flushes the in-memory log, if any, to disk and sets
/// the logging module to send log entries to disk from this point onwards.
/// There is no way back, and the caller program should execute this function as
/// early as possible to ensure that a crash at startup does not discard too
/// many useful log entries.
///
/// Any log entries above the provided new_level are discarded.
///
/// \param new_level The new log level.
/// \param path The file to write the logs to.
///
/// \throw std::range_error If the given log level is invalid.
/// \throw std::runtime_error If the given file cannot be created.
void
logging::set_persistency(const std::string& new_level, const fs::path& path)
{
struct global_state* globals = get_globals();
globals->auto_set_persistency = false;
PRE(globals->logfile.get() == NULL);
// Update doc/troubleshooting.info if you change the log levels.
if (new_level == "debug")
globals->log_level = level_debug;
else if (new_level == "error")
globals->log_level = level_error;
else if (new_level == "info")
globals->log_level = level_info;
else if (new_level == "warning")
globals->log_level = level_warning;
else
throw std::range_error(F("Unrecognized log level '%s'") % new_level);
try {
globals->logfile = utils::open_ostream(path);
} catch (const std::runtime_error& unused_error) {
throw std::runtime_error(F("Failed to create log file %s") % path);
}
for (std::vector< std::pair< logging::level, std::string > >::const_iterator
iter = globals->backlog.begin(); iter != globals->backlog.end();
++iter) {
if ((*iter).first <= globals->log_level)
(*globals->logfile) << (*iter).second << '\n';
}
globals->logfile->flush();
globals->backlog.clear();
}
<|endoftext|> |
<commit_before>// Triangle.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Maze.h"
#include "Cube.h"
#include "EasyBMP\EasyBMP.h"
#include <GLTools.h> // OpenGL toolkit
#include <GLShaderManager.h> // Shader Manager Class
#include <iostream>
#ifdef __APPLE__
#include <glut/glut.h> // OS X version of GLUT
#else
#define FREEGLUT_STATIC
#include <GL/glut.h> // Windows FreeGlut equivalent
#endif
#define MOVE_SPEED 0.1f
#define ROTATE_SPEED 0.1f
#define START_WIDTH 940
#define START_HEIGHT 800
using namespace std;
Cube * model;
GLFrustum viewFrustum;
GLMatrixStack modelViewMatrix;
GLMatrixStack projectionMatrix;
GLfloat fLargest;
GLGeometryTransform transformPipeline;
float camera_position[] = {0, 0, 0};
float rot[] = {0, 0, 0};
GLFrame viewFrame;
int numBlocks = 0;
bool keys[256];
bool escDown, isMipmap, isAniso, canAniso;
int width, height;
int frame=0,time,timebase=0;
float fps;
void changeSize(int w, int h)
{
if(h == 0)
h = 1;
width = w;
height = h;
glViewport(0, 0, w, h);
viewFrustum.SetPerspective(35.0f, float(w)/float(h), 1.0f, 1000.0f);
projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);
modelViewMatrix.LoadIdentity();
}
void setupRC(void/*HINSTANCE hInstance*/)
{
glEnable(GL_DEPTH_TEST);
if(gltIsExtSupported("GL_EXT_texture_filter_anisotropic")){
canAniso = true;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);
}
BMP maze;
maze.ReadFromFile("easybmp1.bmp");
int map[41][41];
int size = 41;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
if(maze(i, j)->Red == 0){
map[i][j] = 1;
numBlocks++;
}else
map[i][j] = 0;
numBlocks *= 2;
model = new Cube[numBlocks];
viewFrame.MoveForward(3.0f);
viewFrame.MoveRight(.0f);
viewFrame.MoveUp(0.0f);
viewFrame.RotateLocalY(m3dDegToRad(180));
int count = 0;
// cout << numBlocks << endl;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
if(map[i][j] == 1)
for(int k = 0; k<2; k++){
float offset[] = {i, k, j};
model[count].init(offset);
model[count].bind(GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
count++;
}
}
void renderScene(void)
{
processSceneInfo();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
modelViewMatrix.PushMatrix();
modelViewMatrix.Rotate(rot[0], 1.0, 0.0, 0.0);
modelViewMatrix.Rotate(rot[2], 0.0, 1.0, 0.0);
//modelViewMatrix.Translate(camera_position[0], camera_position[1], camera_position[2]);
modelViewMatrix.Translate(camera_position[0]-5, camera_position[1]-1, camera_position[2]-5);
for(int i = 0; i<numBlocks; i++)
model[i].draw(transformPipeline);
char topText[256];
sprintf(topText, "FPS: %d", (int) fps);
renderText(topText);
modelViewMatrix.PopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void renderText(char * p){
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, width, 0.0, height);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_CURRENT_BIT);
glColor3f(0.0f, 1.0f, 0.0f); // Green
glDisable(GL_LIGHTING);
glRasterPos2i(10, height - 20);
string s = p;
void * font = GLUT_BITMAP_9_BY_15;
glDisable(GL_TEXTURE_2D);
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glutBitmapCharacter(font, c);
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopAttrib();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void processSceneInfo(void){
if(keys['w'] || keys['W']){
camera_position[0] += -sin((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += cos((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['s'] || keys['S']){
camera_position[0] += sin((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += -cos((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['a'] || keys['A']){
camera_position[0] += cos((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += sin((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['d'] || keys['D']){
camera_position[0] += -cos((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += -sin((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['e'] || keys['E'])
camera_position[1] -= MOVE_SPEED;
if(keys['c'] || keys['C'])
camera_position[1] += MOVE_SPEED;
if(!escDown)
glutWarpPointer(width / 2, height / 2);
if(keys['m'] || keys['M'])
if(isMipmap)
for(int i = 0; i < 20*20; i++)
model[i].onMipmap();
else
for(int i = 0; i < 20*20; i++)
model[i].offMipmap();
if(keys['n'] || keys['N'])
if(isAniso)
for(int i = 0; i < 20*20; i++)
model[i].onAniso(fLargest);
else
for(int i = 0; i < 20*20; i++)
model[i].offAniso();
}
void downKeys(unsigned char key, int x, int y){
keys[key] = true;
if(key == 27)
escDown = !escDown;
if(key == 'm')
isMipmap = !isMipmap;
if(key == 'n' && canAniso)
isAniso = !isAniso;
}
void upKeys(unsigned char key, int x, int y){
keys[key] = false;
}
void mouseFuction(int x, int y){
if(escDown)
return;
float new_x = x-(width/2);
float new_y = y-(height/2);
//if (abs(new_x) < 100 && abs(new_y) < 100){
// rot[0] = 0;
// rot[2] = 0;
//}else{
rot[0] += new_y*ROTATE_SPEED;
rot[2] += new_x*ROTATE_SPEED;
//}
}
void countFPS(){
frame++;
time=glutGet(GLUT_ELAPSED_TIME);
if (time - timebase > 1000) {
fps = (float)(frame*1000.0/(time-timebase));
timebase = time;
frame = 0;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char * argv[])
{
gltSetWorkingDirectory(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(START_WIDTH, START_HEIGHT);
glutCreateWindow("Triangle");
glutIdleFunc(countFPS);
glutReshapeFunc(changeSize);
glutDisplayFunc(renderScene);
glutKeyboardFunc(downKeys);
glutKeyboardUpFunc(upKeys);
glutPassiveMotionFunc(mouseFuction);
GLenum err = glewInit();
if (GLEW_OK != err) {
fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
return 1;
}
setupRC();
glutMainLoop();
return 0;
}<commit_msg>Tried collision<commit_after>// Triangle.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Maze.h"
#include "Cube.h"
#include "EasyBMP\EasyBMP.h"
#include <GLTools.h> // OpenGL toolkit
#include <GLShaderManager.h> // Shader Manager Class
#include <iostream>
#ifdef __APPLE__
#include <glut/glut.h> // OS X version of GLUT
#else
#define FREEGLUT_STATIC
#include <GL/glut.h> // Windows FreeGlut equivalent
#endif
#define MOVE_SPEED 0.1f
#define ROTATE_SPEED 0.1f
#define START_WIDTH 940
#define START_HEIGHT 800
using namespace std;
Cube * model;
GLFrustum viewFrustum;
GLMatrixStack modelViewMatrix;
GLMatrixStack projectionMatrix;
GLfloat fLargest;
GLGeometryTransform transformPipeline;
float camera_position[] = {0, 0, 0};
float rot[] = {0, 0, 0};
GLFrame viewFrame;
int numBlocks = 0;
bool keys[256];
bool escDown, isMipmap, isAniso, canAniso;
int width, height;
int map[41][41];
int frame=0,time,timebase=0;
float fps;
void changeSize(int w, int h)
{
if(h == 0)
h = 1;
width = w;
height = h;
glViewport(0, 0, w, h);
viewFrustum.SetPerspective(35.0f, float(w)/float(h), 1.0f, 1000.0f);
projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);
modelViewMatrix.LoadIdentity();
}
void setupRC(void/*HINSTANCE hInstance*/)
{
glEnable(GL_DEPTH_TEST);
if(gltIsExtSupported("GL_EXT_texture_filter_anisotropic")){
canAniso = true;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);
}
BMP maze;
maze.ReadFromFile("easybmp1.bmp");
int size = 41;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
if(maze(i, j)->Red == 0){
map[i][j] = 1;
numBlocks++;
}else
map[i][j] = 0;
numBlocks *= 2;
model = new Cube[numBlocks];
viewFrame.MoveForward(3.0f);
viewFrame.MoveRight(.0f);
viewFrame.MoveUp(0.0f);
viewFrame.RotateLocalY(m3dDegToRad(180));
int count = 0;
// cout << numBlocks << endl;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
if(map[i][j] == 1)
for(int k = 0; k<2; k++){
float offset[] = {i, k, j};
model[count].init(offset);
model[count].bind(GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
count++;
}
}
void renderScene(void)
{
processSceneInfo();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
modelViewMatrix.PushMatrix();
//cout << (int)camera_position[0] << " " << (int)camera_position[2] << endl;
modelViewMatrix.Rotate(rot[0], 1.0, 0.0, 0.0);
modelViewMatrix.Rotate(rot[2], 0.0, 1.0, 0.0);
//modelViewMatrix.Translate(camera_position[0], camera_position[1], camera_position[2]);
if(!map[ abs((int)camera_position[2]) ][abs((int)camera_position[0])] == 1){
cout << "hi" << endl;
}
modelViewMatrix.Translate(camera_position[0], camera_position[1], camera_position[2]);
for(int i = 0; i<numBlocks; i++)
model[i].draw(transformPipeline);
char topText[256];
sprintf(topText, "FPS: %d", (int) fps);
renderText(topText);
modelViewMatrix.PopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void renderText(char * p){
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, width, 0.0, height);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_CURRENT_BIT);
glColor3f(0.0f, 1.0f, 0.0f); // Green
glDisable(GL_LIGHTING);
glRasterPos2i(10, height - 20);
string s = p;
void * font = GLUT_BITMAP_9_BY_15;
glDisable(GL_TEXTURE_2D);
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glutBitmapCharacter(font, c);
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopAttrib();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void processSceneInfo(void){
if(keys['w'] || keys['W']){
camera_position[0] += -sin((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += cos((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['s'] || keys['S']){
camera_position[0] += sin((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += -cos((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['a'] || keys['A']){
camera_position[0] += cos((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += sin((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['d'] || keys['D']){
camera_position[0] += -cos((3.14/180)*rot[2])*MOVE_SPEED;
camera_position[2] += -sin((3.14/180)*rot[2])*MOVE_SPEED;
}
if(keys['e'] || keys['E'])
camera_position[1] -= MOVE_SPEED;
if(keys['c'] || keys['C'])
camera_position[1] += MOVE_SPEED;
if(!escDown)
glutWarpPointer(width / 2, height / 2);
if(keys['m'] || keys['M'])
if(isMipmap)
for(int i = 0; i < 20*20; i++)
model[i].onMipmap();
else
for(int i = 0; i < 20*20; i++)
model[i].offMipmap();
if(keys['n'] || keys['N'])
if(isAniso)
for(int i = 0; i < 20*20; i++)
model[i].onAniso(fLargest);
else
for(int i = 0; i < 20*20; i++)
model[i].offAniso();
}
void downKeys(unsigned char key, int x, int y){
keys[key] = true;
if(key == 27)
escDown = !escDown;
if(key == 'm')
isMipmap = !isMipmap;
if(key == 'n' && canAniso)
isAniso = !isAniso;
}
void upKeys(unsigned char key, int x, int y){
keys[key] = false;
}
void mouseFuction(int x, int y){
if(escDown)
return;
float new_x = x-(width/2);
float new_y = y-(height/2);
//if (abs(new_x) < 100 && abs(new_y) < 100){
// rot[0] = 0;
// rot[2] = 0;
//}else{
rot[0] += new_y*ROTATE_SPEED;
rot[2] += new_x*ROTATE_SPEED;
//}
}
void countFPS(){
frame++;
time=glutGet(GLUT_ELAPSED_TIME);
if (time - timebase > 1000) {
fps = (float)(frame*1000.0/(time-timebase));
timebase = time;
frame = 0;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char * argv[])
{
gltSetWorkingDirectory(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(START_WIDTH, START_HEIGHT);
glutCreateWindow("Triangle");
glutIdleFunc(countFPS);
glutReshapeFunc(changeSize);
glutDisplayFunc(renderScene);
glutKeyboardFunc(downKeys);
glutKeyboardUpFunc(upKeys);
glutPassiveMotionFunc(mouseFuction);
GLenum err = glewInit();
if (GLEW_OK != err) {
fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
return 1;
}
setupRC();
glutMainLoop();
return 0;
}<|endoftext|> |
<commit_before>/******************************************************************************/
/*
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
#include "sid/sid.h"
/*
This is a simple implementation of SID database, where data is stored linearly and unsorted.
Ideally, you'll want to use a search structure like a binary search tree.
Database file format: Number of data entries (U64) followed by a list of SID-string pairs.
*/
typedef unsigned long long U64;
static const size_t kMaxStrLen = 128;
void PrintUsage()
{
std::cout << "USAGE:\n"
" - siddb --list\n"
" Lists all SID-string pairs in the database.\n\n"
" - siddb --help\n"
" Prints help.\n\n"
" - siddb --clean\n"
" Cleans the database.\n\n"
" - siddb <string ID>\n"
" Looks up corresponding string of provided string ID (hex or decimal).\n\n"
" - siddb <string>\n"
" Looks up corresponding string ID of provided string (unquoted).\n\n";
}
const static char* kDatabaseFile = "siddb.db";
std::FILE* g_pDbFile = nullptr;
bool InitDatabase()
{
g_pDbFile = std::fopen(kDatabaseFile, "r+");
if (!g_pDbFile)
{
const U64 kZero = 0;
g_pDbFile = std::fopen(kDatabaseFile, "w+");
std::fwrite(&kZero, sizeof(kZero), 1, g_pDbFile);
}
if (!g_pDbFile)
return false;
return true;
}
void CleanDatabase()
{
if (g_pDbFile)
{
std::fclose(g_pDbFile);
g_pDbFile = nullptr;
}
std::remove(kDatabaseFile);
std::printf ("SID database cleaned.\n");
}
void ListDatabase()
{
if (!g_pDbFile)
return;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
std::printf("Number of entries: %lld\n", numDataEntries);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int)kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
std::printf("0x%16llx <-> %s\n", sidVal, buffer);
}
}
bool FindStringId(StringId::Storage data, char* pOut)
{
if (!g_pDbFile)
return false;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int) kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
if (data == sidVal)
{
std::strcpy(pOut, buffer);
return true;
}
}
return false;
}
bool FindStringId(const char* str, StringId::Storage* pOut)
{
if (!g_pDbFile)
return false;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int)kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
if (!std::strcmp(str, buffer))
{
*pOut = sidVal;
return true;
}
}
return false;
}
void SaveStringId(const char* str)
{
if (!g_pDbFile)
return;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
++numDataEntries;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fwrite(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
std::fseek(g_pDbFile, 0, SEEK_END);
const StringId::Storage sidVal = SID_VAL(str);
std::fwrite(&sidVal, sizeof(sidVal), 1, g_pDbFile);
const char kWhiteSpace = ' ';
std::fwrite(str, 1, std::min(kMaxStrLen, std::strlen(str)), g_pDbFile);
std::fwrite(&kWhiteSpace, 1, 1, g_pDbFile);
}
int main(int argc, const char** argv)
{
if (!InitDatabase())
return -1;
char* ss = "asdf";
StringId sid = SID(ss);
switch (argc)
{
case 2:
// option
if (std::strlen(argv[1]) > 2 && argv[1][0] == '-' && argv[1][1] == '-')
{
const char* pOption = argv[1] + 2;
if (!std::strcmp(pOption, "list"))
{
ListDatabase();
}
else if (!std::strcmp(pOption, "clean"))
{
CleanDatabase();
}
else /* if (!std::strcmp(pOption, "help")) */
{
PrintUsage();
}
}
// hex
else if (argv[1][0] == '0' && (argv[1][1] == 'x' || argv[1][1] == 'X'))
{
StringId::Storage sidVal;
sscanf_s(argv[1], "%llx", &sidVal);
char str[kMaxStrLen];
if (FindStringId(sidVal, str))
{
std::printf("0x%16llx -> %s", sidVal, str);
}
else
{
std::printf("0x%16llx -> ???", sidVal);
}
}
// dec
else if (argv[1][0] >= '0' && argv[1][0] <= '9')
{
StringId::Storage sidVal;
sscanf_s(argv[1], "%lld", &sidVal);
char str[kMaxStrLen];
if (FindStringId(sidVal, str))
{
std::printf("0x%16llx -> %s", sidVal, str);
}
else
{
std::printf("0x%16llx -> ???", sidVal);
}
}
// string
else
{
StringId::Storage sidVal;
if (FindStringId(argv[1], &sidVal))
{
std::printf("%s -> 0x%16llx", argv[1], sidVal);
}
else
{
SaveStringId(argv[1]);
std::printf("New entry saved:\n%s -> 0x%16llx", argv[1], SID_VAL(argv[1]));
}
}
break;
default:
PrintUsage();
break;
}
if (g_pDbFile)
{
std::fclose(g_pDbFile);
g_pDbFile = nullptr;
}
return 0;
}
<commit_msg>Formatting.<commit_after>/******************************************************************************/
/*
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
#include "sid/sid.h"
/*
This is a simple implementation of SID database, where data is stored linearly and unsorted.
Ideally, you'll want to use a search structure like a binary search tree.
Database file format: Number of data entries (U64) followed by a list of SID-string pairs.
*/
typedef unsigned long long U64;
static const size_t kMaxStrLen = 128;
void PrintUsage()
{
std::cout << "USAGE:\n"
" - siddb --list\n"
" Lists all SID-string pairs in the database.\n\n"
" - siddb --help\n"
" Prints help.\n\n"
" - siddb --clean\n"
" Cleans the database.\n\n"
" - siddb <string ID>\n"
" Looks up corresponding string of provided string ID (hex or decimal).\n\n"
" - siddb <string>\n"
" Looks up corresponding string ID of provided string (unquoted).\n\n";
}
const static char* kDatabaseFile = "siddb.db";
std::FILE* g_pDbFile = nullptr;
bool InitDatabase()
{
g_pDbFile = std::fopen(kDatabaseFile, "r+");
if (!g_pDbFile)
{
const U64 kZero = 0;
g_pDbFile = std::fopen(kDatabaseFile, "w+");
std::fwrite(&kZero, sizeof(kZero), 1, g_pDbFile);
}
if (!g_pDbFile)
return false;
return true;
}
void CleanDatabase()
{
if (g_pDbFile)
{
std::fclose(g_pDbFile);
g_pDbFile = nullptr;
}
std::remove(kDatabaseFile);
std::printf ("SID database cleaned.\n");
}
void ListDatabase()
{
if (!g_pDbFile)
return;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
std::printf("Number of entries: %lld\n", numDataEntries);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int)kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
std::printf("0x%016llx <-> %s\n", sidVal, buffer);
}
}
bool FindStringId(StringId::Storage data, char* pOut)
{
if (!g_pDbFile)
return false;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int) kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
if (data == sidVal)
{
std::strcpy(pOut, buffer);
return true;
}
}
return false;
}
bool FindStringId(const char* str, StringId::Storage* pOut)
{
if (!g_pDbFile)
return false;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
for (U64 i = 0; i < numDataEntries; ++i)
{
StringId::Storage sidVal;
std::fread(&sidVal, sizeof(sidVal), 1, g_pDbFile);
char buffer[kMaxStrLen];
fscanf_s(g_pDbFile, "%s", buffer, (int)kMaxStrLen);
std::fseek(g_pDbFile, 1, SEEK_CUR);
if (!std::strcmp(str, buffer))
{
*pOut = sidVal;
return true;
}
}
return false;
}
void SaveStringId(const char* str)
{
if (!g_pDbFile)
return;
U64 numDataEntries = 0;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fread(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
++numDataEntries;
std::fseek(g_pDbFile, 0, SEEK_SET);
std::fwrite(&numDataEntries, sizeof(numDataEntries), 1, g_pDbFile);
std::fseek(g_pDbFile, 0, SEEK_END);
const StringId::Storage sidVal = SID_VAL(str);
std::fwrite(&sidVal, sizeof(sidVal), 1, g_pDbFile);
const char kWhiteSpace = ' ';
std::fwrite(str, 1, std::min(kMaxStrLen, std::strlen(str)), g_pDbFile);
std::fwrite(&kWhiteSpace, 1, 1, g_pDbFile);
}
int main(int argc, const char** argv)
{
if (!InitDatabase())
return -1;
char* ss = "asdf";
StringId sid = SID(ss);
switch (argc)
{
case 2:
// option
if (std::strlen(argv[1]) > 2 && argv[1][0] == '-' && argv[1][1] == '-')
{
const char* pOption = argv[1] + 2;
if (!std::strcmp(pOption, "list"))
{
ListDatabase();
}
else if (!std::strcmp(pOption, "clean"))
{
CleanDatabase();
}
else /* if (!std::strcmp(pOption, "help")) */
{
PrintUsage();
}
}
// hex
else if (argv[1][0] == '0' && (argv[1][1] == 'x' || argv[1][1] == 'X'))
{
StringId::Storage sidVal;
sscanf_s(argv[1], "%llx", &sidVal);
char str[kMaxStrLen];
if (FindStringId(sidVal, str))
{
std::printf("0x%016llx -> %s", sidVal, str);
}
else
{
std::printf("0x%016llx -> ???", sidVal);
}
}
// dec
else if (argv[1][0] >= '0' && argv[1][0] <= '9')
{
StringId::Storage sidVal;
sscanf_s(argv[1], "%lld", &sidVal);
char str[kMaxStrLen];
if (FindStringId(sidVal, str))
{
std::printf("0x%016llx -> %s", sidVal, str);
}
else
{
std::printf("0x%016llx -> ???", sidVal);
}
}
// string
else
{
StringId::Storage sidVal;
if (FindStringId(argv[1], &sidVal))
{
std::printf("%s -> 0x%016llx", argv[1], sidVal);
}
else
{
SaveStringId(argv[1]);
std::printf("New entry saved:\n%s -> 0x%016llx", argv[1], SID_VAL(argv[1]));
}
}
break;
default:
PrintUsage();
break;
}
if (g_pDbFile)
{
std::fclose(g_pDbFile);
g_pDbFile = nullptr;
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "callouts-gen.hpp"
#include "elog_entry.hpp"
#include <algorithm>
#include <cstring>
#include <phosphor-logging/elog-errors.hpp>
#include <string>
#include <tuple>
#include <vector>
namespace phosphor
{
namespace logging
{
namespace metadata
{
using Metadata = std::string;
namespace associations
{
using Type = void(const std::string&, const std::vector<std::string>&,
AssociationList& list);
/** @brief Pull out metadata name and value from the string
* <metadata name>=<metadata value>
* @param [in] data - metadata key=value entries
* @param [out] metadata - map of metadata name:value
*/
inline void parse(const std::vector<std::string>& data,
std::map<std::string, std::string>& metadata)
{
constexpr auto separator = '=';
for (const auto& entryItem : data)
{
auto pos = entryItem.find(separator);
if (std::string::npos != pos)
{
auto key = entryItem.substr(0, entryItem.find(separator));
auto value = entryItem.substr(entryItem.find(separator) + 1);
metadata.emplace(std::move(key), std::move(value));
}
}
};
/** @brief Combine the metadata keys and values from the map
* into a vector of strings that look like:
* "<metadata name>=<metadata value>"
* @param [in] data - metadata key:value map
* @param [out] metadata - vector of "key=value" strings
*/
inline void combine(const std::map<std::string, std::string>& data,
std::vector<std::string>& metadata)
{
for (const auto& [key, value] : data)
{
std::string line{key};
line += "=" + value;
metadata.push_back(std::move(line));
}
}
/** @brief Build error associations specific to metadata. Specialize this
* template for handling a specific type of metadata.
* @tparam M - type of metadata
* @param [in] match - metadata to be handled
* @param [in] data - metadata key=value entries
* @param [out] list - list of error association objects
*/
template <typename M>
void build(const std::string& match, const std::vector<std::string>& data,
AssociationList& list) = delete;
// Example template specialization - we don't want to do anything
// for this metadata.
using namespace example::xyz::openbmc_project::Example::Elog;
template <>
inline void build<TestErrorTwo::DEV_ID>(const std::string& match,
const std::vector<std::string>& data,
AssociationList& list)
{
}
template <>
inline void
build<example::xyz::openbmc_project::Example::Device::Callout::
CALLOUT_DEVICE_PATH_TEST>(const std::string& match,
const std::vector<std::string>& data,
AssociationList& list)
{
std::map<std::string, std::string> metadata;
parse(data, metadata);
auto iter = metadata.find(match);
if (metadata.end() != iter)
{
auto comp = [](const auto& first, const auto& second) {
return (std::strcmp(std::get<0>(first), second) < 0);
};
auto callout = std::lower_bound(callouts.begin(), callouts.end(),
(iter->second).c_str(), comp);
if ((callouts.end() != callout) &&
!std::strcmp((iter->second).c_str(), std::get<0>(*callout)))
{
constexpr auto ROOT = "/xyz/openbmc_project/inventory";
list.push_back(std::make_tuple(
"callout", "fault", std::string(ROOT) + std::get<1>(*callout)));
}
}
}
// The PROCESS_META flag is needed to get out of tree builds working. Such
// builds will have access only to internal error interfaces, hence handlers
// for out dbus error interfaces won't compile. This flag is not set by default,
// the phosphor-logging recipe enabled it.
#if defined PROCESS_META
template <>
void build<xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH>(
const std::string& match, const std::vector<std::string>& data,
AssociationList& list);
template <>
void build<
xyz::openbmc_project::Common::Callout::Inventory::CALLOUT_INVENTORY_PATH>(
const std::string& match, const std::vector<std::string>& data,
AssociationList& list);
#endif // PROCESS_META
} // namespace associations
} // namespace metadata
} // namespace logging
} // namespace phosphor
<commit_msg>elog_meta: fix pedantic build failure<commit_after>#pragma once
#include "callouts-gen.hpp"
#include "elog_entry.hpp"
#include <algorithm>
#include <cstring>
#include <phosphor-logging/elog-errors.hpp>
#include <string>
#include <tuple>
#include <vector>
namespace phosphor
{
namespace logging
{
namespace metadata
{
using Metadata = std::string;
namespace associations
{
using Type = void(const std::string&, const std::vector<std::string>&,
AssociationList& list);
/** @brief Pull out metadata name and value from the string
* <metadata name>=<metadata value>
* @param [in] data - metadata key=value entries
* @param [out] metadata - map of metadata name:value
*/
inline void parse(const std::vector<std::string>& data,
std::map<std::string, std::string>& metadata)
{
constexpr auto separator = '=';
for (const auto& entryItem : data)
{
auto pos = entryItem.find(separator);
if (std::string::npos != pos)
{
auto key = entryItem.substr(0, entryItem.find(separator));
auto value = entryItem.substr(entryItem.find(separator) + 1);
metadata.emplace(std::move(key), std::move(value));
}
}
}
/** @brief Combine the metadata keys and values from the map
* into a vector of strings that look like:
* "<metadata name>=<metadata value>"
* @param [in] data - metadata key:value map
* @param [out] metadata - vector of "key=value" strings
*/
inline void combine(const std::map<std::string, std::string>& data,
std::vector<std::string>& metadata)
{
for (const auto& [key, value] : data)
{
std::string line{key};
line += "=" + value;
metadata.push_back(std::move(line));
}
}
/** @brief Build error associations specific to metadata. Specialize this
* template for handling a specific type of metadata.
* @tparam M - type of metadata
* @param [in] match - metadata to be handled
* @param [in] data - metadata key=value entries
* @param [out] list - list of error association objects
*/
template <typename M>
void build(const std::string& match, const std::vector<std::string>& data,
AssociationList& list) = delete;
// Example template specialization - we don't want to do anything
// for this metadata.
using namespace example::xyz::openbmc_project::Example::Elog;
template <>
inline void build<TestErrorTwo::DEV_ID>(const std::string& match,
const std::vector<std::string>& data,
AssociationList& list)
{
}
template <>
inline void
build<example::xyz::openbmc_project::Example::Device::Callout::
CALLOUT_DEVICE_PATH_TEST>(const std::string& match,
const std::vector<std::string>& data,
AssociationList& list)
{
std::map<std::string, std::string> metadata;
parse(data, metadata);
auto iter = metadata.find(match);
if (metadata.end() != iter)
{
auto comp = [](const auto& first, const auto& second) {
return (std::strcmp(std::get<0>(first), second) < 0);
};
auto callout = std::lower_bound(callouts.begin(), callouts.end(),
(iter->second).c_str(), comp);
if ((callouts.end() != callout) &&
!std::strcmp((iter->second).c_str(), std::get<0>(*callout)))
{
constexpr auto ROOT = "/xyz/openbmc_project/inventory";
list.push_back(std::make_tuple(
"callout", "fault", std::string(ROOT) + std::get<1>(*callout)));
}
}
}
// The PROCESS_META flag is needed to get out of tree builds working. Such
// builds will have access only to internal error interfaces, hence handlers
// for out dbus error interfaces won't compile. This flag is not set by default,
// the phosphor-logging recipe enabled it.
#if defined PROCESS_META
template <>
void build<xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH>(
const std::string& match, const std::vector<std::string>& data,
AssociationList& list);
template <>
void build<
xyz::openbmc_project::Common::Callout::Inventory::CALLOUT_INVENTORY_PATH>(
const std::string& match, const std::vector<std::string>& data,
AssociationList& list);
#endif // PROCESS_META
} // namespace associations
} // namespace metadata
} // namespace logging
} // namespace phosphor
<|endoftext|> |
<commit_before>#include "helloworld.h"
#include <sampgdk/amxplugin.h>
#include <sampgdk/players.h>
#include <sampgdk/samp.h>
#include <sampgdk/wrapper.h>
#include <cstdio> // for sprintf
#include <cstring> // for strcmp
static logprintf_t logprintf;
using namespace sampgdk;
static HelloWorld theGameMode;
HelloWorld::HelloWorld() {
// Register our gamemode in order to catch events - if we don't do this
// somewhere none of the HelloWorld callbacks will be ever called.
this->Register();
}
HelloWorld::~HelloWorld() {}
void HelloWorld::OnGameModeInit() {
SetGameModeText("Hello, World!");
AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);
logprintf("------------------------------------------\n");
logprintf(" HelloWorld gamemode got loaded. \n");
logprintf("------------------------------------------\n");
}
bool HelloWorld::OnPlayerConnect(int playerid) {
SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
return true;
}
bool HelloWorld::OnPlayerRequestClass(int playerid, int classid) {
SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);
return true;
}
bool HelloWorld::OnPlayerCommandText(int playerid, const char *cmdtext) {
if (std::strcmp(cmdtext, "/hello") == 0) {
char name[MAX_PLAYER_NAME];
GetPlayerName(playerid, name);
char message[128];
std::sprintf(message, "Hello, %s!", name);
SendClientMessage(playerid, 0x00FF00FF, message);
return true;
}
return false;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData) {
logprintf = (logprintf_t)ppPluginData[PLUGIN_DATA_LOGPRINTF];
// Initialize the wrapper - this always should be done here.
Wrapper::GetInstance()->Initialize(ppPluginData);
// Do not call any natives here - they are not yet prepared for use at this stage.
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
<commit_msg>Update helloworld to fix compile errors<commit_after>#include "helloworld.h"
#include <sampgdk/amxplugin.h>
#include <sampgdk/players.h>
#include <sampgdk/samp.h>
#include <sampgdk/wrapper.h>
#include <cstdio> // for sprintf
#include <cstring> // for strcmp
static logprintf_t logprintf;
using namespace sampgdk;
static HelloWorld theGameMode;
HelloWorld::HelloWorld() {
// Register our gamemode in order to catch events - if we don't do this
// somewhere none of the HelloWorld callbacks will be ever called.
this->Register();
}
HelloWorld::~HelloWorld() {}
void HelloWorld::OnGameModeInit() {
SetGameModeText("Hello, World!");
AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);
logprintf("------------------------------------------\n");
logprintf(" HelloWorld gamemode got loaded. \n");
logprintf("------------------------------------------\n");
}
bool HelloWorld::OnPlayerConnect(int playerid) {
SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
return true;
}
bool HelloWorld::OnPlayerRequestClass(int playerid, int classid) {
SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f);
return true;
}
bool HelloWorld::OnPlayerCommandText(int playerid, const char *cmdtext) {
if (std::strcmp(cmdtext, "/hello") == 0) {
char name[MAX_PLAYER_NAME];
GetPlayerName(playerid, name);
char message[128];
std::sprintf(message, "Hello, %s!", name);
SendClientMessage(playerid, 0x00FF00FF, message);
return true;
}
return false;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppPluginData) {
logprintf = (logprintf_t)ppPluginData[PLUGIN_DATA_LOGPRINTF];
// Initialize the wrapper - this always should be done here.
Wrapper::GetInstance().Initialize(ppPluginData);
// Do not call any natives here - they are not yet prepared for use at this stage.
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "global_managers.hpp"
#include "thread_group.hpp"
#include "filesystem.hpp"
#include "event.hpp"
#include "ui_manager.hpp"
#include "common_renderer_data.hpp"
#include "message_queue.hpp"
#include <thread>
#ifdef HAVE_GRANITE_AUDIO
#include "audio_interface.hpp"
#include "audio_mixer.hpp"
#include "audio_events.hpp"
#endif
#ifdef HAVE_GRANITE_PHYSICS
#include "physics_system.hpp"
#endif
namespace Granite
{
namespace Global
{
// Could use unique_ptr here, but would be nice to avoid global ctor/dtor.
struct GlobalManagers
{
Filesystem *filesystem;
EventManager *event_manager;
ThreadGroup *thread_group;
UI::UIManager *ui_manager;
CommonRendererData *common_renderer_data;
Util::MessageQueue *logging;
#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend;
Audio::Mixer *audio_mixer;
#endif
#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics;
#endif
};
static thread_local GlobalManagers global_managers;
GlobalManagersHandle create_thread_context()
{
return GlobalManagersHandle(new GlobalManagers(global_managers));
}
void delete_thread_context(GlobalManagers *managers)
{
delete managers;
}
void GlobalManagerDeleter::operator()(GlobalManagers *managers)
{
delete_thread_context(managers);
}
void set_thread_context(const GlobalManagers &managers)
{
global_managers = managers;
if (managers.thread_group)
managers.thread_group->refresh_global_timeline_trace_file();
}
void clear_thread_context()
{
global_managers = {};
}
Util::MessageQueue *message_queue()
{
if (!global_managers.logging)
global_managers.logging = new Util::MessageQueue;
return global_managers.logging;
}
Filesystem *filesystem()
{
if (!global_managers.filesystem)
{
LOGI("Filesystem was not initialized. Lazily initializing.\n");
global_managers.filesystem = new Filesystem;
}
return global_managers.filesystem;
}
EventManager *event_manager()
{
if (!global_managers.event_manager)
{
LOGI("Event manager was not initialized. Lazily initializing.\n");
global_managers.event_manager = new EventManager;
}
return global_managers.event_manager;
}
ThreadGroup *thread_group()
{
if (!global_managers.thread_group)
{
LOGI("Thread group was not initialized. Lazily initializing.\n"
"This is potentially dangerous if worker threads use globals.\n");
global_managers.thread_group = new ThreadGroup();
global_managers.thread_group->start(std::thread::hardware_concurrency());
}
return global_managers.thread_group;
}
UI::UIManager *ui_manager()
{
if (!global_managers.ui_manager)
{
LOGI("UI manager was not initialized. Lazily initializing.\n");
global_managers.ui_manager = new UI::UIManager;
}
return global_managers.ui_manager;
}
CommonRendererData *common_renderer_data()
{
if (!global_managers.common_renderer_data)
{
LOGI("Common GPU data was not initialized. Lazily initializing.\n");
global_managers.common_renderer_data = new CommonRendererData;
}
return global_managers.common_renderer_data;
}
#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend() { return global_managers.audio_backend; }
Audio::Mixer *audio_mixer() { return global_managers.audio_mixer; }
void install_audio_system(Audio::Backend *backend, Audio::Mixer *mixer)
{
delete global_managers.audio_mixer;
global_managers.audio_mixer = mixer;
delete global_managers.audio_backend;
global_managers.audio_backend = backend;
}
#endif
#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics()
{
if (!global_managers.physics)
{
LOGI("Physics system was not initialized. Lazily initializing.\n");
global_managers.physics = new PhysicsSystem;
}
return global_managers.physics;
}
#endif
void init(ManagerFeatureFlags flags, unsigned max_threads)
{
if (flags & MANAGER_FEATURE_EVENT_BIT)
{
if (!global_managers.event_manager)
global_managers.event_manager = new EventManager;
}
if (flags & MANAGER_FEATURE_FILESYSTEM_BIT)
{
if (!global_managers.filesystem)
global_managers.filesystem = new Filesystem;
}
bool kick_threads = false;
if (flags & MANAGER_FEATURE_THREAD_GROUP_BIT)
{
if (!global_managers.thread_group)
{
global_managers.thread_group = new ThreadGroup;
kick_threads = true;
}
}
if (flags & MANAGER_FEATURE_UI_MANAGER_BIT)
{
if (!global_managers.ui_manager)
global_managers.ui_manager = new UI::UIManager;
}
if (flags & MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT)
{
if (!global_managers.common_renderer_data)
global_managers.common_renderer_data = new CommonRendererData;
}
if (flags & MANAGER_FEATURE_LOGGING_BIT)
{
if (!global_managers.logging)
global_managers.logging = new Util::MessageQueue;
}
#ifdef HAVE_GRANITE_PHYSICS
if (flags & MANAGER_FEATURE_PHYSICS_BIT)
{
if (!global_managers.physics)
global_managers.physics = new PhysicsSystem;
}
#endif
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_mixer)
global_managers.audio_mixer = new Audio::Mixer;
if (!global_managers.audio_backend)
global_managers.audio_backend = Audio::create_default_audio_backend(*global_managers.audio_mixer, 44100.0f, 2);
#endif
// Kick threads after all global managers are set up.
if (kick_threads)
{
unsigned cpu_threads = std::thread::hardware_concurrency();
if (cpu_threads > max_threads)
cpu_threads = max_threads;
global_managers.thread_group->start(cpu_threads);
}
}
void deinit()
{
#ifdef HAVE_GRANITE_AUDIO
if (global_managers.audio_backend)
global_managers.audio_backend->stop();
delete global_managers.audio_backend;
delete global_managers.audio_mixer;
global_managers.audio_backend = nullptr;
global_managers.audio_mixer = nullptr;
#endif
#ifdef HAVE_GRANITE_PHYSICS
delete global_managers.physics;
#endif
delete global_managers.common_renderer_data;
delete global_managers.ui_manager;
delete global_managers.thread_group;
delete global_managers.filesystem;
delete global_managers.event_manager;
delete global_managers.logging;
global_managers.common_renderer_data = nullptr;
global_managers.filesystem = nullptr;
global_managers.event_manager = nullptr;
global_managers.thread_group = nullptr;
global_managers.ui_manager = nullptr;
global_managers.logging = nullptr;
}
void start_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_backend)
return;
if (!global_managers.audio_backend->start())
{
LOGE("Failed to start audio subsystem!\n");
return;
}
if (global_managers.event_manager)
global_managers.event_manager->enqueue_latched<Audio::MixerStartEvent>(*global_managers.audio_mixer);
#endif
}
void stop_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_backend)
return;
if (!global_managers.audio_backend->stop())
LOGE("Failed to stop audio subsystem!\n");
if (global_managers.event_manager)
global_managers.event_manager->dequeue_latched(Audio::MixerStartEvent::get_type_id());
#endif
}
}
}
<commit_msg>Add env-var to set explicit number of worker threads.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "global_managers.hpp"
#include "thread_group.hpp"
#include "filesystem.hpp"
#include "event.hpp"
#include "ui_manager.hpp"
#include "common_renderer_data.hpp"
#include "message_queue.hpp"
#include <thread>
#ifdef HAVE_GRANITE_AUDIO
#include "audio_interface.hpp"
#include "audio_mixer.hpp"
#include "audio_events.hpp"
#endif
#ifdef HAVE_GRANITE_PHYSICS
#include "physics_system.hpp"
#endif
namespace Granite
{
namespace Global
{
// Could use unique_ptr here, but would be nice to avoid global ctor/dtor.
struct GlobalManagers
{
Filesystem *filesystem;
EventManager *event_manager;
ThreadGroup *thread_group;
UI::UIManager *ui_manager;
CommonRendererData *common_renderer_data;
Util::MessageQueue *logging;
#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend;
Audio::Mixer *audio_mixer;
#endif
#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics;
#endif
};
static thread_local GlobalManagers global_managers;
GlobalManagersHandle create_thread_context()
{
return GlobalManagersHandle(new GlobalManagers(global_managers));
}
void delete_thread_context(GlobalManagers *managers)
{
delete managers;
}
void GlobalManagerDeleter::operator()(GlobalManagers *managers)
{
delete_thread_context(managers);
}
void set_thread_context(const GlobalManagers &managers)
{
global_managers = managers;
if (managers.thread_group)
managers.thread_group->refresh_global_timeline_trace_file();
}
void clear_thread_context()
{
global_managers = {};
}
Util::MessageQueue *message_queue()
{
if (!global_managers.logging)
global_managers.logging = new Util::MessageQueue;
return global_managers.logging;
}
Filesystem *filesystem()
{
if (!global_managers.filesystem)
{
LOGI("Filesystem was not initialized. Lazily initializing.\n");
global_managers.filesystem = new Filesystem;
}
return global_managers.filesystem;
}
EventManager *event_manager()
{
if (!global_managers.event_manager)
{
LOGI("Event manager was not initialized. Lazily initializing.\n");
global_managers.event_manager = new EventManager;
}
return global_managers.event_manager;
}
ThreadGroup *thread_group()
{
if (!global_managers.thread_group)
{
LOGI("Thread group was not initialized. Lazily initializing.\n"
"This is potentially dangerous if worker threads use globals.\n");
global_managers.thread_group = new ThreadGroup();
global_managers.thread_group->start(std::thread::hardware_concurrency());
}
return global_managers.thread_group;
}
UI::UIManager *ui_manager()
{
if (!global_managers.ui_manager)
{
LOGI("UI manager was not initialized. Lazily initializing.\n");
global_managers.ui_manager = new UI::UIManager;
}
return global_managers.ui_manager;
}
CommonRendererData *common_renderer_data()
{
if (!global_managers.common_renderer_data)
{
LOGI("Common GPU data was not initialized. Lazily initializing.\n");
global_managers.common_renderer_data = new CommonRendererData;
}
return global_managers.common_renderer_data;
}
#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend() { return global_managers.audio_backend; }
Audio::Mixer *audio_mixer() { return global_managers.audio_mixer; }
void install_audio_system(Audio::Backend *backend, Audio::Mixer *mixer)
{
delete global_managers.audio_mixer;
global_managers.audio_mixer = mixer;
delete global_managers.audio_backend;
global_managers.audio_backend = backend;
}
#endif
#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics()
{
if (!global_managers.physics)
{
LOGI("Physics system was not initialized. Lazily initializing.\n");
global_managers.physics = new PhysicsSystem;
}
return global_managers.physics;
}
#endif
void init(ManagerFeatureFlags flags, unsigned max_threads)
{
if (flags & MANAGER_FEATURE_EVENT_BIT)
{
if (!global_managers.event_manager)
global_managers.event_manager = new EventManager;
}
if (flags & MANAGER_FEATURE_FILESYSTEM_BIT)
{
if (!global_managers.filesystem)
global_managers.filesystem = new Filesystem;
}
bool kick_threads = false;
if (flags & MANAGER_FEATURE_THREAD_GROUP_BIT)
{
if (!global_managers.thread_group)
{
global_managers.thread_group = new ThreadGroup;
kick_threads = true;
}
}
if (flags & MANAGER_FEATURE_UI_MANAGER_BIT)
{
if (!global_managers.ui_manager)
global_managers.ui_manager = new UI::UIManager;
}
if (flags & MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT)
{
if (!global_managers.common_renderer_data)
global_managers.common_renderer_data = new CommonRendererData;
}
if (flags & MANAGER_FEATURE_LOGGING_BIT)
{
if (!global_managers.logging)
global_managers.logging = new Util::MessageQueue;
}
#ifdef HAVE_GRANITE_PHYSICS
if (flags & MANAGER_FEATURE_PHYSICS_BIT)
{
if (!global_managers.physics)
global_managers.physics = new PhysicsSystem;
}
#endif
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_mixer)
global_managers.audio_mixer = new Audio::Mixer;
if (!global_managers.audio_backend)
global_managers.audio_backend = Audio::create_default_audio_backend(*global_managers.audio_mixer, 44100.0f, 2);
#endif
// Kick threads after all global managers are set up.
if (kick_threads)
{
unsigned cpu_threads = std::thread::hardware_concurrency();
if (cpu_threads > max_threads)
cpu_threads = max_threads;
if (const char *env = getenv("GRANITE_NUM_WORKER_THREADS"))
cpu_threads = strtoul(env, nullptr, 0);
global_managers.thread_group->start(cpu_threads);
}
}
void deinit()
{
#ifdef HAVE_GRANITE_AUDIO
if (global_managers.audio_backend)
global_managers.audio_backend->stop();
delete global_managers.audio_backend;
delete global_managers.audio_mixer;
global_managers.audio_backend = nullptr;
global_managers.audio_mixer = nullptr;
#endif
#ifdef HAVE_GRANITE_PHYSICS
delete global_managers.physics;
#endif
delete global_managers.common_renderer_data;
delete global_managers.ui_manager;
delete global_managers.thread_group;
delete global_managers.filesystem;
delete global_managers.event_manager;
delete global_managers.logging;
global_managers.common_renderer_data = nullptr;
global_managers.filesystem = nullptr;
global_managers.event_manager = nullptr;
global_managers.thread_group = nullptr;
global_managers.ui_manager = nullptr;
global_managers.logging = nullptr;
}
void start_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_backend)
return;
if (!global_managers.audio_backend->start())
{
LOGE("Failed to start audio subsystem!\n");
return;
}
if (global_managers.event_manager)
global_managers.event_manager->enqueue_latched<Audio::MixerStartEvent>(*global_managers.audio_mixer);
#endif
}
void stop_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
if (!global_managers.audio_backend)
return;
if (!global_managers.audio_backend->stop())
LOGE("Failed to stop audio subsystem!\n");
if (global_managers.event_manager)
global_managers.event_manager->dequeue_latched(Audio::MixerStartEvent::get_type_id());
#endif
}
}
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <err.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <stdbool.h>
#include <sam.h>
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
#define MIN_NON_OVERLAP 20
#define MAX_UNMAPPED_BASES 50
#define MIN_INDEL_SIZE 50
struct line {
uint32_t pos, raLen, rapos, qaLen, sclip, eclip, SQO, EQO;
char strand;
char *chrm;
};
// This will parse a base 10 int, and change ptr to one char beyond the end of the number.
inline int parseNextInt(char **ptr)
{
int num = 0;
char curChar;
for (curChar = (*ptr)[0]; curChar != 0; curChar = (++(*ptr))[0])
{
int digit = curChar - '0';
if (digit >= 0 && digit <= 9) num = num*10 + digit;
else break;
}
return num;
}
// This will the current char, and move the ptr ahead by one.
inline char parseNextOpCode(char **ptr)
{
return ((*ptr)++)[0];
}
// This just test for end of string.
inline bool moreCigarOps(char *ptr)
{
return (ptr[0] != 0);
}
void calcAlnOffsets(uint32_t *cigar,
uint32_t n_cigar,
uint32_t sa_pos,
char sa_strand,
struct line *l)
{
l->raLen = 0;
l->qaLen = 0;
l->sclip = 0;
l->eclip = 0;
l->SQO = 0;
l->EQO = 0;
bool first = true;
uint32_t k;
for (k = 0; k < n_cigar; ++k)
{
uint32_t opLen = bam_cigar_oplen(cigar[k]);
char opCode = bam_cigar_opchr(cigar[k]);
if (opCode == 'M' || opCode == '=' || opCode == 'X')
{
l->raLen += opLen;
l->qaLen += opLen;
first = false;
}
else if (opCode == 'S' || opCode == 'H')
{
if (first) l->sclip += opLen;
else l->eclip += opLen;
}
else if (opCode == 'D' || opCode == 'N')
{
l->raLen += opLen;
}
else if (opCode == 'I')
{
l->qaLen += opLen;
}
}
//*rapos = str2pos(line->fields[POS]);
l->rapos = sa_pos;
if (sa_strand == '+')
{
l->pos = l->rapos - l->sclip;
l->SQO = l->sclip;
l->EQO = l->sclip + l->qaLen - 1;
}
else
{
l->pos = l->rapos + l->raLen + l->eclip - 1;
l->SQO = l->eclip;
l->EQO = l->eclip + l->qaLen - 1;
}
}
void calcOffsets(char *cigar,
uint32_t sa_pos,
char sa_strand,
struct line *l)
{
l->raLen = 0;
l->qaLen = 0;
l->sclip = 0;
l->eclip = 0;
l->SQO = 0;
l->EQO = 0;
bool first = true;
while (moreCigarOps(cigar))
{
int opLen = parseNextInt(&cigar);
char opCode = parseNextOpCode(&cigar);
if (opCode == 'M' || opCode == '=' || opCode == 'X')
{
l->raLen += opLen;
l->qaLen += opLen;
first = false;
}
else if (opCode == 'S' || opCode == 'H')
{
if (first) l->sclip += opLen;
else l->eclip += opLen;
}
else if (opCode == 'D' || opCode == 'N')
{
l->raLen += opLen;
}
else if (opCode == 'I')
{
l->qaLen += opLen;
}
}
//*rapos = str2pos(line->fields[POS]);
l->rapos = sa_pos;
if (sa_strand == '+')
{
l->pos = l->rapos - l->sclip;
l->SQO = l->sclip;
l->EQO = l->sclip + l->qaLen - 1;
}
else
{
l->pos = l->rapos + l->raLen + l->eclip - 1;
l->SQO = l->eclip;
l->EQO = l->eclip + l->qaLen - 1;
}
}
void split_sa_tag(char *sa_tag,
char **chrm,
uint32_t *pos,
char *strand,
char **cigar)
{
*chrm = strtok(sa_tag, ",");
*pos = atoi(strtok(NULL, ","));
*strand = strtok(NULL, ",")[0];
*cigar = strtok(NULL, ",");
}
int count_tags(char *sa_tag)
{
uint32_t i, c = 0;
for (i = 0; i < strlen(sa_tag); ++i) {
if (sa_tag[i] == ';')
c += 1;
}
return c;
}
int main(int argc, char **argv)
{
if (argc != 4)
errx(1,
"usage\t:%s <bam> <split out> <discord out>",
argv[0]);
char *bam_file_name = argv[1];
char *split_file_name = argv[2];
char *disc_file_name = argv[3];
samFile *disc = sam_open(disc_file_name, "wb");
samFile *split = sam_open(split_file_name, "wb");
samFile *in = sam_open(bam_file_name, "rb");
if(in == NULL)
errx(1, "Unable to open BAM/SAM file.");
hts_idx_t *idx = sam_index_load(in, bam_file_name);
if(idx == NULL)
errx(1,"Unable to open BAM/SAM index.");
bam_hdr_t *hdr = sam_hdr_read(in);
int r = sam_hdr_write(disc, hdr);
r = sam_hdr_write(split, hdr);
bam1_t *aln = bam_init1();
while(sam_read1(in, hdr, aln) >= 0) {
if (((aln->core.flag) & 1294) == 0)
r = sam_write1(disc, hdr, aln);
uint8_t *sa = bam_aux_get(aln, "SA");
if (sa != 0) {
char *sa_tag = strdup(bam_aux2Z(sa));
if ( count_tags(sa_tag) == 1) {
char *chrm, strand, *cigar;
uint32_t pos;
split_sa_tag(sa_tag,
&chrm,
&pos,
&strand,
&cigar);
struct line sa, al;
calcOffsets(cigar,
pos,
strand,
&sa);
sa.chrm = chrm;
sa.strand = strand;
calcAlnOffsets(bam_get_cigar(aln),
aln->core.n_cigar,
aln->core.pos + 1,
bam_is_rev(aln) ? '-' : '+',
&al);
al.chrm = hdr->target_name[aln->core.tid];
al.strand = bam_is_rev(aln) ? '-' : '+';
struct line *left = &al, *right = &sa;
if (left->SQO > right->SQO) {
left = &sa;
right = &al;
}
int overlap = MAX(1 + MIN(left->EQO, right->EQO) -
MAX(left->SQO, right->SQO), 0);
int alen1 = 1 + left->EQO - left->SQO;
int alen2 = 1 + right->EQO - right->SQO;
int mno = MIN(alen1-overlap, alen2-overlap);
if (mno < MIN_NON_OVERLAP)
continue;
if ( (strcmp(left->chrm, right->chrm) == 0) &&
(left->strand == right->strand) ) {
int leftDiag, rightDiag, insSize;
if (left->strand == '-') {
leftDiag = left->rapos - left->sclip;
rightDiag = (right->rapos + right->raLen) -
(right->sclip + right->qaLen);
insSize = rightDiag - leftDiag;
} else {
leftDiag = (left->rapos + left->raLen) -
(left->sclip + left->qaLen);
rightDiag = right->rapos - right->sclip;
insSize = leftDiag - rightDiag;
}
int desert = right->SQO - left->EQO - 1;
if ((abs(insSize) < MIN_INDEL_SIZE) ||
((desert > 0) && (
(desert - (int)MAX(0, insSize)) >
MAX_UNMAPPED_BASES)))
continue;
}
char *qname = bam_get_qname(aln);
if ((aln->core.flag & 64) == 64)
qname[0] = 'A';
else
qname[0] = 'B';
r = sam_write1(split, hdr, aln);
}
free(sa_tag);
}
}
bam_destroy1(aln);
hts_idx_destroy(idx);
bam_hdr_destroy(hdr);
sam_close(in);
sam_close(disc);
sam_close(split);
}
<commit_msg>first draft for testing of complete program<commit_after>#include "process_splitters/Parse.hpp"
#include "process_splitters/Alignment.hpp"
#include <sam.h>
#include <string>
#include <iostream>
#define MIN_NON_OVERLAP 20
#define MAX_UNMAPPED_BASES 50
#define MIN_INDEL_SIZE 50
int main(int argc, char **argv)
{
if (argc != 4)
std::cerr << "usage:\tprocess_splitters <bam> <split out> <discord out>" << std::endl;
char *bam_file_name = argv[1];
char *split_file_name = argv[2];
char *disc_file_name = argv[3];
samFile *disc = sam_open(disc_file_name, "wb");
samFile *split = sam_open(split_file_name, "wb");
samFile *in = sam_open(bam_file_name, "rb");
if(in == NULL)
std::cerr << "Unable to open BAM/SAM file." << std::endl;
hts_idx_t *idx = sam_index_load(in, bam_file_name);
if(idx == NULL)
std::cerr << "Unable to open BAM/SAM index." << std::endl;
bam_hdr_t *hdr = sam_hdr_read(in);
int r = sam_hdr_write(disc, hdr);
r = sam_hdr_write(split, hdr);
bam1_t *aln = bam_init1();
while(sam_read1(in, hdr, aln) >= 0) {
if (((aln->core.flag) & 1294) == 0)
r = sam_write1(disc, hdr, aln);
if (aln->core.flag & (BAM_FUNMAP | BAM_FQCFAIL | BAM_FDUP)) {
continue;
}
uint8_t *sa = bam_aux_get(aln, "SA");
if (sa != 0) {
std::string sa_string = bam_aux2Z(sa);
char const* beg = sa_string.data();
char const* end = beg + sa_string.size();
SimpleTokenizer tok(beg, end, ';');
std::string first_sa;
if (!tok.extract(first_sa)) {
//TODO THROW
}
if (tok.next_delim() == end) {
Alignment first(aln, hdr);
Alignment second(first_sa.data(), first_sa.data() + first_sa.size());
Alignment const* left = &first;
Alignment const* right = &second;
if (left->SQO > right->SQO) {
left = &first;
right = &second;
}
if (mno(*left, *right) < MIN_NON_OVERLAP)
continue;
if (should_check(*left, *right)) {
if ((abs(insert_size(*left, *right) < MIN_INDEL_SIZE)
|| ((desert(*left, *right) > 0)
&& (desert(*left, *right) - (int) std::max(0, insert_size(*left, *right))) > MAX_UNMAPPED_BASES))) {
continue;
}
}
char *qname = bam_get_qname(aln);
if ((aln->core.flag & 64) == 64)
qname[0] = 'A';
else
qname[0] = 'B';
r = sam_write1(split, hdr, aln);
}
}
}
bam_destroy1(aln);
hts_idx_destroy(idx);
bam_hdr_destroy(hdr);
sam_close(in);
sam_close(disc);
sam_close(split);
}
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvbsptreevisitors.h"
#include "vvgltools.h"
#include "vvrendermaster.h"
#include "vvtexrend.h"
vvRenderMaster::vvRenderMaster(std::vector<char*>& slaveNames, std::vector<int>& slavePorts,
std::vector<char*>& slaveFileNames,
const char* fileName)
: _slaveNames(slaveNames), _slavePorts(slavePorts),
_slaveFileNames(slaveFileNames), _fileName(fileName)
{
_visitor = new vvSlaveVisitor();
}
vvRenderMaster::~vvRenderMaster()
{
// The visitor will delete the sockets either.
delete _visitor;
}
vvRenderMaster::ErrorType vvRenderMaster::initSockets(const int defaultPort, vvSocket::SocketType st,
const bool redistributeVolData,
vvVolDesc*& vd)
{
const bool loadVolumeFromFile = !redistributeVolData;
for (int s=0; s<_slaveNames.size(); ++s)
{
if (_slavePorts[s] == -1)
{
_sockets.push_back(new vvSocketIO(defaultPort, _slaveNames[s], st));
}
else
{
_sockets.push_back(new vvSocketIO(_slavePorts[s], _slaveNames[s], st));
}
_sockets[s]->set_debuglevel(vvDebugMsg::getDebugLevel());
_sockets[s]->no_nagle();
if (_sockets[s]->init() == vvSocket::VV_OK)
{
_sockets[s]->putBool(loadVolumeFromFile);
if (loadVolumeFromFile)
{
const bool allFileNamesAreEqual = (_slaveFileNames.size() == 0);
if (allFileNamesAreEqual)
{
_sockets[s]->putFileName(_fileName);
}
else
{
if (_slaveFileNames.size() > s)
{
_sockets[s]->putFileName(_slaveFileNames[s]);
}
else
{
// Not enough file names specified, try this one.
_sockets[s]->putFileName(_fileName);
}
}
}
else
{
switch (_sockets[s]->putVolume(vd))
{
case vvSocket::VV_OK:
cerr << "Volume transferred successfully" << endl;
break;
case vvSocket::VV_ALLOC_ERROR:
cerr << "Not enough memory" << endl;
return VV_SOCKET_ERROR;
default:
cerr << "Cannot write volume to socket" << endl;
return VV_SOCKET_ERROR;
}
}
}
else
{
cerr << "No connection to remote rendering server established at: " << _slaveNames[0] << endl;
cerr << "Falling back to local rendering" << endl;
return VV_SOCKET_ERROR;
}
}
_visitor->setSockets(_sockets);
return VV_OK;
}
vvRenderMaster::ErrorType vvRenderMaster::initBricks(vvTexRend* renderer)
{
// This will build up the bsp tree of the master node.
renderer->prepareDistributedRendering(_slaveNames.size());
// Store a pointer to the bsp tree and set its visitor.
_bspTree = renderer->getBspTree();
_bspTree->setVisitor(_visitor);
_renderer = renderer;
// Distribute the bricks from the bsp tree
for (int s=0; s<_sockets.size(); ++s)
{
switch (_sockets[s]->putBricks(renderer->getBrickListsToDistribute()[s]->at(0)))
{
case vvSocket::VV_OK:
cerr << "Brick outlines transferred successfully" << endl;
break;
default:
cerr << "Unable to transfer brick outlines" << endl;
return VV_SOCKET_ERROR;
}
}
return VV_OK;
}
void vvRenderMaster::render(const float bgColor[3]) const
{
float matrixGL[16];
vvMatrix pr;
glGetFloatv(GL_PROJECTION_MATRIX, matrixGL);
pr.set(matrixGL);
vvMatrix mv;
glGetFloatv(GL_MODELVIEW_MATRIX, matrixGL);
mv.set(matrixGL);
_renderer->calcProjectedScreenRects();
_visitor->setProjectionMatrix(pr);
_visitor->setModelviewMatrix(mv);
glDrawBuffer(GL_BACK);
glClearColor(bgColor[0], bgColor[1], bgColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Retrieve the eye position for bsp-tree traversal
vvVector3 eye;
_renderer->getEyePosition(&eye);
vvMatrix invMV(&mv);
invMV.invert();
eye.multiply(&invMV);
// Orthographic projection.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
// Fix the proxy quad for the frame buffer texture.
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Setup compositing.
glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
_bspTree->traverse(eye);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
<commit_msg>Calculate the eye position for bsp-tree traversal correctly<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvbsptreevisitors.h"
#include "vvgltools.h"
#include "vvrendermaster.h"
#include "vvtexrend.h"
vvRenderMaster::vvRenderMaster(std::vector<char*>& slaveNames, std::vector<int>& slavePorts,
std::vector<char*>& slaveFileNames,
const char* fileName)
: _slaveNames(slaveNames), _slavePorts(slavePorts),
_slaveFileNames(slaveFileNames), _fileName(fileName)
{
_visitor = new vvSlaveVisitor();
}
vvRenderMaster::~vvRenderMaster()
{
// The visitor will delete the sockets either.
delete _visitor;
}
vvRenderMaster::ErrorType vvRenderMaster::initSockets(const int defaultPort, vvSocket::SocketType st,
const bool redistributeVolData,
vvVolDesc*& vd)
{
const bool loadVolumeFromFile = !redistributeVolData;
for (int s=0; s<_slaveNames.size(); ++s)
{
if (_slavePorts[s] == -1)
{
_sockets.push_back(new vvSocketIO(defaultPort, _slaveNames[s], st));
}
else
{
_sockets.push_back(new vvSocketIO(_slavePorts[s], _slaveNames[s], st));
}
_sockets[s]->set_debuglevel(vvDebugMsg::getDebugLevel());
_sockets[s]->no_nagle();
if (_sockets[s]->init() == vvSocket::VV_OK)
{
_sockets[s]->putBool(loadVolumeFromFile);
if (loadVolumeFromFile)
{
const bool allFileNamesAreEqual = (_slaveFileNames.size() == 0);
if (allFileNamesAreEqual)
{
_sockets[s]->putFileName(_fileName);
}
else
{
if (_slaveFileNames.size() > s)
{
_sockets[s]->putFileName(_slaveFileNames[s]);
}
else
{
// Not enough file names specified, try this one.
_sockets[s]->putFileName(_fileName);
}
}
}
else
{
switch (_sockets[s]->putVolume(vd))
{
case vvSocket::VV_OK:
cerr << "Volume transferred successfully" << endl;
break;
case vvSocket::VV_ALLOC_ERROR:
cerr << "Not enough memory" << endl;
return VV_SOCKET_ERROR;
default:
cerr << "Cannot write volume to socket" << endl;
return VV_SOCKET_ERROR;
}
}
}
else
{
cerr << "No connection to remote rendering server established at: " << _slaveNames[0] << endl;
cerr << "Falling back to local rendering" << endl;
return VV_SOCKET_ERROR;
}
}
_visitor->setSockets(_sockets);
return VV_OK;
}
vvRenderMaster::ErrorType vvRenderMaster::initBricks(vvTexRend* renderer)
{
// This will build up the bsp tree of the master node.
renderer->prepareDistributedRendering(_slaveNames.size());
// Store a pointer to the bsp tree and set its visitor.
_bspTree = renderer->getBspTree();
_bspTree->setVisitor(_visitor);
_renderer = renderer;
// Distribute the bricks from the bsp tree
for (int s=0; s<_sockets.size(); ++s)
{
switch (_sockets[s]->putBricks(renderer->getBrickListsToDistribute()[s]->at(0)))
{
case vvSocket::VV_OK:
cerr << "Brick outlines transferred successfully" << endl;
break;
default:
cerr << "Unable to transfer brick outlines" << endl;
return VV_SOCKET_ERROR;
}
}
return VV_OK;
}
void vvRenderMaster::render(const float bgColor[3]) const
{
float matrixGL[16];
vvMatrix pr;
glGetFloatv(GL_PROJECTION_MATRIX, matrixGL);
pr.set(matrixGL);
vvMatrix mv;
glGetFloatv(GL_MODELVIEW_MATRIX, matrixGL);
mv.set(matrixGL);
_renderer->calcProjectedScreenRects();
_visitor->setProjectionMatrix(pr);
_visitor->setModelviewMatrix(mv);
glDrawBuffer(GL_BACK);
glClearColor(bgColor[0], bgColor[1], bgColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Retrieve the eye position for bsp-tree traversal
vvVector3 eye;
_renderer->getEyePosition(&eye);
vvMatrix invMV(&mv);
invMV.invert();
// This is a gl matrix ==> transpose.
invMV.transpose();
eye.multiply(&invMV);
// Orthographic projection.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
// Fix the proxy quad for the frame buffer texture.
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Setup compositing.
glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
_bspTree->traverse(eye);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
<|endoftext|> |
<commit_before>// rungekutta.cpp: program to solve odes with classic Runge-Kutta method
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
// Configure the posit library with arithmetic exceptions
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>
/*
Mathematical C++ Symbol Decimal Representation
Expression
pi M_PI 3.14159265358979323846
pi/2 M_PI_2 1.57079632679489661923
pi/4 M_PI_4 0.785398163397448309616
1/pi M_1_PI 0.318309886183790671538
2/pi M_2_PI 0.636619772367581343076
2/sqrt(pi) M_2_SQRTPI 1.12837916709551257390
sqrt(2) M_SQRT2 1.41421356237309504880
1/sqrt(2) M_SQRT1_2 0.707106781186547524401
e M_E 2.71828182845904523536
log_2(e) M_LOG2E 1.44269504088896340736
log_10(e) M_LOG10E 0.434294481903251827651
log_e(2) M_LN2 0.693147180559945309417
log_e(10) M_LN10 2.30258509299404568402
*/
// constexpr double pi = 3.14159265358979323846; // best practice for C++
// our test function where dy/dx is f(x,y)
template<typename Scalar>
Scalar myFunc(const Scalar& x, const Scalar& y) {
return ((5*x*x - y)/exp ((x + y)));
}
// rk4 algorithm
// requires a two variable function (defined above), initial conditions for x and y,
// number of intervals across which to approximate y(x), and stepsize between intervals
template<typename Scalar>
void rk4(Scalar (*f)(const Scalar&, const Scalar&), int n, Scalar& h, Scalar& x, Scalar& y) {
using namespace std;
const Scalar x0 = x;
for (unsigned int i = 0; i < n + 1; i++) {
x = x0 + i*h;
auto f1 = h*f(x, y);
auto f2 = h*f(x + h/2, y + f1/2);
auto f3 = h*f(x + h/2, y + f2/2);
auto f4 = h*f(x + h, y + f3);
y = y + (f1 + 2*f2 + 2*f3 + f4)/6;
cout << "y(" << x << ") ~= " << y << std::endl;
}
return;
}
int main()
try {
using namespace std;
using namespace sw::unum;
{ using Scalar = posit<16, 2>;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "\nThe ode is: dy/dx = (5*x*x - y)/exp(x + y)\n" << std::endl;
std::cout << "Using posit<16, 1>" << std::endl;
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
{
using Scalar = posit<32, 2>;
std::cout << "\nUsing posit<32, 1>" << std::endl;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
{
using Scalar = posit<64, 2>;
std::cout << "\nUsing posit<64, 1>" << std::endl;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<commit_msg>Update rungakutta<commit_after>// rungekutta.cpp: program to solve odes with classic Runge-Kutta method
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#define _USE_MATH_DEFINES
#include <cmath>
// Configure the posit library with arithmetic exceptions
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>
/*
Mathematical C++ Symbol Decimal Representation
Expression
pi M_PI 3.14159265358979323846
pi/2 M_PI_2 1.57079632679489661923
pi/4 M_PI_4 0.785398163397448309616
1/pi M_1_PI 0.318309886183790671538
2/pi M_2_PI 0.636619772367581343076
2/sqrt(pi) M_2_SQRTPI 1.12837916709551257390
sqrt(2) M_SQRT2 1.41421356237309504880
1/sqrt(2) M_SQRT1_2 0.707106781186547524401
e M_E 2.71828182845904523536
log_2(e) M_LOG2E 1.44269504088896340736
log_10(e) M_LOG10E 0.434294481903251827651
log_e(2) M_LN2 0.693147180559945309417
log_e(10) M_LN10 2.30258509299404568402
*/
// constexpr double pi = 3.14159265358979323846; // best practice for C++
// our test function where dy/dx is f(x,y)
template<typename Scalar>
Scalar myFunc(const Scalar& x, const Scalar& y) {
return ((5*x*x - y)/exp ((x + y)));
}
// rk4 algorithm
// requires a two variable function (defined above), initial conditions for x and y,
// number of intervals across which to approximate y(x), and stepsize between intervals
template<typename Scalar>
void rk4(Scalar (*f)(const Scalar&, const Scalar&), int n, Scalar& h, Scalar& x, Scalar& y) {
using namespace std;
const Scalar x0 = x;
for (unsigned int i = 0; i < n + 1; i++) {
x = x0 + i*h;
auto f1 = h*f(x, y);
auto f2 = h*f(x + h/2, y + f1/2);
auto f3 = h*f(x + h/2, y + f2/2);
auto f4 = h*f(x + h, y + f3);
y = y + (f1 + 2*f2 + 2*f3 + f4)/6;
cout << "y(" << x << ") ~= " << y << std::endl;
}
return;
}
int main()
try {
using namespace std;
using namespace sw::unum;
{ using Scalar = posit<16, 2>;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "\nThe ode is: dy/dx = (5*x*x - y)/exp(x + y)\n" << std::endl;
std::cout << "Using posit<16, 1>" << std::endl;
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
{
using Scalar = posit<32, 2>;
std::cout << "\nUsing posit<32, 1>" << std::endl;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
{
using Scalar = posit<64, 2>;
std::cout << "\nUsing posit<64, 1>" << std::endl;
Scalar x0 = 0; // initial x
Scalar y0 = 1; // initial y
Scalar h = Scalar(M_PI_4); // step size between intervals
int n = 4; // number of intervals
std::cout << "Appoximating y(x) from " << x0 << " to " << x0 + n*h << std::endl;
std::cout << "step size = " << h << std::endl;
rk4 (&myFunc, n, h, x0, y0);
}
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include <Empathy/Empathy/Empathy.h>
#include <Empathy/empathy-linear/linear_empathy.h>
#include <irrKlang.h>
#include <GLFW/glfw3.h>
#define FULL_SCREEN false
#if FULL_SCREEN
#define RENDER_SIZE 768
#define SC_SIZE_X 1366
#define SC_SIZE_Y 768
#else
#define RENDER_SIZE 690
#define SC_SIZE_X 700
#define SC_SIZE_Y 700
#endif
using namespace std;
static GLFWwindow * window;
static GLfloat mouseX,mouseY;
irrklang::ISoundEngine* engine;
static GLdouble lastPressTime;
static GLdouble thresholdTime=0.2;
static GLboolean mousePressed=GL_FALSE;
void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){
empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE);
if(button==GLFW_MOUSE_BUTTON_LEFT ){
event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS);
}else if(button==GLFW_MOUSE_BUTTON_RIGHT){
event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS);
}
event.putDouble(EMPATHY_MOUSE_XPOS,mouseX);
event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY);
empathy::radio::BroadcastStation::emit(event);
}
void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) {
if(action==GLFW_PRESS){
createClickEvent(button);
lastPressTime=glfwGetTime();
mousePressed=GL_TRUE;
}else if(action==GLFW_RELEASE){
lastPressTime=0;
mousePressed=GL_FALSE;
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
// std::cout<<"key call back received"<<action<<std::endl;
// When a user presses the escape key, we set the WindowShouldClose property to true,
// closing the application
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
// glfwSetWindowShouldClose(instance->window, GL_TRUE);
empathy_linear::makeReadyToClose();
return;
}
cout<<"KEY callback"<<endl;
std::string myAction="";
if(action==GLFW_PRESS){
myAction=EMPATHY_EVENT_INPUT_KEY_PRESS;
}else if(action==GLFW_RELEASE){
myAction=EMPATHY_EVENT_INPUT_KEY_RELEASE;
}else if(action==GLFW_REPEAT){
myAction=EMPATHY_EVENT_INPUT_KEY_REPEAT;
}
if(myAction != ""){
empathy::radio::Event event=empathy::radio::Event(myAction);
event.putInt(EMPATHY_EVENT_INPUT_KEY,key);
empathy::radio::BroadcastStation::emit(event);
}
}
void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) {
mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;;
mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2;
}
void initGlfw() {
// cout<<"glfwInit"<<endl;
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
int count;
GLFWmonitor** monitors=glfwGetMonitors(&count);
//Create a GLFW window
window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3",
FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
//set event receiver call backs.
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window,mouse_input_callback);
glfwSetCursorPosCallback(window,mouse_position_callback);
}
void init(){
GLFWmonitor * glfWmonitor=glfwGetPrimaryMonitor();
initGlfw();
empathy_linear::init();
empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2);
empathy_linear::setScreenSize(RENDER_SIZE);
empathy_linear::addJsonBrain("brains/CanonInD.json");
empathy_linear::addDummyTouchBrain();
engine = irrklang::createIrrKlangDevice();
if (!engine)
{
printf("Could not startup engine\n");
exit(EXIT_FAILURE);
}
engine->setSoundVolume(0.4f);
}
void loop(){
while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){
std::stack<empathy::moonlight::BasicNote> audioEvents= empathy_linear::getMusicalKeyboardEvents();
while(! audioEvents.empty()){
empathy::moonlight::BasicNote playableItem=audioEvents.top();
std::string fileName=playableItem.getNote();
fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1);
if(playableItem.isSharp()){
fileName="#"+fileName;
}
std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3");
try{
cout<<"Playing audio "<<fileName<<endl;
engine->play2D(path.c_str());
}catch (int i){
cout<<"Could not play "<<path<<endl;
continue;
}
audioEvents.pop();
}
if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){
createClickEvent();
}
glfwPollEvents();
empathy_linear::loop();
empathy_linear::setTime((GLfloat ) glfwGetTime());
glfwSwapBuffers(window);
}
}
void flush(){
engine->drop();
empathy_linear::flush();
if(window!= nullptr)
glfwSetWindowShouldClose(window,true);
glfwTerminate();
}
int main() {
init();
loop();
flush();
}
<commit_msg>bug fixes<commit_after>#include <Empathy/Empathy/Empathy.h>
#include <Empathy/empathy-linear/linear_empathy.h>
#include <irrKlang.h>
#include <GLFW/glfw3.h>
#define FULL_SCREEN false
#if FULL_SCREEN
#define RENDER_SIZE 768
#define SC_SIZE_X 1366
#define SC_SIZE_Y 768
#else
#define RENDER_SIZE 690
#define SC_SIZE_X 700
#define SC_SIZE_Y 700
#endif
using namespace std;
static GLFWwindow * window;
static GLfloat mouseX,mouseY;
irrklang::ISoundEngine* engine;
static GLdouble lastPressTime;
static GLdouble thresholdTime=0.2;
static GLboolean mousePressed=GL_FALSE;
void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){
empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE);
if(button==GLFW_MOUSE_BUTTON_LEFT ){
event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS);
}else if(button==GLFW_MOUSE_BUTTON_RIGHT){
event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS);
}
event.putDouble(EMPATHY_MOUSE_XPOS,mouseX);
event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY);
empathy::radio::BroadcastStation::emit(event);
}
void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) {
if(action==GLFW_PRESS){
createClickEvent(button);
lastPressTime=glfwGetTime();
mousePressed=GL_TRUE;
}else if(action==GLFW_RELEASE){
lastPressTime=0;
mousePressed=GL_FALSE;
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
// std::cout<<"key call back received"<<action<<std::endl;
// When a user presses the escape key, we set the WindowShouldClose property to true,
// closing the application
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
// glfwSetWindowShouldClose(instance->window, GL_TRUE);
empathy_linear::makeReadyToClose();
return;
}
cout<<"KEY callback"<<endl;
std::string myAction="";
if(action==GLFW_PRESS){
myAction=EMPATHY_EVENT_INPUT_KEY_PRESS;
}else if(action==GLFW_RELEASE){
myAction=EMPATHY_EVENT_INPUT_KEY_RELEASE;
}else if(action==GLFW_REPEAT){
myAction=EMPATHY_EVENT_INPUT_KEY_REPEAT;
}
if(myAction != ""){
empathy::radio::Event event=empathy::radio::Event(myAction);
event.putInt(EMPATHY_EVENT_INPUT_KEY,key);
empathy::radio::BroadcastStation::emit(event);
}
}
void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) {
mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;;
mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2;
}
void initGlfw() {
// cout<<"glfwInit"<<endl;
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
int count;
GLFWmonitor** monitors=glfwGetMonitors(&count);
//Create a GLFW window
window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3",
FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
//set event receiver call backs.
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window,mouse_input_callback);
glfwSetCursorPosCallback(window,mouse_position_callback);
}
void init(){
GLFWmonitor * glfWmonitor=glfwGetPrimaryMonitor();
initGlfw();
empathy_linear::init();
empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2);
empathy_linear::setScreenSize(RENDER_SIZE);
empathy_linear::addJsonBrain("brains/CanonInD.json");
empathy_linear::addDummyTouchBrain();
engine = irrklang::createIrrKlangDevice();
if (!engine)
{
printf("Could not startup engine\n");
exit(EXIT_FAILURE);
}
engine->setSoundVolume(0.4f);
}
void loop(){
while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){
std::stack<empathy::moonlight::BasicNote> audioEvents= empathy_linear::getMusicalKeyboardEvents();
while(! audioEvents.empty()){
empathy::moonlight::BasicNote playableItem=audioEvents.top();
std::string fileName=playableItem.getNote();
fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1);
if(playableItem.isSharp()){
fileName="#"+fileName;
}
std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3");
try{
// cout<<"Playing audio "<<fileName<<endl;
engine->play2D(path.c_str());
}catch (int i){
cout<<"Could not play "<<path<<endl;
continue;
}
audioEvents.pop();
}
if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){
createClickEvent();
}
glfwPollEvents();
empathy_linear::loop();
empathy_linear::setTime((GLfloat ) glfwGetTime());
glfwSwapBuffers(window);
}
}
void flush(){
engine->drop();
empathy_linear::flush();
if(window!= nullptr)
glfwSetWindowShouldClose(window,true);
glfwTerminate();
}
int main() {
init();
loop();
flush();
}
<|endoftext|> |
<commit_before>/*
* This program is just for personal experiments here on C++ mixin for
* handling lifecycle of specific objects.
*/
#include <string.h>
#include <fastarduino/errors.h>
#include <fastarduino/move.h>
#include <fastarduino/time.h>
// includes for the example program itself
#include <fastarduino/tests/assertions.h>
#include <fastarduino/uart.h>
#include <fastarduino/iomanip.h>
#include <fastarduino/flash.h>
// Register vector for UART (used for debug)
REGISTER_UATX_ISR(0)
// API Proof of Concept
//======================
//TODO see if further code size optimization is possible
//TODO work out and check Proxy classes
//FIXME 2 AbstractLifeCycle may have different managers?
// - in this case, how should the move (ctor and assignment) should be handled?
// => that would bring additional code maybe for nothing?
// Forward declaration
class AbstractLifeCycleManager;
template<typename T> class LifeCycle;
// LifeCycle handling
class AbstractLifeCycle
{
public:
AbstractLifeCycle() = default;
AbstractLifeCycle(AbstractLifeCycle&& that);
~AbstractLifeCycle();
AbstractLifeCycle& operator=(AbstractLifeCycle&& that);
AbstractLifeCycle(const AbstractLifeCycle&) = delete;
AbstractLifeCycle& operator=(const AbstractLifeCycle&) = delete;
uint8_t id() const
{
return id_;
}
private:
uint8_t id_ = 0;
AbstractLifeCycleManager* manager_ = nullptr;
friend class AbstractLifeCycleManager;
template<typename T> friend class Proxy;
};
class AbstractLifeCycleManager
{
public:
template<typename T> uint8_t register_(LifeCycle<T>& instance)
{
return register_impl_(instance);
}
bool unregister_(uint8_t id)
{
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr || *slot == nullptr)
return false;
AbstractLifeCycle& source = **slot;
source.id_ = 0;
source.manager_ = nullptr;
*slot = nullptr;
++free_slots_;
return true;
}
uint8_t available_() const
{
return free_slots_;
}
bool move_(uint8_t id, AbstractLifeCycle& dest)
{
// Check this instance is managed
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr || *slot == nullptr) return false;
// Perform move
AbstractLifeCycle& source = **slot;
dest.id_ = source.id_;
dest.manager_ = this;
source.id_ = 0;
source.manager_ = nullptr;
*slot = &dest;
return true;
}
template<typename T> LifeCycle<T>* find_(uint8_t id) const
{
return static_cast<LifeCycle<T>*>(find_impl_(id));
}
protected:
AbstractLifeCycleManager(AbstractLifeCycle** slots, uint8_t size)
: size_{size}, slots_{slots}, free_slots_{size}
{
memset(slots, 0, size * sizeof(AbstractLifeCycle*));
}
~AbstractLifeCycleManager() = default;
AbstractLifeCycleManager(const AbstractLifeCycleManager&) = delete;
AbstractLifeCycleManager& operator=(const AbstractLifeCycleManager&) = delete;
private:
uint8_t register_impl_(AbstractLifeCycle& instance)
{
// Youcannot register any instance if there are no free slots remaining
if (free_slots_ == 0) return 0;
// You cannot register an already registered future
if (instance.id_ != 0) return 0;
// Optimization: we start search AFTER the last removed id
for (uint8_t i = last_removed_id_; i < size_; ++i)
if (register_at_index_(instance, i))
return i + 1;
for (uint8_t i = 0; i <= last_removed_id_; ++i)
if (register_at_index_(instance, i))
return i + 1;
return 0;
}
AbstractLifeCycle* find_impl_(uint8_t id) const
{
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr)
return nullptr;
else
return *slot;
}
AbstractLifeCycle** find_slot_(uint8_t id) const
{
if (id == 0 || id > size_)
return nullptr;
else
return &slots_[id - 1];
}
bool register_at_index_(AbstractLifeCycle& instance, uint8_t index)
{
if (slots_[index] != nullptr)
return false;
instance.id_ = static_cast<uint8_t>(index + 1);
instance.manager_ = this;
slots_[index] = &instance;
--free_slots_;
return true;
}
const uint8_t size_;
AbstractLifeCycle** slots_;
uint8_t free_slots_;
uint8_t last_removed_id_ = 0;
};
template<uint8_t SIZE> class LifeCycleManager : public AbstractLifeCycleManager
{
public:
LifeCycleManager() : AbstractLifeCycleManager{slots_buffer_, SIZE} {}
private:
AbstractLifeCycle* slots_buffer_[SIZE];
};
AbstractLifeCycle::AbstractLifeCycle(AbstractLifeCycle&& that)
{
if (that.id_)
that.manager_->move_(that.id_, *this);
}
AbstractLifeCycle::~AbstractLifeCycle()
{
if (id_)
manager_->unregister_(id_);
}
AbstractLifeCycle& AbstractLifeCycle::operator=(AbstractLifeCycle&& that)
{
if (id_)
manager_->unregister_(id_);
if (that.id_)
that.manager_->move_(that.id_, *this);
return *this;
}
template<typename T> class LifeCycle : public AbstractLifeCycle, public T
{
public:
LifeCycle(const T& value = T{}) : AbstractLifeCycle{}, T{value} {}
// LifeCycle(const LifeCycle<T>&) = delete;
LifeCycle(LifeCycle<T>&& that) = default;
~LifeCycle() = default;
// LifeCycle<T>& operator=(const LifeCycle<T>&) = delete;
LifeCycle<T>& operator=(LifeCycle<T>&& that) = default;
};
// We also need a "direct proxy" specialization for non LifeCycle<T>
template<typename T> class Proxy
{
public:
Proxy(T& dest) : dest_{&dest} {}
Proxy(const Proxy&) = default;
Proxy& operator=(const Proxy&) = default;
T& operator*()
{
return *dest_;
}
T* operator->()
{
return dest_;
}
private:
T* dest_;
};
template<typename T> class Proxy<LifeCycle<T>>
{
using LC = LifeCycle<T>;
public:
Proxy(const LC& dest) : id_{dest.id_}, manager_{dest.manager_} {}
Proxy(const Proxy&) = default;
Proxy& operator=(const Proxy&) = default;
LC& operator*()
{
return *(manager_->find_<T>(id_));
}
LC* operator->()
{
return manager_->find_<T>(id_);
}
private:
const uint8_t id_;
AbstractLifeCycleManager* manager_;
};
// Usage Example
//===============
using namespace streams;
// Define types that output traces on each ctor/dtor/operator=
class Value
{
public:
static void set_out(ostream& out)
{
out_ = &out;
}
Value(int val = 0) : val_{val}
{
trace('c');
}
~Value()
{
trace('d');
}
Value(const Value& that) : val_{that.val_}
{
trace('C');
}
Value(Value&& that) : val_{that.val_}
{
trace('M');
}
Value& operator=(const Value& that)
{
this->val_ = that.val_;
trace('=');
return *this;
}
Value& operator=(Value&& that)
{
this->val_ = that.val_;
trace('m');
return *this;
}
int val() const
{
return val_;
}
static ostream& out()
{
return *out_;
}
protected:
void trace(char method)
{
if (out_)
*out_ << method << dec << val_ << ' ' << hex << this << endl;
}
static ostream* out_;
int val_;
};
ostream* Value::out_ = nullptr;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];
static constexpr const uint8_t MAX_LC_SLOTS = 32;
template<typename T> static void check(ostream& out, AbstractLifeCycleManager& manager, const T& init)
{
{
out << F("0. Instance creation") << endl;
LifeCycle<T> instance{init};
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
assert(out, F("id() after construction"), 0, instance.id());
out << F("1. Registration") << endl;
uint8_t id = manager.register_(instance);
assert(out, F("id returned by register_()"), id);
assert(out, F("id() after registration"), id, instance.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
out << F("2. Find") << endl;
LifeCycle<T>* found = manager.find_<T>(id);
assert(out, F("manager.find_(id)"), found != nullptr);
assert(out, F("manager.find_(id)"), &instance, found);
out << F("val=") << dec << found->val() << endl;
//TODO Check copy never compiles
// LifeCycle<T> copy{instance};
out << F("3. Move constructor") << endl;
LifeCycle<T> move = std::move(instance);
assert(out, F("original id() after registration"), 0, instance.id());
assert(out, F("moved id() after registration"), id, move.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
out << F("4. Find after move") << endl;
found = manager.find_<T>(id);
assert(out, F("manager.find_(id)"), found != nullptr);
assert(out, F("manager.find_(id)"), &move, found);
out << F("val=") << dec << found->val() << endl;
//TODO Check copy never compiles
// LifeCycle<T> copy;
// copy = move;
out << F("5. Move assignment") << endl;
LifeCycle<T> move2;
move2 = std::move(move);
assert(out, F("original id() after registration"), 0, move.id());
assert(out, F("moved id() after registration"), id, move2.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
}
// Check destruction
out << F("6. Destruction") << endl;
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
}
class SubValue : public Value
{
public:
SubValue(int val = 0, int val2 = 0) : Value{val}, val2_{val2} {}
~SubValue() = default;
SubValue(const SubValue& that) = default;
SubValue(SubValue&& that) = default;
SubValue& operator=(const SubValue& that) = default;
SubValue& operator=(SubValue&& that) = default;
int val2() const
{
return val2_;
}
private:
int val2_;
};
void check_proxies(ostream& out)
{
Value v1{10};
SubValue v2{20, 30};
LifeCycle<Value> lc1{v1};
LifeCycle<SubValue> lc2{v2};
Proxy<Value> p1{v1};
Proxy<Value> p2{v2};
Proxy<LifeCycle<Value>> p3{lc1};
Proxy<LifeCycle<Value>> p4{lc2};
out << F("p1->val()") << dec << p1->val() << endl;
out << F("p2->val()") << dec << p2->val() << endl;
//FIXME both lines show 0 for val()
out << F("p3->val()") << dec << p3->val() << endl;
out << F("p4->val()") << dec << p4->val() << endl;
}
int main() __attribute__((OS_main));
int main()
{
board::init();
// Enable interrupts at startup time
sei();
// Initialize debugging output
serial::hard::UATX<board::USART::USART0> uart{output_buffer};
uart.begin(115200);
ostream out = uart.out();
out << boolalpha << showbase;
out << F("Starting...") << endl;
Value::set_out(out);
out << F("Create constant Value first") << endl;
const Value VAL0 = Value{123};
// Create manager
out << F("Instantiate LifeCycleManager") << endl;
LifeCycleManager<MAX_LC_SLOTS> manager;
// Check available slots
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
// Check different types T (int, struct, with/without dtor/ctor/op=...)
check<Value>(out, manager, VAL0);
// check_proxies(out);
}
<commit_msg>Resume work on proxy for lifecycle PoC<commit_after>/*
* This program is just for personal experiments here on C++ mixin for
* handling lifecycle of specific objects.
*/
#include <string.h>
#include <fastarduino/errors.h>
#include <fastarduino/move.h>
#include <fastarduino/time.h>
// includes for the example program itself
#include <fastarduino/tests/assertions.h>
#include <fastarduino/uart.h>
#include <fastarduino/iomanip.h>
#include <fastarduino/flash.h>
// Register vector for UART (used for debug)
REGISTER_UATX_ISR(0)
// API Proof of Concept
//======================
//TODO see if further code size optimization is possible
//TODO work out and check Proxy classes
//FIXME 2 AbstractLifeCycle may have different managers?
// - in this case, how should the move (ctor and assignment) should be handled?
// => that would bring additional code maybe for nothing?
// Forward declaration
class AbstractLifeCycleManager;
template<typename T> class LifeCycle;
// LifeCycle handling
class AbstractLifeCycle
{
public:
AbstractLifeCycle() = default;
AbstractLifeCycle(AbstractLifeCycle&& that);
~AbstractLifeCycle();
AbstractLifeCycle& operator=(AbstractLifeCycle&& that);
AbstractLifeCycle(const AbstractLifeCycle&) = delete;
AbstractLifeCycle& operator=(const AbstractLifeCycle&) = delete;
uint8_t id() const
{
return id_;
}
private:
uint8_t id_ = 0;
AbstractLifeCycleManager* manager_ = nullptr;
friend class AbstractLifeCycleManager;
template<typename T> friend class Proxy;
};
class AbstractLifeCycleManager
{
public:
template<typename T> uint8_t register_(LifeCycle<T>& instance)
{
return register_impl_(instance);
}
bool unregister_(uint8_t id)
{
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr || *slot == nullptr)
return false;
AbstractLifeCycle& source = **slot;
source.id_ = 0;
source.manager_ = nullptr;
*slot = nullptr;
++free_slots_;
return true;
}
uint8_t available_() const
{
return free_slots_;
}
bool move_(uint8_t id, AbstractLifeCycle& dest)
{
// Check this instance is managed
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr || *slot == nullptr) return false;
// Perform move
AbstractLifeCycle& source = **slot;
dest.id_ = source.id_;
dest.manager_ = this;
source.id_ = 0;
source.manager_ = nullptr;
*slot = &dest;
return true;
}
template<typename T> LifeCycle<T>* find_(uint8_t id) const
{
return static_cast<LifeCycle<T>*>(find_impl_(id));
}
protected:
AbstractLifeCycleManager(AbstractLifeCycle** slots, uint8_t size)
: size_{size}, slots_{slots}, free_slots_{size}
{
memset(slots, 0, size * sizeof(AbstractLifeCycle*));
}
~AbstractLifeCycleManager() = default;
AbstractLifeCycleManager(const AbstractLifeCycleManager&) = delete;
AbstractLifeCycleManager& operator=(const AbstractLifeCycleManager&) = delete;
private:
uint8_t register_impl_(AbstractLifeCycle& instance)
{
// Youcannot register any instance if there are no free slots remaining
if (free_slots_ == 0) return 0;
// You cannot register an already registered future
if (instance.id_ != 0) return 0;
// Optimization: we start search AFTER the last removed id
for (uint8_t i = last_removed_id_; i < size_; ++i)
if (register_at_index_(instance, i))
return i + 1;
for (uint8_t i = 0; i <= last_removed_id_; ++i)
if (register_at_index_(instance, i))
return i + 1;
return 0;
}
AbstractLifeCycle* find_impl_(uint8_t id) const
{
AbstractLifeCycle** slot = find_slot_(id);
if (slot == nullptr)
return nullptr;
else
return *slot;
}
AbstractLifeCycle** find_slot_(uint8_t id) const
{
if (id == 0 || id > size_)
return nullptr;
else
return &slots_[id - 1];
}
bool register_at_index_(AbstractLifeCycle& instance, uint8_t index)
{
if (slots_[index] != nullptr)
return false;
instance.id_ = static_cast<uint8_t>(index + 1);
instance.manager_ = this;
slots_[index] = &instance;
--free_slots_;
return true;
}
const uint8_t size_;
AbstractLifeCycle** slots_;
uint8_t free_slots_;
uint8_t last_removed_id_ = 0;
};
template<uint8_t SIZE> class LifeCycleManager : public AbstractLifeCycleManager
{
public:
LifeCycleManager() : AbstractLifeCycleManager{slots_buffer_, SIZE} {}
private:
AbstractLifeCycle* slots_buffer_[SIZE];
};
AbstractLifeCycle::AbstractLifeCycle(AbstractLifeCycle&& that)
{
if (that.id_)
that.manager_->move_(that.id_, *this);
}
AbstractLifeCycle::~AbstractLifeCycle()
{
if (id_)
manager_->unregister_(id_);
}
AbstractLifeCycle& AbstractLifeCycle::operator=(AbstractLifeCycle&& that)
{
if (id_)
manager_->unregister_(id_);
if (that.id_)
that.manager_->move_(that.id_, *this);
return *this;
}
template<typename T> class LifeCycle : public AbstractLifeCycle, public T
{
public:
LifeCycle(const T& value = T{}) : AbstractLifeCycle{}, T{value} {}
LifeCycle(LifeCycle<T>&& that) = default;
~LifeCycle() = default;
LifeCycle<T>& operator=(LifeCycle<T>&& that) = default;
};
// We also need a "direct proxy" specialization for non LifeCycle<T>
template<typename T> class Proxy
{
public:
Proxy(T& dest) : dest_{&dest} {}
Proxy(const Proxy&) = default;
Proxy& operator=(const Proxy&) = default;
T& operator*()
{
return *dest_;
}
T* operator&()
{
return dest_;
}
T* operator->()
{
return dest_;
}
private:
T* dest_;
};
template<typename T> class Proxy<LifeCycle<T>>
{
using LC = LifeCycle<T>;
public:
Proxy(const LC& dest) : id_{dest.id_}, manager_{dest.manager_} {}
Proxy(const Proxy&) = default;
Proxy& operator=(const Proxy&) = default;
LC& operator*()
{
return *(manager_->find_<T>(id_));
}
LC* operator&()
{
return manager_->find_<T>(id_);
}
LC* operator->()
{
return manager_->find_<T>(id_);
}
private:
const uint8_t id_;
AbstractLifeCycleManager* manager_;
//TODO remove (for debug only)
friend void check_proxies(streams::ostream&, AbstractLifeCycleManager&);
};
// Usage Example
//===============
using namespace streams;
// Define types that output traces on each ctor/dtor/operator=
class Value
{
public:
static void set_out(ostream& out)
{
out_ = &out;
}
Value(int val = 0) : val_{val}
{
trace('c');
}
~Value()
{
trace('d');
}
Value(const Value& that) : val_{that.val_}
{
trace('C');
}
Value(Value&& that) : val_{that.val_}
{
trace('M');
}
Value& operator=(const Value& that)
{
this->val_ = that.val_;
trace('=');
return *this;
}
Value& operator=(Value&& that)
{
this->val_ = that.val_;
trace('m');
return *this;
}
int val() const
{
return val_;
}
static ostream& out()
{
return *out_;
}
protected:
void trace(char method)
{
if (out_)
*out_ << method << dec << val_ << ' ' << hex << this << endl;
}
static ostream* out_;
int val_;
};
ostream* Value::out_ = nullptr;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];
static constexpr const uint8_t MAX_LC_SLOTS = 32;
template<typename T> static void check(ostream& out, AbstractLifeCycleManager& manager, const T& init)
{
{
out << F("0. Instance creation") << endl;
LifeCycle<T> instance{init};
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
assert(out, F("id() after construction"), 0, instance.id());
out << F("1. Registration") << endl;
uint8_t id = manager.register_(instance);
assert(out, F("id returned by register_()"), id);
assert(out, F("id() after registration"), id, instance.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
out << F("2. Find") << endl;
LifeCycle<T>* found = manager.find_<T>(id);
assert(out, F("manager.find_(id)"), found != nullptr);
assert(out, F("manager.find_(id)"), &instance, found);
out << F("val=") << dec << found->val() << endl;
//TODO Check copy never compiles
// LifeCycle<T> copy{instance};
out << F("3. Move constructor") << endl;
LifeCycle<T> move = std::move(instance);
assert(out, F("original id() after registration"), 0, instance.id());
assert(out, F("moved id() after registration"), id, move.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
out << F("4. Find after move") << endl;
found = manager.find_<T>(id);
assert(out, F("manager.find_(id)"), found != nullptr);
assert(out, F("manager.find_(id)"), &move, found);
out << F("val=") << dec << found->val() << endl;
//TODO Check copy never compiles
// LifeCycle<T> copy;
// copy = move;
out << F("5. Move assignment") << endl;
LifeCycle<T> move2;
move2 = std::move(move);
assert(out, F("original id() after registration"), 0, move.id());
assert(out, F("moved id() after registration"), id, move2.id());
assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_());
}
// Check destruction
out << F("6. Destruction") << endl;
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
}
class SubValue : public Value
{
public:
SubValue(int val = 0, int val2 = 0) : Value{val}, val2_{val2} {}
~SubValue() = default;
SubValue(const SubValue& that) = default;
SubValue(SubValue&& that) = default;
SubValue& operator=(const SubValue& that) = default;
SubValue& operator=(SubValue&& that) = default;
int val2() const
{
return val2_;
}
private:
int val2_;
};
void check_proxies(ostream& out, AbstractLifeCycleManager& manager)
{
Value v1{10};
SubValue v2{20, 30};
Proxy<Value> p1{v1};
Proxy<Value> p2{v2};
out << F("p1->val() ") << hex << &p1 << ' ' << dec << p1->val() << endl;
out << F("p2->val() ") << hex << &p2 << ' ' << dec << p2->val() << endl;
LifeCycle<Value> lc1{v1};
assert(out, F("manager.register_(lc1)"), 1, manager.register_(lc1));
assert(out, F("lc1.id()"), 1, lc1.id());
LifeCycle<SubValue> lc2{v2};
assert(out, F("manager.register_(lc2)"), 2, manager.register_(lc2));
assert(out, F("lc2.id()"), 2, lc2.id());
Proxy<LifeCycle<Value>> p3{lc1};
out << F("p3.id_=") << dec << p3.id_ << endl;
//TODO The following line does not work
// Proxy<LifeCycle<Value>> p4{lc2};
// But the following line does not work
Proxy<LifeCycle<SubValue>> p4{lc2};
//FIXME this line shows 0 for id_
out << F("p4.id_=") << dec << p4.id_ << F(" p4.manager_=") << hex << p4.manager_ << endl;
out << F("p3->val() ") << hex << &p3 << ' ' << dec << p3->val() << endl;
//FIXME this line shows 0 for val()
out << F("p4->val() ") << hex << &p4 << ' ' << dec << p4->val() << endl;
}
int main() __attribute__((OS_main));
int main()
{
board::init();
// Enable interrupts at startup time
sei();
// Initialize debugging output
serial::hard::UATX<board::USART::USART0> uart{output_buffer};
uart.begin(115200);
ostream out = uart.out();
out << boolalpha << showbase;
out << F("Starting...") << endl;
Value::set_out(out);
out << F("Create constant Value first") << endl;
const Value VAL0 = Value{123};
// Create manager
out << F("Instantiate LifeCycleManager") << endl;
LifeCycleManager<MAX_LC_SLOTS> manager;
// Check available slots
assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_());
// Check different types T (int, struct, with/without dtor/ctor/op=...)
// check<Value>(out, manager, VAL0);
check_proxies(out, manager);
}
<|endoftext|> |
<commit_before>#include "Renderer.h"
#include "BoxActor.h"
Uint8 *keys = NULL;
// Following section is to be implemented by the input coders
/*GLboolean checkKeys(void)
{
static long lastTime = SDL_GetTicks();
const GLfloat speed = 1.0f;
const long updateTime = 10;
if ( keys[SDLK_ESCAPE] )
return true;
long newTime = SDL_GetTicks();
if ( newTime - lastTime > updateTime )
{
if ( keys[SDLK_LEFT] )
cubeRotateY -= speed;
if ( keys[SDLK_RIGHT] )
cubeRotateY += speed;
if ( keys[SDLK_UP] )
cubeRotateX -= speed;
if ( keys[SDLK_DOWN] )
cubeRotateX += speed;
}
return false;
}*/
int main(int argc, char **argv)
{
if ( argc == 2 && strncmp(argv[1], "editor", 6 ) )
{
// Run the editor
}
const Renderer* r=Renderer::getInstanceOf();
World w;
BoxActor b;
w.addActor(b);
int done = 0;
while ( !done )
{
(*r).render(w);
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
done = 1;
keys = SDL_GetKeyState(NULL);
}
// To be implemented by input coders
/*if ( checkKeys() )
done = 1;*/
}
return 1;
}
<commit_msg>Fixed that one line that is annoying Sakkos in main.cpp<commit_after>#include "Renderer.h"
#include "BoxActor.h"
Uint8 *keys = NULL;
// Following section is to be implemented by the input coders
/*GLboolean checkKeys(void)
{
static long lastTime = SDL_GetTicks();
const GLfloat speed = 1.0f;
const long updateTime = 10;
if ( keys[SDLK_ESCAPE] )
return true;
long newTime = SDL_GetTicks();
if ( newTime - lastTime > updateTime )
{
if ( keys[SDLK_LEFT] )
cubeRotateY -= speed;
if ( keys[SDLK_RIGHT] )
cubeRotateY += speed;
if ( keys[SDLK_UP] )
cubeRotateX -= speed;
if ( keys[SDLK_DOWN] )
cubeRotateX += speed;
}
return false;
}*/
int main(int argc, char **argv)
{
if ( argc == 2 && strncmp(argv[1], "editor", 6 ) )
{
// Run the editor
}
const Renderer* r=Renderer::getInstanceOf();
World w;
BoxActor b;
w.addActor(b);
int done = 0;
while ( !done )
{
r->render(w);
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
done = 1;
keys = SDL_GetKeyState(NULL);
}
// To be implemented by input coders
/*if ( checkKeys() )
done = 1;*/
}
return 1;
}
<|endoftext|> |
<commit_before>/* Copyright Robert Osfield, Licensed under the GPL
*
* Experimental base for refactor of Present3D
*
*/
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ScriptEngine>
#include <osg/UserDataContainer>
#include <osgPresentation/Presentation>
#include <osgPresentation/Slide>
#include <osgPresentation/Layer>
#include <osgPresentation/Element>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
typedef std::list< osg::ref_ptr<osg::Script> > Scripts;
Scripts scripts;
std::string filename;
while(arguments.read("--script",filename))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(filename);
if (script.valid()) scripts.push_back(script.get());
}
// create the model
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model) return 1;
// assgin script engine to scene graphs
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.js"));
// assign scripts to scene graph
for(Scripts::iterator itr = scripts.begin();
itr != scripts.end();
++itr)
{
model->addUpdateCallback(new osg::ScriptCallback(itr->get()));
}
#if 0
std::string str;
osg::ref_ptr<osg::ScriptEngine> luaScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua");
if (luaScriptEngine.valid())
{
while (arguments.read("--lua", str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
luaScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> v8ScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.V8");
if (v8ScriptEngine.valid())
{
while (arguments.read("--js",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
v8ScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> pythonScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python");
if (pythonScriptEngine.valid())
{
while (arguments.read("--python",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
pythonScriptEngine->run(script.get());
}
}
}
#endif
osg::ref_ptr<osgPresentation::Presentation> presentation = new osgPresentation::Presentation;
osg::ref_ptr<osgPresentation::Slide> slide = new osgPresentation::Slide;
osg::ref_ptr<osgPresentation::Layer> layer = new osgPresentation::Layer;
osg::ref_ptr<osgPresentation::Group> group = new osgPresentation::Group;
osg::ref_ptr<osgPresentation::Element> element = new osgPresentation::Element;
presentation->addChild(slide.get());
slide->addChild(layer.get());
//layer->addChild(element.get());
layer->addChild(group.get());
group->addChild(element.get());
element->addChild(model.get());
viewer.setSceneData( presentation.get() );
osgDB::writeNodeFile(*presentation, "pres.osgt");
return viewer.run();
}
<commit_msg>Added IO test for new osgPresentation nodes<commit_after>/* Copyright Robert Osfield, Licensed under the GPL
*
* Experimental base for refactor of Present3D
*
*/
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ScriptEngine>
#include <osg/UserDataContainer>
#include <osgPresentation/Presentation>
#include <osgPresentation/Slide>
#include <osgPresentation/Layer>
#include <osgPresentation/Element>
#include <osgPresentation/Model>
#include <osgPresentation/Volume>
#include <osgPresentation/Image>
#include <osgPresentation/Movie>
#include <osgPresentation/Text>
#include <osgPresentation/Audio>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
typedef std::list< osg::ref_ptr<osg::Script> > Scripts;
Scripts scripts;
std::string filename;
while(arguments.read("--script",filename))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(filename);
if (script.valid()) scripts.push_back(script.get());
}
// create the model
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model) return 1;
// assgin script engine to scene graphs
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.js"));
// assign scripts to scene graph
for(Scripts::iterator itr = scripts.begin();
itr != scripts.end();
++itr)
{
model->addUpdateCallback(new osg::ScriptCallback(itr->get()));
}
#if 0
std::string str;
osg::ref_ptr<osg::ScriptEngine> luaScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua");
if (luaScriptEngine.valid())
{
while (arguments.read("--lua", str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
luaScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> v8ScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.V8");
if (v8ScriptEngine.valid())
{
while (arguments.read("--js",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
v8ScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> pythonScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python");
if (pythonScriptEngine.valid())
{
while (arguments.read("--python",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
pythonScriptEngine->run(script.get());
}
}
}
#endif
osg::ref_ptr<osgPresentation::Presentation> presentation = new osgPresentation::Presentation;
osg::ref_ptr<osgPresentation::Slide> slide = new osgPresentation::Slide;
osg::ref_ptr<osgPresentation::Layer> layer = new osgPresentation::Layer;
osg::ref_ptr<osgPresentation::Group> group = new osgPresentation::Group;
osg::ref_ptr<osgPresentation::Element> element = new osgPresentation::Element;
presentation->addChild(slide.get());
slide->addChild(layer.get());
//layer->addChild(element.get());
layer->addChild(group.get());
group->addChild(element.get());
element->addChild(model.get());
group->addChild(new osgPresentation::Model);
group->addChild(new osgPresentation::Text);
group->addChild(new osgPresentation::Audio);
group->addChild(new osgPresentation::Movie);
group->addChild(new osgPresentation::Volume);
viewer.setSceneData( presentation.get() );
osgDB::writeNodeFile(*presentation, "pres.osgt");
return viewer.run();
}
<|endoftext|> |
<commit_before>/* Copyright Robert Osfield, Licensed under the GPL
*
* Experimental base for refactor of Present3D
*
*/
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ScriptEngine>
#include <osg/UserDataContainer>
#include <osgPresentation/Presentation>
#include <osgPresentation/Slide>
#include <osgPresentation/Layer>
#include <osgPresentation/Element>
#include <osgPresentation/Model>
#include <osgPresentation/Volume>
#include <osgPresentation/Image>
#include <osgPresentation/Movie>
#include <osgPresentation/Text>
#include <osgPresentation/Audio>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
#if 0
typedef std::list< osg::ref_ptr<osg::Script> > Scripts;
Scripts scripts;
std::string filename;
while(arguments.read("--script",filename))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(filename);
if (script.valid()) scripts.push_back(script.get());
}
// assgin script engine to scene graphs
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.js"));
// assign scripts to scene graph
for(Scripts::iterator itr = scripts.begin();
itr != scripts.end();
++itr)
{
model->addUpdateCallback(new osg::ScriptCallback(itr->get()));
}
std::string str;
osg::ref_ptr<osg::ScriptEngine> luaScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua");
if (luaScriptEngine.valid())
{
while (arguments.read("--lua", str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
luaScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> v8ScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.V8");
if (v8ScriptEngine.valid())
{
while (arguments.read("--js",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
v8ScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> pythonScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python");
if (pythonScriptEngine.valid())
{
while (arguments.read("--python",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
pythonScriptEngine->run(script.get());
}
}
}
#endif
osg::ref_ptr<osgPresentation::Presentation> presentation = new osgPresentation::Presentation;
osg::ref_ptr<osgPresentation::Slide> slide = new osgPresentation::Slide;
osg::ref_ptr<osgPresentation::Layer> layer = new osgPresentation::Layer;
osg::ref_ptr<osgPresentation::Group> group = new osgPresentation::Group;
osg::ref_ptr<osgPresentation::Element> element = new osgPresentation::Element;
osg::ref_ptr<osgPresentation::Text> text = new osgPresentation::Text;
osg::ref_ptr<osgPresentation::Model> model = new osgPresentation::Model;
presentation->addChild(slide.get());
slide->addChild(layer.get());
//layer->addChild(element.get());
layer->addChild(group.get());
group->addChild(element.get());
group->addChild(model.get());
group->addChild(text.get());
group->addChild(new osgPresentation::Audio);
group->addChild(new osgPresentation::Movie);
group->addChild(new osgPresentation::Volume);
text->setProperty("string",std::string("This is a first test"));
text->setProperty("font",std::string("times.ttf"));
text->setProperty("character_size",2.2);
text->setProperty("width",std::string("103.2"));
model->setProperty("filename", std::string("dumptruck.osgt"));
model->setProperty("scale",2.0);
osgPresentation::PrintSupportedProperties psp(std::cout);
presentation->accept(psp);
osgPresentation::PrintProperties pp(std::cout);
presentation->accept(pp);
osgPresentation::LoadAction load;
presentation->accept( load );
viewer.setSceneData( presentation.get() );
osgDB::writeNodeFile(*presentation, "pres.osgt");
return viewer.run();
}
<commit_msg>Moved the property test from the model to presentation to test out the property inheritance scheme<commit_after>/* Copyright Robert Osfield, Licensed under the GPL
*
* Experimental base for refactor of Present3D
*
*/
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ScriptEngine>
#include <osg/UserDataContainer>
#include <osgPresentation/Presentation>
#include <osgPresentation/Slide>
#include <osgPresentation/Layer>
#include <osgPresentation/Element>
#include <osgPresentation/Model>
#include <osgPresentation/Volume>
#include <osgPresentation/Image>
#include <osgPresentation/Movie>
#include <osgPresentation/Text>
#include <osgPresentation/Audio>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc, argv);
osgViewer::Viewer viewer(arguments);
#if 0
typedef std::list< osg::ref_ptr<osg::Script> > Scripts;
Scripts scripts;
std::string filename;
while(arguments.read("--script",filename))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(filename);
if (script.valid()) scripts.push_back(script.get());
}
// assgin script engine to scene graphs
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python"));
model->getOrCreateUserDataContainer()->addUserObject(osgDB::readFile<osg::ScriptEngine>("ScriptEngine.js"));
// assign scripts to scene graph
for(Scripts::iterator itr = scripts.begin();
itr != scripts.end();
++itr)
{
model->addUpdateCallback(new osg::ScriptCallback(itr->get()));
}
std::string str;
osg::ref_ptr<osg::ScriptEngine> luaScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.lua");
if (luaScriptEngine.valid())
{
while (arguments.read("--lua", str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
luaScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> v8ScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.V8");
if (v8ScriptEngine.valid())
{
while (arguments.read("--js",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
v8ScriptEngine->run(script.get());
}
}
}
osg::ref_ptr<osg::ScriptEngine> pythonScriptEngine = osgDB::readFile<osg::ScriptEngine>("ScriptEngine.python");
if (pythonScriptEngine.valid())
{
while (arguments.read("--python",str))
{
osg::ref_ptr<osg::Script> script = osgDB::readFile<osg::Script>(str);
if (script.valid())
{
pythonScriptEngine->run(script.get());
}
}
}
#endif
osg::ref_ptr<osgPresentation::Presentation> presentation = new osgPresentation::Presentation;
osg::ref_ptr<osgPresentation::Slide> slide = new osgPresentation::Slide;
osg::ref_ptr<osgPresentation::Layer> layer = new osgPresentation::Layer;
osg::ref_ptr<osgPresentation::Group> group = new osgPresentation::Group;
osg::ref_ptr<osgPresentation::Element> element = new osgPresentation::Element;
osg::ref_ptr<osgPresentation::Text> text = new osgPresentation::Text;
osg::ref_ptr<osgPresentation::Model> model = new osgPresentation::Model;
presentation->addChild(slide.get());
slide->addChild(layer.get());
//layer->addChild(element.get());
layer->addChild(group.get());
group->addChild(element.get());
group->addChild(model.get());
group->addChild(text.get());
group->addChild(new osgPresentation::Audio);
group->addChild(new osgPresentation::Movie);
group->addChild(new osgPresentation::Volume);
text->setProperty("string",std::string("This is a first test"));
text->setProperty("font",std::string("times.ttf"));
text->setProperty("character_size",2.2);
text->setProperty("width",std::string("103.2"));
model->setProperty("filename", std::string("dumptruck.osgt"));
presentation->setProperty("scale",2.0);
osgPresentation::PrintSupportedProperties psp(std::cout);
presentation->accept(psp);
osgPresentation::PrintProperties pp(std::cout);
presentation->accept(pp);
osgPresentation::LoadAction load;
presentation->accept( load );
viewer.setSceneData( presentation.get() );
osgDB::writeNodeFile(*presentation, "pres.osgt");
return viewer.run();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datman.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:38:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX
#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORM_HPP_
#include <com/sun/star/form/XForm.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSINGLESELECTQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_
#include <com/sun/star/form/XLoadable.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
// #100312# --------------------
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
class Window;
//-----------------------------------------------------------------------------
namespace bib
{
class BibView;
// #100312# -----------
class BibBeamer;
}
class BibToolBar;
struct BibDBDescriptor;
// #100312# ---------------------
class BibInterceptorHelper
:public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;
protected:
~BibInterceptorHelper( );
public:
BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);
void ReleaseInterceptor();
// XDispatchProvider
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
// XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};
typedef cppu::WeakComponentImplHelper2 < ::com::sun::star::beans::XPropertyChangeListener
, ::com::sun::star::form::XLoadable
> BibDataManager_Base;
class BibDataManager
:public ::comphelper::OMutexAndBroadcastHelper
,public BibDataManager_Base
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > m_xForm;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > m_xGridModel;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSourceProps;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer > m_xParser;
::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > m_xFormCtrl;
// #100312# -------------------
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xFormDispatch;
BibInterceptorHelper* m_pInterceptorHelper;
::rtl::OUString aActiveDataTable;
::rtl::OUString aDataSourceURL;
::rtl::OUString aQuoteChar;
::com::sun::star::uno::Any aUID;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xBibCursor;
::cppu::OInterfaceContainerHelper m_aLoadListeners;
::bib::BibView* pBibView;
BibToolBar* pToolbar;
rtl::OUString sIdentifierMapping;
protected:
void InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
void SetMeAsUidListener();
void RemoveMeAsUidListener();
void UpdateAddressbookCursor(::rtl::OUString aSourceName);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
createGridModel( const ::rtl::OUString& rName );
// XLoadable
virtual void SAL_CALL load( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL unload( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL reload( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isLoaded( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing();
public:
BibDataManager();
~BibDataManager();
virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > createDatabaseForm( BibDBDescriptor& aDesc);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel();
::com::sun::star::uno::Sequence< ::rtl::OUString> getDataSources();
::rtl::OUString getActiveDataSource() {return aDataSourceURL;}
void setActiveDataSource(const ::rtl::OUString& rURL);
::rtl::OUString getActiveDataTable();
void setActiveDataTable(const ::rtl::OUString& rTable);
void setFilter(const ::rtl::OUString& rQuery);
::rtl::OUString getFilter();
::com::sun::star::uno::Sequence< ::rtl::OUString> getQueryFields();
::rtl::OUString getQueryField();
void startQueryWith(const ::rtl::OUString& rQuery);
const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >& getParser() { return m_xParser; }
const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& getForm() { return m_xForm; }
::rtl::OUString getControlName(sal_Int32 nFormatKey );
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > loadControlModel(const ::rtl::OUString& rName,
sal_Bool bForceListBox = sal_False);
void saveCtrModel(const ::rtl::OUString& rName,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel);
sal_Bool moveRelative(sal_Int32 nMove);
void CreateMappingDialog(Window* pParent);
::rtl::OUString CreateDBChangeDialog(Window* pParent);
void DispatchDBChangeDialog();
sal_Bool HasActiveConnection() const;
void SetView( ::bib::BibView* pView ) { pBibView = pView; }
void SetToolbar(BibToolBar* pSet);
const rtl::OUString& GetIdentifierMapping();
void ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}
::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
// #100312# ----------
void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);
sal_Bool HasActiveConnection();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.15.48); FILE MERGED 2008/04/01 15:15:03 thb 1.15.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:41 thb 1.15.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:23 rt 1.15.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datman.hxx,v $
* $Revision: 1.16 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BIB_DATMAN_HXX
#define _BIB_DATMAN_HXX
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/form/XForm.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/form/XFormController.hpp>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <com/sun/star/form/XLoadable.hpp>
#include <comphelper/broadcasthelper.hxx>
// #100312# --------------------
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#include <cppuhelper/implbase1.hxx>
class Window;
//-----------------------------------------------------------------------------
namespace bib
{
class BibView;
// #100312# -----------
class BibBeamer;
}
class BibToolBar;
struct BibDBDescriptor;
// #100312# ---------------------
class BibInterceptorHelper
:public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor >
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception;
protected:
~BibInterceptorHelper( );
public:
BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch);
void ReleaseInterceptor();
// XDispatchProvider
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException);
// XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException);
};
typedef cppu::WeakComponentImplHelper2 < ::com::sun::star::beans::XPropertyChangeListener
, ::com::sun::star::form::XLoadable
> BibDataManager_Base;
class BibDataManager
:public ::comphelper::OMutexAndBroadcastHelper
,public BibDataManager_Base
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > m_xForm;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > m_xGridModel;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSourceProps;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer > m_xParser;
::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > m_xFormCtrl;
// #100312# -------------------
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xFormDispatch;
BibInterceptorHelper* m_pInterceptorHelper;
::rtl::OUString aActiveDataTable;
::rtl::OUString aDataSourceURL;
::rtl::OUString aQuoteChar;
::com::sun::star::uno::Any aUID;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xBibCursor;
::cppu::OInterfaceContainerHelper m_aLoadListeners;
::bib::BibView* pBibView;
BibToolBar* pToolbar;
rtl::OUString sIdentifierMapping;
protected:
void InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid);
void SetMeAsUidListener();
void RemoveMeAsUidListener();
void UpdateAddressbookCursor(::rtl::OUString aSourceName);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >
createGridModel( const ::rtl::OUString& rName );
// XLoadable
virtual void SAL_CALL load( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL unload( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL reload( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isLoaded( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing();
public:
BibDataManager();
~BibDataManager();
virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt)
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > createDatabaseForm( BibDBDescriptor& aDesc);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel();
::com::sun::star::uno::Sequence< ::rtl::OUString> getDataSources();
::rtl::OUString getActiveDataSource() {return aDataSourceURL;}
void setActiveDataSource(const ::rtl::OUString& rURL);
::rtl::OUString getActiveDataTable();
void setActiveDataTable(const ::rtl::OUString& rTable);
void setFilter(const ::rtl::OUString& rQuery);
::rtl::OUString getFilter();
::com::sun::star::uno::Sequence< ::rtl::OUString> getQueryFields();
::rtl::OUString getQueryField();
void startQueryWith(const ::rtl::OUString& rQuery);
const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >& getParser() { return m_xParser; }
const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& getForm() { return m_xForm; }
::rtl::OUString getControlName(sal_Int32 nFormatKey );
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > loadControlModel(const ::rtl::OUString& rName,
sal_Bool bForceListBox = sal_False);
void saveCtrModel(const ::rtl::OUString& rName,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel);
sal_Bool moveRelative(sal_Int32 nMove);
void CreateMappingDialog(Window* pParent);
::rtl::OUString CreateDBChangeDialog(Window* pParent);
void DispatchDBChangeDialog();
sal_Bool HasActiveConnection() const;
void SetView( ::bib::BibView* pView ) { pBibView = pView; }
void SetToolbar(BibToolBar* pSet);
const rtl::OUString& GetIdentifierMapping();
void ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();}
::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController();
// #100312# ----------
void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer);
sal_Bool HasActiveConnection();
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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 "config.h"
#include "base/compiler_specific.h"
#include "KeyboardCodes.h"
#include "StringImpl.h" // This is so that the KJS build works
MSVC_PUSH_WARNING_LEVEL(0);
#include "PlatformKeyboardEvent.h"
#include "PlatformMouseEvent.h"
#include "PlatformWheelEvent.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG
#include "base/gfx/point.h"
#include "base/logging.h"
#include "webkit/glue/event_conversion.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webkit_glue.h"
using namespace WebCore;
// MakePlatformMouseEvent -----------------------------------------------------
int MakePlatformMouseEvent::last_click_count_ = 0;
uint32 MakePlatformMouseEvent::last_click_time_ = 0;
MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget,
const WebMouseEvent& e) {
// TODO(mpcomplete): widget is always toplevel, unless it's a popup. We
// may be able to get rid of this once we abstract popups into a WebKit API.
m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y));
m_globalPosition = IntPoint(e.global_x, e.global_y);
m_button = static_cast<MouseButton>(e.button);
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
m_modifierFlags = e.modifiers;
m_timestamp = e.timestamp_sec;
// This differs slightly from the WebKit code in WebKit/win/WebView.cpp where
// their original code looks buggy.
static IntPoint last_click_position;
static MouseButton last_click_button = LeftButton;
const uint32 current_time = static_cast<uint32>(m_timestamp * 1000);
#if defined(OS_WIN)
const bool cancel_previous_click =
(abs(last_click_position.x() - m_position.x()) >
(GetSystemMetrics(SM_CXDOUBLECLK) / 2)) ||
(abs(last_click_position.y() - m_position.y()) >
(GetSystemMetrics(SM_CYDOUBLECLK) / 2)) ||
((current_time - last_click_time_) > GetDoubleClickTime());
#elif defined(OS_MACOSX) || defined(OS_LINUX)
const bool cancel_previous_click = false;
#endif
switch (e.type) {
case WebInputEvent::MOUSE_MOVE:
case WebInputEvent::MOUSE_LEAVE: // synthesize a move event
if (cancel_previous_click) {
last_click_count_ = 0;
last_click_position = IntPoint();
last_click_time_ = 0;
}
m_clickCount = last_click_count_;
m_eventType = MouseEventMoved;
break;
// TODO(port): make these platform agnostic when we restructure this code.
#if defined(OS_LINUX) || defined(OS_MACOSX)
case WebInputEvent::MOUSE_DOUBLE_CLICK:
++m_clickCount;
// fall through
case WebInputEvent::MOUSE_DOWN:
++m_clickCount;
last_click_time_ = current_time;
last_click_button = m_button;
m_eventType = MouseEventPressed;
break;
#else
case WebInputEvent::MOUSE_DOWN:
case WebInputEvent::MOUSE_DOUBLE_CLICK:
if (!cancel_previous_click && (m_button == last_click_button)) {
++last_click_count_;
} else {
last_click_count_ = 1;
last_click_position = m_position;
}
last_click_time_ = current_time;
last_click_button = m_button;
m_clickCount = last_click_count_;
m_eventType = MouseEventPressed;
break;
#endif
case WebInputEvent::MOUSE_UP:
m_clickCount = last_click_count_;
m_eventType = MouseEventReleased;
break;
default:
NOTREACHED() << "unexpected mouse event type";
}
if (webkit_glue::IsLayoutTestMode()) {
m_clickCount = e.layout_test_click_count;
}
}
// MakePlatformWheelEvent -----------------------------------------------------
MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget,
const WebMouseWheelEvent& e) {
m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y));
m_globalPosition = IntPoint(e.global_x, e.global_y);
m_deltaX = static_cast<float>(e.delta_x);
m_deltaY = static_cast<float>(e.delta_y);
m_isAccepted = false;
m_granularity = ScrollByLineWheelEvent;
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
}
// MakePlatformKeyboardEvent --------------------------------------------------
static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType(
WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::KEY_UP:
return PlatformKeyboardEvent::KeyUp;
case WebInputEvent::KEY_DOWN:
return PlatformKeyboardEvent::KeyDown;
case WebInputEvent::CHAR:
return PlatformKeyboardEvent::Char;
default:
ASSERT_NOT_REACHED();
}
return PlatformKeyboardEvent::KeyDown;
}
static inline String ToSingleCharacterString(UChar c) {
return String(&c, 1);
}
static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) {
switch (keyCode) {
case VKEY_MENU:
return "Alt";
case VKEY_CONTROL:
return "Control";
case VKEY_SHIFT:
return "Shift";
case VKEY_CAPITAL:
return "CapsLock";
case VKEY_LWIN:
case VKEY_RWIN:
return "Win";
case VKEY_CLEAR:
return "Clear";
case VKEY_DOWN:
return "Down";
// "End"
case VKEY_END:
return "End";
// "Enter"
case VKEY_RETURN:
return "Enter";
case VKEY_EXECUTE:
return "Execute";
case VKEY_F1:
return "F1";
case VKEY_F2:
return "F2";
case VKEY_F3:
return "F3";
case VKEY_F4:
return "F4";
case VKEY_F5:
return "F5";
case VKEY_F6:
return "F6";
case VKEY_F7:
return "F7";
case VKEY_F8:
return "F8";
case VKEY_F9:
return "F9";
case VKEY_F10:
return "F11";
case VKEY_F12:
return "F12";
case VKEY_F13:
return "F13";
case VKEY_F14:
return "F14";
case VKEY_F15:
return "F15";
case VKEY_F16:
return "F16";
case VKEY_F17:
return "F17";
case VKEY_F18:
return "F18";
case VKEY_F19:
return "F19";
case VKEY_F20:
return "F20";
case VKEY_F21:
return "F21";
case VKEY_F22:
return "F22";
case VKEY_F23:
return "F23";
case VKEY_F24:
return "F24";
case VKEY_HELP:
return "Help";
case VKEY_HOME:
return "Home";
case VKEY_INSERT:
return "Insert";
case VKEY_LEFT:
return "Left";
case VKEY_NEXT:
return "PageDown";
case VKEY_PRIOR:
return "PageUp";
case VKEY_PAUSE:
return "Pause";
case VKEY_SNAPSHOT:
return "PrintScreen";
case VKEY_RIGHT:
return "Right";
case VKEY_SCROLL:
return "Scroll";
case VKEY_SELECT:
return "Select";
case VKEY_UP:
return "Up";
// Standard says that DEL becomes U+007F.
case VKEY_DELETE:
return "U+007F";
default:
return String::format("U+%04X", toupper(keyCode));
}
}
MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e)
{
m_type = ToPlatformKeyboardEventType(e.type);
if (m_type == Char || m_type == KeyDown) {
#if defined(OS_MACOSX)
m_text = &e.text[0];
m_unmodifiedText = &e.unmodified_text[0];
m_keyIdentifier = &e.key_identifier[0];
// Always use 13 for Enter/Return -- we don't want to use AppKit's
// different character for Enter.
if (m_windowsVirtualKeyCode == '\r') {
m_text = "\r";
m_unmodifiedText = "\r";
}
// The adjustments below are only needed in backward compatibility mode,
// but we cannot tell what mode we are in from here.
// Turn 0x7F into 8, because backspace needs to always be 8.
if (m_text == "\x7F")
m_text = "\x8";
if (m_unmodifiedText == "\x7F")
m_unmodifiedText = "\x8";
// Always use 9 for tab -- we don't want to use AppKit's different character for shift-tab.
if (m_windowsVirtualKeyCode == 9) {
m_text = "\x9";
m_unmodifiedText = "\x9";
}
#elif defined(OS_WIN) || defined(OS_LINUX)
m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code);
#endif
}
#if defined(OS_WIN) || defined(OS_LINUX)
if (m_type != Char)
m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code);
#endif
if (m_type == Char || m_type == KeyDown || m_type == KeyUp ||
m_type == RawKeyDown) {
m_windowsVirtualKeyCode = e.key_code;
} else {
m_windowsVirtualKeyCode = 0;
}
m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0;
m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0;
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
#if defined(OS_WIN)
m_isSystemKey = e.system_key;
// TODO(port): set this field properly for linux and mac.
#elif defined(OS_LINUX)
m_isSystemKey = m_altKey;
#else
m_isSystemKey = false;
#endif
}
void MakePlatformKeyboardEvent::SetKeyType(Type type) {
// According to the behavior of Webkit in Windows platform,
// we need to convert KeyDown to RawKeydown and Char events
// See WebKit/WebKit/Win/WebView.cpp
ASSERT(m_type == KeyDown);
ASSERT(type == RawKeyDown || type == Char);
m_type = type;
if (type == RawKeyDown) {
m_text = String();
m_unmodifiedText = String();
} else {
m_keyIdentifier = String();
m_windowsVirtualKeyCode = 0;
}
}
// Please refer to bug http://b/issue?id=961192, which talks about Webkit
// keyboard event handling changes. It also mentions the list of keys
// which don't have associated character events.
bool MakePlatformKeyboardEvent::IsCharacterKey() const {
switch (windowsVirtualKeyCode()) {
case VKEY_BACK:
case VKEY_ESCAPE:
return false;
default:
break;
}
return true;
}
<commit_msg>Undo part of issue 12981.<commit_after>// Copyright (c) 2006-2008 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 "config.h"
#include "base/compiler_specific.h"
#include "KeyboardCodes.h"
#include "StringImpl.h" // This is so that the KJS build works
MSVC_PUSH_WARNING_LEVEL(0);
#include "PlatformKeyboardEvent.h"
#include "PlatformMouseEvent.h"
#include "PlatformWheelEvent.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG
#include "base/gfx/point.h"
#include "base/logging.h"
#include "webkit/glue/event_conversion.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webkit_glue.h"
using namespace WebCore;
// MakePlatformMouseEvent -----------------------------------------------------
int MakePlatformMouseEvent::last_click_count_ = 0;
uint32 MakePlatformMouseEvent::last_click_time_ = 0;
MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget,
const WebMouseEvent& e) {
// TODO(mpcomplete): widget is always toplevel, unless it's a popup. We
// may be able to get rid of this once we abstract popups into a WebKit API.
m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y));
m_globalPosition = IntPoint(e.global_x, e.global_y);
m_button = static_cast<MouseButton>(e.button);
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
m_modifierFlags = e.modifiers;
m_timestamp = e.timestamp_sec;
// This differs slightly from the WebKit code in WebKit/win/WebView.cpp where
// their original code looks buggy.
static IntPoint last_click_position;
static MouseButton last_click_button = LeftButton;
const uint32 current_time = static_cast<uint32>(m_timestamp * 1000);
#if defined(OS_WIN)
const bool cancel_previous_click =
(abs(last_click_position.x() - m_position.x()) >
(GetSystemMetrics(SM_CXDOUBLECLK) / 2)) ||
(abs(last_click_position.y() - m_position.y()) >
(GetSystemMetrics(SM_CYDOUBLECLK) / 2)) ||
((current_time - last_click_time_) > GetDoubleClickTime());
#elif defined(OS_MACOSX) || defined(OS_LINUX)
const bool cancel_previous_click = false;
#endif
switch (e.type) {
case WebInputEvent::MOUSE_MOVE:
case WebInputEvent::MOUSE_LEAVE: // synthesize a move event
if (cancel_previous_click) {
last_click_count_ = 0;
last_click_position = IntPoint();
last_click_time_ = 0;
}
m_clickCount = last_click_count_;
m_eventType = MouseEventMoved;
break;
// TODO(port): make these platform agnostic when we restructure this code.
#if defined(OS_LINUX) || defined(OS_MACOSX)
case WebInputEvent::MOUSE_DOUBLE_CLICK:
++m_clickCount;
// fall through
case WebInputEvent::MOUSE_DOWN:
++m_clickCount;
last_click_time_ = current_time;
last_click_button = m_button;
m_eventType = MouseEventPressed;
break;
#else
case WebInputEvent::MOUSE_DOWN:
case WebInputEvent::MOUSE_DOUBLE_CLICK:
if (!cancel_previous_click && (m_button == last_click_button)) {
++last_click_count_;
} else {
last_click_count_ = 1;
last_click_position = m_position;
}
last_click_time_ = current_time;
last_click_button = m_button;
m_clickCount = last_click_count_;
m_eventType = MouseEventPressed;
break;
#endif
case WebInputEvent::MOUSE_UP:
m_clickCount = last_click_count_;
m_eventType = MouseEventReleased;
break;
default:
NOTREACHED() << "unexpected mouse event type";
}
if (webkit_glue::IsLayoutTestMode()) {
m_clickCount = e.layout_test_click_count;
}
}
// MakePlatformWheelEvent -----------------------------------------------------
MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget,
const WebMouseWheelEvent& e) {
m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y));
m_globalPosition = IntPoint(e.global_x, e.global_y);
m_deltaX = static_cast<float>(e.delta_x);
m_deltaY = static_cast<float>(e.delta_y);
m_isAccepted = false;
m_granularity = ScrollByLineWheelEvent;
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
}
// MakePlatformKeyboardEvent --------------------------------------------------
static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType(
WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::KEY_UP:
return PlatformKeyboardEvent::KeyUp;
case WebInputEvent::KEY_DOWN:
return PlatformKeyboardEvent::KeyDown;
case WebInputEvent::CHAR:
return PlatformKeyboardEvent::Char;
default:
ASSERT_NOT_REACHED();
}
return PlatformKeyboardEvent::KeyDown;
}
static inline String ToSingleCharacterString(UChar c) {
return String(&c, 1);
}
static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) {
switch (keyCode) {
case VKEY_MENU:
return "Alt";
case VKEY_CONTROL:
return "Control";
case VKEY_SHIFT:
return "Shift";
case VKEY_CAPITAL:
return "CapsLock";
case VKEY_LWIN:
case VKEY_RWIN:
return "Win";
case VKEY_CLEAR:
return "Clear";
case VKEY_DOWN:
return "Down";
// "End"
case VKEY_END:
return "End";
// "Enter"
case VKEY_RETURN:
return "Enter";
case VKEY_EXECUTE:
return "Execute";
case VKEY_F1:
return "F1";
case VKEY_F2:
return "F2";
case VKEY_F3:
return "F3";
case VKEY_F4:
return "F4";
case VKEY_F5:
return "F5";
case VKEY_F6:
return "F6";
case VKEY_F7:
return "F7";
case VKEY_F8:
return "F8";
case VKEY_F9:
return "F9";
case VKEY_F10:
return "F11";
case VKEY_F12:
return "F12";
case VKEY_F13:
return "F13";
case VKEY_F14:
return "F14";
case VKEY_F15:
return "F15";
case VKEY_F16:
return "F16";
case VKEY_F17:
return "F17";
case VKEY_F18:
return "F18";
case VKEY_F19:
return "F19";
case VKEY_F20:
return "F20";
case VKEY_F21:
return "F21";
case VKEY_F22:
return "F22";
case VKEY_F23:
return "F23";
case VKEY_F24:
return "F24";
case VKEY_HELP:
return "Help";
case VKEY_HOME:
return "Home";
case VKEY_INSERT:
return "Insert";
case VKEY_LEFT:
return "Left";
case VKEY_NEXT:
return "PageDown";
case VKEY_PRIOR:
return "PageUp";
case VKEY_PAUSE:
return "Pause";
case VKEY_SNAPSHOT:
return "PrintScreen";
case VKEY_RIGHT:
return "Right";
case VKEY_SCROLL:
return "Scroll";
case VKEY_SELECT:
return "Select";
case VKEY_UP:
return "Up";
// Standard says that DEL becomes U+007F.
case VKEY_DELETE:
return "U+007F";
default:
return String::format("U+%04X", toupper(keyCode));
}
}
MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e)
{
m_type = ToPlatformKeyboardEventType(e.type);
if (m_type == Char || m_type == KeyDown) {
#if defined(OS_MACOSX)
m_text = &e.text[0];
m_unmodifiedText = &e.unmodified_text[0];
m_keyIdentifier = &e.key_identifier[0];
// Always use 13 for Enter/Return -- we don't want to use AppKit's
// different character for Enter.
if (m_windowsVirtualKeyCode == '\r') {
m_text = "\r";
m_unmodifiedText = "\r";
}
// The adjustments below are only needed in backward compatibility mode,
// but we cannot tell what mode we are in from here.
// Turn 0x7F into 8, because backspace needs to always be 8.
if (m_text == "\x7F")
m_text = "\x8";
if (m_unmodifiedText == "\x7F")
m_unmodifiedText = "\x8";
// Always use 9 for tab -- we don't want to use AppKit's different character for shift-tab.
if (m_windowsVirtualKeyCode == 9) {
m_text = "\x9";
m_unmodifiedText = "\x9";
}
#elif defined(OS_WIN)
m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code);
#elif defined(OS_LINUX)
m_text = m_unmodifiedText = ToSingleCharacterString(e.text);
#endif
}
#if defined(OS_WIN) || defined(OS_LINUX)
if (m_type != Char)
m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code);
#endif
if (m_type == Char || m_type == KeyDown || m_type == KeyUp ||
m_type == RawKeyDown) {
m_windowsVirtualKeyCode = e.key_code;
} else {
m_windowsVirtualKeyCode = 0;
}
m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0;
m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0;
m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0;
m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0;
m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0;
m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0;
#if defined(OS_WIN)
m_isSystemKey = e.system_key;
// TODO(port): set this field properly for linux and mac.
#elif defined(OS_LINUX)
m_isSystemKey = m_altKey;
#else
m_isSystemKey = false;
#endif
}
void MakePlatformKeyboardEvent::SetKeyType(Type type) {
// According to the behavior of Webkit in Windows platform,
// we need to convert KeyDown to RawKeydown and Char events
// See WebKit/WebKit/Win/WebView.cpp
ASSERT(m_type == KeyDown);
ASSERT(type == RawKeyDown || type == Char);
m_type = type;
if (type == RawKeyDown) {
m_text = String();
m_unmodifiedText = String();
} else {
m_keyIdentifier = String();
m_windowsVirtualKeyCode = 0;
}
}
// Please refer to bug http://b/issue?id=961192, which talks about Webkit
// keyboard event handling changes. It also mentions the list of keys
// which don't have associated character events.
bool MakePlatformKeyboardEvent::IsCharacterKey() const {
switch (windowsVirtualKeyCode()) {
case VKEY_BACK:
case VKEY_ESCAPE:
return false;
default:
break;
}
return true;
}
<|endoftext|> |
<commit_before>#include "FanCalculatorScene.h"
#include <algorithm>
#include <iterator>
#include "../mahjong-algorithm/stringify.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../UICommon.h"
#include "../widget/TilePickWidget.h"
#include "../widget/ExtraInfoWidget.h"
#include "../widget/Toast.h"
#include "../FanTable/FanTableScene.h"
USING_NS_CC;
static const Color3B C3B_GRAY = Color3B(96, 96, 96);
static const Color3B C3B_BLUE_THEME = Color3B(51, 204, 255);
bool FanCalculatorScene::init() {
if (UNLIKELY(!BaseScene::initWithTitle(__UTF8("国标麻将算番器")))) {
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 选牌面板
TilePickWidget *tilePicker = TilePickWidget::create(visibleSize.width - 10.0f);
const Size &widgetSize = tilePicker->getContentSize();
this->addChild(tilePicker);
tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,
origin.y + visibleSize.height - 35.0f - widgetSize.height * 0.5f));
_tilePicker = tilePicker;
// 其他信息的相关控件
ExtraInfoWidget *extraInfo = ExtraInfoWidget::create(visibleSize.width - 10.0f, [this](Ref *) { calculate(); });
const Size &extraSize = extraInfo->getContentSize();
this->addChild(extraInfo);
extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,
origin.y + visibleSize.height - 35.0f - widgetSize.height - 5.0f - extraSize.height * 0.5f));
_extraInfo = extraInfo;
extraInfo->setInputCallback(std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2));
// 番种显示的Node
Size areaSize(visibleSize.width, visibleSize.height - 35.0f - widgetSize.height - 5.0f - extraSize.height - 10.0f);
Node *node = Node::create();
node->setContentSize(areaSize);
node->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
node->setIgnoreAnchorPointForPosition(false);
this->addChild(node);
node->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5.0f));
_fanAreaNode = node;
tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() {
extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong());
});
tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() {
extraInfo->refreshByWinTile(tilePicker->getServingTile(), !tilePicker->isStandingTilesContainsServingTile(),
tilePicker->countServingTileInFixedPacks(), tilePicker->isFixedPacksContainsKong());
});
return true;
}
cocos2d::Node *createFanResultNode(const mahjong::fan_table_t &fan_table, int fontSize, float resultAreaWidth) {
// 有n个番种,每行排2个
ptrdiff_t fanCnt = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0);
ptrdiff_t rows = (fanCnt >> 1) + (fanCnt & 1); // 需要这么多行
// 排列
Node *node = Node::create();
const int lineHeight = fontSize + 2; // 每行间隔2像素
ptrdiff_t resultAreaHeight = lineHeight * rows;
resultAreaHeight += (5 + lineHeight) + 20; // 总计+提示
node->setContentSize(Size(resultAreaWidth, static_cast<float>(resultAreaHeight)));
uint16_t fan = 0;
for (int i = 0, j = 0; i < fanCnt; ++i) {
while (fan_table[++j] == 0) continue;
uint16_t f = mahjong::fan_value_table[j];
uint16_t n = fan_table[j];
fan += f * n;
std::string str = (n == 1) ? Common::format(__UTF8("%s %hu番\n"), mahjong::fan_name[j], f)
: Common::format(__UTF8("%s %hu番x%hu\n"), mahjong::fan_name[j], f, n);
// 创建label,每行排2个
Label *label = Label::createWithSystemFont(str, "Arial", static_cast<float>(fontSize));
label->setColor(C3B_GRAY);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
div_t ret = div(i, 2);
label->setPosition(Vec2(ret.rem == 0 ? 0.0f : resultAreaWidth * 0.5f, static_cast<float>(resultAreaHeight - lineHeight * (ret.quot + 1))));
// 创建与label同位置的widget
ui::Widget *widget = ui::Widget::create();
widget->setTouchEnabled(true);
widget->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
widget->setPosition(label->getPosition());
widget->setContentSize(label->getContentSize());
node->addChild(widget);
widget->addClickEventListener([j](Ref *) {
FanTableScene::asyncShowFanDefinition(static_cast<size_t>(j));
});
}
Label *label = Label::createWithSystemFont(Common::format(__UTF8("总计:%hu番"), fan), "Arial", static_cast<float>(fontSize));
label->setColor(Color3B::BLACK);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
label->setPosition(Vec2(0.0f, lineHeight * 0.5f + 20.0f));
label = Label::createWithSystemFont(__UTF8("点击番种名可查看番种介绍。"), "Arial", 10);
label->setColor(C3B_BLUE_THEME);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
label->setPosition(Vec2(0.0f, 5.0f));
return node;
}
void FanCalculatorScene::calculate() {
_fanAreaNode->removeAllChildren();
const Size &fanAreaSize = _fanAreaNode->getContentSize();
Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f);
int flowerCnt = _extraInfo->getFlowerCount();
if (flowerCnt > 8) {
Toast::makeText(this, __UTF8("花牌数的范围为0~8"), Toast::LENGTH_LONG)->show();
return;
}
mahjong::calculate_param_t param;
_tilePicker->getData(¶m.hand_tiles, ¶m.win_tile);
if (param.win_tile == 0) {
Toast::makeText(this, __UTF8("牌张数错误"), Toast::LENGTH_LONG)->show();
return;
}
std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count);
param.flower_count = static_cast<uint8_t>(flowerCnt);
mahjong::fan_table_t fan_table = { 0 };
// 获取绝张、杠开、抢杠、海底信息
mahjong::win_flag_t win_flag = _extraInfo->getWinFlag();
// 获取圈风门风
mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind();
mahjong::wind_t seat_wind = _extraInfo->getSeatWind();
// 算番
param.win_flag = win_flag;
param.prevalent_wind = prevalent_wind;
param.seat_wind = seat_wind;
int fan = calculate_fan(¶m, &fan_table);
if (fan == ERROR_NOT_WIN) {
Toast::makeText(this, __UTF8("诈和"), Toast::LENGTH_LONG)->show();
return;
}
if (fan == ERROR_WRONG_TILES_COUNT) {
Toast::makeText(this, __UTF8("牌张数错误"), Toast::LENGTH_LONG)->show();
return;
}
if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) {
Toast::makeText(this, __UTF8("同一种牌最多只能使用4枚"), Toast::LENGTH_LONG)->show();
return;
}
Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width - 10.0f);
// 超出高度就使用ScrollView
if (innerNode->getContentSize().height <= fanAreaSize.height) {
_fanAreaNode->addChild(innerNode);
innerNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
innerNode->setPosition(pos);
}
else {
ui::ScrollView *scrollView = ui::ScrollView::create();
scrollView->setDirection(ui::ScrollView::Direction::VERTICAL);
scrollView->setScrollBarPositionFromCorner(Vec2(2.0f, 2.0f));
scrollView->setScrollBarWidth(4.0f);
scrollView->setScrollBarOpacity(0x99);
scrollView->setContentSize(Size(fanAreaSize.width - 10.0f, fanAreaSize.height));
scrollView->setInnerContainerSize(innerNode->getContentSize());
scrollView->addChild(innerNode);
_fanAreaNode->addChild(scrollView);
scrollView->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
scrollView->setPosition(pos);
}
}
<commit_msg>一些string的format改用c函数<commit_after>#include "FanCalculatorScene.h"
#include <algorithm>
#include <iterator>
#include "../mahjong-algorithm/stringify.h"
#include "../mahjong-algorithm/fan_calculator.h"
#include "../UICommon.h"
#include "../widget/TilePickWidget.h"
#include "../widget/ExtraInfoWidget.h"
#include "../widget/Toast.h"
#include "../FanTable/FanTableScene.h"
USING_NS_CC;
static const Color3B C3B_GRAY = Color3B(96, 96, 96);
static const Color3B C3B_BLUE_THEME = Color3B(51, 204, 255);
bool FanCalculatorScene::init() {
if (UNLIKELY(!BaseScene::initWithTitle(__UTF8("国标麻将算番器")))) {
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 选牌面板
TilePickWidget *tilePicker = TilePickWidget::create(visibleSize.width - 10.0f);
const Size &widgetSize = tilePicker->getContentSize();
this->addChild(tilePicker);
tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,
origin.y + visibleSize.height - 35.0f - widgetSize.height * 0.5f));
_tilePicker = tilePicker;
// 其他信息的相关控件
ExtraInfoWidget *extraInfo = ExtraInfoWidget::create(visibleSize.width - 10.0f, [this](Ref *) { calculate(); });
const Size &extraSize = extraInfo->getContentSize();
this->addChild(extraInfo);
extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,
origin.y + visibleSize.height - 35.0f - widgetSize.height - 5.0f - extraSize.height * 0.5f));
_extraInfo = extraInfo;
extraInfo->setInputCallback(std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2));
// 番种显示的Node
Size areaSize(visibleSize.width, visibleSize.height - 35.0f - widgetSize.height - 5.0f - extraSize.height - 10.0f);
Node *node = Node::create();
node->setContentSize(areaSize);
node->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
node->setIgnoreAnchorPointForPosition(false);
this->addChild(node);
node->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5.0f));
_fanAreaNode = node;
tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() {
extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong());
});
tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() {
extraInfo->refreshByWinTile(tilePicker->getServingTile(), !tilePicker->isStandingTilesContainsServingTile(),
tilePicker->countServingTileInFixedPacks(), tilePicker->isFixedPacksContainsKong());
});
return true;
}
cocos2d::Node *createFanResultNode(const mahjong::fan_table_t &fan_table, int fontSize, float resultAreaWidth) {
// 有n个番种,每行排2个
ptrdiff_t fanCnt = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0);
ptrdiff_t rows = (fanCnt >> 1) + (fanCnt & 1); // 需要这么多行
// 排列
Node *node = Node::create();
const int lineHeight = fontSize + 2; // 每行间隔2像素
ptrdiff_t resultAreaHeight = lineHeight * rows;
resultAreaHeight += (5 + lineHeight) + 20; // 总计+提示
node->setContentSize(Size(resultAreaWidth, static_cast<float>(resultAreaHeight)));
char str[64];
uint16_t fan = 0;
for (int i = 0, j = 0; i < fanCnt; ++i) {
while (fan_table[++j] == 0) continue;
uint16_t f = mahjong::fan_value_table[j];
uint16_t n = fan_table[j];
fan += f * n;
strncpy(str, mahjong::fan_name[j], sizeof(str) - 1);
size_t len = strlen(str);
len += snprintf(str + len, sizeof(str) - len, __UTF8(" %hu番"), f);
if (n > 1) {
snprintf(str + len, sizeof(str) - len, __UTF8("x%hu"), n);
}
// 创建label,每行排2个
Label *label = Label::createWithSystemFont(str, "Arial", static_cast<float>(fontSize));
label->setColor(C3B_GRAY);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
div_t ret = div(i, 2);
label->setPosition(Vec2(ret.rem == 0 ? 0.0f : resultAreaWidth * 0.5f, static_cast<float>(resultAreaHeight - lineHeight * (ret.quot + 0.5f))));
// 创建与label同位置的widget
ui::Widget *widget = ui::Widget::create();
widget->setTouchEnabled(true);
widget->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
widget->setPosition(label->getPosition());
widget->setContentSize(label->getContentSize());
node->addChild(widget);
widget->addClickEventListener([j](Ref *) {
FanTableScene::asyncShowFanDefinition(static_cast<size_t>(j));
});
}
snprintf(str, sizeof(str), __UTF8("总计:%hu番"), fan);
Label *label = Label::createWithSystemFont(str, "Arial", static_cast<float>(fontSize));
label->setColor(Color3B::BLACK);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
label->setPosition(Vec2(0.0f, lineHeight * 0.5f + 20.0f));
label = Label::createWithSystemFont(__UTF8("点击番种名可查看番种介绍。"), "Arial", 10);
label->setColor(C3B_BLUE_THEME);
node->addChild(label);
label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
label->setPosition(Vec2(0.0f, 5.0f));
return node;
}
void FanCalculatorScene::calculate() {
_fanAreaNode->removeAllChildren();
const Size &fanAreaSize = _fanAreaNode->getContentSize();
Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f);
int flowerCnt = _extraInfo->getFlowerCount();
if (flowerCnt > 8) {
Toast::makeText(this, __UTF8("花牌数的范围为0~8"), Toast::LENGTH_LONG)->show();
return;
}
mahjong::calculate_param_t param;
_tilePicker->getData(¶m.hand_tiles, ¶m.win_tile);
if (param.win_tile == 0) {
Toast::makeText(this, __UTF8("牌张数错误"), Toast::LENGTH_LONG)->show();
return;
}
std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count);
param.flower_count = static_cast<uint8_t>(flowerCnt);
mahjong::fan_table_t fan_table = { 0 };
// 获取绝张、杠开、抢杠、海底信息
mahjong::win_flag_t win_flag = _extraInfo->getWinFlag();
// 获取圈风门风
mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind();
mahjong::wind_t seat_wind = _extraInfo->getSeatWind();
// 算番
param.win_flag = win_flag;
param.prevalent_wind = prevalent_wind;
param.seat_wind = seat_wind;
int fan = calculate_fan(¶m, &fan_table);
if (fan == ERROR_NOT_WIN) {
Toast::makeText(this, __UTF8("诈和"), Toast::LENGTH_LONG)->show();
return;
}
if (fan == ERROR_WRONG_TILES_COUNT) {
Toast::makeText(this, __UTF8("牌张数错误"), Toast::LENGTH_LONG)->show();
return;
}
if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) {
Toast::makeText(this, __UTF8("同一种牌最多只能使用4枚"), Toast::LENGTH_LONG)->show();
return;
}
Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width - 10.0f);
// 超出高度就使用ScrollView
if (innerNode->getContentSize().height <= fanAreaSize.height) {
_fanAreaNode->addChild(innerNode);
innerNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
innerNode->setPosition(pos);
}
else {
ui::ScrollView *scrollView = ui::ScrollView::create();
scrollView->setDirection(ui::ScrollView::Direction::VERTICAL);
scrollView->setScrollBarPositionFromCorner(Vec2(2.0f, 2.0f));
scrollView->setScrollBarWidth(4.0f);
scrollView->setScrollBarOpacity(0x99);
scrollView->setContentSize(Size(fanAreaSize.width - 10.0f, fanAreaSize.height));
scrollView->setInnerContainerSize(innerNode->getContentSize());
scrollView->addChild(innerNode);
_fanAreaNode->addChild(scrollView);
scrollView->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
scrollView->setPosition(pos);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include "sqlite.hpp"
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "connection_manager.hpp"
#include "cursorresultset.hpp"
// boost
#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
//stl
#include <iostream>
#include <fstream>
namespace mapnik {
struct blob_to_hex
{
std::string operator() (const char* blob, unsigned size)
{
std::string buf;
buf.reserve(size*2);
std::ostringstream s(buf);
s.seekp(0);
char hex[3];
std::memset(hex,0,3);
for ( unsigned pos=0; pos < size; ++pos)
{
std::sprintf (hex, "%02X", int(blob[pos]) & 0xff);
s << hex;
}
return s.str();
}
};
bool valid_envelope(mapnik::Envelope<double> const& e)
{
return (e.minx() < e.maxx() && e.miny() < e.maxy()) ;
}
std::string table_from_sql(std::string const& sql)
{
std::string table_name = boost::algorithm::to_lower_copy(sql);
boost::algorithm::replace_all(table_name,"\n"," ");
std::string::size_type idx = table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
if (idx != std::string::npos)
{
table_name=table_name.substr(idx);
}
idx=table_name.find_first_of(" ),");
if (idx != std::string::npos)
{
table_name = table_name.substr(0,idx);
}
}
return table_name;
}
template <typename Connection>
void pgsql2sqlite(Connection conn,
std::string const& query,
std::string const& output_table_name,
std::string const& output_filename)
{
namespace sqlite = mapnik::sqlite;
sqlite::database db(output_filename);
boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from (" + query + ") as query limit 0;");
int count = rs->getNumFields();
std::ostringstream select_sql;
select_sql << "select ";
for (int i=0; i<count; ++i)
{
if (i!=0) select_sql << ",";
select_sql << "\"" << rs->getFieldName(i) << "\"";
}
select_sql << " from (" << query << ") as query";
std::string table_name = table_from_sql(query);
std::ostringstream geom_col_sql;
geom_col_sql << "select f_geometry_column,srid,type from geometry_columns ";
geom_col_sql << "where f_table_name='" << table_name << "'";
rs = conn->executeQuery(geom_col_sql.str());
int srid = -1;
std::string geom_col = "UNKNOWN";
std::string geom_type = "UNKNOWN";
if ( rs->next())
{
try
{
srid = boost::lexical_cast<int>(rs->getValue("srid"));
}
catch (boost::bad_lexical_cast &ex)
{
std::clog << ex.what() << std::endl;
}
geom_col = rs->getValue("f_geometry_column");
geom_type = rs->getValue("type");
}
// add AsBinary(<geometry_column>) modifier
std::string select_sql_str = select_sql.str();
boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col);
#ifdef MAPNIK_DEBUG
std::cout << select_sql_str << "\n";
#endif
std::ostringstream cursor_sql;
std::string cursor_name("my_cursor");
cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY";
conn->execute(cursor_sql.str());
boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000));
unsigned num_fields = cursor->getNumFields();
std::ostringstream create_sql;
create_sql << "create table " << output_table_name << "(PK_UID INTEGER PRIMARY KEY AUTOINCREMENT,";
int geometry_oid = -1;
std::string output_table_insert_sql = "insert into " + output_table_name + " values (?";
for ( unsigned pos = 0; pos < num_fields ; ++pos)
{
if (pos > 0)
{
create_sql << ",";
}
output_table_insert_sql +=",?";
if (geom_col == cursor->getFieldName(pos))
{
geometry_oid = cursor->getTypeOID(pos);
create_sql << "'" << cursor->getFieldName(pos) << "' BLOB";
}
else
{
create_sql << "'" << cursor->getFieldName(pos) << "' TEXT";
}
}
create_sql << ");";
output_table_insert_sql +=")";
std::cout << "client_encoding=" << conn->client_encoding() << "\n";
std::cout << "geometry_column=" << geom_col << "(" << geom_type
<< ") srid=" << srid << " oid=" << geometry_oid << "\n";
db.execute("begin;");
// output table sql
db.execute(create_sql.str());
// spatial index sql
std::string spatial_index_sql = "create virtual table idx_" + output_table_name
+ "_" + geom_col + " using rtree(pkid, xmin, xmax, ymin, ymax)";
db.execute(spatial_index_sql);
//blob_to_hex hex;
int pkid = 0;
std::string spatial_index_insert_sql = "insert into idx_" + output_table_name + "_"
+ geom_col + " values (?,?,?,?,?)" ;
sqlite::prepared_statement spatial_index(db,spatial_index_insert_sql);
#ifdef MAPNIK_DEBUG
std::cout << output_table_insert_sql << "\n";
#endif
sqlite::prepared_statement output_table(db,output_table_insert_sql);
while (cursor->next())
{
++pkid;
sqlite::record_type output_rec;
output_rec.push_back(sqlite::value_type(pkid));
bool empty_geom = true;
const char * buf = 0;
for (unsigned pos=0 ; pos < num_fields; ++pos)
{
if (! cursor->isNull(pos))
{
int size=cursor->getFieldLength(pos);
int oid = cursor->getTypeOID(pos);
buf=cursor->getValue(pos);
switch (oid)
{
case 25:
case 1042:
case 1043:
{
std::string text(buf);
boost::algorithm::replace_all(text,"'","''");
output_rec.push_back(sqlite::value_type(text));
break;
}
case 23:
output_rec.push_back(sqlite::value_type(int4net(buf)));
break;
default:
{
if (oid == geometry_oid)
{
mapnik::Feature feat(pkid);
geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric);
if (feat.num_geometries() > 0)
{
geometry2d const& geom=feat.get_geometry(0);
Envelope<double> bbox = geom.envelope();
if (valid_envelope(bbox))
{
sqlite::record_type rec;
rec.push_back(sqlite::value_type(pkid));
rec.push_back(sqlite::value_type(bbox.minx()));
rec.push_back(sqlite::value_type(bbox.maxx()));
rec.push_back(sqlite::value_type(bbox.miny()));
rec.push_back(sqlite::value_type(bbox.maxy()));
spatial_index.insert_record(rec);
empty_geom = false;
}
}
//output_rec.push_back(sqlite::value_type("X'" + hex(buf,size) + "'"));
output_rec.push_back(sqlite::blob(buf,size));
}
else
{
output_rec.push_back(sqlite::null_type());
}
break;
}
}
}
else
{
output_rec.push_back(sqlite::null_type());
}
}
if (!empty_geom) output_table.insert_record(output_rec);
if (pkid % 1000 == 0)
{
std::cout << "\r processing " << pkid << " features";
std::cout.flush();
}
if (pkid % 100000 == 0)
{
db.execute("commit;begin;");
}
}
// commit
db.execute("commit;");
std::cout << "\r processed " << pkid << " features";
std::cout << "\n Done!" << std::endl;
}
}
<commit_msg>+ create table if not exists + use OGC_FID instead of PK_UID<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include "sqlite.hpp"
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "connection_manager.hpp"
#include "cursorresultset.hpp"
// boost
#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
//stl
#include <iostream>
#include <fstream>
namespace mapnik {
struct blob_to_hex
{
std::string operator() (const char* blob, unsigned size)
{
std::string buf;
buf.reserve(size*2);
std::ostringstream s(buf);
s.seekp(0);
char hex[3];
std::memset(hex,0,3);
for ( unsigned pos=0; pos < size; ++pos)
{
std::sprintf (hex, "%02X", int(blob[pos]) & 0xff);
s << hex;
}
return s.str();
}
};
bool valid_envelope(mapnik::Envelope<double> const& e)
{
return (e.minx() < e.maxx() && e.miny() < e.maxy()) ;
}
std::string table_from_sql(std::string const& sql)
{
std::string table_name = boost::algorithm::to_lower_copy(sql);
boost::algorithm::replace_all(table_name,"\n"," ");
std::string::size_type idx = table_name.rfind("from");
if (idx!=std::string::npos)
{
idx=table_name.find_first_not_of(" ",idx+4);
if (idx != std::string::npos)
{
table_name=table_name.substr(idx);
}
idx=table_name.find_first_of(" ),");
if (idx != std::string::npos)
{
table_name = table_name.substr(0,idx);
}
}
return table_name;
}
template <typename Connection>
void pgsql2sqlite(Connection conn,
std::string const& query,
std::string const& output_table_name,
std::string const& output_filename)
{
namespace sqlite = mapnik::sqlite;
sqlite::database db(output_filename);
boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from (" + query + ") as query limit 0;");
int count = rs->getNumFields();
std::ostringstream select_sql;
select_sql << "select ";
for (int i=0; i<count; ++i)
{
if (i!=0) select_sql << ",";
select_sql << "\"" << rs->getFieldName(i) << "\"";
}
select_sql << " from (" << query << ") as query";
std::string table_name = table_from_sql(query);
std::ostringstream geom_col_sql;
geom_col_sql << "select f_geometry_column,srid,type from geometry_columns ";
geom_col_sql << "where f_table_name='" << table_name << "'";
rs = conn->executeQuery(geom_col_sql.str());
int srid = -1;
std::string geom_col = "UNKNOWN";
std::string geom_type = "UNKNOWN";
if ( rs->next())
{
try
{
srid = boost::lexical_cast<int>(rs->getValue("srid"));
}
catch (boost::bad_lexical_cast &ex)
{
std::clog << ex.what() << std::endl;
}
geom_col = rs->getValue("f_geometry_column");
geom_type = rs->getValue("type");
}
// add AsBinary(<geometry_column>) modifier
std::string select_sql_str = select_sql.str();
boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col);
#ifdef MAPNIK_DEBUG
std::cout << select_sql_str << "\n";
#endif
std::ostringstream cursor_sql;
std::string cursor_name("my_cursor");
cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY";
conn->execute(cursor_sql.str());
boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000));
unsigned num_fields = cursor->getNumFields();
std::ostringstream create_sql;
create_sql << "create table if not exists" << output_table_name << "(OGC_FID INTEGER PRIMARY KEY AUTOINCREMENT,";
int geometry_oid = -1;
std::string output_table_insert_sql = "insert into " + output_table_name + " values (?";
for ( unsigned pos = 0; pos < num_fields ; ++pos)
{
if (pos > 0)
{
create_sql << ",";
}
output_table_insert_sql +=",?";
if (geom_col == cursor->getFieldName(pos))
{
geometry_oid = cursor->getTypeOID(pos);
create_sql << "'" << cursor->getFieldName(pos) << "' BLOB";
}
else
{
create_sql << "'" << cursor->getFieldName(pos) << "' TEXT";
}
}
create_sql << ");";
output_table_insert_sql +=")";
std::cout << "client_encoding=" << conn->client_encoding() << "\n";
std::cout << "geometry_column=" << geom_col << "(" << geom_type
<< ") srid=" << srid << " oid=" << geometry_oid << "\n";
db.execute("begin;");
// output table sql
db.execute(create_sql.str());
// spatial index sql
std::string spatial_index_sql = "create virtual table idx_" + output_table_name
+ "_" + geom_col + " using rtree(pkid, xmin, xmax, ymin, ymax)";
db.execute(spatial_index_sql);
//blob_to_hex hex;
int pkid = 0;
std::string spatial_index_insert_sql = "insert into idx_" + output_table_name + "_"
+ geom_col + " values (?,?,?,?,?)" ;
sqlite::prepared_statement spatial_index(db,spatial_index_insert_sql);
#ifdef MAPNIK_DEBUG
std::cout << output_table_insert_sql << "\n";
#endif
sqlite::prepared_statement output_table(db,output_table_insert_sql);
while (cursor->next())
{
++pkid;
sqlite::record_type output_rec;
output_rec.push_back(sqlite::value_type(pkid));
bool empty_geom = true;
const char * buf = 0;
for (unsigned pos=0 ; pos < num_fields; ++pos)
{
if (! cursor->isNull(pos))
{
int size=cursor->getFieldLength(pos);
int oid = cursor->getTypeOID(pos);
buf=cursor->getValue(pos);
switch (oid)
{
case 25:
case 1042:
case 1043:
{
std::string text(buf);
boost::algorithm::replace_all(text,"'","''");
output_rec.push_back(sqlite::value_type(text));
break;
}
case 23:
output_rec.push_back(sqlite::value_type(int4net(buf)));
break;
default:
{
if (oid == geometry_oid)
{
mapnik::Feature feat(pkid);
geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric);
if (feat.num_geometries() > 0)
{
geometry2d const& geom=feat.get_geometry(0);
Envelope<double> bbox = geom.envelope();
if (valid_envelope(bbox))
{
sqlite::record_type rec;
rec.push_back(sqlite::value_type(pkid));
rec.push_back(sqlite::value_type(bbox.minx()));
rec.push_back(sqlite::value_type(bbox.maxx()));
rec.push_back(sqlite::value_type(bbox.miny()));
rec.push_back(sqlite::value_type(bbox.maxy()));
spatial_index.insert_record(rec);
empty_geom = false;
}
}
//output_rec.push_back(sqlite::value_type("X'" + hex(buf,size) + "'"));
output_rec.push_back(sqlite::blob(buf,size));
}
else
{
output_rec.push_back(sqlite::null_type());
}
break;
}
}
}
else
{
output_rec.push_back(sqlite::null_type());
}
}
if (!empty_geom) output_table.insert_record(output_rec);
if (pkid % 1000 == 0)
{
std::cout << "\r processing " << pkid << " features";
std::cout.flush();
}
if (pkid % 100000 == 0)
{
db.execute("commit;begin;");
}
}
// commit
db.execute("commit;");
std::cout << "\r processed " << pkid << " features";
std::cout << "\n Done!" << std::endl;
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <sched.h>
#include <unistd.h>
#include <assert.h>
static int s_called = 0;
#define MAX_PID 32767
static int s_errno ;
static int s_errnos [ MAX_PID + 1 ];
static int32_t s_bad = 0;
static int32_t s_badPid = -1;
// WARNING: you MUST compile with -DREENTRANT for this to work
int *__errno_location (void) {
int32_t pid = (int32_t) getpid();
s_called++;
if ( pid <= (int32_t)MAX_PID ) return &s_errnos[pid];
s_bad++;
s_badPid = pid;
return &s_errno;
}
//extern __thread int errno;
int g_errno = 0;
int startup ( void *state ) {
char buf[5];
// this sets errno, but does not seem to call our __errno_location
// override, BUT does seem to not affect "errno" in main() either!
// maybe this is the TLS support?
int bytes = read(-9,buf,5);
//errno = 7; // E2BIG;
//assert ( errno && bytes == -1 );
g_errno = errno;
}
int main() {
errno = 10; // EINVAL;
g_errno = 10;
char stack[10000];
pid_t pid = clone( startup ,
stack + 10000 ,
//CLONE_SETTLS |
CLONE_VM | SIGCHLD,
NULL );
int status;
waitpid ( pid , &status, 0 );
if ( s_called ) fprintf(stderr,"__errno_location() was called %i "
"times\n",s_called);
if ( errno != 10 ) fprintf(stderr,"errno=%i (failed)\n",errno);
else fprintf(stderr,"errno=%i (success)\n",errno);
if ( g_errno == 10 || g_errno == 0 )
fprintf(stderr,"gerrno=%i (failed)\n",g_errno);
else
fprintf(stderr,"gerrno=%i (success)\n",g_errno);
}
<commit_msg>errnotest.cpp fix<commit_after>#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <sched.h>
#include <unistd.h>
#include <assert.h>
static int s_called = 0;
#define MAX_PID 32767
static int s_errno ;
static int s_errnos [ MAX_PID + 1 ];
static int32_t s_bad = 0;
static int32_t s_badPid = -1;
// WARNING: you MUST compile with -DREENTRANT for this to work
int *__errno_location (void) {
int32_t pid = (int32_t) getpid();
s_called++;
if ( pid <= (int32_t)MAX_PID ) return &s_errnos[pid];
s_bad++;
s_badPid = pid;
return &s_errno;
}
//extern __thread int errno;
int g_errno = 0;
int startup ( void *state ) {
char buf[5];
// this sets errno, but does not seem to call our __errno_location
// override, BUT does seem to not affect "errno" in main() either!
// maybe this is the TLS support?
int bytes = read(-9,buf,5);
//errno = 7; // E2BIG;
//assert ( errno && bytes == -1 );
//g_errno = errno;
}
int main() {
//errno = 10; // EINVAL;
g_errno = 10;
char stack[10000];
pid_t pid = clone( startup ,
stack + 10000 ,
//CLONE_SETTLS |
CLONE_VM | SIGCHLD,
NULL );
int status;
waitpid ( pid , &status, 0 );
fprintf(stderr,"__errno_location() was called %i "
"times\n",s_called);
if ( errno != 10 ) fprintf(stderr,"errno=%i (failed)\n",errno);
else fprintf(stderr,"errno=%i (success)\n",errno);
if ( g_errno == 10 || g_errno == 0 )
fprintf(stderr,"gerrno=%i (failed)\n",g_errno);
else
fprintf(stderr,"gerrno=%i (success)\n",g_errno);
}
<|endoftext|> |
<commit_before>#include "joypad.h"
#include "memory.h"
#include "lr35902.h"
#include <stdio.h>
Joypad::Joypad(LR35902 &lr35902, Memory &mem) : cpu(lr35902), memory(mem)
{
// No buttons pressed at start
memory.direct_io_write8(Memory::IO::JOYP, 0xff);
}
void Joypad::button_pressed(Button::Name b)
{
buttons[b] = true;
memory.direct_io_write8(Memory::IO::JOYP, get_button_state());
cpu.raise_interrupt(LR35902::Interrupt::JOYPAD);
printf("button pressed");
switch (b)
{
case Button::UP:
printf(" UP\n");
break;
case Button::DOWN:
printf(" DOWN\n");
break;
case Button::LEFT:
printf(" LEFT\n");
break;
case Button::RIGHT:
printf(" RIGHT\n");
break;
case Button::START:
printf(" START\n");
break;
case Button::SELECT:
printf(" SELECT\n");
break;
case Button::A:
printf(" A\n");
break;
case Button::B:
printf(" B\n");
break;
default:
printf("error\n");
throw "sdf";
}
}
void Joypad::button_released(Button::Name b)
{
buttons[b] = false;
memory.direct_io_write8(Memory::IO::JOYP, get_button_state());
}
u8 Joypad::get_button_state() const
{
u8 JOYP = memory.get8(Memory::IO::JOYP);
bool direction_keys = !(JOYP & (1 << 4));
bool button_keys = !(JOYP & (1 << 5));
// Right / Button A
bool bit0 = (direction_keys && buttons[Button::RIGHT]) ||
(button_keys && buttons[Button::A]);
// Left / Button B
bool bit1 = (direction_keys && buttons[Button::LEFT]) ||
(button_keys && buttons[Button::B]);
// Up / Select
bool bit2 = (direction_keys && buttons[Button::UP]) ||
(button_keys && buttons[Button::SELECT]);
// Down / Start
bool bit3 = (direction_keys && buttons[Button::DOWN]) ||
(button_keys && buttons[Button::START]);
JOYP = (button_keys << 5) | (direction_keys << 4) |
(bit3 << 3) | (bit2 << 2) | (bit1 << 1) | bit0;
// 0 means button is pressed, 1 means not pressed - invert all bits
return ~JOYP;
}
<commit_msg>Joypad: Only raise interrupt on button press if the keys are enabled too<commit_after>#include "joypad.h"
#include "memory.h"
#include "lr35902.h"
#include <stdio.h>
Joypad::Joypad(LR35902 &lr35902, Memory &mem) : cpu(lr35902), memory(mem)
{
// No buttons pressed at start
memory.direct_io_write8(Memory::IO::JOYP, 0xff);
}
void Joypad::button_pressed(Button::Name b)
{
buttons[b] = true;
memory.direct_io_write8(Memory::IO::JOYP, get_button_state());
/*
printf("button pressed");
switch (b)
{
case Button::UP:
printf(" UP\n");
break;
case Button::DOWN:
printf(" DOWN\n");
break;
case Button::LEFT:
printf(" LEFT\n");
break;
case Button::RIGHT:
printf(" RIGHT\n");
break;
case Button::START:
printf(" START\n");
break;
case Button::SELECT:
printf(" SELECT\n");
break;
case Button::A:
printf(" A\n");
break;
case Button::B:
printf(" B\n");
break;
default:
printf("error\n");
throw "sdf";
}
*/
}
void Joypad::button_released(Button::Name b)
{
buttons[b] = false;
memory.direct_io_write8(Memory::IO::JOYP, get_button_state());
}
u8 Joypad::get_button_state() const
{
u8 JOYP = memory.get8(Memory::IO::JOYP);
bool direction_keys = !(JOYP & (1 << 4));
bool button_keys = !(JOYP & (1 << 5));
// Right / Button A
bool bit0 = (direction_keys && buttons[Button::RIGHT]) ||
(button_keys && buttons[Button::A]);
// Left / Button B
bool bit1 = (direction_keys && buttons[Button::LEFT]) ||
(button_keys && buttons[Button::B]);
// Up / Select
bool bit2 = (direction_keys && buttons[Button::UP]) ||
(button_keys && buttons[Button::SELECT]);
// Down / Start
bool bit3 = (direction_keys && buttons[Button::DOWN]) ||
(button_keys && buttons[Button::START]);
JOYP = (button_keys << 5) | (direction_keys << 4) |
(bit3 << 3) | (bit2 << 2) | (bit1 << 1) | bit0;
if (bit0 || bit1 || bit2 || bit3)
{
cpu.raise_interrupt(LR35902::Interrupt::JOYPAD);
}
// 0 means button is pressed, 1 means not pressed - invert all bits
return ~JOYP;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {HillShadingExample.png}, {HillShadingColorExample.png}
// 6.5 45.5 500 500 0.002 -0.002 ${OTB_DATA_ROOT}/Examples/DEM_srtm
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Visualization of digital elevation models (DEM) is often more intuitive by simulating a
// lighting source and generating the corresponding shadows. This principle is called
// hill shading.
//
// Using a simple functor \doxygen{otb}{HillShadingFunctor} and the dem image generated
// using the \doxygen{otb}{DEMToImageGenerator} (refer to \ref{sec:ReadDEM}) you can easily
// obtain a representation of the DEM. Better yet, using the
// \doxygen{otb}{ScalarToRainbowRGBPixelFunctor}, combined with the
// \doxygen{otb}{ReliefColormapFunctor} you can easily generate the classic elevation maps.
//
// This example will focus on the shading itself.
//
// Software Guide : EndLatex
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbDEMToImageGenerator.h"
#include "otbHillShadingFunctor.h"
#include "otbUnaryFunctorNeighborhoodImageFilter.h"
#include "itkScalarToRGBColormapImageFilter.h"
#include "otbReliefColormapFunctor.h"
#include "itkMultiplyImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbWorldFile.h"
namespace otb {
namespace Functor {
template< class TInput1, class TInput2=TInput1, class TOutput=TInput1>
class MultRGB
{
public:
MultRGB() {}
~MultRGB() {}
inline TOutput operator()( const TInput1 & A, const TInput2 & B) const
{
TOutput out;
out.SetRed(A.GetRed() * B);
out.SetGreen(A.GetGreen() * B);
out.SetBlue(A.GetBlue() * B);
return out;
}
};
}
}
int main(int argc, char * argv[])
{
if (argc != 10)
{
std::cout << argv[0] <<" <output_filename> <output_filename> ";
std::cout << " <Longitude Output Origin point> <Latitude Output Origin point>";
std::cout << " <X Output Size> <Y Output size>";
std::cout << " <X Spacing> <Y Spacing> <DEM folder path>" << std::endl;
return EXIT_FAILURE;
}
typedef double PixelType;
typedef unsigned char UCharPixelType;
typedef itk::RGBPixel<UCharPixelType> RGBPixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::Image<UCharPixelType, 2> ScalarImageType;
typedef otb::StreamingImageFileWriter<RGBImageType> WriterType;
typedef otb::StreamingImageFileWriter<ScalarImageType> ScalarWriterType;
ScalarWriterType::Pointer writer = ScalarWriterType::New();
writer->SetFileName(argv[1]);
WriterType::Pointer writer2 = WriterType::New();
writer2->SetFileName(argv[2]);
typedef otb::DEMToImageGenerator<ImageType> DEMToImageGeneratorType;
DEMToImageGeneratorType::Pointer demToImage = DEMToImageGeneratorType::New();
typedef DEMToImageGeneratorType::SizeType SizeType;
typedef DEMToImageGeneratorType::SpacingType SpacingType;
typedef DEMToImageGeneratorType::DEMHandlerType DEMHandlerType;
typedef DEMHandlerType::PointType PointType;
demToImage->SetDEMDirectoryPath(argv[9]);
PointType origin;
origin[0] = ::atof(argv[3]);
origin[1] = ::atof(argv[4]);
demToImage->SetOutputOrigin(origin);
SizeType size;
size[0] = ::atoi(argv[5]);
size[1] = ::atoi(argv[6]);
demToImage->SetOutputSize(size);
SpacingType spacing;
spacing[0] = ::atof(argv[7]);
spacing[1] = ::atof(argv[8]);
demToImage->SetOutputSpacing(spacing);
//Compute the resolution (Vincenty formula)
double lon1 = origin[0];
double lon2 = origin[0]+size[0]*spacing[0];
double lat1 = origin[1];
double lat2 = origin[1]+size[1]*spacing[1];
double R = 6371; // km
double d = vcl_acos(vcl_sin(lat1)*vcl_sin(lat2) +
vcl_cos(lat1)*vcl_cos(lat2) * vcl_cos(lon2-lon1)) * R;
double res = d / vcl_sqrt(2.0);
// Software Guide : BeginLatex
//
// After generating the dem image as in the DEMToImageGenerator example, you can declare
// the hill shading mechanism. The hill shading is implemented as a functor doing some
// operations in its neighorhood. This functor is used in the
// \doxygen{otb}{UnaryFunctorNeighborhoodImageFilter} that will be in charge of processing
// the whole image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ConstNeighborhoodIterator<ImageType> IterType;
typedef otb::Functor::HillShadingFunctor<IterType, ImageType, PixelType> FunctorType;
typedef otb::UnaryFunctorNeighborhoodImageFilter<ImageType, ImageType, FunctorType> HillShadingFilterType;
HillShadingFilterType::Pointer hillShading = HillShadingFilterType::New();
hillShading->SetRadius(1);
hillShading->SetInput(demToImage->GetOutput());
// Software Guide : EndCodeSnippet
hillShading->GetFunctor().SetXRes(res);
hillShading->GetFunctor().SetYRes(res);
typedef itk::RescaleIntensityImageFilter<ImageType, ScalarImageType> RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->SetInput(hillShading->GetOutput());
writer->SetInput(rescaler->GetOutput());
typedef itk::ScalarToRGBColormapImageFilter<ImageType,RGBImageType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->UseInputImageExtremaForScalingOff();
typedef otb::Functor::ReliefColormapFunctor<PixelType, RGBPixelType> ColorMapFunctorType;
ColorMapFunctorType::Pointer colormap = ColorMapFunctorType::New();
colormap->SetMinimumInputValue(0);
colormap->SetMaximumInputValue(4000);
colormapper->SetColormap(colormap);
colormapper->SetInput(demToImage->GetOutput());
typedef itk::BinaryFunctorImageFilter<RGBImageType, ImageType, RGBImageType,
otb::Functor::MultRGB<RGBPixelType, PixelType, RGBPixelType> > MultiplyFilterType;
MultiplyFilterType::Pointer multiply = MultiplyFilterType::New();
multiply->SetInput1(colormapper->GetOutput());
multiply->SetInput2(hillShading->GetOutput());
writer2->SetInput(multiply->GetOutput());
try
{
writer->Update();
writer2->Update();
}
catch ( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
catch ( ... )
{
std::cout << "Unknown exception !" << std::endl;
return EXIT_FAILURE;
}
otb::WorldFile::Pointer worldFile = otb::WorldFile::New();
worldFile->SetLonOrigin(origin[0]);
worldFile->SetLatOrigin(origin[1]);
worldFile->SetLonSpacing(spacing[0]);
worldFile->SetLatSpacing(spacing[1]);
worldFile->SetImageFilename(argv[1]);
worldFile->Update();
worldFile->SetImageFilename(argv[2]);
worldFile->Update();
// Software Guide : BeginLatex
//
// Figure~\ref{fig:HILL_SHADING} shows the hill shading result from SRTM data.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{HillShadingExample.eps}
// \includegraphics[width=0.44\textwidth]{HillShadingColorExample.eps}
// \itkcaption[Hill shading]{Hill shading obtained from SRTM data (left) and combined with
// the color representation (right)}
// \label{fig:HILL_SHADING}
// \end{figure}
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<commit_msg>BUG: replace rescaler<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {HillShadingExample.png}, {HillShadingColorExample.png}
// 6.5 45.5 500 500 0.002 -0.002 ${OTB_DATA_ROOT}/Examples/DEM_srtm
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Visualization of digital elevation models (DEM) is often more intuitive by simulating a
// lighting source and generating the corresponding shadows. This principle is called
// hill shading.
//
// Using a simple functor \doxygen{otb}{HillShadingFunctor} and the dem image generated
// using the \doxygen{otb}{DEMToImageGenerator} (refer to \ref{sec:ReadDEM}) you can easily
// obtain a representation of the DEM. Better yet, using the
// \doxygen{otb}{ScalarToRainbowRGBPixelFunctor}, combined with the
// \doxygen{otb}{ReliefColormapFunctor} you can easily generate the classic elevation maps.
//
// This example will focus on the shading itself.
//
// Software Guide : EndLatex
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbDEMToImageGenerator.h"
#include "otbHillShadingFunctor.h"
#include "otbUnaryFunctorNeighborhoodImageFilter.h"
#include "itkScalarToRGBColormapImageFilter.h"
#include "otbReliefColormapFunctor.h"
#include "itkMultiplyImageFilter.h"
#include "itkShiftScaleImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "otbWorldFile.h"
namespace otb {
namespace Functor {
template< class TInput1, class TInput2=TInput1, class TOutput=TInput1>
class MultRGB
{
public:
MultRGB() {}
~MultRGB() {}
inline TOutput operator()( const TInput1 & A, const TInput2 & B) const
{
TOutput out;
out.SetRed(A.GetRed() * B);
out.SetGreen(A.GetGreen() * B);
out.SetBlue(A.GetBlue() * B);
return out;
}
};
}
}
int main(int argc, char * argv[])
{
if (argc != 10)
{
std::cout << argv[0] <<" <output_filename> <output_filename> ";
std::cout << " <Longitude Output Origin point> <Latitude Output Origin point>";
std::cout << " <X Output Size> <Y Output size>";
std::cout << " <X Spacing> <Y Spacing> <DEM folder path>" << std::endl;
return EXIT_FAILURE;
}
typedef double PixelType;
typedef unsigned char UCharPixelType;
typedef itk::RGBPixel<UCharPixelType> RGBPixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::Image<UCharPixelType, 2> ScalarImageType;
typedef otb::StreamingImageFileWriter<RGBImageType> WriterType;
typedef otb::StreamingImageFileWriter<ScalarImageType> ScalarWriterType;
ScalarWriterType::Pointer writer = ScalarWriterType::New();
writer->SetFileName(argv[1]);
WriterType::Pointer writer2 = WriterType::New();
writer2->SetFileName(argv[2]);
typedef otb::DEMToImageGenerator<ImageType> DEMToImageGeneratorType;
DEMToImageGeneratorType::Pointer demToImage = DEMToImageGeneratorType::New();
typedef DEMToImageGeneratorType::SizeType SizeType;
typedef DEMToImageGeneratorType::SpacingType SpacingType;
typedef DEMToImageGeneratorType::DEMHandlerType DEMHandlerType;
typedef DEMHandlerType::PointType PointType;
demToImage->SetDEMDirectoryPath(argv[9]);
PointType origin;
origin[0] = ::atof(argv[3]);
origin[1] = ::atof(argv[4]);
demToImage->SetOutputOrigin(origin);
SizeType size;
size[0] = ::atoi(argv[5]);
size[1] = ::atoi(argv[6]);
demToImage->SetOutputSize(size);
SpacingType spacing;
spacing[0] = ::atof(argv[7]);
spacing[1] = ::atof(argv[8]);
demToImage->SetOutputSpacing(spacing);
//Compute the resolution (Vincenty formula)
double lon1 = origin[0];
double lon2 = origin[0]+size[0]*spacing[0];
double lat1 = origin[1];
double lat2 = origin[1]+size[1]*spacing[1];
double R = 6371; // km
double d = vcl_acos(vcl_sin(lat1)*vcl_sin(lat2) +
vcl_cos(lat1)*vcl_cos(lat2) * vcl_cos(lon2-lon1)) * R;
double res = d / vcl_sqrt(2.0);
// Software Guide : BeginLatex
//
// After generating the dem image as in the DEMToImageGenerator example, you can declare
// the hill shading mechanism. The hill shading is implemented as a functor doing some
// operations in its neighorhood. This functor is used in the
// \doxygen{otb}{UnaryFunctorNeighborhoodImageFilter} that will be in charge of processing
// the whole image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ConstNeighborhoodIterator<ImageType> IterType;
typedef otb::Functor::HillShadingFunctor<IterType, ImageType, PixelType> FunctorType;
typedef otb::UnaryFunctorNeighborhoodImageFilter<ImageType, ImageType, FunctorType> HillShadingFilterType;
HillShadingFilterType::Pointer hillShading = HillShadingFilterType::New();
hillShading->SetRadius(1);
hillShading->SetInput(demToImage->GetOutput());
// Software Guide : EndCodeSnippet
hillShading->GetFunctor().SetXRes(res);
hillShading->GetFunctor().SetYRes(res);
typedef itk::ShiftScaleImageFilter<ImageType, ScalarImageType> RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetScale(255.0);
rescaler->SetInput(hillShading->GetOutput());
writer->SetInput(rescaler->GetOutput());
typedef itk::ScalarToRGBColormapImageFilter<ImageType,RGBImageType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->UseInputImageExtremaForScalingOff();
typedef otb::Functor::ReliefColormapFunctor<PixelType, RGBPixelType> ColorMapFunctorType;
ColorMapFunctorType::Pointer colormap = ColorMapFunctorType::New();
colormap->SetMinimumInputValue(0);
colormap->SetMaximumInputValue(4000);
colormapper->SetColormap(colormap);
colormapper->SetInput(demToImage->GetOutput());
typedef itk::BinaryFunctorImageFilter<RGBImageType, ImageType, RGBImageType,
otb::Functor::MultRGB<RGBPixelType, PixelType, RGBPixelType> > MultiplyFilterType;
MultiplyFilterType::Pointer multiply = MultiplyFilterType::New();
multiply->SetInput1(colormapper->GetOutput());
multiply->SetInput2(hillShading->GetOutput());
writer2->SetInput(multiply->GetOutput());
try
{
writer->Update();
writer2->Update();
}
catch ( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
catch ( ... )
{
std::cout << "Unknown exception !" << std::endl;
return EXIT_FAILURE;
}
otb::WorldFile::Pointer worldFile = otb::WorldFile::New();
worldFile->SetLonOrigin(origin[0]);
worldFile->SetLatOrigin(origin[1]);
worldFile->SetLonSpacing(spacing[0]);
worldFile->SetLatSpacing(spacing[1]);
worldFile->SetImageFilename(argv[1]);
worldFile->Update();
worldFile->SetImageFilename(argv[2]);
worldFile->Update();
// Software Guide : BeginLatex
//
// Figure~\ref{fig:HILL_SHADING} shows the hill shading result from SRTM data.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{HillShadingExample.eps}
// \includegraphics[width=0.44\textwidth]{HillShadingColorExample.eps}
// \itkcaption[Hill shading]{Hill shading obtained from SRTM data (left) and combined with
// the color representation (right)}
// \label{fig:HILL_SHADING}
// \end{figure}
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 by Ivan Safrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "ExampleBrowserWindow.h"
ExampleBrowserWindow::ExampleBrowserWindow() : UIWindow(L"Example Browser", 320, 400){
templateFolder = "";
closeOnEscape = true;
defaultTemplateTree = NULL;
Config *conf = CoreServices::getInstance()->getConfig();
String fontName = conf->getStringValue("Polycode", "uiDefaultFontName");
int fontSize = conf->getNumericValue("Polycode", "uiDefaultFontSize");
templateContainer = new UITreeContainer("boxIcon.png", L"Examples", 320, 410-topPadding-padding-padding-40);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 0;
templateContainer->getRootNode()->setUserData(data);
addChild(templateContainer);
templateContainer->setPosition(padding,topPadding+padding);
templateContainer->getRootNode()->toggleCollapsed();
templateContainer->getRootNode()->addEventListener(this, UITreeEvent::SELECTED_EVENT);
vector<OSFileEntry> templates = OSBasics::parseFolder(RESOURCE_PATH"Standalone/Examples/Lua", false);
for(int i=0; i < templates.size(); i++) {
OSFileEntry entry = templates[i];
if(entry.type == OSFileEntry::TYPE_FOLDER) {
UITree *newChild = templateContainer->getRootNode()->addTreeChild("folder.png", entry.name, NULL);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 0;
newChild->setUserData(data);
if(i == 0) {
newChild->toggleCollapsed();
}
parseTemplatesIntoTree(newChild, entry);
}
}
cancelButton = new UIButton(L"Cancel", 100);
cancelButton->addEventListener(this, UIEvent::CLICK_EVENT);
addChild(cancelButton);
cancelButton->setPosition(330-100-padding-80-10, 375);
okButton = new UIButton(L"Open Example", 100);
okButton->addEventListener(this, UIEvent::CLICK_EVENT);
addChild(okButton);
okButton->setPosition(330-80-padding, 375);
}
String ExampleBrowserWindow::getExamplePath() {
String suffix;
std::vector<String> parts = templateFolder.split("/");
return templateFolder+"/"+parts[parts.size()-1]+".polyproject";
}
void ExampleBrowserWindow::ResetForm() {
if(defaultTemplateTree)
defaultTemplateTree->setSelected();
}
void ExampleBrowserWindow::handleEvent(Event *event) {
if(event->getEventType() == "UIEvent") {
if(event->getEventCode() == UIEvent::CLICK_EVENT) {
if(event->getDispatcher() == okButton) {
dispatchEvent(new UIEvent(), UIEvent::OK_EVENT);
}
if(event->getDispatcher() == cancelButton) {
dispatchEvent(new UIEvent(), UIEvent::CLOSE_EVENT);
}
}
}
if(event->getEventType() == "UITreeEvent" && event->getEventCode() == UITreeEvent::SELECTED_EVENT) {
if(event->getDispatcher() == templateContainer->getRootNode()) {
UITreeEvent *treeEvent = (UITreeEvent*) event;
ExampleTemplateUserData *data = (ExampleTemplateUserData *)treeEvent->selection->getUserData();
if(data->type == 1)
templateFolder = data->templateFolder;
}
}
UIWindow::handleEvent(event);
}
void ExampleBrowserWindow::parseTemplatesIntoTree(UITree *tree, OSFileEntry folder) {
vector<OSFileEntry> templates = OSBasics::parseFolder(folder.fullPath, false);
for(int i=0; i < templates.size(); i++) {
OSFileEntry entry = templates[i];
if(entry.type == OSFileEntry::TYPE_FOLDER) {
UITree *newChild = tree->addTreeChild("templateIcon.png", entry.name, NULL);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 1;
data->templateFolder = entry.fullPath;
newChild->setUserData(data);
if(entry.name == "Empty Project") {
defaultTemplateTree = newChild;
newChild->setSelected();
}
}
}
}
ExampleBrowserWindow::~ExampleBrowserWindow() {
}
<commit_msg>Fixed crash that would happen if you tried to open a folder node in ExampleBrowserWindow.<commit_after>/*
Copyright (C) 2012 by Ivan Safrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "ExampleBrowserWindow.h"
ExampleBrowserWindow::ExampleBrowserWindow() : UIWindow(L"Example Browser", 320, 400){
templateFolder = "";
closeOnEscape = true;
defaultTemplateTree = NULL;
Config *conf = CoreServices::getInstance()->getConfig();
String fontName = conf->getStringValue("Polycode", "uiDefaultFontName");
int fontSize = conf->getNumericValue("Polycode", "uiDefaultFontSize");
templateContainer = new UITreeContainer("boxIcon.png", L"Examples", 320, 410-topPadding-padding-padding-40);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 0;
templateContainer->getRootNode()->setUserData(data);
addChild(templateContainer);
templateContainer->setPosition(padding,topPadding+padding);
templateContainer->getRootNode()->toggleCollapsed();
templateContainer->getRootNode()->addEventListener(this, UITreeEvent::SELECTED_EVENT);
vector<OSFileEntry> templates = OSBasics::parseFolder(RESOURCE_PATH"Standalone/Examples/Lua", false);
for(int i=0; i < templates.size(); i++) {
OSFileEntry entry = templates[i];
if(entry.type == OSFileEntry::TYPE_FOLDER) {
UITree *newChild = templateContainer->getRootNode()->addTreeChild("folder.png", entry.name, NULL);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 0;
newChild->setUserData(data);
if(i == 0) {
newChild->toggleCollapsed();
}
parseTemplatesIntoTree(newChild, entry);
}
}
cancelButton = new UIButton(L"Cancel", 100);
cancelButton->addEventListener(this, UIEvent::CLICK_EVENT);
addChild(cancelButton);
cancelButton->setPosition(330-100-padding-80-10, 375);
okButton = new UIButton(L"Open Example", 100);
okButton->addEventListener(this, UIEvent::CLICK_EVENT);
addChild(okButton);
okButton->setPosition(330-80-padding, 375);
}
String ExampleBrowserWindow::getExamplePath() {
String suffix;
std::vector<String> parts = templateFolder.split("/");
return templateFolder+"/"+parts[parts.size()-1]+".polyproject";
}
void ExampleBrowserWindow::ResetForm() {
if(defaultTemplateTree)
defaultTemplateTree->setSelected();
}
void ExampleBrowserWindow::handleEvent(Event *event) {
if(event->getEventType() == "UIEvent") {
if(event->getEventCode() == UIEvent::CLICK_EVENT) {
UITree *node = templateContainer->getRootNode()->getSelectedNode();
ExampleTemplateUserData *data = (ExampleTemplateUserData*)node->getUserData();
if(event->getDispatcher() == okButton && data->type == 1) {
dispatchEvent(new UIEvent(), UIEvent::OK_EVENT);
}
if(event->getDispatcher() == cancelButton) {
dispatchEvent(new UIEvent(), UIEvent::CLOSE_EVENT);
}
}
}
if(event->getEventType() == "UITreeEvent" && event->getEventCode() == UITreeEvent::SELECTED_EVENT) {
if(event->getDispatcher() == templateContainer->getRootNode()) {
UITreeEvent *treeEvent = (UITreeEvent*) event;
ExampleTemplateUserData *data = (ExampleTemplateUserData *)treeEvent->selection->getUserData();
if(data->type == 1)
templateFolder = data->templateFolder;
}
}
UIWindow::handleEvent(event);
}
void ExampleBrowserWindow::parseTemplatesIntoTree(UITree *tree, OSFileEntry folder) {
vector<OSFileEntry> templates = OSBasics::parseFolder(folder.fullPath, false);
for(int i=0; i < templates.size(); i++) {
OSFileEntry entry = templates[i];
if(entry.type == OSFileEntry::TYPE_FOLDER) {
UITree *newChild = tree->addTreeChild("templateIcon.png", entry.name, NULL);
ExampleTemplateUserData *data = new ExampleTemplateUserData();
data->type = 1;
data->templateFolder = entry.fullPath;
newChild->setUserData(data);
if(entry.name == "Empty Project") {
defaultTemplateTree = newChild;
newChild->setSelected();
}
}
}
}
ExampleBrowserWindow::~ExampleBrowserWindow() {
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: controlpropertymap.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:13:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#define _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif
#ifndef _XMLOFF_XMLEXPPR_HXX
#include <xmloff/xmlexppr.hxx>
#endif
struct XMLPropertyMapEntry;
//.........................................................................
namespace xmloff
{
//.........................................................................
const XMLPropertyMapEntry* getControlStylePropertyMap( );
void initializePropertyMaps();
//=====================================================================
//= OFormExportPropertyMapper
//=====================================================================
class OFormExportPropertyMapper : public SvXMLExportPropertyMapper
{
public:
OFormExportPropertyMapper( const UniReference< XMLPropertySetMapper >& _rMapper );
void handleSpecialItem(
SvXMLAttributeList& _rAttrList,
const XMLPropertyState& _rProperty,
const SvXMLUnitConverter& _rUnitConverter,
const SvXMLNamespaceMap& _rNamespaceMap,
const ::std::vector< XMLPropertyState >* _pProperties,
sal_uInt32 _nIdx
) const;
};
//.........................................................................
} // namespace xmloff
//.........................................................................
#endif // _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.162); FILE MERGED 2008/04/01 13:04:48 thb 1.6.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:11 rt 1.6.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: controlpropertymap.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#define _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#include <xmloff/xmlprmap.hxx>
#include <xmloff/xmlexppr.hxx>
struct XMLPropertyMapEntry;
//.........................................................................
namespace xmloff
{
//.........................................................................
const XMLPropertyMapEntry* getControlStylePropertyMap( );
void initializePropertyMaps();
//=====================================================================
//= OFormExportPropertyMapper
//=====================================================================
class OFormExportPropertyMapper : public SvXMLExportPropertyMapper
{
public:
OFormExportPropertyMapper( const UniReference< XMLPropertySetMapper >& _rMapper );
void handleSpecialItem(
SvXMLAttributeList& _rAttrList,
const XMLPropertyState& _rProperty,
const SvXMLUnitConverter& _rUnitConverter,
const SvXMLNamespaceMap& _rNamespaceMap,
const ::std::vector< XMLPropertyState >* _pProperties,
sal_uInt32 _nIdx
) const;
};
//.........................................................................
} // namespace xmloff
//.........................................................................
#endif // _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
<|endoftext|> |
<commit_before>//
// InputEvents.cpp
// moFloTest
//
// Created by Scott Downie on 16/06/2011.
// Copyright 2011 Tag Games. All rights reserved.
//
#include <ChilliSource/GUI/Base/InputEvents.h>
#include <ChilliSource/GUI/Base/GUIView.h>
#include <algorithm>
namespace ChilliSource
{
namespace GUI
{
//-----------------------------------------------------------
/// Get Pressed Inside Event
///
/// A event that is triggered when input is started within
/// the bounds of the view
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetPressedInsideEvent()
{
return mTouchPressedInside;
}
//-----------------------------------------------------------
/// Get Released Inside Event
///
/// A event that is triggered when input is ended within
/// the bounds of the view
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetReleasedInsideEvent()
{
return mTouchReleasedInside;
}
//-----------------------------------------------------------
/// Get Released Outside Event
///
/// A event that is triggered when input is ended outwith
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetReleasedOutsideEvent()
{
return mTouchReleasedOutside;
}
//-----------------------------------------------------------
/// Get Moved Outside Event
///
/// A event that is triggered when input is registered outwith
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedOutsideEvent()
{
return mTouchMoveExit;
}
//-----------------------------------------------------------
/// Get Moved Inside Event
///
/// A event that is triggered when input is detected within
/// the bounds of the view having started outwith it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedInsideEvent()
{
return mTouchMoveEnter;
}
//-----------------------------------------------------------
/// Get Moved Within Event
///
/// A event that is triggered when input is detected within
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedWithinEvent()
{
return mTouchMovedWithin;
}
//---Touch Delegates
//-----------------------------------------------------------
//-----------------------------------------------------------
void InputEvents::OnPointerDown(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer, bool in_containsTouch)
{
//We must contain this point to be notified so we can trigger an event
//Events: PressedInside
//Possible: Released outside, Moved Outside, Moved Within
if(in_containsTouch == true)
{
mTouchPressedInside.NotifyConnections(in_view, in_pointer);
}
mOpenTouches.push_back(in_pointer.m_uniqueId);
}
//-----------------------------------------------------------
//-----------------------------------------------------------
bool InputEvents::OnPointerMoved(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer)
{
auto it = std::find(mOpenTouches.begin(), mOpenTouches.end(), in_pointer.m_uniqueId);
bool bContains = in_view->Contains(in_pointer.m_location);
if(it == mOpenTouches.end() && bContains)
{
//Event: Moved inside
//The touch has moved into us raise an event
mTouchMoveEnter.NotifyConnections(in_view, in_pointer);
}
else if(it != mOpenTouches.end() && bContains)
{
//Event: Moved within
mTouchMovedWithin.NotifyConnections(in_view, in_pointer);
}
else if(it != mOpenTouches.end() && !bContains)
{
//If the touch started within us then we can trigger an event
//Event: Moved outside
mTouchMoveExit.NotifyConnections(in_view, in_pointer);
}
return bContains;
}
//-----------------------------------------------------------
//-----------------------------------------------------------
void InputEvents::OnPointerUp(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer)
{
auto it = std::find(mOpenTouches.begin(), mOpenTouches.end(), in_pointer.m_uniqueId);
if(in_view->Contains(in_pointer.m_location))
{
//We contained the touch when it was released we can raise an event
mTouchReleasedInside.NotifyConnections(in_view, in_pointer);
if(it != mOpenTouches.end())
{
mOpenTouches.erase(it);
}
}
else if(it != mOpenTouches.end())
{
//If the touch started within us then we can trigger an event
mTouchReleasedOutside.NotifyConnections(in_view, in_pointer);
mOpenTouches.erase(it);
}
}
}
}
<commit_msg>Fix from moFlow for incorrect removal and delegate call order in input events<commit_after>//
// InputEvents.cpp
// moFloTest
//
// Created by Scott Downie on 16/06/2011.
// Copyright 2011 Tag Games. All rights reserved.
//
#include <ChilliSource/GUI/Base/InputEvents.h>
#include <ChilliSource/GUI/Base/GUIView.h>
#include <algorithm>
namespace ChilliSource
{
namespace GUI
{
//-----------------------------------------------------------
/// Get Pressed Inside Event
///
/// A event that is triggered when input is started within
/// the bounds of the view
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetPressedInsideEvent()
{
return mTouchPressedInside;
}
//-----------------------------------------------------------
/// Get Released Inside Event
///
/// A event that is triggered when input is ended within
/// the bounds of the view
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetReleasedInsideEvent()
{
return mTouchReleasedInside;
}
//-----------------------------------------------------------
/// Get Released Outside Event
///
/// A event that is triggered when input is ended outwith
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetReleasedOutsideEvent()
{
return mTouchReleasedOutside;
}
//-----------------------------------------------------------
/// Get Moved Outside Event
///
/// A event that is triggered when input is registered outwith
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedOutsideEvent()
{
return mTouchMoveExit;
}
//-----------------------------------------------------------
/// Get Moved Inside Event
///
/// A event that is triggered when input is detected within
/// the bounds of the view having started outwith it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedInsideEvent()
{
return mTouchMoveEnter;
}
//-----------------------------------------------------------
/// Get Moved Within Event
///
/// A event that is triggered when input is detected within
/// the bounds of the view having started within it
///
/// @return Event
//-----------------------------------------------------------
Core::IConnectableEvent<GUIEventDelegate>& InputEvents::GetMovedWithinEvent()
{
return mTouchMovedWithin;
}
//---Touch Delegates
//-----------------------------------------------------------
//-----------------------------------------------------------
void InputEvents::OnPointerDown(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer, bool in_containsTouch)
{
//We must contain this point to be notified so we can trigger an event
//Events: PressedInside
//Possible: Released outside, Moved Outside, Moved Within
if(in_containsTouch == true)
{
mTouchPressedInside.NotifyConnections(in_view, in_pointer);
}
mOpenTouches.push_back(in_pointer.m_uniqueId);
}
//-----------------------------------------------------------
//-----------------------------------------------------------
bool InputEvents::OnPointerMoved(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer)
{
auto it = std::find(mOpenTouches.begin(), mOpenTouches.end(), in_pointer.m_uniqueId);
bool bContains = in_view->Contains(in_pointer.m_location);
if(it == mOpenTouches.end() && bContains)
{
//Event: Moved inside
//The touch has moved into us raise an event
mTouchMoveEnter.NotifyConnections(in_view, in_pointer);
}
else if(it != mOpenTouches.end() && bContains)
{
//Event: Moved within
mTouchMovedWithin.NotifyConnections(in_view, in_pointer);
}
else if(it != mOpenTouches.end() && !bContains)
{
//If the touch started within us then we can trigger an event
//Event: Moved outside
mTouchMoveExit.NotifyConnections(in_view, in_pointer);
}
return bContains;
}
//-----------------------------------------------------------
//-----------------------------------------------------------
void InputEvents::OnPointerUp(GUIView* in_view, const Input::PointerSystem::Pointer& in_pointer)
{
auto it = std::find(mOpenTouches.begin(), mOpenTouches.end(), in_pointer.m_uniqueId);
if(in_view->Contains(in_pointer.m_location))
{
if(it != mOpenTouches.end())
{
mOpenTouches.erase(it);
}
//We contained the touch when it was released we can raise an event
mTouchReleasedInside.NotifyConnections(in_view, in_pointer);
}
else if(it != mOpenTouches.end())
{
mOpenTouches.erase(it);
//If the touch started within us then we can trigger an event
mTouchReleasedOutside.NotifyConnections(in_view, in_pointer);
}
}
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/spd_checker.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
<commit_msg>Add base spd decoder to share among controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/spd_checker.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _SPD_CHECKER_H_
#define _SPD_CHECKER_H_
#include <fapi2.H>
namespace mss
{
namespace check
{
namespace spd
{
///
/// @brief Checks conditional passes and implements traces & exits if it fails
/// @tparam T input data of any size
/// @param[in] i_target fapi2 dimm target
/// @param[in] i_conditional conditional that we are testing against
/// @param[in] i_spd_byte_index current SPD byte
/// @param[in] i_spd_data debug data
/// @param[in] i_err_str error string to print out when conditional fails
/// @return ReturnCode
///
template< typename T >
inline fapi2::ReturnCode fail_for_invalid_value(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const bool i_conditional,
const size_t i_spd_byte_index,
const T i_spd_data,
const char* i_err_str)
{
FAPI_ASSERT(i_conditional,
fapi2::MSS_BAD_SPD().
set_VALUE(i_spd_data).
set_BYTE(i_spd_byte_index).
set_DIMM_TARGET(i_target),
"%s %s Byte %d, Data returned: %d.",
c_str(i_target),
i_err_str,
i_spd_byte_index,
i_spd_data);
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
} // fail_for_invalid_value()
///
/// @brief Checks conditional passes and implements traces if it fails. No FFDC collected.
/// @tparam T input data of any size
/// @param[in] i_target fapi2 dimm target
/// @param[in] i_conditional that we are testing against
/// @param[in] i_spd_byte_index
/// @param[in] i_spd_data debug data
/// @param[in] i_err_str string to print out when conditional fails
/// @return void
///
template< typename T >
inline void warn_for_invalid_value(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const bool i_conditional,
const size_t i_spd_byte_index,
const T i_spd_data,
const char* i_err_str)
{
// Don't print warning conditional if true
if(!i_conditional)
{
FAPI_IMP("%s. %s. Byte %d, Data returned: %d.",
c_str(i_target),
i_err_str,
i_spd_byte_index,
i_spd_data );
}
}// warn_for_invalid_value
///
/// @brief Checks if valid factory parameters are given
/// @param[in] i_target fapi2 dimm target
/// @param[in] i_dimm_type DIMM type enumeration
/// @param[in] i_encoding_rev SPD encoding level rev number
/// @param[in] i_additions_rev SPD additions level rev number
/// @param[in] i_err_str string to print out when conditional fails
/// @return fapi2::ReturnCode
///
inline fapi2::ReturnCode invalid_factory_sel(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint8_t i_dimm_type,
const uint8_t i_encoding_rev,
const uint8_t i_additions_rev,
const char* i_err_str)
{
FAPI_ASSERT(false,
fapi2::MSS_INVALID_DIMM_REV_COMBO().
set_DIMM_TYPE(i_dimm_type).
set_ENCODING_REV(i_encoding_rev).
set_ADDITIONS_REV(i_additions_rev).
set_DIMM_TARGET(i_target),
"%s. %s. Invalid combination for dimm type: %d, rev: %d.%d",
c_str(i_target),
i_err_str,
i_dimm_type,
i_encoding_rev,
i_additions_rev);
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}// invalid_factory_sel
}// spd
}// check
}// mss
#endif
<|endoftext|> |
<commit_before><commit_msg>Update InputManager.cpp<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.70
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h" //For setup object
#include "NumLib.h"
#include "EnergyTypes.h"
#include <iostream>
#include <iomanip>
#include "CUDAMemoryManager.cuh"
#include "GOMCEventsProfile.h"
#define EPSILON 0.001
Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim): ms(multisim)
{
GOMC_EVENT_START(1, GomcProfileEvent::INITIALIZE);
GOMC_EVENT_START(1, GomcProfileEvent::READ_INPUT_FILES);
set.Init(configFileName, multisim);
GOMC_EVENT_STOP(1, GomcProfileEvent::READ_INPUT_FILES);
startStep = 0;
totalSteps = set.config.sys.step.total;
staticValues = new StaticVals(set);
system = new System(*staticValues, set, startStep, multisim);
//Checkpoint must occur before this line
staticValues->Init(set, *system);
system->Init(set);
// This happens after checkpoint has possible changed startStep
// Note: InitStep overwrites checkpoint start step
totalSteps += startStep;
//recalc Init for static value for initializing ewald since ewald is
//initialized in system
staticValues->InitOver(set, *system);
system->InitOver(set, staticValues->mol);
cpu = new CPUSide(*system, *staticValues, set);
cpu->Init(set.pdb, set.config.in, set.config.out, set.config.sys, set.config.sys.step.equil,
totalSteps, startStep);
if(totalSteps == 0) {
frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
}
#if GOMC_LIB_MPI
// set.config.sys.step.parallelTemp is a boolean for enabling/disabling parallel tempering
PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange) : NULL;
exchangeResults.resize(ms->worldSize, false);
#endif
#ifdef GOMC_CUDA
cudaDeviceReset();
#endif
GOMC_EVENT_STOP(1, GomcProfileEvent::INITIALIZE);
}
Simulation::~Simulation()
{
GOMC_EVENT_START(1, GomcProfileEvent::DESTRUCTION);
delete cpu;
delete system;
delete staticValues;
#ifdef GOMC_CUDA
CUDAMemoryManager::isFreed();
#endif
GOMC_EVENT_STOP(1, GomcProfileEvent::DESTRUCTION);
}
void Simulation::RunSimulation(void)
{
GOMC_EVENT_START(1, GomcProfileEvent::MC_RUN);
double startEnergy = system->potential.totalEnergy.total;
if(totalSteps == 0) {
for(int i = 0; i < (int) frameSteps.size(); i++) {
if(i == 0) {
cpu->Output(frameSteps[0] - 1);
continue;
}
system->RecalculateTrajectory(set, i + 1);
cpu->Output(frameSteps[i] - 1);
}
}
for (ulong step = startStep; step < totalSteps; step++) {
system->moveSettings.AdjustMoves(step);
system->ChooseAndRunMove(step);
cpu->Output(step);
if((step + 1) == cpu->equilSteps) {
double currEnergy = system->potential.totalEnergy.total;
if(std::abs(currEnergy - startEnergy) > 1.0e+10) {
printf("Info: Recalculating the total energies to insure the accuracy"
" of the computed \n"
" running energies.\n\n");
system->calcEwald->UpdateVectorsAndRecipTerms(true);
system->potential = system->calcEnergy.SystemTotal();
}
}
#if GOMC_LIB_MPI
//
if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0) {
int maxSwap = 0;
/* Number of rounds of exchanges needed to deal with any multiple
* exchanges. */
/* Where each replica ends up after the exchange attempt(s). */
/* The order in which multiple exchanges will occur. */
bool bThisReplicaExchanged = false;
system->potential = system->calcEnergy.SystemTotal();
PTUtils->evaluateExchangeCriteria(step);
PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged);
PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged);
system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
if (staticValues->forcefield.ewald) {
for(int box = 0; box < BOX_TOTAL; box++) {
system->calcEwald->BoxReciprocalSums(box, system->coordinates, false);
system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box, false);
system->calcEwald->UpdateRecip(box);
}
}
system->potential = system->calcEnergy.SystemTotal();
}
#endif
#ifndef NDEBUG
if((step + 1) % 1000 == 0)
RecalculateAndCheck();
#endif
}
GOMC_EVENT_STOP(1, GomcProfileEvent::MC_RUN);
if(!RecalculateAndCheck()) {
std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n";
}
system->PrintAcceptance();
system->PrintTime();
#if GOMC_LIB_MPI
if (staticValues->simEventFreq.parallelTemp)
PTUtils->print_replica_exchange_statistics(ms->fplog);
#endif
}
bool Simulation::RecalculateAndCheck(void)
{
system->calcEwald->UpdateVectorsAndRecipTerms(false);
SystemPotential pot = system->calcEnergy.SystemTotal();
bool compare = true;
compare &= num::approximatelyEqual(system->potential.totalEnergy.intraBond, pot.totalEnergy.intraBond, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.intraNonbond, pot.totalEnergy.intraNonbond, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.inter, pot.totalEnergy.inter, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.tc, pot.totalEnergy.tc, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.real, pot.totalEnergy.real, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.self, pot.totalEnergy.self, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.correction, pot.totalEnergy.correction, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.recip, pot.totalEnergy.recip, EPSILON);
if(!compare) {
std::cout
<< "=================================================================\n"
<< "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP"
<< std::endl
<< "System: "
<< std::setw(12) << system->potential.totalEnergy.intraBond << " | "
<< std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
<< std::setw(12) << system->potential.totalEnergy.inter << " | "
<< std::setw(12) << system->potential.totalEnergy.tc << " | "
<< std::setw(12) << system->potential.totalEnergy.real << " | "
<< std::setw(12) << system->potential.totalEnergy.self << " | "
<< std::setw(12) << system->potential.totalEnergy.correction << " | "
<< std::setw(12) << system->potential.totalEnergy.recip << std::endl
<< "Recalc: "
<< std::setw(12) << pot.totalEnergy.intraBond << " | "
<< std::setw(12) << pot.totalEnergy.intraNonbond << " | "
<< std::setw(12) << pot.totalEnergy.inter << " | "
<< std::setw(12) << pot.totalEnergy.tc << " | "
<< std::setw(12) << pot.totalEnergy.real << " | "
<< std::setw(12) << pot.totalEnergy.self << " | "
<< std::setw(12) << pot.totalEnergy.correction << " | "
<< std::setw(12) << pot.totalEnergy.recip << std::endl
<< "================================================================"
<< std::endl << std::endl;
}
return compare;
}
#if GOMC_GTEST
SystemPotential & Simulation::GetSystemEnergy(void){
return system->potential;
}
MoleculeLookup & Simulation::GetMolLookup(){
return system->molLookup;
}
MoveSettings & Simulation::GetMoveSettings(){
return system->moveSettings;
}
ulong Simulation::GetTrueStep(){
return system->trueStep;
}
ulong Simulation::GetRunSteps(){
return totalSteps - startStep;
}
#endif
<commit_msg>Move to destructor<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.70
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h" //For setup object
#include "NumLib.h"
#include "EnergyTypes.h"
#include <iostream>
#include <iomanip>
#include "CUDAMemoryManager.cuh"
#include "GOMCEventsProfile.h"
#define EPSILON 0.001
Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim): ms(multisim)
{
GOMC_EVENT_START(1, GomcProfileEvent::INITIALIZE);
GOMC_EVENT_START(1, GomcProfileEvent::READ_INPUT_FILES);
set.Init(configFileName, multisim);
GOMC_EVENT_STOP(1, GomcProfileEvent::READ_INPUT_FILES);
startStep = 0;
totalSteps = set.config.sys.step.total;
staticValues = new StaticVals(set);
system = new System(*staticValues, set, startStep, multisim);
//Checkpoint must occur before this line
staticValues->Init(set, *system);
system->Init(set);
// This happens after checkpoint has possible changed startStep
// Note: InitStep overwrites checkpoint start step
totalSteps += startStep;
//recalc Init for static value for initializing ewald since ewald is
//initialized in system
staticValues->InitOver(set, *system);
system->InitOver(set, staticValues->mol);
cpu = new CPUSide(*system, *staticValues, set);
cpu->Init(set.pdb, set.config.in, set.config.out, set.config.sys, set.config.sys.step.equil,
totalSteps, startStep);
if(totalSteps == 0) {
frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
}
#if GOMC_LIB_MPI
// set.config.sys.step.parallelTemp is a boolean for enabling/disabling parallel tempering
PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange) : NULL;
exchangeResults.resize(ms->worldSize, false);
#endif
GOMC_EVENT_STOP(1, GomcProfileEvent::INITIALIZE);
}
Simulation::~Simulation()
{
GOMC_EVENT_START(1, GomcProfileEvent::DESTRUCTION);
delete cpu;
delete system;
delete staticValues;
#ifdef GOMC_CUDA
CUDAMemoryManager::isFreed();
cudaDeviceReset();
#endif
GOMC_EVENT_STOP(1, GomcProfileEvent::DESTRUCTION);
}
void Simulation::RunSimulation(void)
{
GOMC_EVENT_START(1, GomcProfileEvent::MC_RUN);
double startEnergy = system->potential.totalEnergy.total;
if(totalSteps == 0) {
for(int i = 0; i < (int) frameSteps.size(); i++) {
if(i == 0) {
cpu->Output(frameSteps[0] - 1);
continue;
}
system->RecalculateTrajectory(set, i + 1);
cpu->Output(frameSteps[i] - 1);
}
}
for (ulong step = startStep; step < totalSteps; step++) {
system->moveSettings.AdjustMoves(step);
system->ChooseAndRunMove(step);
cpu->Output(step);
if((step + 1) == cpu->equilSteps) {
double currEnergy = system->potential.totalEnergy.total;
if(std::abs(currEnergy - startEnergy) > 1.0e+10) {
printf("Info: Recalculating the total energies to insure the accuracy"
" of the computed \n"
" running energies.\n\n");
system->calcEwald->UpdateVectorsAndRecipTerms(true);
system->potential = system->calcEnergy.SystemTotal();
}
}
#if GOMC_LIB_MPI
//
if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0) {
int maxSwap = 0;
/* Number of rounds of exchanges needed to deal with any multiple
* exchanges. */
/* Where each replica ends up after the exchange attempt(s). */
/* The order in which multiple exchanges will occur. */
bool bThisReplicaExchanged = false;
system->potential = system->calcEnergy.SystemTotal();
PTUtils->evaluateExchangeCriteria(step);
PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged);
PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged);
system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);
if (staticValues->forcefield.ewald) {
for(int box = 0; box < BOX_TOTAL; box++) {
system->calcEwald->BoxReciprocalSums(box, system->coordinates, false);
system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box, false);
system->calcEwald->UpdateRecip(box);
}
}
system->potential = system->calcEnergy.SystemTotal();
}
#endif
#ifndef NDEBUG
if((step + 1) % 1000 == 0)
RecalculateAndCheck();
#endif
}
GOMC_EVENT_STOP(1, GomcProfileEvent::MC_RUN);
if(!RecalculateAndCheck()) {
std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n";
}
system->PrintAcceptance();
system->PrintTime();
#if GOMC_LIB_MPI
if (staticValues->simEventFreq.parallelTemp)
PTUtils->print_replica_exchange_statistics(ms->fplog);
#endif
}
bool Simulation::RecalculateAndCheck(void)
{
system->calcEwald->UpdateVectorsAndRecipTerms(false);
SystemPotential pot = system->calcEnergy.SystemTotal();
bool compare = true;
compare &= num::approximatelyEqual(system->potential.totalEnergy.intraBond, pot.totalEnergy.intraBond, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.intraNonbond, pot.totalEnergy.intraNonbond, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.inter, pot.totalEnergy.inter, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.tc, pot.totalEnergy.tc, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.real, pot.totalEnergy.real, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.self, pot.totalEnergy.self, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.correction, pot.totalEnergy.correction, EPSILON);
compare &= num::approximatelyEqual(system->potential.totalEnergy.recip, pot.totalEnergy.recip, EPSILON);
if(!compare) {
std::cout
<< "=================================================================\n"
<< "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP"
<< std::endl
<< "System: "
<< std::setw(12) << system->potential.totalEnergy.intraBond << " | "
<< std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
<< std::setw(12) << system->potential.totalEnergy.inter << " | "
<< std::setw(12) << system->potential.totalEnergy.tc << " | "
<< std::setw(12) << system->potential.totalEnergy.real << " | "
<< std::setw(12) << system->potential.totalEnergy.self << " | "
<< std::setw(12) << system->potential.totalEnergy.correction << " | "
<< std::setw(12) << system->potential.totalEnergy.recip << std::endl
<< "Recalc: "
<< std::setw(12) << pot.totalEnergy.intraBond << " | "
<< std::setw(12) << pot.totalEnergy.intraNonbond << " | "
<< std::setw(12) << pot.totalEnergy.inter << " | "
<< std::setw(12) << pot.totalEnergy.tc << " | "
<< std::setw(12) << pot.totalEnergy.real << " | "
<< std::setw(12) << pot.totalEnergy.self << " | "
<< std::setw(12) << pot.totalEnergy.correction << " | "
<< std::setw(12) << pot.totalEnergy.recip << std::endl
<< "================================================================"
<< std::endl << std::endl;
}
return compare;
}
#if GOMC_GTEST
SystemPotential & Simulation::GetSystemEnergy(void){
return system->potential;
}
MoleculeLookup & Simulation::GetMolLookup(){
return system->molLookup;
}
MoveSettings & Simulation::GetMoveSettings(){
return system->moveSettings;
}
ulong Simulation::GetTrueStep(){
return system->trueStep;
}
ulong Simulation::GetRunSteps(){
return totalSteps - startStep;
}
#endif
<|endoftext|> |
<commit_before>#ifndef SNAKE_GAME_HPP
#define SNAKE_GAME_HPP
#include <string>
#include <vector>
#include <ncursesw/ncurses.h>
class Snake_Game
{
public:
// initialise and start game
Snake_Game() { reset(); }
inline void start();
void reset(); // reset game
private:
bool processTrack(const int &); // update head and tail
void keyPressed(); // check what key was pressed
void newAppPos(); // generate new position for apple
void graphics(); // graphics
void gameLogic(); // ...
int gameOver(); // called if the user wants to stop playing or they hit something
unsigned short appPos = 173, SHead = 223; // apple position and Snake Head's position
unsigned short SDir = 4; // Snake length and direction snake is headed(1,2,3,4)
unsigned score = 0; // score
std::string gameMap;
double speed = 1;
std::vector<unsigned> snakePos; // positions of tail
};
inline void Snake_Game::start()
{
reset();
init_pair(1, COLOR_GREEN, COLOR_WHITE); // colour for border
init_pair(2, COLOR_RED, COLOR_GREEN); // colour for game map excluding border
init_pair(3, COLOR_WHITE, COLOR_YELLOW);
init_pair(4, COLOR_BLUE, COLOR_GREEN); // colour for game over text
bkgd(COLOR_PAIR(3));
gameLogic();
}
void menu();
#endif
<commit_msg>added source files<commit_after>#ifndef SNAKE_GAME_HPP
#define SNAKE_GAME_HPP
#include <string>
#include <vector>
#include <ncursesw/ncurses.h>
class Snake_Game
{
public:
// initialise and start game
Snake_Game() { reset(); }
inline void start();
void reset(); // reset game
private:
bool processTrack(const int &); // update head and tail
void keyPressed(); // check what key was pressed
void newAppPos(); // generate new position for apple
void graphics(); // graphics
void gameLogic(); // ...
int gameOver(); // called if the user wants to stop playing or they hit something
unsigned short appPos = 173, SHead = 223; // apple position and Snake Head's position
unsigned short SDir = 4; // Snake length and direction snake is headed(1,2,3,4)
unsigned score = 0; // score
std::string gameMap;
double speed = 1;
std::vector<unsigned> snakePos; // positions of tail
};
inline void Snake_Game::start()
{
reset();
init_pair(1, COLOR_GREEN, COLOR_WHITE); // colour for border
init_pair(2, COLOR_RED, COLOR_GREEN); // colour for game map excluding border
init_pair(3, COLOR_WHITE, COLOR_YELLOW);
init_pair(4, COLOR_BLUE, COLOR_GREEN); // colour for game over text
bkgd(COLOR_PAIR(3));
gameLogic();
}
void menu();
#endif
<|endoftext|> |
<commit_before>#ifndef CMDSTAN_ARGUMENTS_ARGUMENT_PARSER_HPP
#define CMDSTAN_ARGUMENTS_ARGUMENT_PARSER_HPP
#include <cmdstan/arguments/arg_method.hpp>
#include <cmdstan/arguments/argument.hpp>
#include <stan/services/error_codes.hpp>
#include <cstring>
#include <string>
#include <vector>
namespace cmdstan {
class argument_parser {
public:
explicit argument_parser(std::vector<argument *> &valid_args)
: _arguments(valid_args), _help_flag(false), _method_flag(false) {
_arguments.insert(_arguments.begin(), new arg_method());
}
int parse_args(int argc, const char *argv[], stan::callbacks::writer &info,
stan::callbacks::writer &err) {
if (argc == 1) {
print_usage(info, argv[0]);
return stan::services::error_codes::USAGE;
}
std::vector<std::string> args;
// Fill in reverse order as parse_args pops from the back
for (int i = argc - 1; i > 0; --i)
args.push_back(std::string(argv[i]));
bool good_arg = true;
bool valid_arg = true;
_help_flag = false;
std::vector<argument *> unset_args = _arguments;
while (good_arg) {
if (args.size() == 0)
break;
good_arg = false;
std::string cat_name = args.back();
// Check for method arguments entered without the method= prefix
if (!_method_flag) {
list_argument *method
= dynamic_cast<list_argument *>(_arguments.front());
if (method->valid_value(cat_name)) {
cat_name = "method=" + cat_name;
args.back() = cat_name;
}
}
std::string val_name;
std::string val;
argument::split_arg(cat_name, val_name, val);
if (val_name == "method")
_method_flag = true;
std::vector<argument *>::iterator arg_it;
for (arg_it = unset_args.begin(); arg_it != unset_args.end(); ++arg_it) {
if ((*arg_it)->name() == cat_name) {
args.pop_back();
valid_arg &= (*arg_it)->parse_args(args, info, err, _help_flag);
good_arg = true;
break;
} else if ((*arg_it)->name() == val_name) {
valid_arg &= (*arg_it)->parse_args(args, info, err, _help_flag);
good_arg = true;
break;
}
}
if (good_arg)
unset_args.erase(arg_it);
if (cat_name == "help") {
_help_flag |= true;
args.clear();
} else if (cat_name == "help-all") {
print_help(info, true);
_help_flag |= true;
args.clear();
}
if (_help_flag) {
print_usage(info, argv[0]);
return stan::services::error_codes::OK;
}
if (!good_arg) {
err(cat_name + " is either mistyped or misplaced.");
#ifndef STAN_OPENCL
if (cat_name == "opencl") {
err("Re-compile the model with STAN_OPENCL to use OpenCL CmdStan arguments.");
}
#endif
std::vector<std::string> valid_paths;
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->find_arg(val_name, "", valid_paths);
}
if (valid_paths.size()) {
err("Perhaps you meant one of the following "
"valid configurations?");
for (size_t i = 0; i < valid_paths.size(); ++i)
err(" " + valid_paths.at(i));
}
}
}
if (_help_flag)
return stan::services::error_codes::OK;
if (!_method_flag)
err("A method must be specified!");
return (valid_arg && good_arg && _method_flag)
? stan::services::error_codes::OK
: stan::services::error_codes::USAGE;
}
void print(stan::callbacks::writer &w, const std::string &prefix = "") {
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print(w, 0, prefix);
}
}
void print_help(stan::callbacks::writer &w, bool recurse) {
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print_help(w, 1, recurse);
}
}
void print_usage(stan::callbacks::writer &w, const char *executable) {
std::string indent(2, ' ');
int width = 12;
w(std::string("Usage: ") + executable
+ " <arg1> <subarg1_1> ... <subarg1_m>"
+ " ... <arg_n> <subarg_n_1> ... <subarg_n_m>");
w();
w("Begin by selecting amongst the following inference methods"
" and diagnostics,");
std::vector<argument *>::iterator arg_it = _arguments.begin();
list_argument *method = dynamic_cast<list_argument *>(*arg_it);
std::stringstream ss;
ss << std::left;
for (std::vector<argument *>::iterator value_it = method->values().begin();
value_it != method->values().end(); ++value_it) {
ss.str("");
ss << std::setw(width) << indent + (*value_it)->name()
<< indent + (*value_it)->description();
w(ss.str());
}
w();
w("Or see help information with");
ss.str("");
ss << std::setw(width) << indent + "help" << indent + "Prints help";
w(ss.str());
ss.str("");
ss << std::setw(width) << indent + "help-all"
<< indent + "Prints entire argument tree";
w(ss.str());
w();
w("Additional configuration available by specifying");
++arg_it;
for (; arg_it != _arguments.end(); ++arg_it) {
ss.str("");
ss << std::setw(width) << indent + (*arg_it)->name()
<< indent + (*arg_it)->description();
w(ss.str());
}
w();
w(std::string("See ") + executable + " <arg1> [ help | help-all ] "
+ "for details on individual arguments.");
w();
}
argument *arg(const std::string &name) {
for (std::vector<argument *>::iterator it = _arguments.begin();
it != _arguments.end(); ++it)
if (name == (*it)->name())
return (*it);
return 0;
}
bool help_printed() { return _help_flag; }
protected:
std::vector<argument *> &_arguments;
// We can also check for, and warn the user of, deprecated arguments
// std::vector<argument*> deprecated_arguments;
// check_arg_conflict
// Ensure non-zero intersection of valid and deprecated arguments
bool _help_flag;
bool _method_flag;
};
} // namespace cmdstan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef CMDSTAN_ARGUMENTS_ARGUMENT_PARSER_HPP
#define CMDSTAN_ARGUMENTS_ARGUMENT_PARSER_HPP
#include <cmdstan/arguments/arg_method.hpp>
#include <cmdstan/arguments/argument.hpp>
#include <stan/services/error_codes.hpp>
#include <cstring>
#include <string>
#include <vector>
namespace cmdstan {
class argument_parser {
public:
explicit argument_parser(std::vector<argument *> &valid_args)
: _arguments(valid_args), _help_flag(false), _method_flag(false) {
_arguments.insert(_arguments.begin(), new arg_method());
}
int parse_args(int argc, const char *argv[], stan::callbacks::writer &info,
stan::callbacks::writer &err) {
if (argc == 1) {
print_usage(info, argv[0]);
return stan::services::error_codes::USAGE;
}
std::vector<std::string> args;
// Fill in reverse order as parse_args pops from the back
for (int i = argc - 1; i > 0; --i)
args.push_back(std::string(argv[i]));
bool good_arg = true;
bool valid_arg = true;
_help_flag = false;
std::vector<argument *> unset_args = _arguments;
while (good_arg) {
if (args.size() == 0)
break;
good_arg = false;
std::string cat_name = args.back();
// Check for method arguments entered without the method= prefix
if (!_method_flag) {
list_argument *method
= dynamic_cast<list_argument *>(_arguments.front());
if (method->valid_value(cat_name)) {
cat_name = "method=" + cat_name;
args.back() = cat_name;
}
}
std::string val_name;
std::string val;
argument::split_arg(cat_name, val_name, val);
if (val_name == "method")
_method_flag = true;
std::vector<argument *>::iterator arg_it;
for (arg_it = unset_args.begin(); arg_it != unset_args.end(); ++arg_it) {
if ((*arg_it)->name() == cat_name) {
args.pop_back();
valid_arg &= (*arg_it)->parse_args(args, info, err, _help_flag);
good_arg = true;
break;
} else if ((*arg_it)->name() == val_name) {
valid_arg &= (*arg_it)->parse_args(args, info, err, _help_flag);
good_arg = true;
break;
}
}
if (good_arg)
unset_args.erase(arg_it);
if (cat_name == "help") {
_help_flag |= true;
args.clear();
} else if (cat_name == "help-all") {
print_help(info, true);
_help_flag |= true;
args.clear();
}
if (_help_flag) {
print_usage(info, argv[0]);
return stan::services::error_codes::OK;
}
if (!good_arg) {
err(cat_name + " is either mistyped or misplaced.");
#ifndef STAN_OPENCL
if (cat_name == "opencl") {
err("Re-compile the model with STAN_OPENCL to use OpenCL CmdStan "
"arguments.");
}
#endif
std::vector<std::string> valid_paths;
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->find_arg(val_name, "", valid_paths);
}
if (valid_paths.size()) {
err("Perhaps you meant one of the following "
"valid configurations?");
for (size_t i = 0; i < valid_paths.size(); ++i)
err(" " + valid_paths.at(i));
}
}
}
if (_help_flag)
return stan::services::error_codes::OK;
if (!_method_flag)
err("A method must be specified!");
return (valid_arg && good_arg && _method_flag)
? stan::services::error_codes::OK
: stan::services::error_codes::USAGE;
}
void print(stan::callbacks::writer &w, const std::string &prefix = "") {
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print(w, 0, prefix);
}
}
void print_help(stan::callbacks::writer &w, bool recurse) {
for (size_t i = 0; i < _arguments.size(); ++i) {
_arguments.at(i)->print_help(w, 1, recurse);
}
}
void print_usage(stan::callbacks::writer &w, const char *executable) {
std::string indent(2, ' ');
int width = 12;
w(std::string("Usage: ") + executable
+ " <arg1> <subarg1_1> ... <subarg1_m>"
+ " ... <arg_n> <subarg_n_1> ... <subarg_n_m>");
w();
w("Begin by selecting amongst the following inference methods"
" and diagnostics,");
std::vector<argument *>::iterator arg_it = _arguments.begin();
list_argument *method = dynamic_cast<list_argument *>(*arg_it);
std::stringstream ss;
ss << std::left;
for (std::vector<argument *>::iterator value_it = method->values().begin();
value_it != method->values().end(); ++value_it) {
ss.str("");
ss << std::setw(width) << indent + (*value_it)->name()
<< indent + (*value_it)->description();
w(ss.str());
}
w();
w("Or see help information with");
ss.str("");
ss << std::setw(width) << indent + "help" << indent + "Prints help";
w(ss.str());
ss.str("");
ss << std::setw(width) << indent + "help-all"
<< indent + "Prints entire argument tree";
w(ss.str());
w();
w("Additional configuration available by specifying");
++arg_it;
for (; arg_it != _arguments.end(); ++arg_it) {
ss.str("");
ss << std::setw(width) << indent + (*arg_it)->name()
<< indent + (*arg_it)->description();
w(ss.str());
}
w();
w(std::string("See ") + executable + " <arg1> [ help | help-all ] "
+ "for details on individual arguments.");
w();
}
argument *arg(const std::string &name) {
for (std::vector<argument *>::iterator it = _arguments.begin();
it != _arguments.end(); ++it)
if (name == (*it)->name())
return (*it);
return 0;
}
bool help_printed() { return _help_flag; }
protected:
std::vector<argument *> &_arguments;
// We can also check for, and warn the user of, deprecated arguments
// std::vector<argument*> deprecated_arguments;
// check_arg_conflict
// Ensure non-zero intersection of valid and deprecated arguments
bool _help_flag;
bool _method_flag;
};
} // namespace cmdstan
#endif
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017-2019 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/Core/Context.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include "ContentUtilities.h"
namespace Urho3D
{
const ea::vector<ea::string> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const ea::vector<ea::string> wordExtensions_{".doc", ".docx", ".odt"};
const ea::vector<ea::string> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const ea::vector<ea::string> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const ea::vector<ea::string> textExtensions_{".xml", ".json", ".txt", ".yml", ".scene", ".material", ".ui", ".uistyle", ".node", ".particle"};
const ea::vector<ea::string> audioExtensions_{".waw", ".ogg", ".mp3"};
FileType GetFileType(const ea::string& fileName)
{
auto extension = GetExtension(fileName).to_lower();
if (archiveExtensions_.contains(extension))
return FTYPE_ARCHIVE;
if (wordExtensions_.contains(extension))
return FTYPE_WORD;
if (codeExtensions_.contains(extension))
return FTYPE_CODE;
if (imagesExtensions_.contains(extension))
return FTYPE_IMAGE;
if (textExtensions_.contains(extension))
return FTYPE_TEXT;
if (audioExtensions_.contains(extension))
return FTYPE_AUDIO;
if (extension == "pdf")
return FTYPE_PDF;
return FTYPE_FILE;
}
ea::string GetFileIcon(const ea::string& fileName)
{
switch (GetFileType(fileName))
{
case FTYPE_ARCHIVE:
return ICON_FA_FILE_ARCHIVE;
case FTYPE_WORD:
return ICON_FA_FILE_WORD;
case FTYPE_CODE:
return ICON_FA_FILE_CODE;
case FTYPE_IMAGE:
return ICON_FA_FILE_IMAGE;
case FTYPE_PDF:
return ICON_FA_FILE_PDF;
case FTYPE_VIDEO:
return ICON_FA_FILE_VIDEO;
case FTYPE_POWERPOINT:
return ICON_FA_FILE_POWERPOINT;
case FTYPE_TEXT:
return ICON_FA_FILE_ALT;
case FTYPE_FILM:
return ICON_FA_FILE_VIDEO;
case FTYPE_AUDIO:
return ICON_FA_FILE_AUDIO;
case FTYPE_EXCEL:
return ICON_FA_FILE_EXCEL;
default:
return ICON_FA_FILE;
}
}
ContentType GetContentType(Context* context, const ea::string& resourcePath)
{
auto extension = GetExtension(resourcePath).to_lower();
if (extension == ".xml")
{
SharedPtr<XMLFile> xml(context->GetCache()->GetResource<XMLFile>(resourcePath));
if (!xml)
return CTYPE_UNKNOWN;
auto rootElementName = xml->GetRoot().GetName();
if (rootElementName == "scene")
return CTYPE_SCENE;
if (rootElementName == "node")
return CTYPE_SCENEOBJECT;
if (rootElementName == "elements")
return CTYPE_UISTYLE;
if (rootElementName == "element")
return CTYPE_UILAYOUT;
if (rootElementName == "material")
return CTYPE_MATERIAL;
if (rootElementName == "particleeffect")
return CTYPE_PARTICLE;
if (rootElementName == "renderpath")
return CTYPE_RENDERPATH;
if (rootElementName == "texture")
return CTYPE_TEXTUREXML;
}
if (extension == ".mdl")
return CTYPE_MODEL;
if (extension == ".ani")
return CTYPE_ANIMATION;
if (extension == ".scene")
return CTYPE_SCENE;
if (extension == ".ui")
return CTYPE_UILAYOUT;
if (extension == ".style")
return CTYPE_UISTYLE;
if (extension == ".material")
return CTYPE_MATERIAL;
if (extension == ".particle")
return CTYPE_PARTICLE;
if (extension == ".node")
return CTYPE_SCENEOBJECT;
if (audioExtensions_.contains(extension))
return CTYPE_SOUND;
if (imagesExtensions_.contains(extension))
return CTYPE_TEXTURE;
return CTYPE_UNKNOWN;
}
}
<commit_msg>Toolbox: Add support for GetContentType() running off the main thread if full path to file is specified.<commit_after>//
// Copyright (c) 2017-2019 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/Core/Context.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include "ContentUtilities.h"
namespace Urho3D
{
const ea::vector<ea::string> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const ea::vector<ea::string> wordExtensions_{".doc", ".docx", ".odt"};
const ea::vector<ea::string> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const ea::vector<ea::string> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const ea::vector<ea::string> textExtensions_{".xml", ".json", ".txt", ".yml", ".scene", ".material", ".ui", ".uistyle", ".node", ".particle"};
const ea::vector<ea::string> audioExtensions_{".waw", ".ogg", ".mp3"};
FileType GetFileType(const ea::string& fileName)
{
auto extension = GetExtension(fileName).to_lower();
if (archiveExtensions_.contains(extension))
return FTYPE_ARCHIVE;
if (wordExtensions_.contains(extension))
return FTYPE_WORD;
if (codeExtensions_.contains(extension))
return FTYPE_CODE;
if (imagesExtensions_.contains(extension))
return FTYPE_IMAGE;
if (textExtensions_.contains(extension))
return FTYPE_TEXT;
if (audioExtensions_.contains(extension))
return FTYPE_AUDIO;
if (extension == "pdf")
return FTYPE_PDF;
return FTYPE_FILE;
}
ea::string GetFileIcon(const ea::string& fileName)
{
switch (GetFileType(fileName))
{
case FTYPE_ARCHIVE:
return ICON_FA_FILE_ARCHIVE;
case FTYPE_WORD:
return ICON_FA_FILE_WORD;
case FTYPE_CODE:
return ICON_FA_FILE_CODE;
case FTYPE_IMAGE:
return ICON_FA_FILE_IMAGE;
case FTYPE_PDF:
return ICON_FA_FILE_PDF;
case FTYPE_VIDEO:
return ICON_FA_FILE_VIDEO;
case FTYPE_POWERPOINT:
return ICON_FA_FILE_POWERPOINT;
case FTYPE_TEXT:
return ICON_FA_FILE_ALT;
case FTYPE_FILM:
return ICON_FA_FILE_VIDEO;
case FTYPE_AUDIO:
return ICON_FA_FILE_AUDIO;
case FTYPE_EXCEL:
return ICON_FA_FILE_EXCEL;
default:
return ICON_FA_FILE;
}
}
ContentType GetContentType(Context* context, const ea::string& resourcePath)
{
auto extension = GetExtension(resourcePath).to_lower();
if (extension == ".xml")
{
SharedPtr<XMLFile> xml;
if (IsAbsolutePath(resourcePath))
{
xml = SharedPtr<XMLFile>(new XMLFile(context));
if (!xml->LoadFile(resourcePath))
return CTYPE_UNKNOWN;
}
else
xml = context->GetCache()->GetResource<XMLFile>(resourcePath);
if (!xml)
return CTYPE_UNKNOWN;
auto rootElementName = xml->GetRoot().GetName();
if (rootElementName == "scene")
return CTYPE_SCENE;
if (rootElementName == "node")
return CTYPE_SCENEOBJECT;
if (rootElementName == "elements")
return CTYPE_UISTYLE;
if (rootElementName == "element")
return CTYPE_UILAYOUT;
if (rootElementName == "material")
return CTYPE_MATERIAL;
if (rootElementName == "particleeffect")
return CTYPE_PARTICLE;
if (rootElementName == "renderpath")
return CTYPE_RENDERPATH;
if (rootElementName == "texture")
return CTYPE_TEXTUREXML;
}
if (extension == ".mdl")
return CTYPE_MODEL;
if (extension == ".ani")
return CTYPE_ANIMATION;
if (extension == ".scene")
return CTYPE_SCENE;
if (extension == ".ui")
return CTYPE_UILAYOUT;
if (extension == ".style")
return CTYPE_UISTYLE;
if (extension == ".material")
return CTYPE_MATERIAL;
if (extension == ".particle")
return CTYPE_PARTICLE;
if (extension == ".node")
return CTYPE_SCENEOBJECT;
if (audioExtensions_.contains(extension))
return CTYPE_SOUND;
if (imagesExtensions_.contains(extension))
return CTYPE_TEXTURE;
return CTYPE_UNKNOWN;
}
}
<|endoftext|> |
<commit_before>#include <Poco/Logger.h>
#include <Poco/Net/NetException.h>
#include "gws/GatewayConnection.h"
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
GatewayConnection::GatewayConnection(
const GatewayID &gatewayID,
const WebSocket &webSocket,
SocketReactor &reactor,
const EnqueueReadable &enqueueReadable,
size_t maxMessageSize):
m_gatewayID(gatewayID),
m_webSocket(webSocket),
m_reactor(reactor),
m_enqueueReadable(enqueueReadable),
m_receiveBuffer(maxMessageSize),
m_readableObserver(*this, &GatewayConnection::onReadable)
{
if (logger().debug()) {
logger().debug("gateway " + m_gatewayID.toString()
+ " connection created");
}
}
GatewayConnection::~GatewayConnection()
{
if (logger().debug()) {
logger().debug("gateway " + m_gatewayID.toString()
+ " connection destroyed");
}
}
GatewayID GatewayConnection::gatewayID() const
{
return m_gatewayID;
}
void GatewayConnection::addToReactor() const
{
m_reactor.addEventHandler(m_webSocket, m_readableObserver);
}
void GatewayConnection::removeFromReactor() const
{
m_reactor.removeEventHandler(m_webSocket, m_readableObserver);
}
void GatewayConnection::updateLastReceiveTime()
{
FastMutex::ScopedLock guard(m_lastReceiveTimeMutex);
m_lastReceiveTime.update();
}
Poco::Timestamp GatewayConnection::lastReceiveTime()
{
FastMutex::ScopedLock guard(m_lastReceiveTimeMutex);
return m_lastReceiveTime;
}
GWMessage::Ptr GatewayConnection::receiveMessage()
{
int flags;
int ret = m_webSocket.receiveFrame(
m_receiveBuffer.begin(), m_receiveBuffer.size(), flags);
if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE))
throw ConnectionResetException(m_gatewayID.toString());
updateLastReceiveTime();
string msg(m_receiveBuffer.begin(), ret);
if (logger().debug()) {
logger().debug("data from gateway "
+ m_gatewayID.toString() + ":\n" + msg);
}
return GWMessage::fromJSON(msg);
}
void GatewayConnection::sendMessage(const GWMessage::Ptr message)
{
FastMutex::ScopedLock guard(m_sendMutex);
const string &msg = message->toString();
if (logger().debug()) {
logger().debug("message to gateway "
+ m_gatewayID.toString() + ":\n" + msg);
}
m_webSocket.sendFrame(msg.c_str(), msg.length());
}
void GatewayConnection::onReadable(const AutoPtr<ReadableNotification> ¬ification)
{
m_enqueueReadable(AutoPtr<GatewayConnection>(this, true));
}
<commit_msg>GatewayConnection: logging: fix missing __FILE__, __LINE__<commit_after>#include <Poco/Logger.h>
#include <Poco/Net/NetException.h>
#include "gws/GatewayConnection.h"
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
GatewayConnection::GatewayConnection(
const GatewayID &gatewayID,
const WebSocket &webSocket,
SocketReactor &reactor,
const EnqueueReadable &enqueueReadable,
size_t maxMessageSize):
m_gatewayID(gatewayID),
m_webSocket(webSocket),
m_reactor(reactor),
m_enqueueReadable(enqueueReadable),
m_receiveBuffer(maxMessageSize),
m_readableObserver(*this, &GatewayConnection::onReadable)
{
if (logger().debug()) {
logger().debug("gateway " + m_gatewayID.toString()
+ " connection created", __FILE__, __LINE__);
}
}
GatewayConnection::~GatewayConnection()
{
if (logger().debug()) {
logger().debug("gateway " + m_gatewayID.toString()
+ " connection destroyed", __FILE__, __LINE__);
}
}
GatewayID GatewayConnection::gatewayID() const
{
return m_gatewayID;
}
void GatewayConnection::addToReactor() const
{
m_reactor.addEventHandler(m_webSocket, m_readableObserver);
}
void GatewayConnection::removeFromReactor() const
{
m_reactor.removeEventHandler(m_webSocket, m_readableObserver);
}
void GatewayConnection::updateLastReceiveTime()
{
FastMutex::ScopedLock guard(m_lastReceiveTimeMutex);
m_lastReceiveTime.update();
}
Poco::Timestamp GatewayConnection::lastReceiveTime()
{
FastMutex::ScopedLock guard(m_lastReceiveTimeMutex);
return m_lastReceiveTime;
}
GWMessage::Ptr GatewayConnection::receiveMessage()
{
int flags;
int ret = m_webSocket.receiveFrame(
m_receiveBuffer.begin(), m_receiveBuffer.size(), flags);
if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE))
throw ConnectionResetException(m_gatewayID.toString());
updateLastReceiveTime();
string msg(m_receiveBuffer.begin(), ret);
if (logger().debug()) {
logger().debug("data from gateway "
+ m_gatewayID.toString() + ":\n" + msg, __FILE__, __LINE__);
}
return GWMessage::fromJSON(msg);
}
void GatewayConnection::sendMessage(const GWMessage::Ptr message)
{
FastMutex::ScopedLock guard(m_sendMutex);
const string &msg = message->toString();
if (logger().debug()) {
logger().debug("message to gateway "
+ m_gatewayID.toString() + ":\n" + msg, __FILE__, __LINE__);
}
m_webSocket.sendFrame(msg.c_str(), msg.length());
}
void GatewayConnection::onReadable(const AutoPtr<ReadableNotification> ¬ification)
{
m_enqueueReadable(AutoPtr<GatewayConnection>(this, true));
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
Copyright (C) 2004 by Peter Amstutz, Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define CS_IMPLEMENT_PLATFORM_APPLICATION
/* This is needed due the WX headers using free() inline, but the opposing
* malloc() is in the WX libs. */
#define CS_NO_MALLOC_OVERRIDE
#include "cssysdef.h"
#include "cstool/initapp.h"
#include "iutil/objreg.h"
#include "editor.h"
/* Fun fact: should occur after csutil/event.h, otherwise, gcc may report
* missing csMouseEventHelper symbols. */
#include <wx/wx.h>
CS_IMPLEMENT_APPLICATION
#if defined(CS_PLATFORM_WIN32)
#ifndef SW_SHOWNORMAL
#define SW_SHOWNORMAL 1
#endif
/*
WX provides WinMain(), but not main(), which is required for console apps.
*/
int main (int argc, const char* const argv[])
{
return WinMain (GetModuleHandle (0), 0, GetCommandLineA (), SW_SHOWNORMAL);
}
#endif
// Define a new application type
class EditorApp: public wxApp
{
public:
iObjectRegistry* object_reg;
CSE::Editor* editor;
virtual bool OnInit(void);
virtual int OnExit(void);
};
IMPLEMENT_APP(EditorApp)
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
bool EditorApp::OnInit(void)
{
#if defined(wxUSE_UNICODE) && wxUSE_UNICODE
char** csargv;
csargv = (char**)cs_malloc(sizeof(char*) * argc);
for(int i = 0; i < argc; i++)
{
csargv[i] = strdup (wxString(argv[i]).mb_str().data());
}
object_reg = csInitializer::CreateEnvironment (argc, csargv);
//cs_free(csargv);
#else
object_reg = csInitializer::CreateEnvironment (argc, argv);
#endif
editor = new CSE::Editor ();
if (!editor->Initialize (object_reg))
return false;
return true;
}
int EditorApp::OnExit()
{
delete editor;
csInitializer::DestroyApplication (object_reg);
return 0;
}
<commit_msg>Applied r30910 on cseditor as well<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
Copyright (C) 2004 by Peter Amstutz, Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define CS_IMPLEMENT_PLATFORM_APPLICATION
/* This is needed due the WX headers using free() inline, but the opposing
* malloc() is in the WX libs. */
#define CS_NO_MALLOC_OVERRIDE
#include "cssysdef.h"
#include "cstool/initapp.h"
#include "iutil/objreg.h"
#include "editor.h"
/* Fun fact: should occur after csutil/event.h, otherwise, gcc may report
* missing csMouseEventHelper symbols. */
#include "csutil/custom_new_disable.h"
#include <wx/wx.h>
#include "csutil/custom_new_enable.h"
CS_IMPLEMENT_APPLICATION
#if defined(CS_PLATFORM_WIN32)
#ifndef SW_SHOWNORMAL
#define SW_SHOWNORMAL 1
#endif
/*
WX provides WinMain(), but not main(), which is required for console apps.
*/
int main (int argc, const char* const argv[])
{
return WinMain (GetModuleHandle (0), 0, GetCommandLineA (), SW_SHOWNORMAL);
}
#endif
// Define a new application type
class EditorApp: public wxApp
{
public:
iObjectRegistry* object_reg;
CSE::Editor* editor;
virtual bool OnInit(void);
virtual int OnExit(void);
};
IMPLEMENT_APP(EditorApp)
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
bool EditorApp::OnInit(void)
{
#if defined(wxUSE_UNICODE) && wxUSE_UNICODE
char** csargv;
csargv = (char**)cs_malloc(sizeof(char*) * argc);
for(int i = 0; i < argc; i++)
{
csargv[i] = strdup (wxString(argv[i]).mb_str().data());
}
object_reg = csInitializer::CreateEnvironment (argc, csargv);
//cs_free(csargv);
#else
object_reg = csInitializer::CreateEnvironment (argc, argv);
#endif
editor = new CSE::Editor ();
if (!editor->Initialize (object_reg))
return false;
return true;
}
int EditorApp::OnExit()
{
delete editor;
csInitializer::DestroyApplication (object_reg);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>small refinements to blend2d example<commit_after><|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_STATIC_ARRAY_HPP
#define VIENNAGRID_STORAGE_STATIC_ARRAY_HPP
#include "viennagrid/storage/container.hpp"
namespace viennagrid
{
namespace storage
{
template<typename T, std::size_t N>
class static_array {
public:
T elems[N]; // fixed-size array of elements of type T
public:
// type definitions
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
class const_iterator;
// random access iterator: http://www.cplusplus.com/reference/std/iterator/RandomAccessIterator/
class iterator
{
friend class const_iterator;
public:
typedef std::size_t difference_type;
typedef static_array::value_type value_type;
typedef static_array::pointer pointer;
typedef static_array::reference reference;
typedef std::random_access_iterator_tag iterator_category;
// default-constructable
iterator() : ptr_(0) {}
// copy- and copy-constructable
iterator(const iterator & it) : ptr_(it.ptr_) {}
iterator & operator=(const iterator & it) { ptr_ = it.ptr_; return *this; }
// constructor for static_array
iterator(pointer ptr__) : ptr_(ptr__) {}
// equal and inequal compareable
bool operator==(const iterator& i) const { return ptr_ == i.ptr_; }
bool operator!=(const iterator& i) const { return ptr_ != i.ptr_; }
bool operator==(const const_iterator & it) const;
bool operator!=(const const_iterator & it) const;
// dereferenceable
reference operator*() const { return *ptr_; }
pointer operator->() const { return ptr_; }
// increment- and decrementable
iterator & operator++() { ++ptr_; return *this; }
iterator operator++(int) { iterator tmp = *this; ++*this; return tmp; }
iterator & operator--() { --ptr_; return *this; }
iterator operator--(int) { iterator tmp = *this; --*this; return tmp; }
// add and subtractable; operator+ and operator- is below
difference_type operator-(const iterator & it) const { return ptr_ - it.ptr_; }
difference_type operator-(const const_iterator & it) const { return ptr_ - it.ptr_; }
// less and greater compareable
bool operator<(const iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const iterator & it) const { return ptr_ >= it.ptr; }
bool operator<(const const_iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const const_iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const const_iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const const_iterator & it) const { return ptr_ >= it.ptr; }
// compound assign add- and subtractable
iterator & operator+=(long diff) { ptr_ += diff; return *this; }
iterator & operator-=(long diff) { ptr_ -= diff; return *this; }
// offset dereferenceable
reference operator[](std::size_t offset) { return *(ptr_+offset); }
const reference operator[](std::size_t offset) const { return *(ptr_+offset); }
private:
pointer ptr_;
};
class const_iterator
{
friend class iterator;
public:
typedef std::size_t difference_type;
typedef static_array::value_type value_type;
typedef static_array::const_pointer pointer;
typedef static_array::const_reference reference;
typedef std::random_access_iterator_tag iterator_category;
// default-constructable
const_iterator() : ptr_(0) {}
// copy- and copy-constructable
const_iterator(const const_iterator & it) : ptr_(it.ptr_) {}
const_iterator(iterator it) : ptr_(it.ptr_) {}
const_iterator & operator=(const iterator & it) { ptr_ = it.ptr_; return *this; }
const_iterator & operator=(const const_iterator & it) { ptr_ = it.ptr_; return *this; }
// constructor for static_array
const_iterator(const_pointer ptr__) : ptr_(ptr__) {}
// equal and inequal compareable
bool operator==(const const_iterator& i) const { return ptr_ == i.ptr_; }
bool operator!=(const const_iterator& i) const { return ptr_ != i.ptr_; }
bool operator==(const iterator & i) const { return ptr_ == i.ptr_; }
bool operator!=(const iterator & i) const { return ptr_ != i.ptr_; }
// dereferenceable
reference operator*() const { return *ptr_; }
pointer operator->() const { return ptr_; }
// increment- and decrementable
const_iterator & operator++() { ++ptr_; return *this; }
const_iterator operator++(int) { iterator tmp = *this; ++*this; return tmp; }
const_iterator & operator--() { --ptr_; return *this; }
const_iterator operator--(int) { iterator tmp = *this; --*this; return tmp; }
// add and subtractable; operator+ and operator- is below
difference_type operator-(const iterator & it) const { return ptr_ - it.ptr_; }
difference_type operator-(const const_iterator & it) const { return ptr_ - it.ptr_; }
// less and greater compareable
bool operator<(const iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const iterator & it) const { return ptr_ >= it.ptr; }
bool operator<(const const_iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const const_iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const const_iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const const_iterator & it) const { return ptr_ >= it.ptr; }
// compound assign add- and subtractable
const_iterator & operator+=(long diff) { ptr_ += diff; return *this; }
const_iterator & operator-=(long diff) { ptr_ -= diff; return *this; }
// offset dereferenceable
reference operator[](std::size_t offset) { return *(ptr_+offset); }
private:
pointer ptr_;
};
// iterator support
iterator begin() { return iterator(elems); }
const_iterator begin() const { return const_iterator(elems); }
const_iterator cbegin() const { return const_iterator(elems); }
iterator end() { return iterator(elems+N); }
const_iterator end() const { return const_iterator(elems+N); }
const_iterator cend() const { return const_iterator(elems+N); }
// reverse iterator support
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const {
return const_reverse_iterator(end());
}
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const {
return const_reverse_iterator(begin());
}
// operator[]
reference operator[](size_type i)
{
assert( i < N && "out of range" );
return elems[i];
}
const_reference operator[](size_type i) const
{
assert( i < N && "out of range" );
return elems[i];
}
// at() with range check
reference at(size_type i) { assert( i < N && "out of range" ); return elems[i]; }
const_reference at(size_type i) const { assert( i < N && "out of range" ); return elems[i]; }
// front() and back()
reference front()
{
return elems[0];
}
const_reference front() const
{
return elems[0];
}
reference back()
{
return elems[N-1];
}
const_reference back() const
{
return elems[N-1];
}
// size is constant
static size_type size() { return N; }
static void resize(size_type s) {} // { assert( (s >= 0) && (s <= N) ); }
static bool empty() { return false; }
static size_type max_size() { return N; }
enum { static_size = N };
// swap (note: linear complexity)
void swap (static_array<T,N>& y) {
for (size_type i = 0; i < N; ++i)
std::swap(elems[i],y.elems[i]);
}
// direct access to data (read-only)
const T* data() const { return elems; }
T* data() { return elems; }
// use static_array as C array (direct read/write access to data)
T* c_array() { return elems; }
// assignment with type conversion
template <typename T2>
static_array<T,N>& operator= (const static_array<T2,N>& rhs) {
std::copy(rhs.begin(),rhs.end(), begin());
return *this;
}
// assign one value to all elements
void assign (const T& value) { fill ( value ); } // A synonym for fill
void fill (const T& value)
{
std::fill_n(begin(),size(),value);
}
};
// comparisons
template<class T, std::size_t N>
bool operator== (const static_array<T,N>& x, const static_array<T,N>& y) {
return std::equal(x.begin(), x.end(), y.begin());
}
template<class T, std::size_t N>
bool operator< (const static_array<T,N>& x, const static_array<T,N>& y) {
return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end());
}
template<class T, std::size_t N>
bool operator!= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(x==y);
}
template<class T, std::size_t N>
bool operator> (const static_array<T,N>& x, const static_array<T,N>& y) {
return y<x;
}
template<class T, std::size_t N>
bool operator<= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(y<x);
}
template<class T, std::size_t N>
bool operator>= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(x<y);
}
// global swap()
template<class T, std::size_t N>
inline void swap (static_array<T,N>& x, static_array<T,N>& y) {
x.swap(y);
}
// iterator operations
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator+(const typename static_array<T,N>::iterator & it, long diff) { typename static_array<T,N>::iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator+(long diff, const typename static_array<T,N>::iterator & it) { typename static_array<T,N>::iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator-(const typename static_array<T,N>::iterator & it, long diff) { typename static_array<T,N>::iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator-(long diff, const typename static_array<T,N>::iterator & it) { typename static_array<T,N>::iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator+(const typename static_array<T,N>::const_iterator & it, long diff) { typename static_array<T,N>::const_iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator+(long diff, const typename static_array<T,N>::const_iterator & it) { typename static_array<T,N>::const_iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator-(const typename static_array<T,N>::const_iterator & it, long diff) { typename static_array<T,N>::const_iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator-(long diff, const typename static_array<T,N>::const_iterator & it) { typename static_array<T,N>::const_iterator tmp(it); tmp -= diff; return tmp; }
template<long size__>
struct static_array_tag
{
enum { size = size__ };
};
namespace result_of
{
template<typename element_type, long size>
struct container<element_type, static_array_tag<size> >
{
typedef static_array<element_type, size> type;
};
}
}
}
#endif
<commit_msg>resize doesn't assert if the new size fits into the array<commit_after>#ifndef VIENNAGRID_STORAGE_STATIC_ARRAY_HPP
#define VIENNAGRID_STORAGE_STATIC_ARRAY_HPP
#include "viennagrid/storage/container.hpp"
namespace viennagrid
{
namespace storage
{
template<typename T, std::size_t N>
class static_array {
public:
T elems[N]; // fixed-size array of elements of type T
public:
// type definitions
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
class const_iterator;
// random access iterator: http://www.cplusplus.com/reference/std/iterator/RandomAccessIterator/
class iterator
{
friend class const_iterator;
public:
typedef std::size_t difference_type;
typedef static_array::value_type value_type;
typedef static_array::pointer pointer;
typedef static_array::reference reference;
typedef std::random_access_iterator_tag iterator_category;
// default-constructable
iterator() : ptr_(0) {}
// copy- and copy-constructable
iterator(const iterator & it) : ptr_(it.ptr_) {}
iterator & operator=(const iterator & it) { ptr_ = it.ptr_; return *this; }
// constructor for static_array
iterator(pointer ptr__) : ptr_(ptr__) {}
// equal and inequal compareable
bool operator==(const iterator& i) const { return ptr_ == i.ptr_; }
bool operator!=(const iterator& i) const { return ptr_ != i.ptr_; }
bool operator==(const const_iterator & it) const;
bool operator!=(const const_iterator & it) const;
// dereferenceable
reference operator*() const { return *ptr_; }
pointer operator->() const { return ptr_; }
// increment- and decrementable
iterator & operator++() { ++ptr_; return *this; }
iterator operator++(int) { iterator tmp = *this; ++*this; return tmp; }
iterator & operator--() { --ptr_; return *this; }
iterator operator--(int) { iterator tmp = *this; --*this; return tmp; }
// add and subtractable; operator+ and operator- is below
difference_type operator-(const iterator & it) const { return ptr_ - it.ptr_; }
difference_type operator-(const const_iterator & it) const { return ptr_ - it.ptr_; }
// less and greater compareable
bool operator<(const iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const iterator & it) const { return ptr_ >= it.ptr; }
bool operator<(const const_iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const const_iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const const_iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const const_iterator & it) const { return ptr_ >= it.ptr; }
// compound assign add- and subtractable
iterator & operator+=(long diff) { ptr_ += diff; return *this; }
iterator & operator-=(long diff) { ptr_ -= diff; return *this; }
// offset dereferenceable
reference operator[](std::size_t offset) { return *(ptr_+offset); }
const reference operator[](std::size_t offset) const { return *(ptr_+offset); }
private:
pointer ptr_;
};
class const_iterator
{
friend class iterator;
public:
typedef std::size_t difference_type;
typedef static_array::value_type value_type;
typedef static_array::const_pointer pointer;
typedef static_array::const_reference reference;
typedef std::random_access_iterator_tag iterator_category;
// default-constructable
const_iterator() : ptr_(0) {}
// copy- and copy-constructable
const_iterator(const const_iterator & it) : ptr_(it.ptr_) {}
const_iterator(iterator it) : ptr_(it.ptr_) {}
const_iterator & operator=(const iterator & it) { ptr_ = it.ptr_; return *this; }
const_iterator & operator=(const const_iterator & it) { ptr_ = it.ptr_; return *this; }
// constructor for static_array
const_iterator(const_pointer ptr__) : ptr_(ptr__) {}
// equal and inequal compareable
bool operator==(const const_iterator& i) const { return ptr_ == i.ptr_; }
bool operator!=(const const_iterator& i) const { return ptr_ != i.ptr_; }
bool operator==(const iterator & i) const { return ptr_ == i.ptr_; }
bool operator!=(const iterator & i) const { return ptr_ != i.ptr_; }
// dereferenceable
reference operator*() const { return *ptr_; }
pointer operator->() const { return ptr_; }
// increment- and decrementable
const_iterator & operator++() { ++ptr_; return *this; }
const_iterator operator++(int) { iterator tmp = *this; ++*this; return tmp; }
const_iterator & operator--() { --ptr_; return *this; }
const_iterator operator--(int) { iterator tmp = *this; --*this; return tmp; }
// add and subtractable; operator+ and operator- is below
difference_type operator-(const iterator & it) const { return ptr_ - it.ptr_; }
difference_type operator-(const const_iterator & it) const { return ptr_ - it.ptr_; }
// less and greater compareable
bool operator<(const iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const iterator & it) const { return ptr_ >= it.ptr; }
bool operator<(const const_iterator & it) const { return ptr_ < it.ptr; }
bool operator<=(const const_iterator & it) const { return ptr_ <= it.ptr; }
bool operator>(const const_iterator & it) const { return ptr_ > it.ptr; }
bool operator>=(const const_iterator & it) const { return ptr_ >= it.ptr; }
// compound assign add- and subtractable
const_iterator & operator+=(long diff) { ptr_ += diff; return *this; }
const_iterator & operator-=(long diff) { ptr_ -= diff; return *this; }
// offset dereferenceable
reference operator[](std::size_t offset) { return *(ptr_+offset); }
private:
pointer ptr_;
};
// iterator support
iterator begin() { return iterator(elems); }
const_iterator begin() const { return const_iterator(elems); }
const_iterator cbegin() const { return const_iterator(elems); }
iterator end() { return iterator(elems+N); }
const_iterator end() const { return const_iterator(elems+N); }
const_iterator cend() const { return const_iterator(elems+N); }
// reverse iterator support
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const {
return const_reverse_iterator(end());
}
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const {
return const_reverse_iterator(begin());
}
// operator[]
reference operator[](size_type i)
{
assert( i < N && "out of range" );
return elems[i];
}
const_reference operator[](size_type i) const
{
assert( i < N && "out of range" );
return elems[i];
}
// at() with range check
reference at(size_type i) { assert( i < N && "out of range" ); return elems[i]; }
const_reference at(size_type i) const { assert( i < N && "out of range" ); return elems[i]; }
// front() and back()
reference front()
{
return elems[0];
}
const_reference front() const
{
return elems[0];
}
reference back()
{
return elems[N-1];
}
const_reference back() const
{
return elems[N-1];
}
// size is constant
static size_type size() { return N; }
static void resize(size_type s) { assert( (s >= 0) && (s <= N) ); }
static bool empty() { return false; }
static size_type max_size() { return N; }
enum { static_size = N };
// swap (note: linear complexity)
void swap (static_array<T,N>& y) {
for (size_type i = 0; i < N; ++i)
std::swap(elems[i],y.elems[i]);
}
// direct access to data (read-only)
const T* data() const { return elems; }
T* data() { return elems; }
// use static_array as C array (direct read/write access to data)
T* c_array() { return elems; }
// assignment with type conversion
template <typename T2>
static_array<T,N>& operator= (const static_array<T2,N>& rhs) {
std::copy(rhs.begin(),rhs.end(), begin());
return *this;
}
// assign one value to all elements
void assign (const T& value) { fill ( value ); } // A synonym for fill
void fill (const T& value)
{
std::fill_n(begin(),size(),value);
}
};
// comparisons
template<class T, std::size_t N>
bool operator== (const static_array<T,N>& x, const static_array<T,N>& y) {
return std::equal(x.begin(), x.end(), y.begin());
}
template<class T, std::size_t N>
bool operator< (const static_array<T,N>& x, const static_array<T,N>& y) {
return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end());
}
template<class T, std::size_t N>
bool operator!= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(x==y);
}
template<class T, std::size_t N>
bool operator> (const static_array<T,N>& x, const static_array<T,N>& y) {
return y<x;
}
template<class T, std::size_t N>
bool operator<= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(y<x);
}
template<class T, std::size_t N>
bool operator>= (const static_array<T,N>& x, const static_array<T,N>& y) {
return !(x<y);
}
// global swap()
template<class T, std::size_t N>
inline void swap (static_array<T,N>& x, static_array<T,N>& y) {
x.swap(y);
}
// iterator operations
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator+(const typename static_array<T,N>::iterator & it, long diff) { typename static_array<T,N>::iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator+(long diff, const typename static_array<T,N>::iterator & it) { typename static_array<T,N>::iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator-(const typename static_array<T,N>::iterator & it, long diff) { typename static_array<T,N>::iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::iterator operator-(long diff, const typename static_array<T,N>::iterator & it) { typename static_array<T,N>::iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator+(const typename static_array<T,N>::const_iterator & it, long diff) { typename static_array<T,N>::const_iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator+(long diff, const typename static_array<T,N>::const_iterator & it) { typename static_array<T,N>::const_iterator tmp(it); tmp += diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator-(const typename static_array<T,N>::const_iterator & it, long diff) { typename static_array<T,N>::const_iterator tmp(it); tmp -= diff; return tmp; }
template<typename T, std::size_t N>
typename static_array<T,N>::const_iterator operator-(long diff, const typename static_array<T,N>::const_iterator & it) { typename static_array<T,N>::const_iterator tmp(it); tmp -= diff; return tmp; }
template<long size__>
struct static_array_tag
{
enum { size = size__ };
};
namespace result_of
{
template<typename element_type, long size>
struct container<element_type, static_array_tag<size> >
{
typedef static_array<element_type, size> type;
};
}
}
}
#endif
<|endoftext|> |
<commit_before>#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgSim/OverlayNode>
#include <osgViewer/Viewer>
#include <iostream>
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createBase(const osg::Vec3& center,float radius)
{
int numTilesX = 10;
int numTilesY = 10;
float width = 2*radius;
float height = 2*radius;
osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));
osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f));
osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f));
// fill in vertices for grid, note numTilesX+1 * numTilesY+1...
osg::Vec3Array* coords = new osg::Vec3Array;
int iy;
for(iy=0;iy<=numTilesY;++iy)
{
for(int ix=0;ix<=numTilesX;++ix)
{
coords->push_back(v000+dx*(float)ix+dy*(float)iy);
}
}
//Just two colours - black and white.
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white
colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
int numColors=colors->size();
int numIndicesPerRow=numTilesX+1;
osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points...
osg::UByteArray* colorIndices = new osg::UByteArray;
for(iy=0;iy<numTilesY;++iy)
{
for(int ix=0;ix<numTilesX;++ix)
{
// four vertices per quad.
coordIndices->push_back(ix +(iy+1)*numIndicesPerRow);
coordIndices->push_back(ix +iy*numIndicesPerRow);
coordIndices->push_back((ix+1)+iy*numIndicesPerRow);
coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);
// one color per quad
colorIndices->push_back((ix+iy)%numColors);
}
}
// set up a single normal
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
osg::Geometry* geom = new osg::Geometry;
geom->setVertexArray(coords);
geom->setVertexIndices(coordIndices);
geom->setColorArray(colors);
geom->setColorIndices(colorIndices);
geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
geom->setNormalArray(normals);
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
return geode;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* glider = osgDB::readNodeFile("glider.osg");
if (glider)
{
const osg::BoundingSphere& bs = glider->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
positioned->addChild(glider);
osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
xform->addChild(positioned);
model->addChild(xform);
}
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
positioned->addChild(cessna);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
model->addChild(xform);
}
return model;
}
osg::Node* createModel(bool overlay)
{
osg::Vec3 center(0.0f,0.0f,0.0f);
float radius = 100.0f;
osg::Group* root = new osg::Group;
osg::Node* baseModel = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius);
osg::Node* movingModel = createMovingModel(center,radius*0.8f);
if (overlay)
{
osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
overlayNode->setContinuousUpdate(true);
overlayNode->setOverlaySubgraph(movingModel);
overlayNode->addChild(baseModel);
root->addChild(overlayNode);
}
else
{
root->addChild(baseModel);
}
root->addChild(movingModel);
return root;
}
int main( int argc, char **argv )
{
bool overlay = false;
osg::ArgumentParser arguments(&argc,argv);
while (arguments.read("--overlay")) overlay = true;
// initialize the viewer.
osgViewer::Viewer viewer;
// load the nodes from the commandline arguments.
osg::Node* model = createModel(overlay);
if (!model)
{
return 1;
}
// tilt the scene so the default eye position is looking down on the model.
osg::MatrixTransform* rootnode = new osg::MatrixTransform;
rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));
rootnode->addChild(model);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// set the scene to render
viewer.setSceneData(rootnode);
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
#if 0
// use of custom simulation time.
viewer.realize();
double simulationTime = 100.0;
while (!viewer.done())
{
viewer.frame(simulationTime);
simulationTime -= 0.01;
}
return 0;
#else
// normal viewer usage.
return viewer.run();
#endif
}
<commit_msg>Added option for using the different overlay techniques.<commit_after>#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgSim/OverlayNode>
#include <osgViewer/Viewer>
#include <iostream>
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->setLoopMode(osg::AnimationPath::LOOP);
int numSamples = 40;
float yaw = 0.0f;
float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
float roll = osg::inDegrees(30.0f);
double time=0.0f;
double time_delta = looptime/(double)numSamples;
for(int i=0;i<numSamples;++i)
{
osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
yaw += yaw_delta;
time += time_delta;
}
return animationPath;
}
osg::Node* createBase(const osg::Vec3& center,float radius)
{
int numTilesX = 10;
int numTilesY = 10;
float width = 2*radius;
float height = 2*radius;
osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));
osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f));
osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f));
// fill in vertices for grid, note numTilesX+1 * numTilesY+1...
osg::Vec3Array* coords = new osg::Vec3Array;
int iy;
for(iy=0;iy<=numTilesY;++iy)
{
for(int ix=0;ix<=numTilesX;++ix)
{
coords->push_back(v000+dx*(float)ix+dy*(float)iy);
}
}
//Just two colours - black and white.
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white
colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
int numColors=colors->size();
int numIndicesPerRow=numTilesX+1;
osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points...
osg::UByteArray* colorIndices = new osg::UByteArray;
for(iy=0;iy<numTilesY;++iy)
{
for(int ix=0;ix<numTilesX;++ix)
{
// four vertices per quad.
coordIndices->push_back(ix +(iy+1)*numIndicesPerRow);
coordIndices->push_back(ix +iy*numIndicesPerRow);
coordIndices->push_back((ix+1)+iy*numIndicesPerRow);
coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);
// one color per quad
colorIndices->push_back((ix+iy)%numColors);
}
}
// set up a single normal
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
osg::Geometry* geom = new osg::Geometry;
geom->setVertexArray(coords);
geom->setVertexIndices(coordIndices);
geom->setColorArray(colors);
geom->setColorIndices(colorIndices);
geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
geom->setNormalArray(normals);
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
return geode;
}
osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
float animationLength = 10.0f;
osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
osg::Group* model = new osg::Group;
osg::Node* glider = osgDB::readNodeFile("glider.osg");
if (glider)
{
const osg::BoundingSphere& bs = glider->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
positioned->addChild(glider);
osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
xform->addChild(positioned);
model->addChild(xform);
}
osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
if (cessna)
{
const osg::BoundingSphere& bs = cessna->getBound();
float size = radius/bs.radius()*0.3f;
osg::MatrixTransform* positioned = new osg::MatrixTransform;
positioned->setDataVariance(osg::Object::STATIC);
positioned->setMatrix(osg::Matrix::translate(-bs.center())*
osg::Matrix::scale(size,size,size)*
osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
positioned->addChild(cessna);
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
xform->addChild(positioned);
model->addChild(xform);
}
return model;
}
osg::Node* createModel(bool overlay, osgSim::OverlayNode::OverlayTechnique technique)
{
osg::Vec3 center(0.0f,0.0f,0.0f);
float radius = 100.0f;
osg::Group* root = new osg::Group;
osg::Node* baseModel = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius);
osg::Node* movingModel = createMovingModel(center,radius*0.8f);
if (overlay)
{
osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);
overlayNode->setContinuousUpdate(true);
overlayNode->setOverlaySubgraph(movingModel);
overlayNode->addChild(baseModel);
root->addChild(overlayNode);
}
else
{
root->addChild(baseModel);
}
root->addChild(movingModel);
return root;
}
int main( int argc, char **argv )
{
bool overlay = false;
osg::ArgumentParser arguments(&argc,argv);
while (arguments.read("--overlay")) overlay = true;
osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
while (arguments.read("--object")) { technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }
while (arguments.read("--ortho") || arguments.read("--orthographic")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }
while (arguments.read("--persp") || arguments.read("--perspective")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY; overlay=true; }
// initialize the viewer.
osgViewer::Viewer viewer;
// load the nodes from the commandline arguments.
osg::Node* model = createModel(overlay, technique);
if (!model)
{
return 1;
}
// tilt the scene so the default eye position is looking down on the model.
osg::MatrixTransform* rootnode = new osg::MatrixTransform;
rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));
rootnode->addChild(model);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// set the scene to render
viewer.setSceneData(rootnode);
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
#if 0
// use of custom simulation time.
viewer.realize();
double simulationTime = 100.0;
while (!viewer.done())
{
viewer.frame(simulationTime);
simulationTime -= 0.01;
}
return 0;
#else
// normal viewer usage.
return viewer.run();
#endif
}
<|endoftext|> |
<commit_before>// Copyright 2021 Google LLC
//
// 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
//
// https://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 "google/cloud/internal/absl_str_join_quiet.h"
#include "google/cloud/log.h"
#include "google/cloud/status_or.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "generator/generator.h"
#include "generator/generator_config.pb.h"
#include "generator/internal/scaffold_generator.h"
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <fstream>
#include <future>
#include <iostream>
ABSL_FLAG(std::string, config_file, "",
"Text proto configuration file specifying the code to be generated.");
ABSL_FLAG(std::string, protobuf_proto_path, "",
"Path to root dir of protos distributed with protobuf.");
ABSL_FLAG(std::string, googleapis_proto_path, "",
"Path to root dir of protos distributed with googleapis.");
ABSL_FLAG(std::string, output_path, ".",
"Path to root dir where code is emitted.");
ABSL_FLAG(std::string, scaffold, "",
"Generate the library support files for the given directory.");
namespace {
google::cloud::StatusOr<google::cloud::cpp::generator::GeneratorConfiguration>
GetConfig(std::string const& filepath) {
std::ifstream input(filepath);
std::stringstream buffer;
buffer << input.rdbuf();
google::cloud::cpp::generator::GeneratorConfiguration generator_config;
auto parse_result = google::protobuf::TextFormat::ParseFromString(
buffer.str(), &generator_config);
if (parse_result) return generator_config;
return google::cloud::Status(google::cloud::StatusCode::kInvalidArgument,
"Unable to parse textproto file.");
}
/**
* Return the parent directory of @path, if any.
*
* @note The return value for absolute paths or paths without `/` is
* unspecified, as we do not expect any such inputs.
*
* @return For a path of the form `a/b/c` returns `a/b`.
*/
std::string Dirname(std::string const& path) {
return path.substr(0, path.find_last_of('/'));
}
std::vector<std::string> Parents(std::string path) {
std::vector<std::string> p;
p.push_back(path);
while (path.find('/') != std::string::npos) {
path = Dirname(path);
p.push_back(path);
}
return p;
}
int WriteInstallDirectories(
google::cloud::cpp::generator::GeneratorConfiguration const& config,
std::string const& output_path) {
std::vector<std::string> install_directories{".", "./lib64", "./lib64/cmake"};
for (auto const& service : config.service()) {
if (service.product_path().empty()) {
GCP_LOG(ERROR) << "Empty product path in config, service="
<< service.DebugString() << "\n";
return 1;
}
if (service.service_proto_path().empty()) {
GCP_LOG(ERROR) << "Empty service proto path in config, service="
<< service.DebugString() << "\n";
return 1;
}
auto const& product_path = service.product_path();
for (auto const& p : Parents("./include/" + product_path)) {
install_directories.push_back(p);
}
install_directories.push_back("./include/" + product_path + "/internal");
for (auto const& p :
Parents("./include/" + Dirname(service.service_proto_path()))) {
install_directories.push_back(p);
}
// Bigtable and Spanner use a custom path for generated code.
auto const lib = google::cloud::generator_internal::LibraryName(service);
if (lib != "admin") {
install_directories.push_back("./include/" + product_path + "/mocks");
install_directories.push_back("./lib64/cmake/google_cloud_cpp_" + lib);
}
}
std::sort(install_directories.begin(), install_directories.end());
auto end =
std::unique(install_directories.begin(), install_directories.end());
std::ofstream of(output_path + "/ci/etc/expected_install_directories");
std::copy(install_directories.begin(), end,
std::ostream_iterator<std::string>(of, "\n"));
return 0;
}
int WriteFeatureList(
google::cloud::cpp::generator::GeneratorConfiguration const& config,
std::string const& output_path) {
std::vector<std::string> features;
for (auto const& service : config.service()) {
if (service.product_path().empty()) {
GCP_LOG(ERROR) << "Empty product path in config, service="
<< service.DebugString() << "\n";
return 1;
}
auto feature = google::cloud::generator_internal::LibraryName(service);
// Spanner and Bigtable use a custom directory for generated files
if (feature == "admin") continue;
features.push_back(std::move(feature));
}
std::sort(features.begin(), features.end());
auto const end = std::unique(features.begin(), features.end());
std::ofstream of(output_path + "/ci/etc/full_feature_list");
std::copy(features.begin(), end,
std::ostream_iterator<std::string>(of, "\n"));
return 0;
}
} // namespace
/**
* C++ microgenerator.
*
* @par Command line arguments:
* --config-file=<path> REQUIRED should be a textproto file for
* GeneratorConfiguration message.
* --protobuf_proto_path=<path> REQUIRED path to .proto files distributed with
* protobuf.
* --googleapis_proto_path=<path> REQUIRED path to .proto files distributed
* with googleapis repo.
* --output_path=<path> OPTIONAL defaults to current directory.
*/
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
google::cloud::LogSink::EnableStdClog(
google::cloud::Severity::GCP_LS_WARNING);
auto proto_path = absl::GetFlag(FLAGS_protobuf_proto_path);
auto googleapis_path = absl::GetFlag(FLAGS_googleapis_proto_path);
auto config_file = absl::GetFlag(FLAGS_config_file);
auto output_path = absl::GetFlag(FLAGS_output_path);
auto scaffold = absl::GetFlag(FLAGS_scaffold);
GCP_LOG(INFO) << "proto_path = " << proto_path << "\n";
GCP_LOG(INFO) << "googleapis_path = " << googleapis_path << "\n";
GCP_LOG(INFO) << "config_file = " << config_file << "\n";
GCP_LOG(INFO) << "output_path = " << output_path << "\n";
auto config = GetConfig(config_file);
if (!config.ok()) {
GCP_LOG(ERROR) << "Failed to parse config file: " << config_file << "\n";
}
auto const install_result = WriteInstallDirectories(*config, output_path);
if (install_result != 0) return install_result;
auto const features_result = WriteFeatureList(*config, output_path);
if (features_result != 0) return features_result;
std::vector<std::future<google::cloud::Status>> tasks;
for (auto const& service : config->service()) {
if (service.product_path() == scaffold) {
google::cloud::generator_internal::GenerateScaffold(googleapis_path,
output_path, service);
}
std::vector<std::string> args;
// empty arg prevents first real arg from being ignored.
args.emplace_back("");
args.emplace_back("--proto_path=" + proto_path);
args.emplace_back("--proto_path=" + googleapis_path);
args.emplace_back("--cpp_codegen_out=" + output_path);
args.emplace_back("--cpp_codegen_opt=product_path=" +
service.product_path());
args.emplace_back("--cpp_codegen_opt=copyright_year=" +
service.initial_copyright_year());
for (auto const& omit_service : service.omitted_services()) {
args.emplace_back("--cpp_codegen_opt=omit_service=" + omit_service);
}
for (auto const& omit_rpc : service.omitted_rpcs()) {
args.emplace_back("--cpp_codegen_opt=omit_rpc=" + omit_rpc);
}
if (service.backwards_compatibility_namespace_alias()) {
args.emplace_back(
"--cpp_codegen_opt=backwards_compatibility_namespace_alias=true");
}
for (auto const& retry_code : service.retryable_status_codes()) {
args.emplace_back("--cpp_codegen_opt=retry_status_code=" + retry_code);
}
if (service.omit_client()) {
args.emplace_back("--cpp_codegen_opt=omit_client=true");
}
if (service.omit_connection()) {
args.emplace_back("--cpp_codegen_opt=omit_connection=true");
}
if (service.omit_stub_factory()) {
args.emplace_back("--cpp_codegen_opt=omit_stub_factory=true");
}
args.emplace_back("--cpp_codegen_opt=service_endpoint_env_var=" +
service.service_endpoint_env_var());
args.emplace_back("--cpp_codegen_opt=emulator_endpoint_env_var=" +
service.emulator_endpoint_env_var());
for (auto const& gen_async_rpc : service.gen_async_rpcs()) {
args.emplace_back("--cpp_codegen_opt=gen_async_rpc=" + gen_async_rpc);
}
for (auto const& additional_proto_file : service.additional_proto_files()) {
args.emplace_back("--cpp_codegen_opt=additional_proto_file=" +
additional_proto_file);
}
args.emplace_back(service.service_proto_path());
for (auto const& additional_proto_file : service.additional_proto_files()) {
args.emplace_back(additional_proto_file);
}
GCP_LOG(INFO) << "Generating service code using: "
<< absl::StrJoin(args, ";") << "\n";
tasks.push_back(std::async(std::launch::async, [args] {
google::protobuf::compiler::CommandLineInterface cli;
google::cloud::generator::Generator generator;
cli.RegisterGenerator("--cpp_codegen_out", "--cpp_codegen_opt",
&generator, "Codegen C++ Generator");
std::vector<char const*> c_args;
c_args.reserve(args.size());
for (auto const& arg : args) {
c_args.push_back(arg.c_str());
}
if (cli.Run(static_cast<int>(c_args.size()), c_args.data()) != 0)
return google::cloud::Status(google::cloud::StatusCode::kInternal,
absl::StrCat("Generating service from ",
c_args.back(), " failed."));
return google::cloud::Status{};
}));
}
std::string error_message;
for (auto& t : tasks) {
auto result = t.get();
if (!result.ok()) {
absl::StrAppend(&error_message, result.message(), "\n");
}
}
if (!error_message.empty()) {
GCP_LOG(ERROR) << error_message;
return 1;
}
return 0;
}
<commit_msg>fix(generator): no include/../mocks without a connection (#8005)<commit_after>// Copyright 2021 Google LLC
//
// 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
//
// https://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 "google/cloud/internal/absl_str_join_quiet.h"
#include "google/cloud/log.h"
#include "google/cloud/status_or.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "generator/generator.h"
#include "generator/generator_config.pb.h"
#include "generator/internal/scaffold_generator.h"
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <fstream>
#include <future>
#include <iostream>
ABSL_FLAG(std::string, config_file, "",
"Text proto configuration file specifying the code to be generated.");
ABSL_FLAG(std::string, protobuf_proto_path, "",
"Path to root dir of protos distributed with protobuf.");
ABSL_FLAG(std::string, googleapis_proto_path, "",
"Path to root dir of protos distributed with googleapis.");
ABSL_FLAG(std::string, output_path, ".",
"Path to root dir where code is emitted.");
ABSL_FLAG(std::string, scaffold, "",
"Generate the library support files for the given directory.");
namespace {
google::cloud::StatusOr<google::cloud::cpp::generator::GeneratorConfiguration>
GetConfig(std::string const& filepath) {
std::ifstream input(filepath);
std::stringstream buffer;
buffer << input.rdbuf();
google::cloud::cpp::generator::GeneratorConfiguration generator_config;
auto parse_result = google::protobuf::TextFormat::ParseFromString(
buffer.str(), &generator_config);
if (parse_result) return generator_config;
return google::cloud::Status(google::cloud::StatusCode::kInvalidArgument,
"Unable to parse textproto file.");
}
/**
* Return the parent directory of @path, if any.
*
* @note The return value for absolute paths or paths without `/` is
* unspecified, as we do not expect any such inputs.
*
* @return For a path of the form `a/b/c` returns `a/b`.
*/
std::string Dirname(std::string const& path) {
return path.substr(0, path.find_last_of('/'));
}
std::vector<std::string> Parents(std::string path) {
std::vector<std::string> p;
p.push_back(path);
while (path.find('/') != std::string::npos) {
path = Dirname(path);
p.push_back(path);
}
return p;
}
int WriteInstallDirectories(
google::cloud::cpp::generator::GeneratorConfiguration const& config,
std::string const& output_path) {
std::vector<std::string> install_directories{".", "./lib64", "./lib64/cmake"};
for (auto const& service : config.service()) {
if (service.product_path().empty()) {
GCP_LOG(ERROR) << "Empty product path in config, service="
<< service.DebugString() << "\n";
return 1;
}
if (service.service_proto_path().empty()) {
GCP_LOG(ERROR) << "Empty service proto path in config, service="
<< service.DebugString() << "\n";
return 1;
}
auto const& product_path = service.product_path();
for (auto const& p : Parents("./include/" + product_path)) {
install_directories.push_back(p);
}
install_directories.push_back("./include/" + product_path + "/internal");
for (auto const& p :
Parents("./include/" + Dirname(service.service_proto_path()))) {
install_directories.push_back(p);
}
auto const lib = google::cloud::generator_internal::LibraryName(service);
// Bigtable and Spanner use a custom path for generated code.
if (lib == "admin") continue;
// Services without a connection do not create mocks.
if (!service.omit_connection()) {
install_directories.push_back("./include/" + product_path + "/mocks");
}
install_directories.push_back("./lib64/cmake/google_cloud_cpp_" + lib);
}
std::sort(install_directories.begin(), install_directories.end());
auto end =
std::unique(install_directories.begin(), install_directories.end());
std::ofstream of(output_path + "/ci/etc/expected_install_directories");
std::copy(install_directories.begin(), end,
std::ostream_iterator<std::string>(of, "\n"));
return 0;
}
int WriteFeatureList(
google::cloud::cpp::generator::GeneratorConfiguration const& config,
std::string const& output_path) {
std::vector<std::string> features;
for (auto const& service : config.service()) {
if (service.product_path().empty()) {
GCP_LOG(ERROR) << "Empty product path in config, service="
<< service.DebugString() << "\n";
return 1;
}
auto feature = google::cloud::generator_internal::LibraryName(service);
// Spanner and Bigtable use a custom directory for generated files
if (feature == "admin") continue;
features.push_back(std::move(feature));
}
std::sort(features.begin(), features.end());
auto const end = std::unique(features.begin(), features.end());
std::ofstream of(output_path + "/ci/etc/full_feature_list");
std::copy(features.begin(), end,
std::ostream_iterator<std::string>(of, "\n"));
return 0;
}
} // namespace
/**
* C++ microgenerator.
*
* @par Command line arguments:
* --config-file=<path> REQUIRED should be a textproto file for
* GeneratorConfiguration message.
* --protobuf_proto_path=<path> REQUIRED path to .proto files distributed with
* protobuf.
* --googleapis_proto_path=<path> REQUIRED path to .proto files distributed
* with googleapis repo.
* --output_path=<path> OPTIONAL defaults to current directory.
*/
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
google::cloud::LogSink::EnableStdClog(
google::cloud::Severity::GCP_LS_WARNING);
auto proto_path = absl::GetFlag(FLAGS_protobuf_proto_path);
auto googleapis_path = absl::GetFlag(FLAGS_googleapis_proto_path);
auto config_file = absl::GetFlag(FLAGS_config_file);
auto output_path = absl::GetFlag(FLAGS_output_path);
auto scaffold = absl::GetFlag(FLAGS_scaffold);
GCP_LOG(INFO) << "proto_path = " << proto_path << "\n";
GCP_LOG(INFO) << "googleapis_path = " << googleapis_path << "\n";
GCP_LOG(INFO) << "config_file = " << config_file << "\n";
GCP_LOG(INFO) << "output_path = " << output_path << "\n";
auto config = GetConfig(config_file);
if (!config.ok()) {
GCP_LOG(ERROR) << "Failed to parse config file: " << config_file << "\n";
}
auto const install_result = WriteInstallDirectories(*config, output_path);
if (install_result != 0) return install_result;
auto const features_result = WriteFeatureList(*config, output_path);
if (features_result != 0) return features_result;
std::vector<std::future<google::cloud::Status>> tasks;
for (auto const& service : config->service()) {
if (service.product_path() == scaffold) {
google::cloud::generator_internal::GenerateScaffold(googleapis_path,
output_path, service);
}
std::vector<std::string> args;
// empty arg prevents first real arg from being ignored.
args.emplace_back("");
args.emplace_back("--proto_path=" + proto_path);
args.emplace_back("--proto_path=" + googleapis_path);
args.emplace_back("--cpp_codegen_out=" + output_path);
args.emplace_back("--cpp_codegen_opt=product_path=" +
service.product_path());
args.emplace_back("--cpp_codegen_opt=copyright_year=" +
service.initial_copyright_year());
for (auto const& omit_service : service.omitted_services()) {
args.emplace_back("--cpp_codegen_opt=omit_service=" + omit_service);
}
for (auto const& omit_rpc : service.omitted_rpcs()) {
args.emplace_back("--cpp_codegen_opt=omit_rpc=" + omit_rpc);
}
if (service.backwards_compatibility_namespace_alias()) {
args.emplace_back(
"--cpp_codegen_opt=backwards_compatibility_namespace_alias=true");
}
for (auto const& retry_code : service.retryable_status_codes()) {
args.emplace_back("--cpp_codegen_opt=retry_status_code=" + retry_code);
}
if (service.omit_client()) {
args.emplace_back("--cpp_codegen_opt=omit_client=true");
}
if (service.omit_connection()) {
args.emplace_back("--cpp_codegen_opt=omit_connection=true");
}
if (service.omit_stub_factory()) {
args.emplace_back("--cpp_codegen_opt=omit_stub_factory=true");
}
args.emplace_back("--cpp_codegen_opt=service_endpoint_env_var=" +
service.service_endpoint_env_var());
args.emplace_back("--cpp_codegen_opt=emulator_endpoint_env_var=" +
service.emulator_endpoint_env_var());
for (auto const& gen_async_rpc : service.gen_async_rpcs()) {
args.emplace_back("--cpp_codegen_opt=gen_async_rpc=" + gen_async_rpc);
}
for (auto const& additional_proto_file : service.additional_proto_files()) {
args.emplace_back("--cpp_codegen_opt=additional_proto_file=" +
additional_proto_file);
}
args.emplace_back(service.service_proto_path());
for (auto const& additional_proto_file : service.additional_proto_files()) {
args.emplace_back(additional_proto_file);
}
GCP_LOG(INFO) << "Generating service code using: "
<< absl::StrJoin(args, ";") << "\n";
tasks.push_back(std::async(std::launch::async, [args] {
google::protobuf::compiler::CommandLineInterface cli;
google::cloud::generator::Generator generator;
cli.RegisterGenerator("--cpp_codegen_out", "--cpp_codegen_opt",
&generator, "Codegen C++ Generator");
std::vector<char const*> c_args;
c_args.reserve(args.size());
for (auto const& arg : args) {
c_args.push_back(arg.c_str());
}
if (cli.Run(static_cast<int>(c_args.size()), c_args.data()) != 0)
return google::cloud::Status(google::cloud::StatusCode::kInternal,
absl::StrCat("Generating service from ",
c_args.back(), " failed."));
return google::cloud::Status{};
}));
}
std::string error_message;
for (auto& t : tasks) {
auto result = t.get();
if (!result.ok()) {
absl::StrAppend(&error_message, result.message(), "\n");
}
}
if (!error_message.empty()) {
GCP_LOG(ERROR) << error_message;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <array>
#include <memory>
#include <string>
#include "soma_clustering_test.h"
#include "base_simulation_test.h"
#include "param.h"
#include "matrix.h"
#include "sim_state_serialization_util.h"
#include "cells/cell.h"
#include "cells/cell_factory.h"
#include "local_biology/abstract_local_biology_module.h"
#include "local_biology/cell_element.h"
#include "local_biology/neurite_element.h"
#include "local_biology/local_biology_module.h"
#include "physics/substance.h"
#include "physics/default_force.h"
#include "physics/physical_node_movement_listener.h"
#include "simulation/ecm.h"
#include "simulation/scheduler.h"
using namespace bdm;
using cells::Cell;
using cells::CellFactory;
using local_biology::CellElement;
using local_biology::NeuriteElement;
using local_biology::AbstractLocalBiologyModule;
using local_biology::LocalBiologyModule;
using physics::PhysicalNode;
using physics::Substance;
using physics::DefaultForce;
using physics::PhysicalObject;
using physics::PhysicalNodeMovementListener;
using simulation::ECM;
using simulation::Scheduler;
using spatial_organization::SpaceNode;
using synapse::Excrescence;
std::vector<physics::PhysicalNode::UPtr> physical_nodes;
void simulate()
{
auto ecm = ECM::getInstance();
Random::setSeed(1L);
PhysicalNodeMovementListener::setMovementOperationId((int)(10000 * Random::nextDouble()));
auto yellow_substance = Substance::UPtr(new Substance("Yellow", 1000, 0.01));
auto violet_substance = Substance::UPtr(new Substance("Violet", 1000, 0.01));
ecm->addNewSubstanceTemplate(std::move(yellow_substance));
ecm->addNewSubstanceTemplate(std::move(violet_substance));
for (int i = 0; i < 400; i++) {
physical_nodes.push_back(ecm->createPhysicalNodeInstance(Random::nextNoise(700)));
}
for (int i = 0; i < 60; i++) {
auto c = CellFactory::getCellInstance(Random::nextNoise(50));
c->getSomaElement()->addLocalBiologyModule(LocalBiologyModule::UPtr { new SomaClustering("Yellow") });
c->setColorForAllPhysicalObjects(Param::kYellowSolid);
}
for (int i = 0; i < 60; i++) {
auto c = CellFactory::getCellInstance(Random::nextNoise(50));
c->getSomaElement()->addLocalBiologyModule(LocalBiologyModule::UPtr { new SomaClustering("Violet") });
c->setColorForAllPhysicalObjects(Param::kVioletSolid);
}
auto scheduler = Scheduler::getInstance();
for (int i = 0; i < 1000; i++) {
scheduler->simulateOneStep();
}
}
int soma_clustering()
{
// Run the soma clsutering test
// setup
ECM::getInstance()->clearAll();
Cell::reset();
CellElement::reset();
PhysicalNode::reset();
SpaceNode < PhysicalNode > ::reset();
Random::setSeed(1L);
PhysicalObject::setInterObjectForce(DefaultForce::UPtr(new DefaultForce()));
// run simulation
gROOT->Time();
simulate();
return 0;
}<commit_msg>Added missing include needed when compiling via ROOT ACLiC.<commit_after>#include <array>
#include <memory>
#include <string>
#include <TROOT.h>
#include "soma_clustering_test.h"
#include "base_simulation_test.h"
#include "param.h"
#include "matrix.h"
#include "sim_state_serialization_util.h"
#include "cells/cell.h"
#include "cells/cell_factory.h"
#include "local_biology/abstract_local_biology_module.h"
#include "local_biology/cell_element.h"
#include "local_biology/neurite_element.h"
#include "local_biology/local_biology_module.h"
#include "physics/substance.h"
#include "physics/default_force.h"
#include "physics/physical_node_movement_listener.h"
#include "simulation/ecm.h"
#include "simulation/scheduler.h"
using namespace bdm;
using cells::Cell;
using cells::CellFactory;
using local_biology::CellElement;
using local_biology::NeuriteElement;
using local_biology::AbstractLocalBiologyModule;
using local_biology::LocalBiologyModule;
using physics::PhysicalNode;
using physics::Substance;
using physics::DefaultForce;
using physics::PhysicalObject;
using physics::PhysicalNodeMovementListener;
using simulation::ECM;
using simulation::Scheduler;
using spatial_organization::SpaceNode;
using synapse::Excrescence;
std::vector<physics::PhysicalNode::UPtr> physical_nodes;
void simulate()
{
auto ecm = ECM::getInstance();
Random::setSeed(1L);
PhysicalNodeMovementListener::setMovementOperationId((int)(10000 * Random::nextDouble()));
auto yellow_substance = Substance::UPtr(new Substance("Yellow", 1000, 0.01));
auto violet_substance = Substance::UPtr(new Substance("Violet", 1000, 0.01));
ecm->addNewSubstanceTemplate(std::move(yellow_substance));
ecm->addNewSubstanceTemplate(std::move(violet_substance));
for (int i = 0; i < 400; i++) {
physical_nodes.push_back(ecm->createPhysicalNodeInstance(Random::nextNoise(700)));
}
for (int i = 0; i < 60; i++) {
auto c = CellFactory::getCellInstance(Random::nextNoise(50));
c->getSomaElement()->addLocalBiologyModule(LocalBiologyModule::UPtr { new SomaClustering("Yellow") });
c->setColorForAllPhysicalObjects(Param::kYellowSolid);
}
for (int i = 0; i < 60; i++) {
auto c = CellFactory::getCellInstance(Random::nextNoise(50));
c->getSomaElement()->addLocalBiologyModule(LocalBiologyModule::UPtr { new SomaClustering("Violet") });
c->setColorForAllPhysicalObjects(Param::kVioletSolid);
}
auto scheduler = Scheduler::getInstance();
for (int i = 0; i < 1000; i++) {
scheduler->simulateOneStep();
}
}
int soma_clustering()
{
// Run the soma clsutering test
// setup
ECM::getInstance()->clearAll();
Cell::reset();
CellElement::reset();
PhysicalNode::reset();
SpaceNode < PhysicalNode > ::reset();
Random::setSeed(1L);
PhysicalObject::setInterObjectForce(DefaultForce::UPtr(new DefaultForce()));
// run simulation
gROOT->Time();
simulate();
return 0;
}
<|endoftext|> |
<commit_before>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes( T &s )
{
if( sizeof( T ) == 1 ) return;
T d = s;
BytePtr sptr = (BytePtr)&s;
BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);
for( unsigned int i = 0; i < sizeof(T); i++ )
*(sptr++) = *(dptr--);
}
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = 0x12345678;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void checkByteOrder( void )
{
if( _byte_order == 0x78563412 ) // We're backwards
{
swapBytes( _byte_order );
swapBytes( _masterKilled );
for( int i = 0; i < 16; i++ )
swapBytes( _matrix.ptr()[i] );
// umm.. we should byte swap _frameStamp too...
}
}
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned long _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
};
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
float socketNumber=8100.0f;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=45.0f;
while (arguments.read("-f",camera_fov))
{
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,camera_fov*viewer.getLensVerticalFov()/viewer.getLensHorizontalFov(),1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
CameraPacket cp;
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp.setPacket(modelview,viewer.getFrameStamp());
bc.setBuffer(&cp, sizeof( CameraPacket ));
bc.sync();
}
break;
case(SLAVE):
{
CameraPacket cp;
rc.setBuffer(&cp, sizeof( CameraPacket ));
rc.sync();
cp.checkByteOrder();
osg::Matrix modelview;
cp.getModelView(modelview,camera_offset);
viewer.setView(modelview);
if (cp.getMasterKilled())
{
std::cout << "received master killed"<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
CameraPacket cp;
cp.setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp.setMasterKilled(true);
bc.setBuffer(&cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "broadcasting death"<<std::endl;
}
return 0;
}
<commit_msg>Fixed tabbing.<commit_after>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes( T &s )
{
if( sizeof( T ) == 1 ) return;
T d = s;
BytePtr sptr = (BytePtr)&s;
BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);
for( unsigned int i = 0; i < sizeof(T); i++ )
*(sptr++) = *(dptr--);
}
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = 0x12345678;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void checkByteOrder( void )
{
if( _byte_order == 0x78563412 ) // We're backwards
{
swapBytes( _byte_order );
swapBytes( _masterKilled );
for( int i = 0; i < 16; i++ )
swapBytes( _matrix.ptr()[i] );
// umm.. we should byte swap _frameStamp too...
}
}
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned long _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
};
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
float socketNumber=8100.0f;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=45.0f;
while (arguments.read("-f",camera_fov))
{
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,camera_fov*viewer.getLensVerticalFov()/viewer.getLensHorizontalFov(),1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
CameraPacket cp;
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp.setPacket(modelview,viewer.getFrameStamp());
bc.setBuffer(&cp, sizeof( CameraPacket ));
bc.sync();
}
break;
case(SLAVE):
{
CameraPacket cp;
rc.setBuffer(&cp, sizeof( CameraPacket ));
rc.sync();
cp.checkByteOrder();
osg::Matrix modelview;
cp.getModelView(modelview,camera_offset);
viewer.setView(modelview);
if (cp.getMasterKilled())
{
std::cout << "received master killed"<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
CameraPacket cp;
cp.setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp.setMasterKilled(true);
bc.setBuffer(&cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "broadcasting death"<<std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "sparse.h"
template<typename Scalar> void sparse_vector(int rows, int cols)
{
double densityMat = (std::max)(8./(rows*cols), 0.01);
double densityVec = (std::max)(8./float(rows), 0.1);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
typedef SparseVector<Scalar> SparseVectorType;
typedef SparseMatrix<Scalar> SparseMatrixType;
Scalar eps = 1e-6;
SparseMatrixType m1(rows,rows);
SparseVectorType v1(rows), v2(rows), v3(rows);
DenseMatrix refM1 = DenseMatrix::Zero(rows, rows);
DenseVector refV1 = DenseVector::Random(rows),
refV2 = DenseVector::Random(rows),
refV3 = DenseVector::Random(rows);
std::vector<int> zerocoords, nonzerocoords;
initSparse<Scalar>(densityVec, refV1, v1, &zerocoords, &nonzerocoords);
initSparse<Scalar>(densityMat, refM1, m1);
initSparse<Scalar>(densityVec, refV2, v2);
initSparse<Scalar>(densityVec, refV3, v3);
Scalar s1 = internal::random<Scalar>();
// test coeff and coeffRef
for (unsigned int i=0; i<zerocoords.size(); ++i)
{
VERIFY_IS_MUCH_SMALLER_THAN( v1.coeff(zerocoords[i]), eps );
//VERIFY_RAISES_ASSERT( v1.coeffRef(zerocoords[i]) = 5 );
}
{
VERIFY(int(nonzerocoords.size()) == v1.nonZeros());
int j=0;
for (typename SparseVectorType::InnerIterator it(v1); it; ++it,++j)
{
VERIFY(nonzerocoords[j]==it.index());
VERIFY(it.value()==v1.coeff(it.index()));
VERIFY(it.value()==refV1.coeff(it.index()));
}
}
VERIFY_IS_APPROX(v1, refV1);
v1.coeffRef(nonzerocoords[0]) = Scalar(5);
refV1.coeffRef(nonzerocoords[0]) = Scalar(5);
VERIFY_IS_APPROX(v1, refV1);
VERIFY_IS_APPROX(v1+v2, refV1+refV2);
VERIFY_IS_APPROX(v1+v2+v3, refV1+refV2+refV3);
VERIFY_IS_APPROX(v1*s1-v2, refV1*s1-refV2);
VERIFY_IS_APPROX(v1*=s1, refV1*=s1);
VERIFY_IS_APPROX(v1/=s1, refV1/=s1);
VERIFY_IS_APPROX(v1+=v2, refV1+=refV2);
VERIFY_IS_APPROX(v1-=v2, refV1-=refV2);
VERIFY_IS_APPROX(v1.dot(v2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(refV2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(m1*v2), refV1.dot(refM1*refV2));
int i = internal::random<int>(0,rows-1);
VERIFY_IS_APPROX(v1.dot(m1.col(i)), refV1.dot(refM1.col(i)));
VERIFY_IS_APPROX(v1.squaredNorm(), refV1.squaredNorm());
// test aliasing
VERIFY_IS_APPROX((v1 = -v1), (refV1 = -refV1));
VERIFY_IS_APPROX((v1 = v1.transpose()), (refV1 = refV1.transpose().eval()));
VERIFY_IS_APPROX((v1 += -v1), (refV1 += -refV1));
}
void test_sparse_vector()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( sparse_vector<double>(8, 8) );
CALL_SUBTEST_2( sparse_vector<std::complex<double> >(16, 16) );
CALL_SUBTEST_1( sparse_vector<double>(299, 535) );
}
}
<commit_msg>Test for the sparse Blue norm<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "sparse.h"
template<typename Scalar> void sparse_vector(int rows, int cols)
{
double densityMat = (std::max)(8./(rows*cols), 0.01);
double densityVec = (std::max)(8./float(rows), 0.1);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
typedef SparseVector<Scalar> SparseVectorType;
typedef SparseMatrix<Scalar> SparseMatrixType;
Scalar eps = 1e-6;
SparseMatrixType m1(rows,rows);
SparseVectorType v1(rows), v2(rows), v3(rows);
DenseMatrix refM1 = DenseMatrix::Zero(rows, rows);
DenseVector refV1 = DenseVector::Random(rows),
refV2 = DenseVector::Random(rows),
refV3 = DenseVector::Random(rows);
std::vector<int> zerocoords, nonzerocoords;
initSparse<Scalar>(densityVec, refV1, v1, &zerocoords, &nonzerocoords);
initSparse<Scalar>(densityMat, refM1, m1);
initSparse<Scalar>(densityVec, refV2, v2);
initSparse<Scalar>(densityVec, refV3, v3);
Scalar s1 = internal::random<Scalar>();
// test coeff and coeffRef
for (unsigned int i=0; i<zerocoords.size(); ++i)
{
VERIFY_IS_MUCH_SMALLER_THAN( v1.coeff(zerocoords[i]), eps );
//VERIFY_RAISES_ASSERT( v1.coeffRef(zerocoords[i]) = 5 );
}
{
VERIFY(int(nonzerocoords.size()) == v1.nonZeros());
int j=0;
for (typename SparseVectorType::InnerIterator it(v1); it; ++it,++j)
{
VERIFY(nonzerocoords[j]==it.index());
VERIFY(it.value()==v1.coeff(it.index()));
VERIFY(it.value()==refV1.coeff(it.index()));
}
}
VERIFY_IS_APPROX(v1, refV1);
v1.coeffRef(nonzerocoords[0]) = Scalar(5);
refV1.coeffRef(nonzerocoords[0]) = Scalar(5);
VERIFY_IS_APPROX(v1, refV1);
VERIFY_IS_APPROX(v1+v2, refV1+refV2);
VERIFY_IS_APPROX(v1+v2+v3, refV1+refV2+refV3);
VERIFY_IS_APPROX(v1*s1-v2, refV1*s1-refV2);
VERIFY_IS_APPROX(v1*=s1, refV1*=s1);
VERIFY_IS_APPROX(v1/=s1, refV1/=s1);
VERIFY_IS_APPROX(v1+=v2, refV1+=refV2);
VERIFY_IS_APPROX(v1-=v2, refV1-=refV2);
VERIFY_IS_APPROX(v1.dot(v2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(refV2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(m1*v2), refV1.dot(refM1*refV2));
int i = internal::random<int>(0,rows-1);
VERIFY_IS_APPROX(v1.dot(m1.col(i)), refV1.dot(refM1.col(i)));
VERIFY_IS_APPROX(v1.squaredNorm(), refV1.squaredNorm());
VERIFY_IS_APPROX(v1.blueNorm(), refV1.blueNorm());
// test aliasing
VERIFY_IS_APPROX((v1 = -v1), (refV1 = -refV1));
VERIFY_IS_APPROX((v1 = v1.transpose()), (refV1 = refV1.transpose().eval()));
VERIFY_IS_APPROX((v1 += -v1), (refV1 += -refV1));
}
void test_sparse_vector()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( sparse_vector<double>(8, 8) );
CALL_SUBTEST_2( sparse_vector<std::complex<double> >(16, 16) );
CALL_SUBTEST_1( sparse_vector<double>(299, 535) );
}
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include <iphlpapi.h>
void GetMACAddresses(unsigned char*& paiAddresses, size_t& iAddresses)
{
static unsigned char aiAddresses[16][8];
IP_ADAPTER_INFO AdapterInfo[16];
DWORD dwBufLen = sizeof(AdapterInfo);
DWORD dwStatus = GetAdaptersInfo(
AdapterInfo,
&dwBufLen);
iAddresses = 0;
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
do {
// Use only ethernet, not wireless controllers. They are more reliable and wireless controllers get disabled sometimes.
if (pAdapterInfo->Type != MIB_IF_TYPE_ETHERNET)
continue;
// Skip virtual controllers, they can be changed or disabled.
if (strstr(pAdapterInfo->Description, "VMware"))
continue;
if (strstr(pAdapterInfo->Description, "Hamachi"))
continue;
memcpy(aiAddresses[iAddresses++], pAdapterInfo->Address, sizeof(char)*8);
}
while(pAdapterInfo = pAdapterInfo->Next);
paiAddresses = &aiAddresses[0][0];
}
<commit_msg>Skip USB controllers when looking for a physical address, they can be unplugged.<commit_after>#include <windows.h>
#include <iphlpapi.h>
void GetMACAddresses(unsigned char*& paiAddresses, size_t& iAddresses)
{
static unsigned char aiAddresses[16][8];
IP_ADAPTER_INFO AdapterInfo[16];
DWORD dwBufLen = sizeof(AdapterInfo);
DWORD dwStatus = GetAdaptersInfo(
AdapterInfo,
&dwBufLen);
iAddresses = 0;
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
do {
// Use only ethernet, not wireless controllers. They are more reliable and wireless controllers get disabled sometimes.
if (pAdapterInfo->Type != MIB_IF_TYPE_ETHERNET)
continue;
// Skip virtual controllers, they can be changed or disabled.
if (strstr(pAdapterInfo->Description, "VMware"))
continue;
if (strstr(pAdapterInfo->Description, "Hamachi"))
continue;
// Skip USB controllers, they can be unplugged.
if (strstr(pAdapterInfo->Description, "USB"))
continue;
memcpy(aiAddresses[iAddresses++], pAdapterInfo->Address, sizeof(char)*8);
}
while(pAdapterInfo = pAdapterInfo->Next);
paiAddresses = &aiAddresses[0][0];
}
<|endoftext|> |
<commit_before>#include "DeadScreen.hpp"
//-- Public
const std::string rd::DeadScreen::PARAM_REMAINING_TIME = "remaining_time";
const std::string rd::DeadScreen::PARAM_LAST_CAMERA_FRAME = "last_camera_frame";
//-- Protected
const std::string rd::DeadScreen::SKULL_PATH = "../images/skull.png";
const std::string rd::DeadScreen::FONT_PATH = "../fonts/FreeMono.ttf";
//-- Private
const SDL_Color rd::DeadScreen::TEXT_COLOR = {0,255,0,0};
rd::DeadScreen::DeadScreen()
{
}
bool rd::DeadScreen::init()
{
//-- Find the real path to the resources with ResourceFinder
yarp::os::ResourceFinder rf;
rf.setDefaultContext("robotDevastation");
rf.setDefaultConfigFile("robotDevastation.ini");
//-- Load skull image resource
skull_image = IMG_Load(rf.findFileByName(SKULL_PATH).c_str());
if (skull_image == NULL)
{
RD_ERROR("Unable to load skull image (resource: %s)!\n SDL_image Error: %s\n", SKULL_PATH.c_str(), IMG_GetError())
return false;
}
//-- Load the font
font = TTF_OpenFont(rf.findFileByName(FONT_PATH).c_str(), 32);
if (font == NULL)
{
RD_ERROR("Unable to load font: %s %s \n", rf.findFileByName(FONT_PATH).c_str(), TTF_GetError());
return false;
}
window = NULL;
//-- Default values:
this->camera_frame = NULL;
this->update(PARAM_REMAINING_TIME, "10");
return true;
}
bool rd::DeadScreen::cleanup()
{
SDL_FreeSurface(screen);
SDL_FreeSurface(skull_image);
SDL_FreeSurface(text_surface);
if (camera_frame)
SDL_FreeSurface(camera_frame);
SDL_DestroyWindow(window);
screen = NULL;
window = NULL;
skull_image = NULL;
camera_frame = NULL;
}
bool rd::DeadScreen::show()
{
if (window == NULL)
{
//-- Init screen
window = SDL_CreateWindow("Robot Devastation",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
skull_image->w,
skull_image->h,
0); // 16, SDL_DOUBLEBUF // SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL
if (!window)
{
RD_ERROR("Unable to set video mode: %s\n", SDL_GetError());
return false;
}
//Get window surface
screen = SDL_GetWindowSurface( window );
}
//-- Clear screen
SDL_FillRect(screen, NULL, 0xFFFFFF);
if (camera_frame)
{
//-- Draw camera frame
SDL_Rect camera_frame_rect = {0,0, camera_frame->w, camera_frame->h};
SDL_BlitSurface(camera_frame, NULL, screen, &camera_frame_rect);
//-- Draw skull
SDL_Rect skull_rect = {(camera_frame->w-skull_image->w)/2,(camera_frame->h-skull_image->h)/2,
skull_image->w, skull_image->h};
SDL_BlitSurface(skull_image, NULL, screen, &skull_rect);
//-- Draw text
SDL_Rect text_rect = {(camera_frame->w-text_surface->w)/2,camera_frame->h-text_surface->h,
text_surface->w, text_surface->h};
SDL_BlitSurface(text_surface, NULL, screen, &text_rect);
}
else
{
//-- Draw skull
SDL_Rect skull_rect = {0,0, skull_image->w, skull_image->h};
SDL_BlitSurface(skull_image, NULL, screen, &skull_rect);
//-- Draw text
SDL_Rect text_rect = {(skull_image->w-text_surface->w)/2,skull_image->h-text_surface->h, text_surface->w, text_surface->h};
SDL_BlitSurface(text_surface, NULL, screen, &text_rect);
}
SDL_UpdateWindowSurface(window); //Refresh the screen
SDL_Delay(20); //Wait a bit :)
return true;
}
rd::DeadScreen::~DeadScreen()
{
}
bool rd::DeadScreen::update(std::string parameter, std::string value)
{
if (parameter == PARAM_REMAINING_TIME)
{
//-- Create new text from font
remaining_time = value;
text_surface = TTF_RenderText_Solid(font, ("Respawn in: "+remaining_time+"s").c_str(), TEXT_COLOR);
return true;
}
RD_ERROR("No string parameter %s exists.\n", parameter.c_str());
return false;
}
bool rd::DeadScreen::update(std::string parameter, rd::RdImage value)
{
if (value.width() == 0 || value.height() == 0)
{
RD_ERROR("Invalid image");
return false;
}
if (parameter == PARAM_LAST_CAMERA_FRAME)
{
last_camera_frame = RdImage(value);
//-- Convert from RdImage to SDL
camera_frame = RdImage2SDLImage(last_camera_frame);
//-- Set new window size
window = SDL_CreateWindow("Robot Devastation",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
camera_frame->w,
camera_frame->h,
0); // 16, SDL_DOUBLEBUF // SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL
if (!window)
{
RD_ERROR("Unable to set video mode: %s\n", SDL_GetError());
return false;
}
//Get window surface
screen = SDL_GetWindowSurface( window );
return true;
}
RD_ERROR("No RdImage parameter %s exists.\n", parameter.c_str());
return false;
}
<commit_msg>Change DeadScreen font to bold to increase legibility<commit_after>#include "DeadScreen.hpp"
//-- Public
const std::string rd::DeadScreen::PARAM_REMAINING_TIME = "remaining_time";
const std::string rd::DeadScreen::PARAM_LAST_CAMERA_FRAME = "last_camera_frame";
//-- Protected
const std::string rd::DeadScreen::SKULL_PATH = "../images/skull.png";
const std::string rd::DeadScreen::FONT_PATH = "../fonts/FreeMono.ttf";
//-- Private
const SDL_Color rd::DeadScreen::TEXT_COLOR = {0,255,0,0};
rd::DeadScreen::DeadScreen()
{
}
bool rd::DeadScreen::init()
{
//-- Find the real path to the resources with ResourceFinder
yarp::os::ResourceFinder rf;
rf.setDefaultContext("robotDevastation");
rf.setDefaultConfigFile("robotDevastation.ini");
//-- Load skull image resource
skull_image = IMG_Load(rf.findFileByName(SKULL_PATH).c_str());
if (skull_image == NULL)
{
RD_ERROR("Unable to load skull image (resource: %s)!\n SDL_image Error: %s\n", SKULL_PATH.c_str(), IMG_GetError())
return false;
}
//-- Load the font
font = TTF_OpenFont(rf.findFileByName(FONT_PATH).c_str(), 32);
if (font == NULL)
{
RD_ERROR("Unable to load font: %s %s \n", rf.findFileByName(FONT_PATH).c_str(), TTF_GetError());
return false;
}
TTF_SetFontStyle(font, TTF_STYLE_BOLD);
window = NULL;
//-- Default values:
this->camera_frame = NULL;
this->update(PARAM_REMAINING_TIME, "10");
return true;
}
bool rd::DeadScreen::cleanup()
{
SDL_FreeSurface(screen);
SDL_FreeSurface(skull_image);
SDL_FreeSurface(text_surface);
if (camera_frame)
SDL_FreeSurface(camera_frame);
SDL_DestroyWindow(window);
screen = NULL;
window = NULL;
skull_image = NULL;
camera_frame = NULL;
}
bool rd::DeadScreen::show()
{
if (window == NULL)
{
//-- Init screen
window = SDL_CreateWindow("Robot Devastation",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
skull_image->w,
skull_image->h,
0); // 16, SDL_DOUBLEBUF // SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL
if (!window)
{
RD_ERROR("Unable to set video mode: %s\n", SDL_GetError());
return false;
}
//Get window surface
screen = SDL_GetWindowSurface( window );
}
//-- Clear screen
SDL_FillRect(screen, NULL, 0xFFFFFF);
if (camera_frame)
{
//-- Draw camera frame
SDL_Rect camera_frame_rect = {0,0, camera_frame->w, camera_frame->h};
SDL_BlitSurface(camera_frame, NULL, screen, &camera_frame_rect);
//-- Draw skull
SDL_Rect skull_rect = {(camera_frame->w-skull_image->w)/2,(camera_frame->h-skull_image->h)/2,
skull_image->w, skull_image->h};
SDL_BlitSurface(skull_image, NULL, screen, &skull_rect);
//-- Draw text
SDL_Rect text_rect = {(camera_frame->w-text_surface->w)/2,camera_frame->h-text_surface->h,
text_surface->w, text_surface->h};
SDL_BlitSurface(text_surface, NULL, screen, &text_rect);
}
else
{
//-- Draw skull
SDL_Rect skull_rect = {0,0, skull_image->w, skull_image->h};
SDL_BlitSurface(skull_image, NULL, screen, &skull_rect);
//-- Draw text
SDL_Rect text_rect = {(skull_image->w-text_surface->w)/2,skull_image->h-text_surface->h, text_surface->w, text_surface->h};
SDL_BlitSurface(text_surface, NULL, screen, &text_rect);
}
SDL_UpdateWindowSurface(window); //Refresh the screen
SDL_Delay(20); //Wait a bit :)
return true;
}
rd::DeadScreen::~DeadScreen()
{
}
bool rd::DeadScreen::update(std::string parameter, std::string value)
{
if (parameter == PARAM_REMAINING_TIME)
{
//-- Create new text from font
remaining_time = value;
text_surface = TTF_RenderText_Solid(font, ("Respawn in: "+remaining_time+"s").c_str(), TEXT_COLOR);
return true;
}
RD_ERROR("No string parameter %s exists.\n", parameter.c_str());
return false;
}
bool rd::DeadScreen::update(std::string parameter, rd::RdImage value)
{
if (value.width() == 0 || value.height() == 0)
{
RD_ERROR("Invalid image");
return false;
}
if (parameter == PARAM_LAST_CAMERA_FRAME)
{
last_camera_frame = RdImage(value);
//-- Convert from RdImage to SDL
camera_frame = RdImage2SDLImage(last_camera_frame);
//-- Set new window size
window = SDL_CreateWindow("Robot Devastation",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
camera_frame->w,
camera_frame->h,
0); // 16, SDL_DOUBLEBUF // SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL
if (!window)
{
RD_ERROR("Unable to set video mode: %s\n", SDL_GetError());
return false;
}
//Get window surface
screen = SDL_GetWindowSurface( window );
return true;
}
RD_ERROR("No RdImage parameter %s exists.\n", parameter.c_str());
return false;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
if (meta_class->name().startsWith("QtScript")) return false;
if (meta_class->name().startsWith("QFuture")) return false;
if (meta_class->name().startsWith("Global")) return false;
if (meta_class->name().startsWith("QStyleOptionComplex")) return false;
if (meta_class->name().startsWith("QTextLayout")) return false;
//if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators
//if (meta_class->name().startsWith("QDataStream")) return false; // "
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName))
s << " " << arg->argumentName();
if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->originalDefaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
if (expr.contains("defaultConnection")) {
expr.replace("defaultConnection","QSqlDatabase::defaultConnection");
}
if (expr == "MediaSource()") {
expr = "Phonon::MediaSource()";
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
s << name_prefix << function_name;
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "_setter";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "_getter";
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
resultFunctions << func;
}
}
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
// | AbstractMetaClass::NotRemovedFromTargetLang
);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (!func->isPublic() || func->isVirtual()) {
functions << func;
}
}
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<commit_msg>added alphabetic sorting<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
if (meta_class->name().startsWith("QtScript")) return false;
if (meta_class->name().startsWith("QFuture")) return false;
if (meta_class->name().startsWith("Global")) return false;
if (meta_class->name().startsWith("QStyleOptionComplex")) return false;
if (meta_class->name().startsWith("QTextLayout")) return false;
//if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators
//if (meta_class->name().startsWith("QDataStream")) return false; // "
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName))
s << " " << arg->argumentName();
if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->originalDefaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
if (expr.contains("defaultConnection")) {
expr.replace("defaultConnection","QSqlDatabase::defaultConnection");
}
if (expr == "MediaSource()") {
expr = "Phonon::MediaSource()";
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
s << name_prefix << function_name;
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "_setter";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "_getter";
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
resultFunctions << func;
}
}
qStableSort(resultFunctions);
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
// | AbstractMetaClass::NotRemovedFromTargetLang
);
qStableSort(functions);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (!func->isPublic() || func->isVirtual()) {
functions << func;
}
}
qStableSort(functions);
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial applications,
* as long as this copyright notice is maintained.
*
* This application 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.
*/
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <Demeter/Terrain.h>
#include <Demeter/Loader.h>
#include <Demeter/DemeterDrawable.h>
Demeter::Terrain* loadTerrain()
{
#ifdef _WIN32
char fileSeparator = '\\';
#else
char fileSeparator = '/';
#endif
char szMediaPath[17];
sprintf(szMediaPath,"..%cdata%cLlano",fileSeparator,fileSeparator);
Demeter::Settings::GetInstance()->SetMediaPath(szMediaPath);
// Load a terrain that was generated in the Demeter Texture Editor
Demeter::Terrain* pTerrain = new Demeter::Terrain();
try
{
#ifdef _DEBUG
Demeter::Loader::GetInstance()->LoadElevations("DemeterElevationLoaderDebug","Llano.terrain",pTerrain);
Demeter::Loader::GetInstance()->LoadTerrainTexture("DemeterTextureLoaderDebug","Llano.terrain",pTerrain);
#else
Demeter::Loader::GetInstance()->LoadElevations("DemeterElevationLoader","Llano.terrain",pTerrain);
Demeter::Loader::GetInstance()->LoadTerrainTexture("DemeterTextureLoader","Llano.terrain",pTerrain);
#endif
}
catch(Demeter::DemeterException* pEx)
{
std::cerr<<pEx->GetErrorMessage()<<std::endl;
return 0;
}
return pTerrain;
}
osg::Node* createSceneWithTerrain(Demeter::Terrain* pTerrain)
{
Demeter::DemeterDrawable* pDrawable = new Demeter::DemeterDrawable;
pDrawable->SetTerrain(pTerrain);
osg::Geode* pGeode = new osg::Geode;
pGeode->addDrawable(pDrawable);
float detailThreshold = 9.0f;
pTerrain->SetDetailThreshold(detailThreshold);
return pGeode;
}
class KeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
KeyboardEventHandler(Demeter::Terrain* pTerrain):
_pTerrain(pTerrain) {}
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='n')
{
_pTerrain->SetDetailThreshold(_pTerrain->GetDetailThreshold()+0.1f);
std::cout << "_pTerrain->GetDetailThreshold() = "<<_pTerrain->GetDetailThreshold() << std::endl;
return true;
}
else if (ea.getKey()=='n')
{
_pTerrain->SetDetailThreshold(_pTerrain->GetDetailThreshold()-0.1f);
std::cout << "_pTerrain->GetDetailThreshold() = "<<_pTerrain->GetDetailThreshold() << std::endl;
return true;
}
break;
}
default:
break;
}
return false;
}
virtual void accept(osgGA::GUIEventHandlerVisitor& v)
{
v.visit(*this);
}
Demeter::Terrain* _pTerrain;
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
//
// if (arguments.argc()<=1)
// {
// arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
// return 1;
// }
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
Demeter::Terrain* pTerrain = loadTerrain();
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = createSceneWithTerrain(pTerrain);
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
std::cout << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
// set the scene to render
viewer.setSceneData(loadedModel.get());
viewer.getEventHandlerList().push_front(new KeyboardEventHandler(pTerrain));
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>From Clay Fowler, fixes to osgdemeter so that the whole terrain model can be visualised at once.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This application is open source and may be redistributed and/or modified
* freely and without restriction, both in commericial and non commericial applications,
* as long as this copyright notice is maintained.
*
* This application 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.
*/
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <Demeter/Terrain.h>
#include <Demeter/Loader.h>
#include <Demeter/DemeterDrawable.h>
Demeter::Terrain* loadTerrain()
{
#ifdef _WIN32
char fileSeparator = '\\';
#else
char fileSeparator = '/';
#endif
char szMediaPath[17];
sprintf(szMediaPath,"..%cdata%cLlano",fileSeparator,fileSeparator);
Demeter::Settings::GetInstance()->SetMediaPath(szMediaPath);
Demeter::Settings::GetInstance()->SetTessellateMethod(Demeter::Settings::TM_2D_ROLLONLY);
// Load a terrain that was generated in the Demeter Texture Editor
Demeter::Terrain* pTerrain = new Demeter::Terrain(500000,0.0f,0.0f);
try
{
#ifdef _DEBUG
Demeter::Loader::GetInstance()->LoadElevations("DemeterElevationLoaderDebug","Llano.terrain",pTerrain);
Demeter::Loader::GetInstance()->LoadTerrainTexture("DemeterTextureLoaderDebug","Llano.terrain",pTerrain);
#else
Demeter::Loader::GetInstance()->LoadElevations("DemeterElevationLoader","Llano.terrain",pTerrain);
Demeter::Loader::GetInstance()->LoadTerrainTexture("DemeterTextureLoader","Llano.terrain",pTerrain);
#endif
}
catch(Demeter::DemeterException* pEx)
{
std::cerr<<pEx->GetErrorMessage()<<std::endl;
return 0;
}
return pTerrain;
}
osg::Node* createSceneWithTerrain(Demeter::Terrain* pTerrain)
{
Demeter::DemeterDrawable* pDrawable = new Demeter::DemeterDrawable;
pDrawable->SetTerrain(pTerrain);
osg::Geode* pGeode = new osg::Geode;
pGeode->addDrawable(pDrawable);
float detailThreshold = 9.0f;
pTerrain->SetDetailThreshold(detailThreshold);
return pGeode;
}
class KeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
KeyboardEventHandler(Demeter::Terrain* pTerrain):
_pTerrain(pTerrain) {}
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='n')
{
_pTerrain->SetDetailThreshold(_pTerrain->GetDetailThreshold()+0.1f);
std::cout << "_pTerrain->GetDetailThreshold() = "<<_pTerrain->GetDetailThreshold() << std::endl;
return true;
}
else if (ea.getKey()=='n')
{
_pTerrain->SetDetailThreshold(_pTerrain->GetDetailThreshold()-0.1f);
std::cout << "_pTerrain->GetDetailThreshold() = "<<_pTerrain->GetDetailThreshold() << std::endl;
return true;
}
break;
}
default:
break;
}
return false;
}
virtual void accept(osgGA::GUIEventHandlerVisitor& v)
{
v.visit(*this);
}
Demeter::Terrain* _pTerrain;
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
//
// if (arguments.argc()<=1)
// {
// arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
// return 1;
// }
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
Demeter::Terrain* pTerrain = loadTerrain();
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = createSceneWithTerrain(pTerrain);
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
std::cout << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
// set the scene to render
viewer.setSceneData(loadedModel.get());
viewer.getEventHandlerList().push_front(new KeyboardEventHandler(pTerrain));
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* *
* Copyright (c) 2016 Boris Pek <tehnick-8@yandex.ru> *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to *
* the following conditions: *
* *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
*****************************************************************************/
#include <QMap>
#include <QStringList>
#include "applicationsettings.h"
#include "resourcemanager.h"
#include "sessionsmanager.h"
#include "localization.h"
#include "htmlpage.h"
struct HtmlPage::HtmlPagePrivate
{
bool admin = false;
bool autorized = false;
QByteArray page;
QByteArray head;
QByteArray body;
QByteArray title;
QByteArray content;
QByteArray redirect;
QByteArray prefix;
QByteArray jquery;
CommonSettings commonSettings;
UserSettings userSettings;
Localization localization;
QMap<QByteArray, QByteArray> extraReplacements;
};
HtmlPage::HtmlPage(const Request &request) :
d(new HtmlPagePrivate)
{
d->prefix = APP_S().prefixString().toUtf8();
d->jquery = APP_S().jqueryUrl().toUtf8();
d->redirect = request.scriptName().toUtf8();
if (request.get("ajax").isEmpty()) {
const ResourceManager res;
setPage(res.read("/html/page-template.html"));
setTitle("%basic_title%");
setHead(res.read("/html/head-template.html"));
setBody(res.read("/html/body-template.html"));
setContent(res.read("/html/404-template.html"));
}
checkAutorization(request);
if (request.get("ajax").isEmpty()) {
d->localization.setFileName(d->commonSettings.l10nFile());
d->localization.readSettings();
setContentType("text/html");
update();
}
}
HtmlPage::~HtmlPage()
{
delete d;
}
void HtmlPage::setHead(const QByteArray &head)
{
d->head = head;
}
void HtmlPage::setBody(const QByteArray &body)
{
d->body = body;
}
void HtmlPage::setTitle(const QByteArray &title)
{
d->title = title;
}
void HtmlPage::setContent(const QByteArray &content)
{
d->content = content;
}
void HtmlPage::addToHead(const QByteArray &head)
{
setHead(d->head + "\n" + head);
}
void HtmlPage::addToBody(const QByteArray &body)
{
setBody(d->body + "\n" + body);
}
void HtmlPage::addToTitle(const QByteArray &title)
{
setTitle(d->title + title);
}
void HtmlPage::addToContent(const QByteArray &content)
{
setContent(d->content + "\n" + content);
}
void HtmlPage::addExtraReplacements(const QByteArray &from,
const QByteArray &to)
{
if (from.isEmpty())
return;
d->extraReplacements[from] = to;
}
void HtmlPage::addStyleSheetToHead(const QByteArray &styleSheet)
{
addToHead(" <link rel=\"stylesheet\" type=\"text/css\" href=\"" +
styleSheet + "\">\n");
}
void HtmlPage::addScriptToHead(const QByteArray &script)
{
addToHead(" <script src=\"" + script + "\"></script>");
}
bool HtmlPage::isAutorizedUser() const
{
return d->autorized;
}
bool HtmlPage::isAdmin() const
{
return d->admin;
}
void HtmlPage::setPage(const QByteArray &page)
{
d->page = page;
}
void HtmlPage::checkAutorization(const Request &request)
{
QByteArray out;
out += " <script>\n";
SessionsManager sm(request);
if (sm.isAutorized()) {
d->autorized = true;
d->userSettings.setFileName("users/" + sm.get("user_name") + ".json");
d->userSettings.readSettings();
}
else if (d->userSettings.isValidAutorizationRequest(request)) {
d->autorized = true;
sm.setFileName(d->userSettings.get("user_id") + ".json");
if (sm.beginNewSession(d->userSettings.get("user_name"))) {
const bool httpsOnly = d->commonSettings.getBool("https_only");
setCookie("user_id", d->userSettings.get("user_id"),
"", "/", "", httpsOnly, false);
setCookie("session_id", sm.get("session_id"),
"", "/", "", httpsOnly, false);
}
}
else {
if (request.isPost()) {
if (!request.post().isEmpty()) {
if (!request.post("user_name").isEmpty() &&
!request.post("password").isEmpty()) {
out += " show_auth_error();\n";
out += " begin_authorization();\n";
}
}
}
}
if (d->autorized) {
out += " authorized_user();\n";
d->admin = d->userSettings.getBool("admin");
if (d->admin) {
out += " admin();\n";
}
else {
out += " not_admin();\n";
}
if (d->userSettings.get("user_email").isEmpty()) {
out += " email_is_unknown();\n";
}
}
else {
out += " unauthorized_user();\n";
}
out += " </script>";
addToBody(out);
}
void HtmlPage::forceAuthorization()
{
if (!d->autorized) {
addToBody(" <script>begin_authorization()</script>");
}
}
void HtmlPage::forbidAccess()
{
const ResourceManager res;
setContent(res.read("/html/403-template.html"));
}
void HtmlPage::update()
{
QByteArray out = d->page;
out.replace("%head%", d->head);
out.replace("%body%", d->body);
out.replace("%title%", d->title);
out.replace("%content%", d->content);
out.replace("%page_style%", d->userSettings.get("page_style").toUtf8());
out.replace("%user_email%", d->userSettings.get("user_email").toUtf8());
out.replace("%gravatar_icon_url%", d->userSettings.gravatarIconUrl());
if (!d->autorized) {
const ResourceManager res;
out.replace("%auth_form%", res.read("/html/auth-template.html"));
}
else {
out.replace("%auth_form%", "");
}
const QStringList names = {
d->userSettings.get("desirable_user_name"),
d->userSettings.get("full_user_name"),
d->userSettings.get("user_name")
};
for (const QString &name : names) {
if (!name.isEmpty()) {
out.replace("%user_name%", name.toUtf8());
}
}
for (const auto &key : d->localization.keys()) {
out.replace("%" + key.toUtf8() + "%",
d->localization.get(key).toUtf8());
}
for (const auto &key : d->extraReplacements.keys()) {
out.replace("%" + key + "%", d->extraReplacements[key]);
}
out.replace("%redirect%", d->redirect);
out.replace("%prefix%", d->prefix);
out.replace("%jquery_url%", d->jquery);
setData(out);
}
CommonSettings& HtmlPage::commonSettings() const
{
return d->commonSettings;
}
UserSettings &HtmlPage::userSettings() const
{
return d->userSettings;
}
QString HtmlPage::get(const QString &key) const
{
return d->commonSettings.get(key);
}
bool HtmlPage::getBool(const QString &key) const
{
return d->commonSettings.getBool(key);
}
<commit_msg>HtmlPage: improve addStyleSheetToHead() method<commit_after>/*****************************************************************************
* *
* Copyright (c) 2016 Boris Pek <tehnick-8@yandex.ru> *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to *
* the following conditions: *
* *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
*****************************************************************************/
#include <QMap>
#include <QStringList>
#include <QByteArrayList>
#include "applicationsettings.h"
#include "resourcemanager.h"
#include "sessionsmanager.h"
#include "localization.h"
#include "htmlpage.h"
struct HtmlPage::HtmlPagePrivate
{
bool admin = false;
bool autorized = false;
QByteArray page;
QByteArray head;
QByteArray body;
QByteArray title;
QByteArray content;
QByteArray redirect;
QByteArray prefix;
QByteArray jquery;
CommonSettings commonSettings;
UserSettings userSettings;
Localization localization;
QMap<QByteArray, QByteArray> extraReplacements;
};
HtmlPage::HtmlPage(const Request &request) :
d(new HtmlPagePrivate)
{
d->prefix = APP_S().prefixString().toUtf8();
d->jquery = APP_S().jqueryUrl().toUtf8();
d->redirect = request.scriptName().toUtf8();
if (request.get("ajax").isEmpty()) {
const ResourceManager res;
setPage(res.read("/html/page-template.html"));
setTitle("%basic_title%");
setHead(res.read("/html/head-template.html"));
setBody(res.read("/html/body-template.html"));
setContent(res.read("/html/404-template.html"));
}
checkAutorization(request);
if (request.get("ajax").isEmpty()) {
d->localization.setFileName(d->commonSettings.l10nFile());
d->localization.readSettings();
setContentType("text/html");
update();
}
}
HtmlPage::~HtmlPage()
{
delete d;
}
void HtmlPage::setHead(const QByteArray &head)
{
d->head = head;
}
void HtmlPage::setBody(const QByteArray &body)
{
d->body = body;
}
void HtmlPage::setTitle(const QByteArray &title)
{
d->title = title;
}
void HtmlPage::setContent(const QByteArray &content)
{
d->content = content;
}
void HtmlPage::addToHead(const QByteArray &head)
{
setHead(d->head + "\n" + head);
}
void HtmlPage::addToBody(const QByteArray &body)
{
setBody(d->body + "\n" + body);
}
void HtmlPage::addToTitle(const QByteArray &title)
{
setTitle(d->title + title);
}
void HtmlPage::addToContent(const QByteArray &content)
{
setContent(d->content + "\n" + content);
}
void HtmlPage::addExtraReplacements(const QByteArray &from,
const QByteArray &to)
{
if (from.isEmpty())
return;
d->extraReplacements[from] = to;
}
void HtmlPage::addStyleSheetToHead(const QByteArray &styleSheet)
{
if (d->head.isEmpty()) {
setHead(styleSheet);
return;
}
if (!d->head.contains("link rel=\"stylesheet\"")) {
addToHead(styleSheet);
return;
}
const QByteArray &&html =
" <link rel=\"stylesheet\" type=\"text/css\" href=\"" +
styleSheet + "\">";
QByteArrayList list = d->head.split('\n');
for (int k = list.size()-1; k > 0; --k) {
if (list[k].contains("link rel=\"stylesheet\"")) {
list.insert(k, html);
}
}
setHead(list.join('\n'));
}
void HtmlPage::addScriptToHead(const QByteArray &script)
{
addToHead(" <script src=\"" + script + "\"></script>");
}
bool HtmlPage::isAutorizedUser() const
{
return d->autorized;
}
bool HtmlPage::isAdmin() const
{
return d->admin;
}
void HtmlPage::setPage(const QByteArray &page)
{
d->page = page;
}
void HtmlPage::checkAutorization(const Request &request)
{
QByteArray out;
out += " <script>\n";
SessionsManager sm(request);
if (sm.isAutorized()) {
d->autorized = true;
d->userSettings.setFileName("users/" + sm.get("user_name") + ".json");
d->userSettings.readSettings();
}
else if (d->userSettings.isValidAutorizationRequest(request)) {
d->autorized = true;
sm.setFileName(d->userSettings.get("user_id") + ".json");
if (sm.beginNewSession(d->userSettings.get("user_name"))) {
const bool httpsOnly = d->commonSettings.getBool("https_only");
setCookie("user_id", d->userSettings.get("user_id"),
"", "/", "", httpsOnly, false);
setCookie("session_id", sm.get("session_id"),
"", "/", "", httpsOnly, false);
}
}
else {
if (request.isPost()) {
if (!request.post().isEmpty()) {
if (!request.post("user_name").isEmpty() &&
!request.post("password").isEmpty()) {
out += " show_auth_error();\n";
out += " begin_authorization();\n";
}
}
}
}
if (d->autorized) {
out += " authorized_user();\n";
d->admin = d->userSettings.getBool("admin");
if (d->admin) {
out += " admin();\n";
}
else {
out += " not_admin();\n";
}
if (d->userSettings.get("user_email").isEmpty()) {
out += " email_is_unknown();\n";
}
}
else {
out += " unauthorized_user();\n";
}
out += " </script>";
addToBody(out);
}
void HtmlPage::forceAuthorization()
{
if (!d->autorized) {
addToBody(" <script>begin_authorization()</script>");
}
}
void HtmlPage::forbidAccess()
{
const ResourceManager res;
setContent(res.read("/html/403-template.html"));
}
void HtmlPage::update()
{
QByteArray out = d->page;
out.replace("%head%", d->head);
out.replace("%body%", d->body);
out.replace("%title%", d->title);
out.replace("%content%", d->content);
out.replace("%page_style%", d->userSettings.get("page_style").toUtf8());
out.replace("%user_email%", d->userSettings.get("user_email").toUtf8());
out.replace("%gravatar_icon_url%", d->userSettings.gravatarIconUrl());
if (!d->autorized) {
const ResourceManager res;
out.replace("%auth_form%", res.read("/html/auth-template.html"));
}
else {
out.replace("%auth_form%", "");
}
const QStringList names = {
d->userSettings.get("desirable_user_name"),
d->userSettings.get("full_user_name"),
d->userSettings.get("user_name")
};
for (const QString &name : names) {
if (!name.isEmpty()) {
out.replace("%user_name%", name.toUtf8());
}
}
for (const auto &key : d->localization.keys()) {
out.replace("%" + key.toUtf8() + "%",
d->localization.get(key).toUtf8());
}
for (const auto &key : d->extraReplacements.keys()) {
out.replace("%" + key + "%", d->extraReplacements[key]);
}
out.replace("%redirect%", d->redirect);
out.replace("%prefix%", d->prefix);
out.replace("%jquery_url%", d->jquery);
setData(out);
}
CommonSettings& HtmlPage::commonSettings() const
{
return d->commonSettings;
}
UserSettings &HtmlPage::userSettings() const
{
return d->userSettings;
}
QString HtmlPage::get(const QString &key) const
{
return d->commonSettings.get(key);
}
bool HtmlPage::getBool(const QString &key) const
{
return d->commonSettings.getBool(key);
}
<|endoftext|> |
<commit_before>#ifndef MS_RTC_CONSUMER_HPP
#define MS_RTC_CONSUMER_HPP
#include "common.hpp"
#include "Channel/Notifier.hpp"
#include "RTC/Codecs/PayloadDescriptorHandler.hpp"
#include "RTC/ConsumerListener.hpp"
#include "RTC/RTCP/CompoundPacket.hpp"
#include "RTC/RTCP/FeedbackRtpNack.hpp"
#include "RTC/RTCP/ReceiverReport.hpp"
#include "RTC/RTCP/Sdes.hpp"
#include "RTC/RtpDataCounter.hpp"
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpMonitor.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtpStreamSend.hpp"
#include "RTC/SeqManager.hpp"
#include "RTC/Transport.hpp"
#include <json/json.h>
#include <set>
#include <unordered_set>
namespace RTC
{
class Consumer : public RTC::RtpMonitor::Listener
{
static constexpr uint16_t RtpPacketsBeforeProbation{ 2000 };
// Must be a power of 2.
static constexpr uint16_t ProbationPacketNumber{ 256 };
public:
Consumer(
Channel::Notifier* notifier,
uint32_t consumerId,
RTC::Media::Kind kind,
uint32_t sourceProducerId);
private:
virtual ~Consumer();
public:
void Destroy();
Json::Value ToJson() const;
Json::Value GetStats() const;
void AddListener(RTC::ConsumerListener* listener);
void RemoveListener(RTC::ConsumerListener* listener);
void Enable(RTC::Transport* transport, RTC::RtpParameters& rtpParameters);
void Pause();
void Resume();
void SourcePause();
void SourceResume();
void AddProfile(const RTC::RtpEncodingParameters::Profile profile, const RTC::RtpStream* rtpStream);
void RemoveProfile(const RTC::RtpEncodingParameters::Profile profile);
void SourceRtpParametersUpdated();
void SetPreferredProfile(const RTC::RtpEncodingParameters::Profile profile);
void SetSourcePreferredProfile(const RTC::RtpEncodingParameters::Profile profile);
void SetEncodingPreferences(const RTC::Codecs::EncodingContext::Preferences preferences);
void Disable();
bool IsEnabled() const;
const RTC::RtpParameters& GetParameters() const;
bool IsPaused() const;
RTC::RtpEncodingParameters::Profile GetPreferredProfile() const;
void SendRtpPacket(RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile);
void GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now);
void ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket);
void ReceiveKeyFrameRequest(RTCP::FeedbackPs::MessageType messageType);
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
uint32_t GetTransmissionRate(uint64_t now);
float GetLossPercentage() const;
void RequestKeyFrame();
private:
void FillSupportedCodecPayloadTypes();
void CreateRtpStream(RTC::RtpEncodingParameters& encoding);
void RetransmitRtpPacket(RTC::RtpPacket* packet);
void RecalculateTargetProfile(bool force = false);
void SetEffectiveProfile(RTC::RtpEncodingParameters::Profile profile);
void MayRunProbation();
bool IsProbing() const;
void StartProbation(RTC::RtpEncodingParameters::Profile profile);
void StopProbation();
void SendProbation(RTC::RtpPacket* packet);
/* Pure virtual methods inherited from RTC::RtpMonitor::Listener. */
public:
void OnRtpMonitorScore(uint8_t score) override;
public:
// Passed by argument.
uint32_t consumerId{ 0 };
RTC::Media::Kind kind;
uint32_t sourceProducerId{ 0 };
private:
// Passed by argument.
Channel::Notifier* notifier{ nullptr };
RTC::Transport* transport{ nullptr };
RTC::RtpParameters rtpParameters;
std::unordered_set<RTC::ConsumerListener*> listeners;
// Allocated by this.
RTC::RtpStreamSend* rtpStream{ nullptr };
RtpMonitor* rtpMonitor{ nullptr };
// Others.
std::unordered_set<uint8_t> supportedCodecPayloadTypes;
bool paused{ false };
bool sourcePaused{ false };
// Timestamp when last RTCP was sent.
uint64_t lastRtcpSentTime{ 0 };
uint16_t maxRtcpInterval{ 0 };
// RTP counters.
RTC::RtpDataCounter retransmittedCounter;
// RTP sequence number and timestamp.
RTC::SeqManager<uint16_t> rtpSeqManager;
RTC::SeqManager<uint32_t> rtpTimestampManager;
bool syncRequired{ true };
// RTP payload descriptor encoding.
std::unique_ptr<RTC::Codecs::EncodingContext> encodingContext;
// RTP profiles.
std::map<RTC::RtpEncodingParameters::Profile, const RTC::RtpStream*> mapProfileRtpStream;
RTC::RtpEncodingParameters::Profile preferredProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile sourcePreferredProfile{
RTC::RtpEncodingParameters::Profile::DEFAULT
};
RTC::RtpEncodingParameters::Profile targetProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile effectiveProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile probingProfile{ RTC::RtpEncodingParameters::Profile::NONE };
// RTP probation.
uint16_t rtpPacketsBeforeProbation{ RtpPacketsBeforeProbation };
uint16_t probationPackets{ 0 };
};
/* Inline methods. */
inline void Consumer::AddListener(RTC::ConsumerListener* listener)
{
this->listeners.insert(listener);
}
inline void Consumer::RemoveListener(RTC::ConsumerListener* listener)
{
this->listeners.erase(listener);
}
inline bool Consumer::IsEnabled() const
{
return this->transport != nullptr;
}
inline const RTC::RtpParameters& Consumer::GetParameters() const
{
return this->rtpParameters;
}
inline bool Consumer::IsPaused() const
{
return this->paused || this->sourcePaused;
}
inline RTC::RtpEncodingParameters::Profile Consumer::GetPreferredProfile() const
{
// If Consumer preferred profile and source (Producer) preferred profile
// are the same, that's.
if (this->preferredProfile == this->sourcePreferredProfile)
return this->preferredProfile;
// If Consumer preferred profile is 'default', use whichever the source
// preferred profile is.
if (this->preferredProfile == RTC::RtpEncodingParameters::Profile::DEFAULT)
return this->sourcePreferredProfile;
// If source preferred profile is 'default', use whichever the Consumer
// preferred profile is.
if (this->sourcePreferredProfile == RTC::RtpEncodingParameters::Profile::DEFAULT)
return this->preferredProfile;
// Otherwise the Consumer preferred profile is chosen.
return this->preferredProfile;
}
inline uint32_t Consumer::GetTransmissionRate(uint64_t now)
{
return this->rtpStream->GetRate(now) + this->retransmittedCounter.GetRate(now);
}
inline bool Consumer::IsProbing() const
{
return this->probationPackets != 0;
}
inline void Consumer::StartProbation(RTC::RtpEncodingParameters::Profile profile)
{
this->probationPackets = ProbationPacketNumber;
this->probingProfile = profile;
}
inline void Consumer::StopProbation()
{
this->probationPackets = 0;
this->probingProfile = RTC::RtpEncodingParameters::Profile::NONE;
}
} // namespace RTC
#endif
<commit_msg>Fix #185. Consumer: initialize effective profile to 'NONE'<commit_after>#ifndef MS_RTC_CONSUMER_HPP
#define MS_RTC_CONSUMER_HPP
#include "common.hpp"
#include "Channel/Notifier.hpp"
#include "RTC/Codecs/PayloadDescriptorHandler.hpp"
#include "RTC/ConsumerListener.hpp"
#include "RTC/RTCP/CompoundPacket.hpp"
#include "RTC/RTCP/FeedbackRtpNack.hpp"
#include "RTC/RTCP/ReceiverReport.hpp"
#include "RTC/RTCP/Sdes.hpp"
#include "RTC/RtpDataCounter.hpp"
#include "RTC/RtpDictionaries.hpp"
#include "RTC/RtpMonitor.hpp"
#include "RTC/RtpPacket.hpp"
#include "RTC/RtpStreamSend.hpp"
#include "RTC/SeqManager.hpp"
#include "RTC/Transport.hpp"
#include <json/json.h>
#include <set>
#include <unordered_set>
namespace RTC
{
class Consumer : public RTC::RtpMonitor::Listener
{
static constexpr uint16_t RtpPacketsBeforeProbation{ 2000 };
// Must be a power of 2.
static constexpr uint16_t ProbationPacketNumber{ 256 };
public:
Consumer(
Channel::Notifier* notifier,
uint32_t consumerId,
RTC::Media::Kind kind,
uint32_t sourceProducerId);
private:
virtual ~Consumer();
public:
void Destroy();
Json::Value ToJson() const;
Json::Value GetStats() const;
void AddListener(RTC::ConsumerListener* listener);
void RemoveListener(RTC::ConsumerListener* listener);
void Enable(RTC::Transport* transport, RTC::RtpParameters& rtpParameters);
void Pause();
void Resume();
void SourcePause();
void SourceResume();
void AddProfile(const RTC::RtpEncodingParameters::Profile profile, const RTC::RtpStream* rtpStream);
void RemoveProfile(const RTC::RtpEncodingParameters::Profile profile);
void SourceRtpParametersUpdated();
void SetPreferredProfile(const RTC::RtpEncodingParameters::Profile profile);
void SetSourcePreferredProfile(const RTC::RtpEncodingParameters::Profile profile);
void SetEncodingPreferences(const RTC::Codecs::EncodingContext::Preferences preferences);
void Disable();
bool IsEnabled() const;
const RTC::RtpParameters& GetParameters() const;
bool IsPaused() const;
RTC::RtpEncodingParameters::Profile GetPreferredProfile() const;
void SendRtpPacket(RTC::RtpPacket* packet, RTC::RtpEncodingParameters::Profile profile);
void GetRtcp(RTC::RTCP::CompoundPacket* packet, uint64_t now);
void ReceiveNack(RTC::RTCP::FeedbackRtpNackPacket* nackPacket);
void ReceiveKeyFrameRequest(RTCP::FeedbackPs::MessageType messageType);
void ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report);
uint32_t GetTransmissionRate(uint64_t now);
float GetLossPercentage() const;
void RequestKeyFrame();
private:
void FillSupportedCodecPayloadTypes();
void CreateRtpStream(RTC::RtpEncodingParameters& encoding);
void RetransmitRtpPacket(RTC::RtpPacket* packet);
void RecalculateTargetProfile(bool force = false);
void SetEffectiveProfile(RTC::RtpEncodingParameters::Profile profile);
void MayRunProbation();
bool IsProbing() const;
void StartProbation(RTC::RtpEncodingParameters::Profile profile);
void StopProbation();
void SendProbation(RTC::RtpPacket* packet);
/* Pure virtual methods inherited from RTC::RtpMonitor::Listener. */
public:
void OnRtpMonitorScore(uint8_t score) override;
public:
// Passed by argument.
uint32_t consumerId{ 0 };
RTC::Media::Kind kind;
uint32_t sourceProducerId{ 0 };
private:
// Passed by argument.
Channel::Notifier* notifier{ nullptr };
RTC::Transport* transport{ nullptr };
RTC::RtpParameters rtpParameters;
std::unordered_set<RTC::ConsumerListener*> listeners;
// Allocated by this.
RTC::RtpStreamSend* rtpStream{ nullptr };
RtpMonitor* rtpMonitor{ nullptr };
// Others.
std::unordered_set<uint8_t> supportedCodecPayloadTypes;
bool paused{ false };
bool sourcePaused{ false };
// Timestamp when last RTCP was sent.
uint64_t lastRtcpSentTime{ 0 };
uint16_t maxRtcpInterval{ 0 };
// RTP counters.
RTC::RtpDataCounter retransmittedCounter;
// RTP sequence number and timestamp.
RTC::SeqManager<uint16_t> rtpSeqManager;
RTC::SeqManager<uint32_t> rtpTimestampManager;
bool syncRequired{ true };
// RTP payload descriptor encoding.
std::unique_ptr<RTC::Codecs::EncodingContext> encodingContext;
// RTP profiles.
std::map<RTC::RtpEncodingParameters::Profile, const RTC::RtpStream*> mapProfileRtpStream;
RTC::RtpEncodingParameters::Profile preferredProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile sourcePreferredProfile{
RTC::RtpEncodingParameters::Profile::DEFAULT
};
RTC::RtpEncodingParameters::Profile targetProfile{ RTC::RtpEncodingParameters::Profile::DEFAULT };
RTC::RtpEncodingParameters::Profile effectiveProfile{ RTC::RtpEncodingParameters::Profile::NONE };
RTC::RtpEncodingParameters::Profile probingProfile{ RTC::RtpEncodingParameters::Profile::NONE };
// RTP probation.
uint16_t rtpPacketsBeforeProbation{ RtpPacketsBeforeProbation };
uint16_t probationPackets{ 0 };
};
/* Inline methods. */
inline void Consumer::AddListener(RTC::ConsumerListener* listener)
{
this->listeners.insert(listener);
}
inline void Consumer::RemoveListener(RTC::ConsumerListener* listener)
{
this->listeners.erase(listener);
}
inline bool Consumer::IsEnabled() const
{
return this->transport != nullptr;
}
inline const RTC::RtpParameters& Consumer::GetParameters() const
{
return this->rtpParameters;
}
inline bool Consumer::IsPaused() const
{
return this->paused || this->sourcePaused;
}
inline RTC::RtpEncodingParameters::Profile Consumer::GetPreferredProfile() const
{
// If Consumer preferred profile and source (Producer) preferred profile
// are the same, that's.
if (this->preferredProfile == this->sourcePreferredProfile)
return this->preferredProfile;
// If Consumer preferred profile is 'default', use whichever the source
// preferred profile is.
if (this->preferredProfile == RTC::RtpEncodingParameters::Profile::DEFAULT)
return this->sourcePreferredProfile;
// If source preferred profile is 'default', use whichever the Consumer
// preferred profile is.
if (this->sourcePreferredProfile == RTC::RtpEncodingParameters::Profile::DEFAULT)
return this->preferredProfile;
// Otherwise the Consumer preferred profile is chosen.
return this->preferredProfile;
}
inline uint32_t Consumer::GetTransmissionRate(uint64_t now)
{
return this->rtpStream->GetRate(now) + this->retransmittedCounter.GetRate(now);
}
inline bool Consumer::IsProbing() const
{
return this->probationPackets != 0;
}
inline void Consumer::StartProbation(RTC::RtpEncodingParameters::Profile profile)
{
this->probationPackets = ProbationPacketNumber;
this->probingProfile = profile;
}
inline void Consumer::StopProbation()
{
this->probationPackets = 0;
this->probingProfile = RTC::RtpEncodingParameters::Profile::NONE;
}
} // namespace RTC
#endif
<|endoftext|> |
<commit_before>#include <tiramisu/tiramisu.h>
#include "configuration.h"
#define GEMM_BATCH 10
using namespace tiramisu;
int main(int argc, char **argv)
{
// Single LSTM block without minibatching
tiramisu::init("lstm");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Inner dimensions
var i("i", 0, FEATURE_SIZE), j("j", 0, FEATURE_SIZE), k("k", 0, BATCH_SIZE);
var i_merged("i_merged", 0, 4 * FEATURE_SIZE);
var i0("i0"), i1("i1"), k0("k0"), k1("k1");
// Outer dimensions
var l("l", 0, NUM_LAYERS), s("s", 0, SEQ_LENGTH);
var s0("s0", 0, SEQ_LENGTH / GEMM_BATCH), s1("s1", 0, GEMM_BATCH);
// After skewing
var l_s("l_s"), s_s("s_s");
input x("x", {s, k, i}, p_float32);
input weights("weights", {l, var("w_i", 0, 2), i_merged, j}, p_float32);
input biases("biases", {l, i_merged}, p_float32);
input tmp("tmp", {s, k, i_merged}, p_float32);
weights.get_buffer()->tag_gpu_global();
biases.get_buffer()->tag_gpu_global();
tmp.get_buffer()->tag_gpu_global();
buffer buf_Weights_cpu("buf_Weights_cpu", {NUM_LAYERS, 2, 4 * FEATURE_SIZE, FEATURE_SIZE}, p_float32, a_input);
buffer buf_h("buf_h", {NUM_LAYERS + 1, SEQ_LENGTH + 1, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_biases_cpu("buf_biases_cpu", {NUM_LAYERS, 4 * FEATURE_SIZE}, p_float32, a_input);
buffer buf_x_cpu("buf_x_cpu", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_input);
buffer buf_y_cpu("buf_y_cpu", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_output);
buffer buf_x("buf_x", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_y("buf_y", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_tmp_i("buf_tmp_i", {NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_tmp_z("buf_tmp_z", {NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_tmp_o("buf_tmp_o", {NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_tmp_f("buf_tmp_f", {NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buffer buf_c("buf_c", {NUM_LAYERS, SEQ_LENGTH + 1, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary);
buf_h.tag_gpu_global();
buf_x.tag_gpu_global();
buf_y.tag_gpu_global();
buf_tmp_i.tag_gpu_global();
buf_tmp_z.tag_gpu_global();
buf_tmp_o.tag_gpu_global();
buf_tmp_f.tag_gpu_global();
buf_c.tag_gpu_global();
// Transpose Weights
var w_t_i("w_i", 0, 2); // Dummy variable
computation weights_T({l, w_t_i, j, i_merged}, weights(l, w_t_i, i_merged, j));
weights_T.get_buffer()->tag_gpu_global();
// h(l, s) is the output of the block (l, s)
// which takes h(l, s - 1) and h(l - 1, s) as inputs
// initial hidden states are h(l, -1) and c(l, -1)
// input x is copied to h(-1, s)
computation h({l, s, k, i}, p_float32);
computation c({l, s, k, i}, p_float32);
computation h_init({l, k, i}, expr(float(0)));
computation c_init({l, k, i}, expr(float(0)));
computation h_copy_x({s, k, i}, x(s, k, i));
// Multiplication from input is batched:
computation sum1({l, s0},
cublas_sgemm(buf_h, *weights_T.get_buffer(), *tmp.get_buffer(),
GEMM_BATCH * BATCH_SIZE, 4 * FEATURE_SIZE, FEATURE_SIZE,
1, 0, // alpha, beta
0, 0, 0, // ldABC
(l * (SEQ_LENGTH + 1) + s0 * GEMM_BATCH + 1) * BATCH_SIZE * FEATURE_SIZE, //offsetA
(l * 2 + 1) * 4 * FEATURE_SIZE * FEATURE_SIZE, //offsetB
s0 * GEMM_BATCH * BATCH_SIZE * 4 * FEATURE_SIZE, // offsetC
false, false));
computation sum2({l, s},
cublas_sgemm(buf_h, *weights_T.get_buffer(), *tmp.get_buffer(),
BATCH_SIZE, 4 * FEATURE_SIZE, FEATURE_SIZE,
1, 1, // alpha, beta
0, 0, 0, // ldABC
((l + 1) * (SEQ_LENGTH + 1) + s) * BATCH_SIZE * FEATURE_SIZE, //offsetA
(l * 2) * 4 * FEATURE_SIZE * FEATURE_SIZE, //offsetB
s * BATCH_SIZE * 4 * FEATURE_SIZE, // offsetC
false, false));
#define sigmoid(x) expr(float(1)) / (1 + expr(o_expo, -(x)))
computation sig_i({l, s, k, i}, sigmoid(tmp(s, k, i + 0 * FEATURE_SIZE) + biases(l, i + 0 * FEATURE_SIZE)));
computation tnh_z({l, s, k, i}, expr(o_tanh, tmp(s, k, i + 1 * FEATURE_SIZE) + biases(l, i + 1 * FEATURE_SIZE)));
computation sig_o({l, s, k, i}, sigmoid(tmp(s, k, i + 2 * FEATURE_SIZE) + biases(l, i + 2 * FEATURE_SIZE)));
computation sig_f({l, s, k, i}, sigmoid(tmp(s, k, i + 3 * FEATURE_SIZE) + biases(l, i + 3 * FEATURE_SIZE)));
computation mul_iz({l, s, k, i}, sig_i(l, s, k, i) * tnh_z(l, s, k, i));
computation mul_fc({l, s, k, i}, sig_f(l, s, k, i) * c(l, s - 1, k, i));
c.set_expression(mul_iz(l, s, k, i) + mul_fc(l, s, k, i));
computation tnh_c({l, s, k, i}, expr(o_tanh, c(l, s, k, i)));
h.set_expression(tnh_c(l, s, k, i) * sig_o(l, s, k, i));
computation stream_sync({l, s0}, cuda_stream_synchronize());
// Output is the last layer
computation y({s, k, i}, h(NUM_LAYERS - 1, s, k, i));
// Copies
computation copy_Weights_to_device({}, memcpy(buf_Weights_cpu, *weights.get_buffer()));
computation copy_biases_to_device({}, memcpy(buf_biases_cpu, *biases.get_buffer()));
computation copy_x_to_device({}, memcpy(buf_x_cpu, buf_x));
computation copy_y_to_host({}, memcpy(buf_y, buf_y_cpu));
computation final_stream_sync({var("dummy", 0, 1)}, cuda_stream_synchronize());
computation time_start({var("dummy", 0, 1)}, expr(o_call, "get_time", {int32_t(0)}, p_float32));
computation time_end({var("dummy", 0, 1)}, expr(o_call, "get_time", {int32_t(0)}, p_float32));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Fuse kernels by moving gpu iterators out
weights_T.interchange(w_t_i, j);
weights_T.interchange(w_t_i, i_merged);
weights_T.interchange(l, j);
weights_T.interchange(l, i_merged);
h_init.interchange(l, k);
h_init.interchange(l, i);
c_init.interchange(l, k);
c_init.interchange(l, i);
h_copy_x.interchange(s, k);
h_copy_x.interchange(s, i);
y.interchange(s, k);
y.interchange(s, i);
weights_T.gpu_tile(j, i_merged, 16, 16);
block nonlinear_block({&sig_i, &tnh_z, &sig_o, &sig_f, &mul_iz, &mul_fc, &c,
&tnh_c, &h});
// Batch Input GEMMs
block({&sum2, &nonlinear_block}).split(s, GEMM_BATCH, s0, s1);
block ki_block({&h_init, &c_init, &h_copy_x, &nonlinear_block, &y});
// Interchange to get better locality
ki_block.interchange(k, i);
ki_block.gpu_tile(i, k, 16, 16, i0, k0, i1, k1);
block lstm_block({&sum1, &sum2, &nonlinear_block, &stream_sync});
// Skew and interchange to get diagonal traversal
lstm_block.skew(l, s0, 1, l_s, s_s);
lstm_block.interchange(l_s, s_s);
// Parallelize diagonal traversal
// Due to a bug in tagging system we only need to parallelize one computation
sum1.parallelize(l_s);
// Scheduling commands
copy_Weights_to_device
.then(copy_biases_to_device, computation::root)
.then(copy_x_to_device, computation::root)
.then(time_start, computation::root)
.then(weights_T, computation::root)
.then(h_init, computation::root)
.then(c_init, computation::root)
.then(h_copy_x, computation::root)
.then(sum1, computation::root)
.then(sum2, l_s)
.then(sig_i, s1)
.then(tnh_z, k1)
.then(sig_o, k1)
.then(sig_f, k1)
.then(mul_iz, k1)
.then(mul_fc, k1)
.then(c, k1)
.then(tnh_c, k1)
.then(h, k1)
.then(stream_sync, l_s)
.then(y, computation::root)
.then(final_stream_sync, computation::root)
.then(time_end, computation::root)
.then(copy_y_to_host, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
// Weights and biases are packed
x.store_in(&buf_x);
y.store_in(&buf_y);
sig_i.store_in(&buf_tmp_i, {l, k, i});
tnh_z.store_in(&buf_tmp_z, {l, k, i});
sig_o.store_in(&buf_tmp_o, {l, k, i});
sig_f.store_in(&buf_tmp_f, {l, k, i});
mul_iz.store_in(&buf_tmp_i, {l, k, i});
mul_fc.store_in(&buf_tmp_f, {l, k, i});
tnh_c.store_in(&buf_tmp_i, {l, k, i});
h.store_in(&buf_h, {l + 1, s + 1, k, i});
c.store_in(&buf_c, {l, s + 1, k, i});
h_init.store_in(&buf_h, {l + 1, 0, k, i});
c_init.store_in(&buf_c, {l, 0, k, i});
h_copy_x.store_in(&buf_h, {0, s + 1, k, i});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Generate object files.
tiramisu::codegen({
&buf_Weights_cpu,
&buf_biases_cpu,
&buf_x_cpu,
&buf_y_cpu,
time_start.get_buffer(),
time_end.get_buffer(),
}, "lstm.o", true);
return 0;
}
<commit_msg>LSTM_cublas cleanup, use new buffer API<commit_after>#include <tiramisu/tiramisu.h>
#include "configuration.h"
#define GEMM_BATCH 10
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("lstm");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Inner dimensions
var i("i", 0, FEATURE_SIZE), j("j", 0, FEATURE_SIZE), k("k", 0, BATCH_SIZE);
var i_merged("i_merged", 0, 4 * FEATURE_SIZE);
var i0("i0"), i1("i1"), k0("k0"), k1("k1");
// Outer dimensions
var l("l", 0, NUM_LAYERS), s("s", 0, SEQ_LENGTH);
var s0("s0", 0, SEQ_LENGTH / GEMM_BATCH), s1("s1", 0, GEMM_BATCH);
// After skewing
var l_s("l_s"), s_s("s_s");
// Input-output CPU buffers
buffer buf_Weights_cpu("buf_Weights_cpu", {NUM_LAYERS, 2, 4 * FEATURE_SIZE, FEATURE_SIZE}, p_float32, a_input);
buffer buf_biases_cpu("buf_biases_cpu", {NUM_LAYERS, 4 * FEATURE_SIZE}, p_float32, a_input);
buffer buf_x_cpu("buf_x_cpu", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_input);
buffer buf_y_cpu("buf_y_cpu", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_output);
// GPU buffers
input x("x", {s, k, i}, p_float32);
input weights("weights", {l, var("w_i", 0, 2), i_merged, j}, p_float32);
input biases("biases", {l, i_merged}, p_float32);
input tmp("tmp", {s, k, i_merged}, p_float32);
x.get_buffer()->tag_gpu_global();
weights.get_buffer()->tag_gpu_global();
biases.get_buffer()->tag_gpu_global();
tmp.get_buffer()->tag_gpu_global();
// Transpose Weights
var w_t_i("w_i", 0, 2); // Dummy variable
computation weights_T({l, w_t_i, j, i_merged}, weights(l, w_t_i, i_merged, j));
weights_T.get_buffer()->tag_gpu_global();
// h(l, s) is the output of the block (l, s)
// which takes h(l, s - 1) and h(l - 1, s) as inputs
// Initial hidden states are h(l, -1) and c(l, -1)
// Input x is copied to h(-1, s)
computation h({l, s, k, i}, p_float32);
computation c({l, s, k, i}, p_float32);
// Pad buffers to make room for edges
h.store_in({l + 1, s + 1, k, i}, {NUM_LAYERS + 1, SEQ_LENGTH + 1, BATCH_SIZE, FEATURE_SIZE});
c.store_in({l, s + 1, k, i}, {NUM_LAYERS, SEQ_LENGTH + 1, BATCH_SIZE, FEATURE_SIZE});
h.get_buffer()->tag_gpu_global();
c.get_buffer()->tag_gpu_global();
// Initial sets and stores
computation h_init({l, k, i}, expr(float(0)));
computation c_init({l, k, i}, expr(float(0)));
computation h_copy_x({s, k, i}, x(s, k, i));
// Multiplication from input is batched
computation sum1({l, s0},
cublas_sgemm(*h.get_buffer(), *weights_T.get_buffer(), *tmp.get_buffer(),
GEMM_BATCH * BATCH_SIZE, 4 * FEATURE_SIZE, FEATURE_SIZE,
1, 0, // alpha, beta
0, 0, 0, // ldABC
(l * (SEQ_LENGTH + 1) + s0 * GEMM_BATCH + 1) * BATCH_SIZE * FEATURE_SIZE, //offsetA
(l * 2 + 1) * 4 * FEATURE_SIZE * FEATURE_SIZE, //offsetB
s0 * GEMM_BATCH * BATCH_SIZE * 4 * FEATURE_SIZE, // offsetC
false, false));
computation sum2({l, s},
cublas_sgemm(*h.get_buffer(), *weights_T.get_buffer(), *tmp.get_buffer(),
BATCH_SIZE, 4 * FEATURE_SIZE, FEATURE_SIZE,
1, 1, // alpha, beta
0, 0, 0, // ldABC
((l + 1) * (SEQ_LENGTH + 1) + s) * BATCH_SIZE * FEATURE_SIZE, //offsetA
(l * 2) * 4 * FEATURE_SIZE * FEATURE_SIZE, //offsetB
s * BATCH_SIZE * 4 * FEATURE_SIZE, // offsetC
false, false));
// Nonlinear operations as well as biases
#define sigmoid(x) expr(float(1)) / (1 + expr(o_expo, -(x)))
computation sig_i({l, s, k, i}, sigmoid(tmp(s, k, i + 0 * FEATURE_SIZE) + biases(l, i + 0 * FEATURE_SIZE)));
computation tnh_z({l, s, k, i}, expr(o_tanh, tmp(s, k, i + 1 * FEATURE_SIZE) + biases(l, i + 1 * FEATURE_SIZE)));
computation sig_o({l, s, k, i}, sigmoid(tmp(s, k, i + 2 * FEATURE_SIZE) + biases(l, i + 2 * FEATURE_SIZE)));
computation sig_f({l, s, k, i}, sigmoid(tmp(s, k, i + 3 * FEATURE_SIZE) + biases(l, i + 3 * FEATURE_SIZE)));
// Update cells
c.set_expression(sig_i(l, s, k, i) * tnh_z(l, s, k, i) + sig_f(l, s, k, i) * c(l, s - 1, k, i));
h.set_expression(expr(o_tanh, c(l, s, k, i)) * sig_o(l, s, k, i));
// Synchronize GEMMS and kernels before thread is destroyed
computation stream_sync({l, s0}, cuda_stream_synchronize());
// Output is the last layer
computation y({s, k, i}, h(NUM_LAYERS - 1, s, k, i));
y.get_buffer()->tag_gpu_global();
// Copies
computation copy_Weights_to_device({}, memcpy(buf_Weights_cpu, *weights.get_buffer()));
computation copy_biases_to_device({}, memcpy(buf_biases_cpu, *biases.get_buffer()));
computation copy_x_to_device({}, memcpy(buf_x_cpu, *x.get_buffer()));
computation copy_y_to_host({}, memcpy(*y.get_buffer(), buf_y_cpu));
computation final_stream_sync({var("dummy", 0, 1)}, cuda_stream_synchronize());
computation time_start({var("dummy", 0, 1)}, expr(o_call, "get_time", {int32_t(0)}, p_float32));
computation time_end({var("dummy", 0, 1)}, expr(o_call, "get_time", {int32_t(0)}, p_float32));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Fuse kernels by moving gpu iterators out
weights_T.interchange(w_t_i, j);
weights_T.interchange(w_t_i, i_merged);
weights_T.interchange(l, j);
weights_T.interchange(l, i_merged);
h_init.interchange(l, k);
h_init.interchange(l, i);
c_init.interchange(l, k);
c_init.interchange(l, i);
h_copy_x.interchange(s, k);
h_copy_x.interchange(s, i);
y.interchange(s, k);
y.interchange(s, i);
weights_T.gpu_tile(j, i_merged, 16, 16);
block nonlinear_block({&sig_i, &tnh_z, &sig_o, &sig_f, &c, &h});
// Batch Input GEMMs
block({&sum2, &nonlinear_block}).split(s, GEMM_BATCH, s0, s1);
block ki_block({&h_init, &c_init, &h_copy_x, &nonlinear_block, &y});
// Interchange to get better locality
ki_block.interchange(k, i);
ki_block.gpu_tile(i, k, 16, 16, i0, k0, i1, k1);
block lstm_block({&sum1, &sum2, &nonlinear_block, &stream_sync});
// Skew and interchange to get diagonal traversal
lstm_block.skew(l, s0, 1, l_s, s_s);
lstm_block.interchange(l_s, s_s);
// Parallelize diagonal traversal
// Due to a bug in tagging system we only need to parallelize a single computation
sum1.parallelize(l_s);
// Scheduling commands
copy_Weights_to_device
.then(copy_biases_to_device, computation::root)
.then(copy_x_to_device, computation::root)
.then(time_start, computation::root)
.then(weights_T, computation::root)
.then(h_init, computation::root)
.then(c_init, computation::root)
.then(h_copy_x, computation::root)
.then(sum1, computation::root)
.then(sum2, l_s)
.then(sig_i, s1)
.then(tnh_z, k1)
.then(sig_o, k1)
.then(sig_f, k1)
.then(c, k1)
.then(h, k1)
.then(stream_sync, l_s)
.then(y, computation::root)
.then(final_stream_sync, computation::root)
.then(time_end, computation::root)
.then(copy_y_to_host, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
sig_i.store_in(tmp.get_buffer(), {s, k, i + 0 * FEATURE_SIZE});
tnh_z.store_in(tmp.get_buffer(), {s, k, i + 1 * FEATURE_SIZE});
sig_o.store_in(tmp.get_buffer(), {s, k, i + 2 * FEATURE_SIZE});
sig_f.store_in(tmp.get_buffer(), {s, k, i + 3 * FEATURE_SIZE});
h_init.store_in(h.get_buffer(), {l + 1, 0, k, i});
c_init.store_in(c.get_buffer(), {l, 0, k, i});
h_copy_x.store_in(h.get_buffer(), {0, s + 1, k, i});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Generate object files.
tiramisu::codegen({
&buf_Weights_cpu,
&buf_biases_cpu,
&buf_x_cpu,
&buf_y_cpu,
time_start.get_buffer(),
time_end.get_buffer(),
}, "lstm.o", true);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>update POT to latest version<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/dfe.h"
#include "bin/dartutils.h"
#include "bin/directory.h"
#include "bin/error_exit.h"
#include "bin/file.h"
#include "bin/platform.h"
#include "bin/utils.h"
#include "include/dart_tools_api.h"
#include "platform/utils.h"
#include "vm/os.h"
extern "C" {
#if !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
extern const uint8_t kKernelServiceDill[];
extern intptr_t kKernelServiceDillSize;
extern const uint8_t kPlatformDill[];
extern intptr_t kPlatformDillSize;
extern const uint8_t kPlatformStrongDill[];
extern intptr_t kPlatformStrongDillSize;
#else
const uint8_t* kKernelServiceDill = NULL;
intptr_t kKernelServiceDillSize = 0;
const uint8_t* kPlatformDill = NULL;
intptr_t kPlatformDillSize = 0;
const uint8_t* kPlatformStrongDill = NULL;
intptr_t kPlatformStrongDillSize = 0;
#endif // !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
}
namespace dart {
namespace bin {
#if !defined(DART_PRECOMPILED_RUNTIME)
DFE dfe;
#endif
#if defined(DART_NO_SNAPSHOT) || defined(DART_PRECOMPILER)
const uint8_t* kernel_service_dill = NULL;
const intptr_t kernel_service_dill_size = 0;
const uint8_t* platform_dill = NULL;
const intptr_t platform_dill_size = 0;
const uint8_t* platform_strong_dill = NULL;
const intptr_t platform_strong_dill_size = 0;
#else
const uint8_t* kernel_service_dill = kKernelServiceDill;
const intptr_t kernel_service_dill_size = kKernelServiceDillSize;
const uint8_t* platform_dill = kPlatformDill;
const intptr_t platform_dill_size = kPlatformDillSize;
const uint8_t* platform_strong_dill = kPlatformStrongDill;
const intptr_t platform_strong_dill_size = kPlatformStrongDillSize;
#endif
const char kKernelServiceSnapshot[] = "kernel-service.dart.snapshot";
const char kSnapshotsDirectory[] = "snapshots";
static char* GetDirectoryPrefixFromExeName() {
const char* name = Platform::GetExecutableName();
const char* sep = File::PathSeparator();
for (intptr_t i = strlen(name) - 1; i >= 0; --i) {
const char* str = name + i;
if (strstr(str, sep) == str
#if defined(HOST_OS_WINDOWS)
// TODO(aam): GetExecutableName doesn't work reliably on Windows,
// the code below is a workaround for that (we would be using
// just single Platform::Separator instead of both slashes if it did).
|| *str == '/'
#endif
) {
return Utils::StrNDup(name, i + 1);
}
}
return strdup("");
}
DFE::DFE()
: use_dfe_(false),
frontend_filename_(NULL),
application_kernel_buffer_(NULL),
application_kernel_buffer_size_(0) {}
DFE::~DFE() {
if (frontend_filename_ != NULL) {
free(frontend_filename_);
}
frontend_filename_ = NULL;
free(application_kernel_buffer_);
application_kernel_buffer_ = NULL;
application_kernel_buffer_size_ = 0;
}
void DFE::Init() {
if (platform_dill == NULL) {
return;
}
if (frontend_filename_ == NULL) {
// Look for the frontend snapshot next to the executable.
char* dir_prefix = GetDirectoryPrefixFromExeName();
// |dir_prefix| includes the last path seperator.
frontend_filename_ =
OS::SCreate(NULL, "%s%s", dir_prefix, kKernelServiceSnapshot);
if (!File::Exists(NULL, frontend_filename_)) {
// If the frontend snapshot is not found next to the executable,
// then look for it in the "snapshots" directory.
free(frontend_filename_);
// |dir_prefix| includes the last path seperator.
frontend_filename_ =
OS::SCreate(NULL, "%s%s%s%s", dir_prefix, kSnapshotsDirectory,
File::PathSeparator(), kKernelServiceSnapshot);
}
free(dir_prefix);
if (!File::Exists(NULL, frontend_filename_)) {
free(frontend_filename_);
frontend_filename_ = NULL;
}
}
}
bool DFE::KernelServiceDillAvailable() {
return kernel_service_dill != NULL;
}
void DFE::LoadKernelService(const uint8_t** kernel_service_buffer,
intptr_t* kernel_service_buffer_size) {
*kernel_service_buffer = kernel_service_dill;
*kernel_service_buffer_size = kernel_service_dill_size;
}
void DFE::LoadPlatform(const uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size,
bool strong) {
if (strong) {
*kernel_buffer = platform_strong_dill;
*kernel_buffer_size = platform_strong_dill_size;
} else {
*kernel_buffer = platform_dill;
*kernel_buffer_size = platform_dill_size;
}
}
bool DFE::CanUseDartFrontend() const {
return (platform_dill != NULL) &&
(KernelServiceDillAvailable() || (frontend_filename() != NULL));
}
class WindowsPathSanitizer {
public:
explicit WindowsPathSanitizer(const char* path) {
// For Windows we need to massage the paths a bit according to
// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx
//
// Convert
// C:\one\two\three
// to
// /C:/one/two/three
//
// (see builtin.dart#_sanitizeWindowsPath)
intptr_t len = strlen(path);
sanitized_uri_ = reinterpret_cast<char*>(malloc(len + 1 + 1));
if (sanitized_uri_ == NULL) {
OUT_OF_MEMORY();
}
char* s = sanitized_uri_;
if (len > 2 && path[1] == ':') {
*s++ = '/';
}
for (const char *p = path; *p; ++p, ++s) {
*s = *p == '\\' ? '/' : *p;
}
*s = '\0';
}
~WindowsPathSanitizer() { free(sanitized_uri_); }
const char* sanitized_uri() { return sanitized_uri_; }
private:
char* sanitized_uri_;
DISALLOW_COPY_AND_ASSIGN(WindowsPathSanitizer);
};
Dart_KernelCompilationResult DFE::CompileScript(const char* script_uri,
bool strong,
bool incremental,
const char* package_config) {
// TODO(aam): When Frontend is ready, VM should be passing vm_outline.dill
// instead of vm_platform.dill to Frontend for compilation.
#if defined(HOST_OS_WINDOWS)
WindowsPathSanitizer path_sanitizer(script_uri);
const char* sanitized_uri = path_sanitizer.sanitized_uri();
#else
const char* sanitized_uri = script_uri;
#endif
const uint8_t* platform_binary =
strong ? platform_strong_dill : platform_dill;
intptr_t platform_binary_size =
strong ? platform_strong_dill_size : platform_dill_size;
return Dart_CompileToKernel(sanitized_uri, platform_binary,
platform_binary_size, incremental,
package_config);
}
void DFE::CompileAndReadScript(const char* script_uri,
uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size,
char** error,
int* exit_code,
bool strong,
const char* package_config) {
Dart_KernelCompilationResult result =
CompileScript(script_uri, strong, true, package_config);
switch (result.status) {
case Dart_KernelCompilationStatus_Ok:
*kernel_buffer = result.kernel;
*kernel_buffer_size = result.kernel_size;
*error = NULL;
*exit_code = 0;
break;
case Dart_KernelCompilationStatus_Error:
*error = result.error; // Copy error message.
*exit_code = kCompilationErrorExitCode;
break;
case Dart_KernelCompilationStatus_Crash:
*error = result.error; // Copy error message.
*exit_code = kDartFrontendErrorExitCode;
break;
case Dart_KernelCompilationStatus_Unknown:
*error = result.error; // Copy error message.
*exit_code = kErrorExitCode;
break;
}
}
void DFE::ReadScript(const char* script_uri,
uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size) const {
int64_t start = Dart_TimelineGetMicros();
if (!TryReadKernelFile(script_uri, kernel_buffer, kernel_buffer_size)) {
return;
}
if (!Dart_IsKernel(*kernel_buffer, *kernel_buffer_size)) {
free(*kernel_buffer);
*kernel_buffer = NULL;
*kernel_buffer_size = -1;
}
int64_t end = Dart_TimelineGetMicros();
Dart_TimelineEvent("DFE::ReadScript", start, end,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
}
bool DFE::TryReadKernelFile(const char* script_uri,
uint8_t** kernel_ir,
intptr_t* kernel_ir_size) {
*kernel_ir = NULL;
*kernel_ir_size = -1;
void* script_file = DartUtils::OpenFileUri(script_uri, false);
if (script_file == NULL) {
return false;
}
uint8_t* buffer = NULL;
DartUtils::ReadFile(&buffer, kernel_ir_size, script_file);
DartUtils::CloseFile(script_file);
if (*kernel_ir_size == 0 || buffer == NULL) {
return false;
}
if (DartUtils::SniffForMagicNumber(buffer, *kernel_ir_size) !=
DartUtils::kKernelMagicNumber) {
free(buffer);
*kernel_ir = NULL;
*kernel_ir_size = -1;
return false;
}
// Do not free buffer if this is a kernel file - kernel_file will be
// backed by the same memory as the buffer and caller will own it.
// Caller is responsible for freeing the buffer when this function
// returns true.
*kernel_ir = buffer;
return true;
}
} // namespace bin
} // namespace dart
<commit_msg>Replace strstr with strncmp looking for path separator<commit_after>// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/dfe.h"
#include "bin/dartutils.h"
#include "bin/directory.h"
#include "bin/error_exit.h"
#include "bin/file.h"
#include "bin/platform.h"
#include "bin/utils.h"
#include "include/dart_tools_api.h"
#include "platform/utils.h"
#include "vm/os.h"
extern "C" {
#if !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
extern const uint8_t kKernelServiceDill[];
extern intptr_t kKernelServiceDillSize;
extern const uint8_t kPlatformDill[];
extern intptr_t kPlatformDillSize;
extern const uint8_t kPlatformStrongDill[];
extern intptr_t kPlatformStrongDillSize;
#else
const uint8_t* kKernelServiceDill = NULL;
intptr_t kKernelServiceDillSize = 0;
const uint8_t* kPlatformDill = NULL;
intptr_t kPlatformDillSize = 0;
const uint8_t* kPlatformStrongDill = NULL;
intptr_t kPlatformStrongDillSize = 0;
#endif // !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
}
namespace dart {
namespace bin {
#if !defined(DART_PRECOMPILED_RUNTIME)
DFE dfe;
#endif
#if defined(DART_NO_SNAPSHOT) || defined(DART_PRECOMPILER)
const uint8_t* kernel_service_dill = NULL;
const intptr_t kernel_service_dill_size = 0;
const uint8_t* platform_dill = NULL;
const intptr_t platform_dill_size = 0;
const uint8_t* platform_strong_dill = NULL;
const intptr_t platform_strong_dill_size = 0;
#else
const uint8_t* kernel_service_dill = kKernelServiceDill;
const intptr_t kernel_service_dill_size = kKernelServiceDillSize;
const uint8_t* platform_dill = kPlatformDill;
const intptr_t platform_dill_size = kPlatformDillSize;
const uint8_t* platform_strong_dill = kPlatformStrongDill;
const intptr_t platform_strong_dill_size = kPlatformStrongDillSize;
#endif
const char kKernelServiceSnapshot[] = "kernel-service.dart.snapshot";
const char kSnapshotsDirectory[] = "snapshots";
static char* GetDirectoryPrefixFromExeName() {
const char* name = Platform::GetExecutableName();
const char* sep = File::PathSeparator();
const intptr_t sep_length = strlen(sep);
for (intptr_t i = strlen(name) - 1; i >= 0; --i) {
const char* str = name + i;
if (strncmp(str, sep, sep_length) == 0
#if defined(HOST_OS_WINDOWS)
// TODO(aam): GetExecutableName doesn't work reliably on Windows,
// the code below is a workaround for that (we would be using
// just single Platform::Separator instead of both slashes if it did).
|| *str == '/'
#endif
) {
return Utils::StrNDup(name, i + 1);
}
}
return strdup("");
}
DFE::DFE()
: use_dfe_(false),
frontend_filename_(NULL),
application_kernel_buffer_(NULL),
application_kernel_buffer_size_(0) {}
DFE::~DFE() {
if (frontend_filename_ != NULL) {
free(frontend_filename_);
}
frontend_filename_ = NULL;
free(application_kernel_buffer_);
application_kernel_buffer_ = NULL;
application_kernel_buffer_size_ = 0;
}
void DFE::Init() {
if (platform_dill == NULL) {
return;
}
if (frontend_filename_ == NULL) {
// Look for the frontend snapshot next to the executable.
char* dir_prefix = GetDirectoryPrefixFromExeName();
// |dir_prefix| includes the last path seperator.
frontend_filename_ =
OS::SCreate(NULL, "%s%s", dir_prefix, kKernelServiceSnapshot);
if (!File::Exists(NULL, frontend_filename_)) {
// If the frontend snapshot is not found next to the executable,
// then look for it in the "snapshots" directory.
free(frontend_filename_);
// |dir_prefix| includes the last path seperator.
frontend_filename_ =
OS::SCreate(NULL, "%s%s%s%s", dir_prefix, kSnapshotsDirectory,
File::PathSeparator(), kKernelServiceSnapshot);
}
free(dir_prefix);
if (!File::Exists(NULL, frontend_filename_)) {
free(frontend_filename_);
frontend_filename_ = NULL;
}
}
}
bool DFE::KernelServiceDillAvailable() {
return kernel_service_dill != NULL;
}
void DFE::LoadKernelService(const uint8_t** kernel_service_buffer,
intptr_t* kernel_service_buffer_size) {
*kernel_service_buffer = kernel_service_dill;
*kernel_service_buffer_size = kernel_service_dill_size;
}
void DFE::LoadPlatform(const uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size,
bool strong) {
if (strong) {
*kernel_buffer = platform_strong_dill;
*kernel_buffer_size = platform_strong_dill_size;
} else {
*kernel_buffer = platform_dill;
*kernel_buffer_size = platform_dill_size;
}
}
bool DFE::CanUseDartFrontend() const {
return (platform_dill != NULL) &&
(KernelServiceDillAvailable() || (frontend_filename() != NULL));
}
class WindowsPathSanitizer {
public:
explicit WindowsPathSanitizer(const char* path) {
// For Windows we need to massage the paths a bit according to
// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx
//
// Convert
// C:\one\two\three
// to
// /C:/one/two/three
//
// (see builtin.dart#_sanitizeWindowsPath)
intptr_t len = strlen(path);
sanitized_uri_ = reinterpret_cast<char*>(malloc(len + 1 + 1));
if (sanitized_uri_ == NULL) {
OUT_OF_MEMORY();
}
char* s = sanitized_uri_;
if (len > 2 && path[1] == ':') {
*s++ = '/';
}
for (const char *p = path; *p; ++p, ++s) {
*s = *p == '\\' ? '/' : *p;
}
*s = '\0';
}
~WindowsPathSanitizer() { free(sanitized_uri_); }
const char* sanitized_uri() { return sanitized_uri_; }
private:
char* sanitized_uri_;
DISALLOW_COPY_AND_ASSIGN(WindowsPathSanitizer);
};
Dart_KernelCompilationResult DFE::CompileScript(const char* script_uri,
bool strong,
bool incremental,
const char* package_config) {
// TODO(aam): When Frontend is ready, VM should be passing vm_outline.dill
// instead of vm_platform.dill to Frontend for compilation.
#if defined(HOST_OS_WINDOWS)
WindowsPathSanitizer path_sanitizer(script_uri);
const char* sanitized_uri = path_sanitizer.sanitized_uri();
#else
const char* sanitized_uri = script_uri;
#endif
const uint8_t* platform_binary =
strong ? platform_strong_dill : platform_dill;
intptr_t platform_binary_size =
strong ? platform_strong_dill_size : platform_dill_size;
return Dart_CompileToKernel(sanitized_uri, platform_binary,
platform_binary_size, incremental,
package_config);
}
void DFE::CompileAndReadScript(const char* script_uri,
uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size,
char** error,
int* exit_code,
bool strong,
const char* package_config) {
Dart_KernelCompilationResult result =
CompileScript(script_uri, strong, true, package_config);
switch (result.status) {
case Dart_KernelCompilationStatus_Ok:
*kernel_buffer = result.kernel;
*kernel_buffer_size = result.kernel_size;
*error = NULL;
*exit_code = 0;
break;
case Dart_KernelCompilationStatus_Error:
*error = result.error; // Copy error message.
*exit_code = kCompilationErrorExitCode;
break;
case Dart_KernelCompilationStatus_Crash:
*error = result.error; // Copy error message.
*exit_code = kDartFrontendErrorExitCode;
break;
case Dart_KernelCompilationStatus_Unknown:
*error = result.error; // Copy error message.
*exit_code = kErrorExitCode;
break;
}
}
void DFE::ReadScript(const char* script_uri,
uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size) const {
int64_t start = Dart_TimelineGetMicros();
if (!TryReadKernelFile(script_uri, kernel_buffer, kernel_buffer_size)) {
return;
}
if (!Dart_IsKernel(*kernel_buffer, *kernel_buffer_size)) {
free(*kernel_buffer);
*kernel_buffer = NULL;
*kernel_buffer_size = -1;
}
int64_t end = Dart_TimelineGetMicros();
Dart_TimelineEvent("DFE::ReadScript", start, end,
Dart_Timeline_Event_Duration, 0, NULL, NULL);
}
bool DFE::TryReadKernelFile(const char* script_uri,
uint8_t** kernel_ir,
intptr_t* kernel_ir_size) {
*kernel_ir = NULL;
*kernel_ir_size = -1;
void* script_file = DartUtils::OpenFileUri(script_uri, false);
if (script_file == NULL) {
return false;
}
uint8_t* buffer = NULL;
DartUtils::ReadFile(&buffer, kernel_ir_size, script_file);
DartUtils::CloseFile(script_file);
if (*kernel_ir_size == 0 || buffer == NULL) {
return false;
}
if (DartUtils::SniffForMagicNumber(buffer, *kernel_ir_size) !=
DartUtils::kKernelMagicNumber) {
free(buffer);
*kernel_ir = NULL;
*kernel_ir_size = -1;
return false;
}
// Do not free buffer if this is a kernel file - kernel_file will be
// backed by the same memory as the buffer and caller will own it.
// Caller is responsible for freeing the buffer when this function
// returns true.
*kernel_ir = buffer;
return true;
}
} // namespace bin
} // namespace dart
<|endoftext|> |
<commit_before>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: IObserver (parent)
, AbstractClientObserver(channelFilter)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
qDebug ("Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
qDebug ("But we weren't asked to notify anything, so go away");
return;
}
msg = QString("There are %1 channels in channels list")
.arg (channels.size ());
qDebug () << msg;
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
qDebug ("Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("Waiting for channel to become ready");
}
qDebug ("All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
qDebug ("Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
qWarning ("Failed while waiting for something");
break;
}
QString msg;
msg = QString("Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
qDebug () << msg;
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
qDebug () << msg;
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
qDebug ("Channel that we're not interested in");
break;
}
qDebug ("Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
qWarning ("Failed to accept call");
}
else
{
qDebug ("Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
qWarning ("Dammit the channel is still not ready");
}
else
{
qDebug ("Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
qWarning ("Dammit the connection is still not ready");
}
else
{
qDebug ("Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
qWarning ("Dammit the account is still not ready");
}
else
{
qDebug ("Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<commit_msg>debug messages<commit_after>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: IObserver (parent)
, AbstractClientObserver(channelFilter)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
qDebug() << "TpObserver: Start monitoring" << strC;
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
qDebug() << "TpObserver: Stop monitoring" << strContact;
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
qDebug ("TpObserver: Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
qDebug ("TpObserver: But we weren't asked to notify anything, so go away");
return;
}
msg = QString("TpObserver: There are %1 channels in channels list")
.arg (channels.size ());
qDebug () << msg;
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
qDebug ("TpObserver: Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("TpObserver: Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("TpObserver: Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
qDebug ("TpObserver: Waiting for channel to become ready");
}
qDebug ("TpObserver: All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
qDebug ("TpObserver: Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
qWarning ("TpObserver: Failed while waiting for something");
break;
}
QString msg;
msg = QString("TpObserver: Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
qDebug () << msg;
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("TpObserver: Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
qDebug () << msg;
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
qDebug ("TpObserver: Channel that we're not interested in");
break;
}
qDebug ("TpObserver: Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
qWarning ("TpObserver: Failed to accept call");
}
else
{
qDebug ("TpObserver: Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("TpObserver: Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
qWarning ("TpObserver: Dammit the channel is still not ready");
}
else
{
qDebug ("TpObserver: Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("TpObserver: Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
qWarning ("TpObserver: Dammit the connection is still not ready");
}
else
{
qDebug ("TpObserver: Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
qWarning ("TpObserver: Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
qWarning ("TpObserver: Dammit the account is still not ready");
}
else
{
qDebug ("TpObserver: Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<|endoftext|> |
<commit_before>/*
* ProjectMain.cpp
*
* Created: 5/26/2015 2:22:43 PM
* Author: barna.peto
*/
/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>
#include <PWM.h>
/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>
/*
* Main code called on reset is in Arduino.h
*/
void task20ms(void) {};
void task40ms(void) {};
void task60ms(void) {};
void task100ms(void) {};
void task1000ms(void) {};
static TaskType_stType tasks_st[] = {
{ T_INTERVAL_20MS, task20ms },
{ T_INTERVAL_40MS, task40ms },
{ T_INTERVAL_60MS, task60ms },
{ T_INTERVAL_100MS, task100ms },
{ T_INTERVAL_1000MS,task1000ms },
};
TaskType_stType *taskGetConfigPtr(void) {
return tasks_st;
}
uint8_t getNrTasks(void) {
return sizeof(tasks_st) / sizeof(*tasks_st);
}
void timer1_init() {
// set the timer with a prescaler = 1024;
TCCR1B |= (1<<CS02)|(1<<CS00);
// initialize counter
TCNT1 = T_TIMER_START;
// enable overflow interrupt
TIMSK1 |= (1<<TOIE1);
//enable global intterupts
sei();
}
void PWM_Init() {
//PWM setup
DDRD |= (1 << DDD5) | (1 << DDD6 ));
// PD6 is now an output
//OCR2A = PWM_DC_Max/(100/PWM_DC);
//OCR2B = PWM_DC_Max/(100/PWM_DC);
//functie apelata ciclic cu request-ul respectiv
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22); //????
// set prescaler to ??? and starts PWM*/
}
uint16_t stui_tick;
uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();
static TaskType_stType *taskPtr;
ISR(TIMER1_OVF_vect) {
TCNT1 = T_TIMER_START;
taskTimeCounterFlag_u8 = 1;
taskTimeCounter_u8++;
}
void setup()
{
taskTimeCounterFlag_u8 = 0;
taskTimeCounter_u8 = 0;
/*This is the setup function. It will be called once
pinMode(13,OUTPUT);
Serial.begin(9600);
Serial.print("Hello World!");
//PWM setup
DDRD |= (1 << DDD6);
// PD6 is now an output
OCR2A = 128;
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS21);
// set prescaler to 8 and starts PWM*/
timer1_init();
stui_tick = 0; // System tick
stui_TaskIndex = 0;
taskPtr = taskGetConfigPtr();
}
void loop()
{
// if 20ms have passed
if(taskTimeCounterFlag_u8==1) {
for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {
if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
(*taskPtr[stui_TaskIndex].ptrFunc)();
} else {
// do nothing
}
}
}
taskTimeCounterFlag_u8 = 0;
}
}
<commit_msg>Progmain.cpp<commit_after>/*
* ProjectMain.cpp
*
* Created: 5/26/2015 2:22:43 PM
* Author: barna.peto
*/
/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>
#include <PWM.h>
/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>
/*Include C Files*/
#include "TaskFunctions.c"
/*
* Main code called on reset is in Arduino.h
*/
void task20ms(void) {};
void task40ms(void) {};
void task60ms(void) {};
void task100ms(void) {};
void task1000ms(void) {};
static TaskType_stType tasks_st[] = {
{ T_INTERVAL_20MS, task20ms },
{ T_INTERVAL_40MS, task40ms },
{ T_INTERVAL_60MS, task60ms },
{ T_INTERVAL_100MS, task100ms },
{ T_INTERVAL_1000MS,task1000ms },
};
/**
* Function Implementation
* Return a pointer to tasks configuration table
*/
TaskType_stType *taskGetConfigPtr(void) {
return tasks_st;
}
/**
* Function Implementation
* Return the number of current tasks scheduled to run
*/
uint8_t getNrTasks(void) {
return sizeof(tasks_st) / sizeof(*tasks_st);
}
/**
* Function Implementation
* Initialize the timer
*/
void timer1_init() {
// set the timer with a prescaler = 256;
TCCR1B |= (1<<CS12);
// initialize counter
TCNT1 = T_TIMER_START;
// enable overflow interrupt
TIMSK1 |= (1<<TOIE1);
//enable global intterupts
sei();
}
void PWM_Init() {
//PWM setup
DDRD |= (1 << DDD5) | (1 << DDD6 ));
// PD6 is now an output
//OCR2A = PWM_DC_Max/(100/PWM_DC);
//OCR2B = PWM_DC_Max/(100/PWM_DC);
//functie apelata ciclic cu request-ul respectiv
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22); //????
// set prescaler to ??? and starts PWM*/
}
uint16_t stui_tick;
uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();
static TaskType_stType *taskPtr;
ISR(TIMER1_OVF_vect) {
TCNT1 = T_TIMER_START;
taskTimeCounterFlag_u8 = 1;
taskTimeCounter_u8++;
}
void setup()
{
taskTimeCounterFlag_u8 = 0;
taskTimeCounter_u8 = 0;
InitPWM(pin); /*Functia de initializare pwm*/
/*This is the setup function. It will be called once
pinMode(13,OUTPUT);
Serial.begin(9600);
Serial.print("Hello World!");
//PWM setup
DDRD |= (1 << DDD6);
// PD6 is now an output
OCR2A = 128;
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS21);
// set prescaler to 8 and starts PWM*/
timer1_init();
stui_tick = 0; // System tick
stui_TaskIndex = 0;
taskPtr = taskGetConfigPtr();
}
void loop()
{
// if 20ms have passed
if(taskTimeCounterFlag_u8==1) {
for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {
if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
(*taskPtr[stui_TaskIndex].ptrFunc)();
} else {
// do nothing
}
}
}
taskTimeCounterFlag_u8 = 0;
}
}
//------------------------Cod pentru Citire IMPUTS---------------
#define CHECK_BIT(var,pos) ((var) & (1<<(pos))) //macro care verifica o pozitie din registru daca e pe 1 logic
//functia pentru citirea unui pin
int getValue(uint8_t pin){
uint8_t Register; // variabila in care stocam valoarea registrului din care citim
//cautam registrul aferent piniului selectat, PINx de unde citim starea pinului
if ((0 <=pin)||(pin <=7))
{
Register = PIND; //Registrii PINx sunt Read Only
}
else if((8 >=pin)||(pin <=13))
{
Register = PINB;
//pin= pin-7; resetam pinul astfel incat sa putem citi din registrul pinB daca acesta nu e setat in memorie in continuare la PIND
}
else if((14 >=pin)||(pin <=19))
{
Register = PINC;
//pin= pin-13;
}
else
Register=NOT_A_PIN;
//cautam pinul din registrul aferent,de aici putem afla starea pinilor daca sunt Input (1), sau Output (0);
if(CHECK_BIT(Register,pin)==1)
{ return true;}
else
{return false;}
}
//-------------Cod pentru Setare Output PWM-----------------
int DOPWM_setValue(char pin, int duty)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
char value;
//formula pentru duty cycle in procente
value = (duty*256)/100;
//Setam duty cycle pentru fiecare pin cu registrii OCR2A, OCR2B
OCR2A = value;
}
//functie de initializare pwm
InitPWM(char pin)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
/* SETAM TIMERUL 2 PENTRU Modul PHASE CORRECTED PWM*/
//setam Timer Counter Control Register A pe None-inverting mode si PWM Phase Corrected Mode
TCCR2A |= (1 << COM2A1) | (0 << COM2A0) | (1 << COM2B1)| (0 << COM2B0);
// set none-inverting mode on bytes (7,6,5,4) for timer 2
TCCR2A |= (0 << WGM21) | (1 << WGM20);
// set PWM Phase Corrected Mode using OCR2A TOP value on bytes (1,0)
// setam Timer Counter Control Register B pe PWM Phase Corrected Mode si cu un prescaler de 64
TCCR2B |= (1 << CS22) | (1 << WGM22);
// set prescaler to 64 and starts PWM and sets PWM Phase Corrected Mode
}
<|endoftext|> |
<commit_before>#include <Poco/AutoPtr.h>
#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>
#include "db.h"
#ifdef ENABLE_SQLITE3
extern "C" {
extern DB::Connection *create_sqlite3_connection(void);
};
class SqliteInvalidTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open(".", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
ASSERT_EQ(connection->isConnected(), false);
}
class SqliteDefaultTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
EXPECT_EQ(connection->isConnected(), true);
}
TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}
TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("BYE"), false);
}
TEST_F(SqliteDefaultTest, EscapeCharacters) {
EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}
TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
const char *t = connection->unixtimeToSql((time_t) 1414965631);
EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}
TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
EXPECT_EQ(connection->errorno(), 0);
EXPECT_STREQ(connection->errormsg(), "not an error");
}
TEST_F(SqliteDefaultTest, VersionString) {
const char *v = connection->version();
bool correct = false;
if (strstr(v, "Sqlite3 Driver v0.2")) {
correct = true;
}
EXPECT_EQ(correct, true);
}
class SqliteTransactionTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)");
connection->beginTrans();
}
virtual void TearDown() {
connection->commitTrans();
connection->execute("DROP TABLE testing");
connection->close();
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteTransactionTest, SingleInsert) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}
TEST_F(SqliteTransactionTest, SingleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
EXPECT_EQ(connection->commitTrans(), true);
EXPECT_EQ(connection->beginTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 42);
EXPECT_EQ(rs->getFloat(3), 42.0f);
EXPECT_EQ(rs->getDouble(3), 42.0F);
EXPECT_EQ(rs->getLong(3), 42l);
EXPECT_EQ(rs->getBool(3), false);
EXPECT_EQ(rs->getShort(3), (short) 42);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
EXPECT_EQ(rs->recordCount(), 0);
rs->close();
}
TEST_F(SqliteTransactionTest, DoubleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->commitTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 1);
EXPECT_EQ(rs->getFloat(3), 1.0f);
EXPECT_EQ(rs->getDouble(3), 1.0F);
EXPECT_EQ(rs->getLong(3), 1l);
EXPECT_EQ(rs->getBool(3), true);
EXPECT_EQ(rs->getShort(3), (short) 1);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
rs->close();
}
TEST_F(SqliteTransactionTest, QueryString) {
connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED);
connection->setTransactionMode(DB::Connection::READ_COMMITTED);
connection->setTransactionMode(DB::Connection::REPEATABLE_READ);
connection->setTransactionMode(DB::Connection::SERIALIZABLE);
DB::Query q(*connection);
q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
q << "," << 42.0f << ");";
EXPECT_EQ(connection->execute(q.str()), true);
unsigned long id = connection->insertId();
EXPECT_EQ(id, 1);
EXPECT_EQ(connection->commitTrans(), true);
}
TEST_F(SqliteTransactionTest, RollbackTransaction) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
EXPECT_EQ(connection->rollbackTrans(), true);
}
TEST_F(SqliteTransactionTest, QueryStringTypes) {
DB::Query q(*connection);
q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
EXPECT_EQ(strlen(q.str()), 80);
}
TEST_F(SqliteTransactionTest, QueryStringTypes2) {
DB::Query q(*connection);
std::stringstream world;
world << " World" << std::ends;
q << std::string("Hello") << world;
EXPECT_EQ(strlen(q.str()), 11);
}
TEST_F(SqliteTransactionTest, QueryNumberTypes) {
DB::Query q(*connection);
double d = 42.2;
short s = 42;
unsigned short su = 42;
q << 42 << " " << d << " " << s << (const unsigned char *) " ";
q << 42u << " " << 42ul << " " << su;
}
#endif
<commit_msg>Fixed schema for older sqlite3.<commit_after>#include <Poco/AutoPtr.h>
#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>
#include "db.h"
#ifdef ENABLE_SQLITE3
extern "C" {
extern DB::Connection *create_sqlite3_connection(void);
};
class SqliteInvalidTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open(".", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
ASSERT_EQ(connection->isConnected(), false);
}
class SqliteDefaultTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
EXPECT_EQ(connection->isConnected(), true);
}
TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}
TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("BYE"), false);
}
TEST_F(SqliteDefaultTest, EscapeCharacters) {
EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}
TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
const char *t = connection->unixtimeToSql((time_t) 1414965631);
EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}
TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
EXPECT_EQ(connection->errorno(), 0);
EXPECT_STREQ(connection->errormsg(), "not an error");
}
TEST_F(SqliteDefaultTest, VersionString) {
const char *v = connection->version();
bool correct = false;
if (strstr(v, "Sqlite3 Driver v0.2")) {
correct = true;
}
EXPECT_EQ(correct, true);
}
class SqliteTransactionTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)"), true);
connection->beginTrans();
}
virtual void TearDown() {
connection->commitTrans();
connection->execute("DROP TABLE testing");
connection->close();
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteTransactionTest, SingleInsert) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}
TEST_F(SqliteTransactionTest, SingleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
EXPECT_EQ(connection->commitTrans(), true);
EXPECT_EQ(connection->beginTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 42);
EXPECT_EQ(rs->getFloat(3), 42.0f);
EXPECT_EQ(rs->getDouble(3), 42.0F);
EXPECT_EQ(rs->getLong(3), 42l);
EXPECT_EQ(rs->getBool(3), false);
EXPECT_EQ(rs->getShort(3), (short) 42);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
EXPECT_EQ(rs->recordCount(), 0);
rs->close();
}
TEST_F(SqliteTransactionTest, DoubleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->commitTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 1);
EXPECT_EQ(rs->getFloat(3), 1.0f);
EXPECT_EQ(rs->getDouble(3), 1.0F);
EXPECT_EQ(rs->getLong(3), 1l);
EXPECT_EQ(rs->getBool(3), true);
EXPECT_EQ(rs->getShort(3), (short) 1);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
rs->close();
}
TEST_F(SqliteTransactionTest, QueryString) {
connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED);
connection->setTransactionMode(DB::Connection::READ_COMMITTED);
connection->setTransactionMode(DB::Connection::REPEATABLE_READ);
connection->setTransactionMode(DB::Connection::SERIALIZABLE);
DB::Query q(*connection);
q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
q << "," << 42.0f << ");";
EXPECT_EQ(connection->execute(q.str()), true);
unsigned long id = connection->insertId();
EXPECT_EQ(id, 1);
EXPECT_EQ(connection->commitTrans(), true);
}
TEST_F(SqliteTransactionTest, RollbackTransaction) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
EXPECT_EQ(connection->rollbackTrans(), true);
}
TEST_F(SqliteTransactionTest, QueryStringTypes) {
DB::Query q(*connection);
q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
EXPECT_EQ(strlen(q.str()), 80);
}
TEST_F(SqliteTransactionTest, QueryStringTypes2) {
DB::Query q(*connection);
std::stringstream world;
world << " World" << std::ends;
q << std::string("Hello") << world;
EXPECT_EQ(strlen(q.str()), 11);
}
TEST_F(SqliteTransactionTest, QueryNumberTypes) {
DB::Query q(*connection);
double d = 42.2;
short s = 42;
unsigned short su = 42;
q << 42 << " " << d << " " << s << (const unsigned char *) " ";
q << 42u << " " << 42ul << " " << su;
}
#endif
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* \file CanIf.hxx
*
* Defines a service for interfacing with a CANbus. The interface receives
* incoming frames from the bus device and proxies it to various handlers that
* the user may register for specific ranges of CAN identifiers.
*
* @author Balazs Racz
* @date 11 May 2014
*/
#ifndef _UTILS_CANIF_HXX_
#define _UTILS_CANIF_HXX_
#include "nmranet_can.h"
#include "utils/PipeFlow.hxx"
/** Thin wrapper around struct can_frame that will allow a dispatcher select
* the frames by CAN ID and mask as desired by the handlers. */
struct CanMessageData : public can_frame
{
/** Constructor. Resets the inlined frame to an empty extended frame. */
CanMessageData()
{
CLR_CAN_FRAME_ERR(*this);
CLR_CAN_FRAME_RTR(*this);
SET_CAN_FRAME_EFF(*this);
can_dlc = 0;
}
typedef uint32_t id_type;
/** This bit will be set in standard CAN frames when they get to the
* dispatcher. */
static const id_type STANDARD_FRAME_BIT = (1U << 30);
/** Filter to OR onto a can ID to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_EXT_FRAME_FILTER = 0;
/** Mask to OR onto a can mask to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_EXT_FRAME_MASK = ~0x1FFFFFFFU;
/** @returns the identifier for dispatching */
id_type id()
{
if (IS_CAN_FRAME_EFF(*this))
{
return GET_CAN_FRAME_ID_EFF(*this);
}
else
{
return GET_CAN_FRAME_ID(*this) | STANDARD_FRAME_BIT;
}
}
/** @Returns a mutable pointer to the embedded CAN frame. */
struct can_frame *mutable_frame()
{
return this;
}
/** @Returns the embedded CAN frame. */
const struct can_frame &frame() const
{
return *this;
}
/* This will be aliased onto CanHubData::skipMember_. It is needed to keep
* the two structures the same size for casting between them. */
void *unused;
};
/** @todo(balazs.racz) make these two somehow compatible with each other. It's
* not easy, because they use different ID functions and their size differs
* a bit as well. */
typedef FlowInterface<Buffer<CanMessageData>> IncomingFrameHandler;
typedef FlowInterface<Buffer<CanHubData>> OutgoingFrameHandler;
class CanIf;
/** Interface class for the asynchronous frame write flow. This flow allows you
to write frames to the CAN bus.
Usage:
. allocate a buffer for this flow.
. fill in buffer->data()->mutable_frame() [*]
. call flow->send(buffer)
*/
class CanFrameWriteFlow : public OutgoingFrameHandler
{
public:
CanFrameWriteFlow(CanIf *service)
: ifCan_(service)
{
}
virtual DynamicPool *pool();
virtual void send(Buffer<CanHubData> *message,
unsigned priority = UINT_MAX);
private:
CanIf *ifCan_;
};
/** This flow is responsible for taking data from the can HUB and sending it to
* the IfCan's dispatcher. */
class CanFrameReadFlow : public OutgoingFrameHandler
{
public:
CanFrameReadFlow(CanIf *service)
: ifCan_(service)
{
}
virtual DynamicPool *pool();
virtual void send(Buffer<CanHubData> *message,
unsigned priority = UINT_MAX);
private:
CanIf *ifCan_;
};
class CanIf
{
public:
CanIf(Service *service, CanHubFlow *device);
~CanIf();
typedef DispatchFlow<Buffer<CanMessageData>, 4> FrameDispatchFlow;
/// @returns the dispatcher of incoming CAN frames.
FrameDispatchFlow *frame_dispatcher()
{
return &frameDispatcher_;
}
/// @returns the flow for writing CAN frames to the bus.
OutgoingFrameHandler *frame_write_flow()
{
return &frameWriteFlow_;
}
private:
friend class CanFrameWriteFlow;
// friend class CanFrameReadFlow;
/** The device we need to send packets to. */
CanHubFlow *device_;
/** Flow responsible for writing packets to the CAN hub. */
CanFrameWriteFlow frameWriteFlow_;
/** Flow responsible for translating from CAN hub packets to dispatcher
* packets. */
CanFrameReadFlow frameReadFlow_;
/// Flow responsible for routing incoming messages to handlers.
FrameDispatchFlow frameDispatcher_;
/// @returns the asynchronous read/write object.
CanHubPortInterface *hub_port()
{
return &frameReadFlow_;
}
/// @returns the device (hub) that we need to send the packets to.
CanHubFlow *device()
{
return device_;
}
};
#endif // _UTILS_CANIF_HXX_
<commit_msg>Adds constants for matching against standard frames in a CAN dispatcher flow. Adds a typedef for a base class for incoming frame flows.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* \file CanIf.hxx
*
* Defines a service for interfacing with a CANbus. The interface receives
* incoming frames from the bus device and proxies it to various handlers that
* the user may register for specific ranges of CAN identifiers.
*
* @author Balazs Racz
* @date 11 May 2014
*/
#ifndef _UTILS_CANIF_HXX_
#define _UTILS_CANIF_HXX_
#include "nmranet_can.h"
#include "utils/PipeFlow.hxx"
/** Thin wrapper around struct can_frame that will allow a dispatcher select
* the frames by CAN ID and mask as desired by the handlers. */
struct CanMessageData : public can_frame
{
/** Constructor. Resets the inlined frame to an empty extended frame. */
CanMessageData()
{
CLR_CAN_FRAME_ERR(*this);
CLR_CAN_FRAME_RTR(*this);
SET_CAN_FRAME_EFF(*this);
can_dlc = 0;
}
typedef uint32_t id_type;
/** This bit will be set in standard CAN frames when they get to the
* dispatcher. */
static const id_type STANDARD_FRAME_BIT = (1U << 30);
/** Filter to OR onto a can ID to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_EXT_FRAME_FILTER = 0;
/** Mask to OR onto a can mask to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_EXT_FRAME_MASK = ~0x1FFFFFFFU;
/** Filter to OR onto a can ID to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_STD_FRAME_FILTER = STANDARD_FRAME_BIT;
/** Mask to OR onto a can mask to tell the dispatcher to only consider
* extended can frames. */
static const uint32_t CAN_STD_FRAME_MASK = ~0x7FFU;
/** @returns the identifier for dispatching */
id_type id()
{
if (IS_CAN_FRAME_EFF(*this))
{
return GET_CAN_FRAME_ID_EFF(*this);
}
else
{
return GET_CAN_FRAME_ID(*this) | STANDARD_FRAME_BIT;
}
}
/** @Returns a mutable pointer to the embedded CAN frame. */
struct can_frame *mutable_frame()
{
return this;
}
/** @Returns the embedded CAN frame. */
const struct can_frame &frame() const
{
return *this;
}
/* This will be aliased onto CanHubData::skipMember_. It is needed to keep
* the two structures the same size for casting between them. */
void *unused;
};
/** @todo(balazs.racz) make these two somehow compatible with each other. It's
* not easy, because they use different ID functions and their size differs
* a bit as well. */
typedef FlowInterface<Buffer<CanMessageData>> IncomingFrameHandler;
typedef StateFlow<Buffer<CanMessageData>, QList<1>> IncomingFrameFlow;
typedef FlowInterface<Buffer<CanHubData>> OutgoingFrameHandler;
class CanIf;
/** Interface class for the asynchronous frame write flow. This flow allows you
to write frames to the CAN bus.
Usage:
. allocate a buffer for this flow.
. fill in buffer->data()->mutable_frame() [*]
. call flow->send(buffer)
*/
class CanFrameWriteFlow : public OutgoingFrameHandler
{
public:
CanFrameWriteFlow(CanIf *service)
: ifCan_(service)
{
}
virtual DynamicPool *pool();
virtual void send(Buffer<CanHubData> *message,
unsigned priority = UINT_MAX);
private:
CanIf *ifCan_;
};
/** This flow is responsible for taking data from the can HUB and sending it to
* the IfCan's dispatcher. */
class CanFrameReadFlow : public OutgoingFrameHandler
{
public:
CanFrameReadFlow(CanIf *service)
: ifCan_(service)
{
}
virtual DynamicPool *pool();
virtual void send(Buffer<CanHubData> *message,
unsigned priority = UINT_MAX);
private:
CanIf *ifCan_;
};
class CanIf
{
public:
CanIf(Service *service, CanHubFlow *device);
~CanIf();
typedef DispatchFlow<Buffer<CanMessageData>, 4> FrameDispatchFlow;
Service *service()
{
return frameDispatcher_.service();
}
/// @returns the dispatcher of incoming CAN frames.
FrameDispatchFlow *frame_dispatcher()
{
return &frameDispatcher_;
}
/// @returns the flow for writing CAN frames to the bus.
OutgoingFrameHandler *frame_write_flow()
{
return &frameWriteFlow_;
}
private:
friend class CanFrameWriteFlow;
// friend class CanFrameReadFlow;
/** The device we need to send packets to. */
CanHubFlow *device_;
/** Flow responsible for writing packets to the CAN hub. */
CanFrameWriteFlow frameWriteFlow_;
/** Flow responsible for translating from CAN hub packets to dispatcher
* packets. */
CanFrameReadFlow frameReadFlow_;
/// Flow responsible for routing incoming messages to handlers.
FrameDispatchFlow frameDispatcher_;
/// @returns the asynchronous read/write object.
CanHubPortInterface *hub_port()
{
return &frameReadFlow_;
}
/// @returns the device (hub) that we need to send the packets to.
CanHubFlow *device()
{
return device_;
}
};
#endif // _UTILS_CANIF_HXX_
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOpenGL3Renderer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/ImageCodec.h"
#include "CEGUI/DynamicModule.h"
#include "CEGUI/RendererModules/OpenGL/ViewportTarget.h"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Logger.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RenderMaterial.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"
#include <sstream>
#include <algorithm>
#include <cstring>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// The following are some GL extension / version dependant related items.
// This is all done totally internally here; no need for external interface
// to show any of this.
//----------------------------------------------------------------------------//
// we only really need this with MSVC / Windows(?) and by now it should already
// be defined on that platform, so we just define it as empty macro so the
// compile does not break on other systems.
#ifndef APIENTRY
# define APIENTRY
#endif
//! Dummy function for if real ones are not present (saves testing each render)
static void APIENTRY activeTextureDummy(GLenum) {}
//----------------------------------------------------------------------------//
// template specialised class that does the real work for us
template<typename T>
class OGLTemplateTargetFactory : public OGLTextureTargetFactory
{
TextureTarget* create(OpenGLRendererBase& r) const
{ return CEGUI_NEW_AO T(static_cast<OpenGL3Renderer&>(r)); }
};
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
if (System::getSingletonPtr())
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is already initialised."));
OpenGL3Renderer& renderer(create());
DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider();
System::create(renderer, rp);
return renderer;
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const Sizef& display_size,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
if (System::getSingletonPtr())
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is already initialised."));
OpenGL3Renderer& renderer(create(display_size));
DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider();
System::create(renderer, rp);
return renderer;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::destroySystem()
{
System* sys;
if (!(sys = System::getSingletonPtr()))
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is not created or was already destroyed."));
OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(sys->getRenderer());
DefaultResourceProvider* rp =
static_cast<DefaultResourceProvider*>(sys->getResourceProvider());
System::destroy();
CEGUI_DELETE_AO rp;
destroy(*renderer);
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::create(const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
return *CEGUI_NEW_AO OpenGL3Renderer();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::create(const Sizef& display_size,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
return *CEGUI_NEW_AO OpenGL3Renderer(display_size);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::destroy(OpenGL3Renderer& renderer)
{
CEGUI_DELETE_AO &renderer;
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::OpenGL3Renderer() :
d_shaderWrapperTextured(0),
d_openGLStateChanger(0),
d_shaderManager(0)
{
initialiseRendererIDString();
initialiseGLExtensions();
d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this);
initialiseTextureTargetFactory();
initialiseOpenGLShaders();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::OpenGL3Renderer(const Sizef& display_size) :
OpenGLRendererBase(display_size),
d_shaderWrapperTextured(0),
d_openGLStateChanger(0),
d_shaderManager(0)
{
initialiseRendererIDString();
initialiseGLExtensions();
d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this);
initialiseTextureTargetFactory();
initialiseOpenGLShaders();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::~OpenGL3Renderer()
{
CEGUI_DELETE_AO d_textureTargetFactory;
CEGUI_DELETE_AO d_openGLStateChanger;
CEGUI_DELETE_AO d_shaderManager;
delete d_shaderWrapperTextured;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseRendererIDString()
{
d_rendererID =
"CEGUI::OpenGL3Renderer - Official OpenGL 3.2 core based "
"renderer module.";
}
//----------------------------------------------------------------------------//
OpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial)
{
return CEGUI_NEW_AO OpenGL3GeometryBuffer(*this, renderMaterial);
}
//----------------------------------------------------------------------------//
TextureTarget* OpenGL3Renderer::createTextureTarget_impl()
{
return d_textureTargetFactory->create(*this);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::beginRendering()
{
// do required set-up. yes, it really is this minimal ;)
glEnable(GL_SCISSOR_TEST);
glEnable(GL_BLEND);
// force set blending ops to get to a known state.
setupRenderingBlendMode(BM_NORMAL, true);
// if enabled, restores a subset of the GL state back to default values.
if (d_initExtraStates)
setupExtraStates();
d_openGLStateChanger->reset();
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::endRendering()
{
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::setupExtraStates()
{
glActiveTexture(GL_TEXTURE0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseTextureTargetFactory()
{
//Use OGL core implementation for FBOs
d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation.";
d_textureTargetFactory = CEGUI_NEW_AO OGLTemplateTargetFactory<OpenGL3FBOTextureTarget>;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode,
const bool force)
{
// exit if mode is already set up (and update not forced)
if ((d_activeBlendMode == mode) && !force)
return;
d_activeBlendMode = mode;
if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)
{
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE);
}
}
//----------------------------------------------------------------------------//
Sizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz) const
{
return Sizef(sz);
}
//----------------------------------------------------------------------------//
OpenGL3StateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger()
{
return d_openGLStateChanger;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseOpenGLShaders()
{
checkGLErrors();
d_shaderManager = CEGUI_NEW_AO OpenGL3ShaderManager(d_openGLStateChanger);
d_shaderManager->initialiseShaders();
initialiseStandardTexturedShaderWrapper();
initialiseStandardSolidShaderWrapper();
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseGLExtensions()
{
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK)
{
std::ostringstream err_string;
//Problem: glewInit failed, something is seriously wrong.
err_string << "failed to initialise the GLEW library. "
<< glewGetErrorString(err);
CEGUI_THROW(RendererException(err_string.str().c_str()));
}
//Clear the useless error glew produces as of version 1.7.0, when using OGL3.2 Core Profile
glGetError();
// Why do we do this and not use GLEW_EXT_texture_compression_s3tc?
// Because of glewExperimental, of course!
int ext_count;
glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count);
for(int i = 0; i < ext_count; ++i)
{
if (!std::strcmp(
reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)),
"GL_EXT_texture_compression_s3tc"))
{
d_s3tcSupported = true;
break;
}
}
}
//----------------------------------------------------------------------------//
bool OpenGL3Renderer::isS3TCSupported() const
{
return d_s3tcSupported;
}
//----------------------------------------------------------------------------//
RefCounted<RenderMaterial> OpenGL3Renderer::createRenderMaterial(const DefaultShaderType shaderType) const
{
if(shaderType == DS_TEXTURED)
{
RefCounted<RenderMaterial> render_material(CEGUI_NEW_AO RenderMaterial(d_shaderWrapperTextured));
return render_material;
}
else if(shaderType == DS_SOLID);
{
RefCounted<RenderMaterial> render_material(CEGUI_NEW_AO RenderMaterial(d_shaderWrapperSolid));
return render_material;
}
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseStandardTexturedShaderWrapper()
{
OpenGL3Shader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED);
d_shaderWrapperTextured = new OpenGL3ShaderWrapper(*shader_standard_textured);
d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0);
d_shaderWrapperTextured->addUniformVariable("modelViewPerspMatrix");
d_shaderWrapperTextured->addAttributeVariable("inPosition");
d_shaderWrapperTextured->addAttributeVariable("inTexCoord");
d_shaderWrapperTextured->addAttributeVariable("inColour");
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseStandardSolidShaderWrapper()
{
OpenGL3Shader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID);
d_shaderWrapperSolid = new OpenGL3ShaderWrapper(*shader_standard_solid);
d_shaderWrapperSolid->addTextureUniformVariable("texture0", 0);
d_shaderWrapperSolid->addUniformVariable("modelViewPerspMatrix");
d_shaderWrapperSolid->addAttributeVariable("inPosition");
d_shaderWrapperSolid->addAttributeVariable("inColour");
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: Semicolon typo fix<commit_after>/***********************************************************************
filename: CEGUIOpenGL3Renderer.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/ImageCodec.h"
#include "CEGUI/DynamicModule.h"
#include "CEGUI/RendererModules/OpenGL/ViewportTarget.h"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Logger.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RenderMaterial.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"
#include <sstream>
#include <algorithm>
#include <cstring>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// The following are some GL extension / version dependant related items.
// This is all done totally internally here; no need for external interface
// to show any of this.
//----------------------------------------------------------------------------//
// we only really need this with MSVC / Windows(?) and by now it should already
// be defined on that platform, so we just define it as empty macro so the
// compile does not break on other systems.
#ifndef APIENTRY
# define APIENTRY
#endif
//! Dummy function for if real ones are not present (saves testing each render)
static void APIENTRY activeTextureDummy(GLenum) {}
//----------------------------------------------------------------------------//
// template specialised class that does the real work for us
template<typename T>
class OGLTemplateTargetFactory : public OGLTextureTargetFactory
{
TextureTarget* create(OpenGLRendererBase& r) const
{ return CEGUI_NEW_AO T(static_cast<OpenGL3Renderer&>(r)); }
};
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
if (System::getSingletonPtr())
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is already initialised."));
OpenGL3Renderer& renderer(create());
DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider();
System::create(renderer, rp);
return renderer;
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const Sizef& display_size,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
if (System::getSingletonPtr())
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is already initialised."));
OpenGL3Renderer& renderer(create(display_size));
DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider();
System::create(renderer, rp);
return renderer;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::destroySystem()
{
System* sys;
if (!(sys = System::getSingletonPtr()))
CEGUI_THROW(InvalidRequestException(
"CEGUI::System object is not created or was already destroyed."));
OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(sys->getRenderer());
DefaultResourceProvider* rp =
static_cast<DefaultResourceProvider*>(sys->getResourceProvider());
System::destroy();
CEGUI_DELETE_AO rp;
destroy(*renderer);
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::create(const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
return *CEGUI_NEW_AO OpenGL3Renderer();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer& OpenGL3Renderer::create(const Sizef& display_size,
const int abi)
{
System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);
return *CEGUI_NEW_AO OpenGL3Renderer(display_size);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::destroy(OpenGL3Renderer& renderer)
{
CEGUI_DELETE_AO &renderer;
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::OpenGL3Renderer() :
d_shaderWrapperTextured(0),
d_openGLStateChanger(0),
d_shaderManager(0)
{
initialiseRendererIDString();
initialiseGLExtensions();
d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this);
initialiseTextureTargetFactory();
initialiseOpenGLShaders();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::OpenGL3Renderer(const Sizef& display_size) :
OpenGLRendererBase(display_size),
d_shaderWrapperTextured(0),
d_openGLStateChanger(0),
d_shaderManager(0)
{
initialiseRendererIDString();
initialiseGLExtensions();
d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this);
initialiseTextureTargetFactory();
initialiseOpenGLShaders();
}
//----------------------------------------------------------------------------//
OpenGL3Renderer::~OpenGL3Renderer()
{
CEGUI_DELETE_AO d_textureTargetFactory;
CEGUI_DELETE_AO d_openGLStateChanger;
CEGUI_DELETE_AO d_shaderManager;
delete d_shaderWrapperTextured;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseRendererIDString()
{
d_rendererID =
"CEGUI::OpenGL3Renderer - Official OpenGL 3.2 core based "
"renderer module.";
}
//----------------------------------------------------------------------------//
OpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial)
{
return CEGUI_NEW_AO OpenGL3GeometryBuffer(*this, renderMaterial);
}
//----------------------------------------------------------------------------//
TextureTarget* OpenGL3Renderer::createTextureTarget_impl()
{
return d_textureTargetFactory->create(*this);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::beginRendering()
{
// do required set-up. yes, it really is this minimal ;)
glEnable(GL_SCISSOR_TEST);
glEnable(GL_BLEND);
// force set blending ops to get to a known state.
setupRenderingBlendMode(BM_NORMAL, true);
// if enabled, restores a subset of the GL state back to default values.
if (d_initExtraStates)
setupExtraStates();
d_openGLStateChanger->reset();
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::endRendering()
{
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::setupExtraStates()
{
glActiveTexture(GL_TEXTURE0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseTextureTargetFactory()
{
//Use OGL core implementation for FBOs
d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation.";
d_textureTargetFactory = CEGUI_NEW_AO OGLTemplateTargetFactory<OpenGL3FBOTextureTarget>;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode,
const bool force)
{
// exit if mode is already set up (and update not forced)
if ((d_activeBlendMode == mode) && !force)
return;
d_activeBlendMode = mode;
if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)
{
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE);
}
}
//----------------------------------------------------------------------------//
Sizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz) const
{
return Sizef(sz);
}
//----------------------------------------------------------------------------//
OpenGL3StateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger()
{
return d_openGLStateChanger;
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseOpenGLShaders()
{
checkGLErrors();
d_shaderManager = CEGUI_NEW_AO OpenGL3ShaderManager(d_openGLStateChanger);
d_shaderManager->initialiseShaders();
initialiseStandardTexturedShaderWrapper();
initialiseStandardSolidShaderWrapper();
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseGLExtensions()
{
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK)
{
std::ostringstream err_string;
//Problem: glewInit failed, something is seriously wrong.
err_string << "failed to initialise the GLEW library. "
<< glewGetErrorString(err);
CEGUI_THROW(RendererException(err_string.str().c_str()));
}
//Clear the useless error glew produces as of version 1.7.0, when using OGL3.2 Core Profile
glGetError();
// Why do we do this and not use GLEW_EXT_texture_compression_s3tc?
// Because of glewExperimental, of course!
int ext_count;
glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count);
for(int i = 0; i < ext_count; ++i)
{
if (!std::strcmp(
reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)),
"GL_EXT_texture_compression_s3tc"))
{
d_s3tcSupported = true;
break;
}
}
}
//----------------------------------------------------------------------------//
bool OpenGL3Renderer::isS3TCSupported() const
{
return d_s3tcSupported;
}
//----------------------------------------------------------------------------//
RefCounted<RenderMaterial> OpenGL3Renderer::createRenderMaterial(const DefaultShaderType shaderType) const
{
if(shaderType == DS_TEXTURED)
{
RefCounted<RenderMaterial> render_material(CEGUI_NEW_AO RenderMaterial(d_shaderWrapperTextured));
return render_material;
}
else if(shaderType == DS_SOLID)
{
RefCounted<RenderMaterial> render_material(CEGUI_NEW_AO RenderMaterial(d_shaderWrapperSolid));
return render_material;
}
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseStandardTexturedShaderWrapper()
{
OpenGL3Shader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED);
d_shaderWrapperTextured = new OpenGL3ShaderWrapper(*shader_standard_textured);
d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0);
d_shaderWrapperTextured->addUniformVariable("modelViewPerspMatrix");
d_shaderWrapperTextured->addAttributeVariable("inPosition");
d_shaderWrapperTextured->addAttributeVariable("inTexCoord");
d_shaderWrapperTextured->addAttributeVariable("inColour");
}
//----------------------------------------------------------------------------//
void OpenGL3Renderer::initialiseStandardSolidShaderWrapper()
{
OpenGL3Shader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID);
d_shaderWrapperSolid = new OpenGL3ShaderWrapper(*shader_standard_solid);
d_shaderWrapperSolid->addTextureUniformVariable("texture0", 0);
d_shaderWrapperSolid->addUniformVariable("modelViewPerspMatrix");
d_shaderWrapperSolid->addAttributeVariable("inPosition");
d_shaderWrapperSolid->addAttributeVariable("inColour");
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "console.hpp"
#include <unistd.h>
#include <iostream>
#include "exception.hpp"
namespace Quoridor {
namespace UI {
Console::Console(int player_num)
: game_(std::shared_ptr<Board>(new Board(10, 10)))
{
static std::string colors[4] = {
"red", "green", "pink", "blue"
};
if ((player_num != 2) && (player_num != 4)) {
throw Exception();
}
for (int i = 0; i < player_num; ++i) {
game_.add_pawn(std::shared_ptr<Pawn>(new Pawn(colors[i])));
}
}
Console::~Console()
{
}
void Console::run()
{
bool is_run = true;
BoardMoves move;
pos_t start_pos;
pos_t end_pos;
int rc;
// main loop
while (is_run) {
for (auto pawn: game_.pawn_list()) {
start_pos = game_.pawn_pos(pawn);
while (true) {
while (read_move(&move) < 0) {
}
std::cout << "make move ";
while ((rc = game_.make_move(move, pawn)) == -1) {
}
// player have to continue turn
if (rc == 0) {
break;
}
else if (rc == -2) {
continue;
}
// not possible
else {
throw Exception();
}
}
start_pos = game_.pawn_pos(pawn);
std::cout << pawn->color()
<< ": (" << start_pos.first << "," << start_pos.second <<
") => (" << end_pos.first << "," << end_pos.second << ")"
<< std::endl;
if (game_.is_win(pawn)) {
std::cout << pawn->color() << " win" << std::endl;
is_run = false;
break;
}
}
usleep(500000);
}
}
int Console::read_move(BoardMoves *move)
{
int m;
// std::cin >> m;
m = 0;
if (m < kEND) {
*move = static_cast<BoardMoves>(m);
}
return 0;
}
} /* namespace UI */
} /* namespace Quoridor */
<commit_msg>Fix position calcalation at the end of the turn.<commit_after>#include "console.hpp"
#include <unistd.h>
#include <iostream>
#include "exception.hpp"
namespace Quoridor {
namespace UI {
Console::Console(int player_num)
: game_(std::shared_ptr<Board>(new Board(10, 10)))
{
static std::string colors[4] = {
"red", "green", "pink", "blue"
};
if ((player_num != 2) && (player_num != 4)) {
throw Exception();
}
for (int i = 0; i < player_num; ++i) {
game_.add_pawn(std::shared_ptr<Pawn>(new Pawn(colors[i])));
}
}
Console::~Console()
{
}
void Console::run()
{
bool is_run = true;
BoardMoves move;
pos_t start_pos;
pos_t end_pos;
int rc;
// main loop
while (is_run) {
for (auto pawn: game_.pawn_list()) {
start_pos = game_.pawn_pos(pawn);
while (true) {
while (read_move(&move) < 0) {
}
std::cout << "make move ";
while ((rc = game_.make_move(move, pawn)) == -1) {
}
// player have to continue turn
if (rc == 0) {
break;
}
else if (rc == -2) {
continue;
}
// not possible
else {
throw Exception();
}
}
end_pos = game_.pawn_pos(pawn);
std::cout << pawn->color()
<< ": (" << start_pos.first << "," << start_pos.second <<
") => (" << end_pos.first << "," << end_pos.second << ")"
<< std::endl;
if (game_.is_win(pawn)) {
std::cout << pawn->color() << " win" << std::endl;
is_run = false;
break;
}
}
usleep(500000);
}
}
int Console::read_move(BoardMoves *move)
{
int m;
// std::cin >> m;
m = 0;
if (m < kEND) {
*move = static_cast<BoardMoves>(m);
}
return 0;
}
} /* namespace UI */
} /* namespace Quoridor */
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/extensions/convert_user_script.h"
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "base/sha2.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/json_value_serializer.h"
#include "googleurl/src/gurl.h"
namespace keys = extension_manifest_keys;
Extension* ConvertUserScriptToExtension(const FilePath& user_script_path,
const GURL& original_url,
std::string* error) {
std::string content;
if (!file_util::ReadFileToString(user_script_path, &content)) {
*error = "Could not read source file: " +
WideToASCII(user_script_path.ToWStringHack());
return NULL;
}
UserScript script;
if (!UserScriptMaster::ScriptReloader::ParseMetadataHeader(content,
&script)) {
*error = "Invalid script header.";
return NULL;
}
ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDir()) {
*error = "Could not create temporary directory.";
return NULL;
}
// Create the manifest
scoped_ptr<DictionaryValue> root(new DictionaryValue);
std::string script_name;
if (!script.name().empty() && !script.name_space().empty())
script_name = script.name_space() + "/" + script.name();
else
script_name = original_url.spec();
// Create the public key.
// User scripts are not signed, but the public key for an extension doubles as
// its unique identity, and we need one of those. A user script's unique
// identity is its namespace+name, so we hash that to create a public key.
// There will be no corresponding private key, which means user scripts cannot
// be auto-updated, or claimed in the gallery.
char raw[base::SHA256_LENGTH] = {0};
std::string key;
base::SHA256HashString(script_name, raw, base::SHA256_LENGTH);
base::Base64Encode(std::string(raw, base::SHA256_LENGTH), &key);
// The script may not have a name field, but we need one for an extension. If
// it is missing, use the filename of the original URL.
if (!script.name().empty())
root->SetString(keys::kName, script.name());
else
root->SetString(keys::kName, original_url.ExtractFileName());
// Not all scripts have a version, but we need one. Default to 1.0 if it is
// missing.
if (!script.version().empty())
root->SetString(keys::kVersion, script.version());
else
root->SetString(keys::kVersion, "1.0");
root->SetString(keys::kDescription, script.description());
root->SetString(keys::kPublicKey, key);
root->SetBoolean(keys::kConvertedFromUserScript, true);
ListValue* js_files = new ListValue();
js_files->Append(Value::CreateStringValue("script.js"));
// If the script provides its own match patterns, we use those. Otherwise, we
// generate some using the include globs.
ListValue* matches = new ListValue();
if (!script.url_patterns().empty()) {
for (size_t i = 0; i < script.url_patterns().size(); ++i) {
matches->Append(Value::CreateStringValue(
script.url_patterns()[i].GetAsString()));
}
} else {
// TODO(aa): Derive tighter matches where possible.
matches->Append(Value::CreateStringValue("http://*/*"));
matches->Append(Value::CreateStringValue("https://*/*"));
}
ListValue* includes = new ListValue();
for (size_t i = 0; i < script.globs().size(); ++i)
includes->Append(Value::CreateStringValue(script.globs().at(i)));
ListValue* excludes = new ListValue();
for (size_t i = 0; i < script.exclude_globs().size(); ++i)
excludes->Append(Value::CreateStringValue(script.exclude_globs().at(i)));
DictionaryValue* content_script = new DictionaryValue();
content_script->Set(keys::kMatches, matches);
content_script->Set(keys::kIncludeGlobs, includes);
content_script->Set(keys::kExcludeGlobs, excludes);
content_script->Set(keys::kJs, js_files);
ListValue* content_scripts = new ListValue();
content_scripts->Append(content_script);
root->Set(keys::kContentScripts, content_scripts);
FilePath manifest_path = temp_dir.path().Append(
Extension::kManifestFilename);
JSONFileValueSerializer serializer(manifest_path);
if (!serializer.Serialize(*root)) {
*error = "Could not write JSON.";
return NULL;
}
// Write the script file.
if (!file_util::CopyFile(user_script_path,
temp_dir.path().AppendASCII("script.js"))) {
*error = "Could not copy script file.";
return NULL;
}
scoped_ptr<Extension> extension(new Extension(temp_dir.path()));
if (!extension->InitFromValue(*root, false, error)) {
NOTREACHED() << "Could not init extension " << *error;
return NULL;
}
temp_dir.Take(); // The caller takes ownership of the directory.
return extension.release();
}
<commit_msg>Pack content scripts in a temp directory in the profile dir.<commit_after>// Copyright (c) 2009 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/extensions/convert_user_script.h"
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/sha2.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/json_value_serializer.h"
#include "googleurl/src/gurl.h"
namespace keys = extension_manifest_keys;
Extension* ConvertUserScriptToExtension(const FilePath& user_script_path,
const GURL& original_url,
std::string* error) {
std::string content;
if (!file_util::ReadFileToString(user_script_path, &content)) {
*error = "Could not read source file: " +
WideToASCII(user_script_path.ToWStringHack());
return NULL;
}
UserScript script;
if (!UserScriptMaster::ScriptReloader::ParseMetadataHeader(content,
&script)) {
*error = "Invalid script header.";
return NULL;
}
FilePath user_data_temp_dir;
CHECK(PathService::Get(chrome::DIR_USER_DATA_TEMP, &user_data_temp_dir));
ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDirUnderPath(user_data_temp_dir, false)) {
*error = "Could not create temporary directory.";
return NULL;
}
// Create the manifest
scoped_ptr<DictionaryValue> root(new DictionaryValue);
std::string script_name;
if (!script.name().empty() && !script.name_space().empty())
script_name = script.name_space() + "/" + script.name();
else
script_name = original_url.spec();
// Create the public key.
// User scripts are not signed, but the public key for an extension doubles as
// its unique identity, and we need one of those. A user script's unique
// identity is its namespace+name, so we hash that to create a public key.
// There will be no corresponding private key, which means user scripts cannot
// be auto-updated, or claimed in the gallery.
char raw[base::SHA256_LENGTH] = {0};
std::string key;
base::SHA256HashString(script_name, raw, base::SHA256_LENGTH);
base::Base64Encode(std::string(raw, base::SHA256_LENGTH), &key);
// The script may not have a name field, but we need one for an extension. If
// it is missing, use the filename of the original URL.
if (!script.name().empty())
root->SetString(keys::kName, script.name());
else
root->SetString(keys::kName, original_url.ExtractFileName());
// Not all scripts have a version, but we need one. Default to 1.0 if it is
// missing.
if (!script.version().empty())
root->SetString(keys::kVersion, script.version());
else
root->SetString(keys::kVersion, "1.0");
root->SetString(keys::kDescription, script.description());
root->SetString(keys::kPublicKey, key);
root->SetBoolean(keys::kConvertedFromUserScript, true);
ListValue* js_files = new ListValue();
js_files->Append(Value::CreateStringValue("script.js"));
// If the script provides its own match patterns, we use those. Otherwise, we
// generate some using the include globs.
ListValue* matches = new ListValue();
if (!script.url_patterns().empty()) {
for (size_t i = 0; i < script.url_patterns().size(); ++i) {
matches->Append(Value::CreateStringValue(
script.url_patterns()[i].GetAsString()));
}
} else {
// TODO(aa): Derive tighter matches where possible.
matches->Append(Value::CreateStringValue("http://*/*"));
matches->Append(Value::CreateStringValue("https://*/*"));
}
ListValue* includes = new ListValue();
for (size_t i = 0; i < script.globs().size(); ++i)
includes->Append(Value::CreateStringValue(script.globs().at(i)));
ListValue* excludes = new ListValue();
for (size_t i = 0; i < script.exclude_globs().size(); ++i)
excludes->Append(Value::CreateStringValue(script.exclude_globs().at(i)));
DictionaryValue* content_script = new DictionaryValue();
content_script->Set(keys::kMatches, matches);
content_script->Set(keys::kIncludeGlobs, includes);
content_script->Set(keys::kExcludeGlobs, excludes);
content_script->Set(keys::kJs, js_files);
ListValue* content_scripts = new ListValue();
content_scripts->Append(content_script);
root->Set(keys::kContentScripts, content_scripts);
FilePath manifest_path = temp_dir.path().Append(
Extension::kManifestFilename);
JSONFileValueSerializer serializer(manifest_path);
if (!serializer.Serialize(*root)) {
*error = "Could not write JSON.";
return NULL;
}
// Write the script file.
if (!file_util::CopyFile(user_script_path,
temp_dir.path().AppendASCII("script.js"))) {
*error = "Could not copy script file.";
return NULL;
}
scoped_ptr<Extension> extension(new Extension(temp_dir.path()));
if (!extension->InitFromValue(*root, false, error)) {
NOTREACHED() << "Could not init extension " << *error;
return NULL;
}
temp_dir.Take(); // The caller takes ownership of the directory.
return extension.release();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
// All kinds of crashes on Linux http://crbug.com/41027
#if defined(OS_LINUX)
#define FavIconPermission DISABLED_FavIconPermission
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<commit_msg>TTF: Enable the FavIconPermission test, as it appears to be working.<commit_after>// Copyright (c) 2009 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/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<commit_msg>Disable ExtensionApiTest.FavIconPermission on Linux<commit_after>// Copyright (c) 2009 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/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
// All kinds of crashes on Linux http://crbug.com/41027
#if defined(OS_LINUX)
#define FavIconPermission DISABLED_FavIconPermission
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// It's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowOpen) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("window_open").AppendASCII("spanning")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Mark a test flaky.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WindowOpen) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("window_open").AppendASCII("spanning")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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/app/chrome_dll_resource.h"
#include "chrome/browser/find_in_page_controller.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"
class FindInPageControllerTest : public UITest {
public:
FindInPageControllerTest() {
show_window_ = true;
}
};
const std::wstring kFramePage = L"files/find_in_page/frames.html";
const std::wstring kUserSelectPage = L"files/find_in_page/user-select.html";
const std::wstring kCrashPage = L"files/find_in_page/crash_1341577.html";
const std::wstring kTooFewMatchesPage = L"files/find_in_page/bug_1155639.html";
// This test loads a page with frames and starts FindInPage requests
TEST_F(FindInPageControllerTest, FindInPageFrames) {
TestServer server(L"chrome/test/data");
// First we navigate to our frames page.
GURL url = server.TestServerPageW(kFramePage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// Try incremental search (mimicking user typing in).
EXPECT_EQ(18, tab->FindInPage(L"g", FWD, IGNORE_CASE, false));
EXPECT_EQ(11, tab->FindInPage(L"go", FWD, IGNORE_CASE, false));
EXPECT_EQ(04, tab->FindInPage(L"goo", FWD, IGNORE_CASE, false));
EXPECT_EQ(03, tab->FindInPage(L"goog", FWD, IGNORE_CASE, false));
EXPECT_EQ(02, tab->FindInPage(L"googl", FWD, IGNORE_CASE, false));
EXPECT_EQ(01, tab->FindInPage(L"google", FWD, IGNORE_CASE, false));
EXPECT_EQ(00, tab->FindInPage(L"google!", FWD, IGNORE_CASE, false));
// Negative test (no matches should be found).
EXPECT_EQ(0, tab->FindInPage(L"Non-existing string", FWD, IGNORE_CASE,
false));
// 'horse' only exists in the three right frames.
EXPECT_EQ(3, tab->FindInPage(L"horse", FWD, IGNORE_CASE, false));
// 'cat' only exists in the first frame.
EXPECT_EQ(1, tab->FindInPage(L"cat", FWD, IGNORE_CASE, false));
// Try searching again, should still come up with 1 match.
EXPECT_EQ(1, tab->FindInPage(L"cat", FWD, IGNORE_CASE, false));
// Try searching backwards, ignoring case, should still come up with 1 match.
EXPECT_EQ(1, tab->FindInPage(L"CAT", BACK, IGNORE_CASE, false));
// Try case sensitive, should NOT find it.
EXPECT_EQ(0, tab->FindInPage(L"CAT", FWD, CASE_SENSITIVE, false));
// Try again case sensitive, but this time with right case.
EXPECT_EQ(1, tab->FindInPage(L"dog", FWD, CASE_SENSITIVE, false));
// Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).
EXPECT_EQ(1, tab->FindInPage(L"Hreggvi\u00F0ur", FWD, IGNORE_CASE, false));
EXPECT_EQ(1, tab->FindInPage(L"Hreggvi\u00F0ur", FWD, CASE_SENSITIVE, false));
EXPECT_EQ(0, tab->FindInPage(L"hreggvi\u00F0ur", FWD, CASE_SENSITIVE, false));
}
// Load a page with no selectable text and make sure we don't crash.
TEST_F(FindInPageControllerTest, FindUnSelectableText) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kUserSelectPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(0, tab->FindInPage(L"text", FWD, IGNORE_CASE, false));
EXPECT_EQ(0, tab->FindInPage(L"Non-existing string", FWD, IGNORE_CASE,
false));
}
// Try to reproduce the crash seen in issue 1341577.
TEST_F(FindInPageControllerTest, DISABLED_FindCrash_Issue1341577) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kCrashPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// This would crash the tab. These must be the first two find requests issued
// against the frame, otherwise an active frame pointer is set and it wont
// produce the crash.
EXPECT_EQ(1, tab->FindInPage(L"\u0D4C", FWD, IGNORE_CASE, false));
EXPECT_EQ(1, tab->FindInPage(L"\u0D4C", FWD, IGNORE_CASE, true)); // FindNext
// This should work fine.
EXPECT_EQ(1, tab->FindInPage(L"\u0D24\u0D46", FWD, IGNORE_CASE, false));
EXPECT_EQ(0, tab->FindInPage(L"nostring", FWD, IGNORE_CASE, false));
}
// Test to make sure Find does the right thing when restarting from a timeout.
// We used to have a problem where we'd stop finding matches when all of the
// following conditions were true:
// 1) The page has a lot of text to search.
// 2) The page contains more than one match.
// 3) It takes longer than the time-slice given to each Find operation (100
// ms) to find one or more of those matches (so Find times out and has to try
// again from where it left off).
TEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1341577) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kTooFewMatchesPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// This string appears 5 times at the bottom of a long page. If Find restarts
// properly after a timeout, it will find 5 matches, not just 1.
EXPECT_EQ(5, tab->FindInPage(L"008.xml", FWD, IGNORE_CASE, false));
}
// The find window should not change its location just because we open and close
// a new tab.
TEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kFramePage);
scoped_ptr<TabProxy> tabA(GetActiveTab());
ASSERT_TRUE(tabA->NavigateToURL(url));
scoped_ptr<BrowserProxy> browser(automation()->GetLastActiveBrowserWindow());
ASSERT_TRUE(browser.get() != NULL);
// Toggle the bookmark bar state.
browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);
EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));
// Open the Find window and wait for it to animate.
EXPECT_TRUE(tabA->OpenFindInPage());
EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));
// Find its location.
int x = -1, y = -1;
EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));
// Open another tab (tab B).
EXPECT_TRUE(browser->AppendTab(url));
scoped_ptr<TabProxy> tabB(GetActiveTab());
// Close tab B.
EXPECT_TRUE(tabB->Close(true));
// See if the Find window has moved.
int new_x = -1, new_y = -1;
EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));
EXPECT_EQ(x, new_x);
EXPECT_EQ(y, new_y);
// Now reset the bookmarks bar state and try the same again.
browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);
EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));
// Bookmark bar has moved, reset our coordinates.
EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));
// Open another tab (tab C).
EXPECT_TRUE(browser->AppendTab(url));
scoped_ptr<TabProxy> tabC(GetActiveTab());
// Close it.
EXPECT_TRUE(tabC->Close(true));
// See if the Find window has moved.
EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));
EXPECT_EQ(x, new_x);
EXPECT_EQ(y, new_y);
}
<commit_msg>Occasionally GetLastActiveBrowserWindow fails on the build bots, probably because of the locked desktop. Replace this call in the non-interactive ui tests with a call to GetBrowserWindow(0), which is what GetActiveTab (called a few lines earlier) does anyway.<commit_after>// Copyright (c) 2006-2008 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/app/chrome_dll_resource.h"
#include "chrome/browser/find_in_page_controller.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"
class FindInPageControllerTest : public UITest {
public:
FindInPageControllerTest() {
show_window_ = true;
}
};
const std::wstring kFramePage = L"files/find_in_page/frames.html";
const std::wstring kUserSelectPage = L"files/find_in_page/user-select.html";
const std::wstring kCrashPage = L"files/find_in_page/crash_1341577.html";
const std::wstring kTooFewMatchesPage = L"files/find_in_page/bug_1155639.html";
// This test loads a page with frames and starts FindInPage requests
TEST_F(FindInPageControllerTest, FindInPageFrames) {
TestServer server(L"chrome/test/data");
// First we navigate to our frames page.
GURL url = server.TestServerPageW(kFramePage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// Try incremental search (mimicking user typing in).
EXPECT_EQ(18, tab->FindInPage(L"g", FWD, IGNORE_CASE, false));
EXPECT_EQ(11, tab->FindInPage(L"go", FWD, IGNORE_CASE, false));
EXPECT_EQ(04, tab->FindInPage(L"goo", FWD, IGNORE_CASE, false));
EXPECT_EQ(03, tab->FindInPage(L"goog", FWD, IGNORE_CASE, false));
EXPECT_EQ(02, tab->FindInPage(L"googl", FWD, IGNORE_CASE, false));
EXPECT_EQ(01, tab->FindInPage(L"google", FWD, IGNORE_CASE, false));
EXPECT_EQ(00, tab->FindInPage(L"google!", FWD, IGNORE_CASE, false));
// Negative test (no matches should be found).
EXPECT_EQ(0, tab->FindInPage(L"Non-existing string", FWD, IGNORE_CASE,
false));
// 'horse' only exists in the three right frames.
EXPECT_EQ(3, tab->FindInPage(L"horse", FWD, IGNORE_CASE, false));
// 'cat' only exists in the first frame.
EXPECT_EQ(1, tab->FindInPage(L"cat", FWD, IGNORE_CASE, false));
// Try searching again, should still come up with 1 match.
EXPECT_EQ(1, tab->FindInPage(L"cat", FWD, IGNORE_CASE, false));
// Try searching backwards, ignoring case, should still come up with 1 match.
EXPECT_EQ(1, tab->FindInPage(L"CAT", BACK, IGNORE_CASE, false));
// Try case sensitive, should NOT find it.
EXPECT_EQ(0, tab->FindInPage(L"CAT", FWD, CASE_SENSITIVE, false));
// Try again case sensitive, but this time with right case.
EXPECT_EQ(1, tab->FindInPage(L"dog", FWD, CASE_SENSITIVE, false));
// Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).
EXPECT_EQ(1, tab->FindInPage(L"Hreggvi\u00F0ur", FWD, IGNORE_CASE, false));
EXPECT_EQ(1, tab->FindInPage(L"Hreggvi\u00F0ur", FWD, CASE_SENSITIVE, false));
EXPECT_EQ(0, tab->FindInPage(L"hreggvi\u00F0ur", FWD, CASE_SENSITIVE, false));
}
// Load a page with no selectable text and make sure we don't crash.
TEST_F(FindInPageControllerTest, FindUnSelectableText) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kUserSelectPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(0, tab->FindInPage(L"text", FWD, IGNORE_CASE, false));
EXPECT_EQ(0, tab->FindInPage(L"Non-existing string", FWD, IGNORE_CASE,
false));
}
// Try to reproduce the crash seen in issue 1341577.
TEST_F(FindInPageControllerTest, DISABLED_FindCrash_Issue1341577) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kCrashPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// This would crash the tab. These must be the first two find requests issued
// against the frame, otherwise an active frame pointer is set and it wont
// produce the crash.
EXPECT_EQ(1, tab->FindInPage(L"\u0D4C", FWD, IGNORE_CASE, false));
EXPECT_EQ(1, tab->FindInPage(L"\u0D4C", FWD, IGNORE_CASE, true)); // FindNext
// This should work fine.
EXPECT_EQ(1, tab->FindInPage(L"\u0D24\u0D46", FWD, IGNORE_CASE, false));
EXPECT_EQ(0, tab->FindInPage(L"nostring", FWD, IGNORE_CASE, false));
}
// Test to make sure Find does the right thing when restarting from a timeout.
// We used to have a problem where we'd stop finding matches when all of the
// following conditions were true:
// 1) The page has a lot of text to search.
// 2) The page contains more than one match.
// 3) It takes longer than the time-slice given to each Find operation (100
// ms) to find one or more of those matches (so Find times out and has to try
// again from where it left off).
TEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1341577) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kTooFewMatchesPage);
scoped_ptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab->NavigateToURL(url));
// This string appears 5 times at the bottom of a long page. If Find restarts
// properly after a timeout, it will find 5 matches, not just 1.
EXPECT_EQ(5, tab->FindInPage(L"008.xml", FWD, IGNORE_CASE, false));
}
// The find window should not change its location just because we open and close
// a new tab.
TEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {
TestServer server(L"chrome/test/data");
GURL url = server.TestServerPageW(kFramePage);
scoped_ptr<TabProxy> tabA(GetActiveTab());
ASSERT_TRUE(tabA->NavigateToURL(url));
scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get() != NULL);
// Toggle the bookmark bar state.
browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);
EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));
// Open the Find window and wait for it to animate.
EXPECT_TRUE(tabA->OpenFindInPage());
EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));
// Find its location.
int x = -1, y = -1;
EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));
// Open another tab (tab B).
EXPECT_TRUE(browser->AppendTab(url));
scoped_ptr<TabProxy> tabB(GetActiveTab());
// Close tab B.
EXPECT_TRUE(tabB->Close(true));
// See if the Find window has moved.
int new_x = -1, new_y = -1;
EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));
EXPECT_EQ(x, new_x);
EXPECT_EQ(y, new_y);
// Now reset the bookmarks bar state and try the same again.
browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);
EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));
// Bookmark bar has moved, reset our coordinates.
EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));
// Open another tab (tab C).
EXPECT_TRUE(browser->AppendTab(url));
scoped_ptr<TabProxy> tabC(GetActiveTab());
// Close it.
EXPECT_TRUE(tabC->Close(true));
// See if the Find window has moved.
EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));
EXPECT_EQ(x, new_x);
EXPECT_EQ(y, new_y);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2009 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 <gtk/gtk.h>
#include "chrome/browser/options_window.h"
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_member.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#ifdef CHROME_PERSONALIZATION
#include "chrome/personalization/personalization.h"
#endif
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk
//
// The contents of the Options dialog window.
class OptionsWindowGtk {
public:
explicit OptionsWindowGtk(Profile* profile);
~OptionsWindowGtk();
// Shows the Tab corresponding to the specified OptionsPage.
void ShowOptionsPage(OptionsPage page, OptionsGroup highlight_group);
private:
static void OnSwitchPage(GtkNotebook* notebook, GtkNotebookPage* page,
guint page_num, OptionsWindowGtk* options_window);
static void OnWindowDestroy(GtkWidget* widget, OptionsWindowGtk* window);
// The options dialog
GtkWidget *dialog_;
// The container of the option pages
GtkWidget *notebook_;
// The Profile associated with these options.
Profile* profile_;
// The last page the user was on when they opened the Options window.
IntegerPrefMember last_selected_page_;
DISALLOW_COPY_AND_ASSIGN(OptionsWindowGtk);
};
static OptionsWindowGtk* instance_ = NULL;
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk, public:
OptionsWindowGtk::OptionsWindowGtk(Profile* profile)
// Always show preferences for the original profile. Most state when off
// the record comes from the original profile, but we explicitly use
// the original profile to avoid potential problems.
: profile_(profile->GetOriginalProfile()) {
// The download manager needs to be initialized before the contents of the
// Options Window are created.
profile_->GetDownloadManager();
// We don't need to observe changes in this value.
last_selected_page_.Init(prefs::kOptionsWindowLastTabIndex,
g_browser_process->local_state(), NULL);
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringFUTF8(IDS_OPTIONS_DIALOG_TITLE,
WideToUTF16(l10n_util::GetString(IDS_PRODUCT_NAME))).c_str(),
// Prefs window is shared between all browser windows.
NULL,
// Non-modal.
GTK_DIALOG_NO_SEPARATOR,
GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE,
NULL);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), 18);
notebook_ = gtk_notebook_new();
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO general"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_GENERAL_TAB_LABEL).c_str()));
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO content"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_CONTENT_TAB_LABEL).c_str()));
#ifdef CHROME_PERSONALIZATION
if (!Personalization::IsP13NDisabled()) {
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO personalization"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_USER_DATA_TAB_LABEL).c_str()));
}
#endif
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO advanced"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_TAB_LABEL).c_str()));
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), notebook_);
DCHECK(
gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)) == OPTIONS_PAGE_COUNT);
// Need to show the notebook before connecting switch-page signal, otherwise
// we'll immediately get a signal switching to page 0 and overwrite our
// last_selected_page_ value.
gtk_widget_show_all(dialog_);
g_signal_connect(notebook_, "switch-page", G_CALLBACK(OnSwitchPage), this);
// We only have one button and don't do any special handling, so just hook it
// directly to gtk_widget_destroy.
g_signal_connect_swapped(dialog_, "response", G_CALLBACK(gtk_widget_destroy),
dialog_);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this);
}
OptionsWindowGtk::~OptionsWindowGtk() {
}
void OptionsWindowGtk::ShowOptionsPage(OptionsPage page,
OptionsGroup highlight_group) {
// Bring options window to front if it already existed and isn't already
// in front
// TODO(mattm): docs say it's preferable to use gtk_window_present_with_time
gtk_window_present(GTK_WINDOW(dialog_));
if (page == OPTIONS_PAGE_DEFAULT) {
// Remember the last visited page from local state.
page = static_cast<OptionsPage>(last_selected_page_.GetValue());
if (page == OPTIONS_PAGE_DEFAULT)
page = OPTIONS_PAGE_GENERAL;
}
// If the page number is out of bounds, reset to the first tab.
if (page < 0 || page >= gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)))
page = OPTIONS_PAGE_GENERAL;
gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook_), page);
// TODO(mattm): set highlight_group
}
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk, private:
// static
void OptionsWindowGtk::OnSwitchPage(GtkNotebook* notebook,
GtkNotebookPage* page,
guint page_num,
OptionsWindowGtk* options_window) {
int index = page_num;
DCHECK(index > OPTIONS_PAGE_DEFAULT && index < OPTIONS_PAGE_COUNT);
options_window->last_selected_page_.SetValue(index);
}
// static
void OptionsWindowGtk::OnWindowDestroy(GtkWidget* widget,
OptionsWindowGtk* options_window) {
instance_ = NULL;
MessageLoop::current()->DeleteSoon(FROM_HERE, options_window);
}
///////////////////////////////////////////////////////////////////////////////
// Factory/finder method:
void ShowOptionsWindow(OptionsPage page,
OptionsGroup highlight_group,
Profile* profile) {
DCHECK(profile);
// If there's already an existing options window, activate it and switch to
// the specified page.
if (!instance_) {
instance_ = new OptionsWindowGtk(profile);
}
instance_->ShowOptionsPage(page, highlight_group);
}
<commit_msg>Add option to enable/disable reporting.<commit_after>// Copyright (c) 2006-2009 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 <gtk/gtk.h>
#include "chrome/browser/options_window.h"
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_member.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#ifdef CHROME_PERSONALIZATION
#include "chrome/personalization/personalization.h"
#endif
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk
//
// The contents of the Options dialog window.
class OptionsWindowGtk {
public:
explicit OptionsWindowGtk(Profile* profile);
~OptionsWindowGtk();
// Shows the Tab corresponding to the specified OptionsPage.
void ShowOptionsPage(OptionsPage page, OptionsGroup highlight_group);
private:
// This is the callback function for Stats reporting checkbox.
static void OnLoggingChange(GtkWidget* widget,
OptionsWindowGtk* options_window);
static void OnSwitchPage(GtkNotebook* notebook, GtkNotebookPage* page,
guint page_num, OptionsWindowGtk* options_window);
static void OnWindowDestroy(GtkWidget* widget, OptionsWindowGtk* window);
// This function gets called when stats reporting option is changed.
void LoggingChanged(GtkWidget* widget);
// The options dialog
GtkWidget *dialog_;
// The container of the option pages
GtkWidget *notebook_;
// The Profile associated with these options.
Profile* profile_;
// The last page the user was on when they opened the Options window.
IntegerPrefMember last_selected_page_;
DISALLOW_COPY_AND_ASSIGN(OptionsWindowGtk);
};
static OptionsWindowGtk* instance_ = NULL;
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk, public:
OptionsWindowGtk::OptionsWindowGtk(Profile* profile)
// Always show preferences for the original profile. Most state when off
// the record comes from the original profile, but we explicitly use
// the original profile to avoid potential problems.
: profile_(profile->GetOriginalProfile()) {
// The download manager needs to be initialized before the contents of the
// Options Window are created.
profile_->GetDownloadManager();
// We don't need to observe changes in this value.
last_selected_page_.Init(prefs::kOptionsWindowLastTabIndex,
g_browser_process->local_state(), NULL);
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringFUTF8(IDS_OPTIONS_DIALOG_TITLE,
WideToUTF16(l10n_util::GetString(IDS_PRODUCT_NAME))).c_str(),
// Prefs window is shared between all browser windows.
NULL,
// Non-modal.
GTK_DIALOG_NO_SEPARATOR,
GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE,
NULL);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), 18);
notebook_ = gtk_notebook_new();
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO general"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_GENERAL_TAB_LABEL).c_str()));
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO content"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_CONTENT_TAB_LABEL).c_str()));
#ifdef CHROME_PERSONALIZATION
if (!Personalization::IsP13NDisabled()) {
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
gtk_label_new("TODO personalization"),
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_USER_DATA_TAB_LABEL).c_str()));
}
#endif
GtkWidget* metrics_vbox = gtk_vbox_new(FALSE, 5);
GtkWidget* metrics = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str());
gtk_box_pack_start(GTK_BOX(metrics_vbox), metrics, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(metrics_vbox),
gtk_label_new("TODO rest of the advanced options"),
FALSE, FALSE, 0);
g_signal_connect(metrics, "clicked", G_CALLBACK(OnLoggingChange), this);
gtk_notebook_append_page(
GTK_NOTEBOOK(notebook_),
metrics_vbox,
gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_TAB_LABEL).c_str()));
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), notebook_);
DCHECK(
gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)) == OPTIONS_PAGE_COUNT);
// Need to show the notebook before connecting switch-page signal, otherwise
// we'll immediately get a signal switching to page 0 and overwrite our
// last_selected_page_ value.
gtk_widget_show_all(dialog_);
g_signal_connect(notebook_, "switch-page", G_CALLBACK(OnSwitchPage), this);
// We only have one button and don't do any special handling, so just hook it
// directly to gtk_widget_destroy.
g_signal_connect_swapped(dialog_, "response", G_CALLBACK(gtk_widget_destroy),
dialog_);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this);
}
OptionsWindowGtk::~OptionsWindowGtk() {
}
void OptionsWindowGtk::ShowOptionsPage(OptionsPage page,
OptionsGroup highlight_group) {
// Bring options window to front if it already existed and isn't already
// in front
// TODO(mattm): docs say it's preferable to use gtk_window_present_with_time
gtk_window_present(GTK_WINDOW(dialog_));
if (page == OPTIONS_PAGE_DEFAULT) {
// Remember the last visited page from local state.
page = static_cast<OptionsPage>(last_selected_page_.GetValue());
if (page == OPTIONS_PAGE_DEFAULT)
page = OPTIONS_PAGE_GENERAL;
}
// If the page number is out of bounds, reset to the first tab.
if (page < 0 || page >= gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)))
page = OPTIONS_PAGE_GENERAL;
gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook_), page);
// TODO(mattm): set highlight_group
}
///////////////////////////////////////////////////////////////////////////////
// OptionsWindowGtk, private:
// static
void OptionsWindowGtk::OnLoggingChange(GtkWidget* widget,
OptionsWindowGtk* options_window) {
options_window->LoggingChanged(widget);
}
// static
void OptionsWindowGtk::OnSwitchPage(GtkNotebook* notebook,
GtkNotebookPage* page,
guint page_num,
OptionsWindowGtk* options_window) {
int index = page_num;
DCHECK(index > OPTIONS_PAGE_DEFAULT && index < OPTIONS_PAGE_COUNT);
options_window->last_selected_page_.SetValue(index);
}
// static
void OptionsWindowGtk::OnWindowDestroy(GtkWidget* widget,
OptionsWindowGtk* options_window) {
instance_ = NULL;
MessageLoop::current()->DeleteSoon(FROM_HERE, options_window);
}
void OptionsWindowGtk::LoggingChanged(GtkWidget* metrics) {
// TODO: Once crash reporting is working for Linux, make the actual call to
// enable/disable it.
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(metrics)))
LOG(INFO) << "Reporting enabled";
else
LOG(INFO) << "Reporting disabled";
}
///////////////////////////////////////////////////////////////////////////////
// Factory/finder method:
void ShowOptionsWindow(OptionsPage page,
OptionsGroup highlight_group,
Profile* profile) {
DCHECK(profile);
// If there's already an existing options window, activate it and switch to
// the specified page.
if (!instance_) {
instance_ = new OptionsWindowGtk(profile);
}
instance_->ShowOptionsPage(page, highlight_group);
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <string>
#include <vector>
#include "../../NULLC/nullc.h"
#include "context.h"
#include "handler.h"
#include <Windows.h>
#pragma warning(disable: 4996)
int main(int argc, char **argv)
{
while(!IsDebuggerPresent())
Sleep(1000);
Context ctx;
for(int i = 1; i < argc; i++)
{
if(strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0)
{
ctx.infoMode = true;
ctx.debugMode = true;
}
}
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
if(ctx.infoMode)
fprintf(stderr, "INFO: Launching\r\n");
std::vector<char> header;
std::vector<char> message;
unsigned expectedLength = 0;
char ch = 0;
while(std::cin.get(ch))
{
// Header field ends with \r\n
if(ch == '\r')
{
if(!std::cin.get(ch))
break;
if(ch != '\n')
{
fprintf(stderr, "ERROR: Expected '\\n' after '\\r' after the header\r\n");
return 1;
}
// If buffer is empty that means headers have ended and we can read the message
if(header.empty())
{
message.resize(expectedLength + 1);
std::cin.read(message.data(), expectedLength);
if(ctx.debugMode)
fprintf(stderr, "DEBUG: Received message '%.*s'\r\n", (int)expectedLength, message.data());
message.back() = 0;
if(!HandleMessage(ctx, message.data(), expectedLength))
return 1;
expectedLength = 0;
}
else
{
header.push_back(0);
if(strstr(header.data(), "Content-Length") == header.data())
{
const char *pos = strstr(header.data(), ": ");
if(!pos)
{
fprintf(stderr, "ERROR: Content-Length is not followed by ': '\r\n");
return 1;
}
pos += 2;
expectedLength = strtoul(pos, nullptr, 10);
header.clear();
}
else if(strstr(header.data(), "Content-Type") == header.data())
{
// Don't care about encoding, we support all defined by spec
header.clear();
}
else
{
fprintf(stderr, "WARNING: Unknown header '%.*s'\r\n", (int)header.size(), header.data());
header.clear();
}
}
}
else
{
header.push_back(ch);
}
}
if(ctx.nullcInitialized)
nullcTerminate();
}
<commit_msg>Extension update: removed debugger launch wait loop<commit_after>#include <assert.h>
#include <stdio.h>
#if defined(_WIN32)
#include <io.h>
#include <fcntl.h>
#endif
#include <iostream>
#include <string>
#include <vector>
#include "../../NULLC/nullc.h"
#include "context.h"
#include "handler.h"
#pragma warning(disable: 4996)
int main(int argc, char **argv)
{
Context ctx;
for(int i = 1; i < argc; i++)
{
if(strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0)
{
ctx.infoMode = true;
ctx.debugMode = true;
}
}
#if defined(_WIN32)
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
if(ctx.infoMode)
fprintf(stderr, "INFO: Launching\r\n");
std::vector<char> header;
std::vector<char> message;
unsigned expectedLength = 0;
char ch = 0;
while(std::cin.get(ch))
{
// Header field ends with \r\n
if(ch == '\r')
{
if(!std::cin.get(ch))
break;
if(ch != '\n')
{
fprintf(stderr, "ERROR: Expected '\\n' after '\\r' after the header\r\n");
return 1;
}
// If buffer is empty that means headers have ended and we can read the message
if(header.empty())
{
message.resize(expectedLength + 1);
std::cin.read(message.data(), expectedLength);
if(ctx.debugMode)
fprintf(stderr, "DEBUG: Received message '%.*s'\r\n", (int)expectedLength, message.data());
message.back() = 0;
if(!HandleMessage(ctx, message.data(), expectedLength))
return 1;
expectedLength = 0;
}
else
{
header.push_back(0);
if(strstr(header.data(), "Content-Length") == header.data())
{
const char *pos = strstr(header.data(), ": ");
if(!pos)
{
fprintf(stderr, "ERROR: Content-Length is not followed by ': '\r\n");
return 1;
}
pos += 2;
expectedLength = strtoul(pos, nullptr, 10);
header.clear();
}
else if(strstr(header.data(), "Content-Type") == header.data())
{
// Don't care about encoding, we support all defined by spec
header.clear();
}
else
{
fprintf(stderr, "WARNING: Unknown header '%.*s'\r\n", (int)header.size(), header.data());
header.clear();
}
}
}
else
{
header.push_back(ch);
}
}
if(ctx.nullcInitialized)
nullcTerminate();
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2015-2017 John D. Haughton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//------------------------------------------------------------------------------
#include "PLT/File.h"
#include "STB/Lex.h"
#include "STB/Oil.h"
namespace STB {
namespace OIL {
void Member::write(PLT::File& file, void* that) const
{
file.printf(" %s=\"", name);
if (elements > 1) file.printf("[");
for(size_t i=0; i<elements; ++i)
{
if (i > 0) file.printf(", ");
void* data = (uint8_t*)that + offset + size*i;
switch(type)
{
case Type::BOOL:
file.printf("%s", *(bool*)data ? "true" : "false");
break;
case Type::SIGNED:
switch(size)
{
case 1: file.printf("%d", *(int8_t*)data); break;
case 2: file.printf("%d", *(int16_t*)data); break;
case 4: file.printf("%d", *(int32_t*)data); break;
case 8: file.printf("%lld", *(int64_t*)data); break;
default: assert(!"unexpected member size"); break;
}
break;
case Type::ENUM:
case Type::UNSIGNED:
{
bool hex = (flags & HEX) != 0;
switch(size)
{
case 1: file.printf(hex ? "0x%02x" : "%u", *(uint8_t*)data); break;
case 2: file.printf(hex ? "0x%04x" : "%u", *(uint16_t*)data); break;
case 4: file.printf(hex ? "0x%08x" : "%u", *(uint32_t*)data); break;
case 8: file.printf(hex ? "0x%016llx" : "%llu", *(uint64_t*)data); break;
default: assert(!"unexpected member size"); break;
}
}
break;
case Type::FLOAT:
switch(size)
{
case 4: file.printf("%g", *(float*)data); break;
case 8: file.printf("%g", *(double*)data); break;
default: assert(!"unexpected member size"); break;
}
break;
}
}
if (elements > 1) file.printf("]");
file.printf("\"\n");
}
void ClassBase::write(PLT::File& file, void* that) const
{
file.printf("<%s\n", name);
for(const auto& member : member_list)
{
member.write(file, that);
}
file.printf("/>\n");
}
void ClassBase::write(void* that) const
{
PLT::File file(nullptr, name, "xml");
if (file.openForWrite())
{
write(file, that);
}
}
bool Member::read(Lex& lex, void* that) const
{
if (elements > 1)
{
if (!lex.match('[')) return false;
}
for(size_t i=0; i<elements; ++i)
{
if (i > 0)
{
if (!lex.match(',')) return false;
}
void* data = (uint8_t*)that + offset + size*i;
switch(type)
{
case Type::BOOL:
if (lex.isMatch("true"))
{
*(bool*)data = true;
}
else if (lex.isMatch("false"))
{
*(bool*)data = false;
}
else
{
return lex.error("Expected boolean value");
}
break;
case Type::SIGNED:
{
int64_t value = 0;
if (!lex.matchSigned(value)) return false;
int64_t unused = value >> (size*8);
if ((unused != 0) || (unused != -1))
{
return lex.error("signed integer value too big");
}
switch(size)
{
case 1: *(int8_t*)data = int8_t(value); break;
case 2: *(int16_t*)data = int16_t(value); break;
case 4: *(int32_t*)data = int32_t(value); break;
case 8: *(int64_t*)data = value; break;
}
}
break;
case Type::ENUM:
case Type::UNSIGNED:
{
uint64_t value = 0;
if (!lex.matchUnsigned(value)) return false;
uint64_t unused = value >> (size*8);
if (unused != 0)
{
return lex.error("unsigned integer value too big");
}
switch(size)
{
case 1: *(uint8_t*)data = uint8_t(value); break;
case 2: *(uint16_t*)data = uint32_t(value); break;
case 4: *(uint32_t*)data = uint32_t(value); break;
case 8: *(uint64_t*)data = value; break;
}
}
break;
case Type::FLOAT:
{
double value = 0.0;
if (!lex.matchFloat(value)) return false;
switch(size)
{
case 4: *(float*)data = float(value); break;
case 8: *(double*)data = value; break;
}
}
break;
}
}
if (elements > 1)
{
if (!lex.match(']')) return false;
}
return true;
}
bool ClassBase::read(Lex& lex, void* that) const
{
if (!lex.match('<')) return false;
if (!lex.match(name)) return false;
while(!lex.isMatch("/>"))
{
std::string ident;
if (!lex.matchIdent(ident)) return false;
const Member* member = findMember(ident.c_str());
if (member == nullptr) return lex.error("bad member name '%s'", ident.c_str());
if (!lex.match('=')) return false;
if (!lex.match('"')) return false;
if (!member->read(lex, that)) return false;
if (!lex.match('"')) return false;
}
return true;
}
bool ClassBase::read(void* that) const
{
LEX::File lex(name, "xml");
if (lex.isEof()) return false;
return read(lex, that);
}
bool ClassBase::exists(void* that) const
{
std::string filename = name;
filename += ".xml";
return PLT::File::exists(filename.c_str());
}
} // namespace OIL
} // namespace STB
<commit_msg>Fix for compile warning overlapping comparison<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2015-2017 John D. Haughton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//------------------------------------------------------------------------------
#include "PLT/File.h"
#include "STB/Lex.h"
#include "STB/Oil.h"
namespace STB {
namespace OIL {
void Member::write(PLT::File& file, void* that) const
{
file.printf(" %s=\"", name);
if (elements > 1) file.printf("[");
for(size_t i=0; i<elements; ++i)
{
if (i > 0) file.printf(", ");
void* data = (uint8_t*)that + offset + size*i;
switch(type)
{
case Type::BOOL:
file.printf("%s", *(bool*)data ? "true" : "false");
break;
case Type::SIGNED:
switch(size)
{
case 1: file.printf("%d", *(int8_t*)data); break;
case 2: file.printf("%d", *(int16_t*)data); break;
case 4: file.printf("%d", *(int32_t*)data); break;
case 8: file.printf("%lld", *(int64_t*)data); break;
default: assert(!"unexpected member size"); break;
}
break;
case Type::ENUM:
case Type::UNSIGNED:
{
bool hex = (flags & HEX) != 0;
switch(size)
{
case 1: file.printf(hex ? "0x%02x" : "%u", *(uint8_t*)data); break;
case 2: file.printf(hex ? "0x%04x" : "%u", *(uint16_t*)data); break;
case 4: file.printf(hex ? "0x%08x" : "%u", *(uint32_t*)data); break;
case 8: file.printf(hex ? "0x%016llx" : "%llu", *(uint64_t*)data); break;
default: assert(!"unexpected member size"); break;
}
}
break;
case Type::FLOAT:
switch(size)
{
case 4: file.printf("%g", *(float*)data); break;
case 8: file.printf("%g", *(double*)data); break;
default: assert(!"unexpected member size"); break;
}
break;
}
}
if (elements > 1) file.printf("]");
file.printf("\"\n");
}
void ClassBase::write(PLT::File& file, void* that) const
{
file.printf("<%s\n", name);
for(const auto& member : member_list)
{
member.write(file, that);
}
file.printf("/>\n");
}
void ClassBase::write(void* that) const
{
PLT::File file(nullptr, name, "xml");
if (file.openForWrite())
{
write(file, that);
}
}
bool Member::read(Lex& lex, void* that) const
{
if (elements > 1)
{
if (!lex.match('[')) return false;
}
for(size_t i=0; i<elements; ++i)
{
if (i > 0)
{
if (!lex.match(',')) return false;
}
void* data = (uint8_t*)that + offset + size*i;
switch(type)
{
case Type::BOOL:
if (lex.isMatch("true"))
{
*(bool*)data = true;
}
else if (lex.isMatch("false"))
{
*(bool*)data = false;
}
else
{
return lex.error("Expected boolean value");
}
break;
case Type::SIGNED:
{
int64_t value = 0;
if (!lex.matchSigned(value)) return false;
int64_t unused = value >> (size*8);
if ((unused != 0) && (unused != -1))
{
return lex.error("signed integer value too big");
}
switch(size)
{
case 1: *(int8_t*)data = int8_t(value); break;
case 2: *(int16_t*)data = int16_t(value); break;
case 4: *(int32_t*)data = int32_t(value); break;
case 8: *(int64_t*)data = value; break;
}
}
break;
case Type::ENUM:
case Type::UNSIGNED:
{
uint64_t value = 0;
if (!lex.matchUnsigned(value)) return false;
uint64_t unused = value >> (size*8);
if (unused != 0)
{
return lex.error("unsigned integer value too big");
}
switch(size)
{
case 1: *(uint8_t*)data = uint8_t(value); break;
case 2: *(uint16_t*)data = uint32_t(value); break;
case 4: *(uint32_t*)data = uint32_t(value); break;
case 8: *(uint64_t*)data = value; break;
}
}
break;
case Type::FLOAT:
{
double value = 0.0;
if (!lex.matchFloat(value)) return false;
switch(size)
{
case 4: *(float*)data = float(value); break;
case 8: *(double*)data = value; break;
}
}
break;
}
}
if (elements > 1)
{
if (!lex.match(']')) return false;
}
return true;
}
bool ClassBase::read(Lex& lex, void* that) const
{
if (!lex.match('<')) return false;
if (!lex.match(name)) return false;
while(!lex.isMatch("/>"))
{
std::string ident;
if (!lex.matchIdent(ident)) return false;
const Member* member = findMember(ident.c_str());
if (member == nullptr) return lex.error("bad member name '%s'", ident.c_str());
if (!lex.match('=')) return false;
if (!lex.match('"')) return false;
if (!member->read(lex, that)) return false;
if (!lex.match('"')) return false;
}
return true;
}
bool ClassBase::read(void* that) const
{
LEX::File lex(name, "xml");
if (lex.isEof()) return false;
return read(lex, that);
}
bool ClassBase::exists(void* that) const
{
std::string filename = name;
filename += ".xml";
return PLT::File::exists(filename.c_str());
}
} // namespace OIL
} // namespace STB
<|endoftext|> |
<commit_before>
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include "Technique.hxx"
#include "Pass.hxx"
#include "EffectCullVisitor.hxx"
#include <boost/foreach.hpp>
#include <iterator>
#include <vector>
#include <string>
#include <osg/GLExtensions>
#include <osg/GL2Extensions>
#include <osg/Math>
#include <osg/Texture2D>
#include <osg/CopyOp>
#include <osgUtil/CullVisitor>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/ParameterOutput>
#include <simgear/props/props.hxx>
#include <simgear/structure/OSGUtils.hxx>
namespace simgear
{
using namespace osg;
using namespace osgUtil;
namespace
{
struct ValidateOperation : GraphicsOperation
{
ValidateOperation(Technique* technique_)
: GraphicsOperation(opName, false), technique(technique_)
{
}
virtual void operator() (GraphicsContext* gc);
osg::ref_ptr<Technique> technique;
static const std::string opName;
};
const std::string ValidateOperation::opName("ValidateOperation");
void ValidateOperation::operator() (GraphicsContext* gc)
{
technique->validateInContext(gc);
}
}
Technique::Technique(bool alwaysValid)
: _alwaysValid(alwaysValid), _contextIdLocation(-1)
{
}
Technique::Technique(const Technique& rhs, const osg::CopyOp& copyop) :
osg::Object(rhs,copyop),
_contextMap(rhs._contextMap), _alwaysValid(rhs._alwaysValid),
_shadowingStateSet(copyop(rhs._shadowingStateSet.get())),
_validExpression(rhs._validExpression),
_contextIdLocation(rhs._contextIdLocation)
{
for (std::vector<ref_ptr<Pass> >::const_iterator itr = rhs.passes.begin(),
end = rhs.passes.end();
itr != end;
++itr)
passes.push_back(static_cast<Pass*>(copyop(itr->get())));
}
Technique::~Technique()
{
}
Technique::Status Technique::valid(osg::RenderInfo* renderInfo)
{
if (_alwaysValid)
return VALID;
unsigned contextID = renderInfo->getContextID();
ContextInfo& contextInfo = _contextMap[contextID];
Status status = contextInfo.valid();
if (status != UNKNOWN)
return status;
Status newStatus = QUERY_IN_PROGRESS;
// lock and spawn validity check.
if (!contextInfo.valid.compareAndSwap(status, newStatus)) {
// Lost the race with another thread spawning a request
return contextInfo.valid();
}
ref_ptr<ValidateOperation> validOp = new ValidateOperation(this);
GraphicsContext* context = renderInfo->getState()->getGraphicsContext();
GraphicsThread* thread = context->getGraphicsThread();
if (thread)
thread->add(validOp.get());
else
context->add(validOp.get());
return newStatus;
}
Technique::Status Technique::getValidStatus(const RenderInfo* renderInfo) const
{
if (_alwaysValid)
return VALID;
ContextInfo& contextInfo = _contextMap[renderInfo->getContextID()];
return contextInfo.valid();
}
void Technique::validateInContext(GraphicsContext* gc)
{
unsigned int contextId = gc->getState()->getContextID();
ContextInfo& contextInfo = _contextMap[contextId];
Status oldVal = contextInfo.valid();
Status newVal = INVALID;
expression::FixedLengthBinding<1> binding;
binding.getBindings()[_contextIdLocation].val.intVal = contextId;
if (_validExpression->getValue(&binding))
newVal = VALID;
contextInfo.valid.compareAndSwap(oldVal, newVal);
}
namespace
{
enum NumDrawables {NUM_DRAWABLES = 128};
}
EffectGeode::DrawablesIterator
Technique::processDrawables(const EffectGeode::DrawablesIterator& begin,
const EffectGeode::DrawablesIterator& end,
CullVisitor* cv,
bool isCullingActive)
{
RefMatrix& matrix = *cv->getModelViewMatrix();
float depth[NUM_DRAWABLES];
EffectGeode::DrawablesIterator itr = begin;
bool computeNearFar
= cv->getComputeNearFarMode() != CullVisitor::DO_NOT_COMPUTE_NEAR_FAR;
for (int i = 0; i < NUM_DRAWABLES && itr != end; ++itr, ++i) {
Drawable* drawable = itr->get();
const BoundingBox& bb = drawable->getBound();
if ((drawable->getCullCallback()
&& drawable->getCullCallback()->cull(cv, drawable,
&cv->getRenderInfo()))
|| (isCullingActive && cv->isCulled(bb))) {
depth[i] = FLT_MAX;
continue;
}
if (computeNearFar && bb.valid()) {
if (!cv->updateCalculatedNearFar(matrix, *drawable, false)) {
depth[i] = FLT_MAX;
continue;
}
}
depth[i] = (bb.valid()
? cv->getDistanceFromEyePoint(bb.center(), false)
: 0.0f);
if (isNaN(depth[i]))
depth[i] = FLT_MAX;
}
EffectCullVisitor* ecv = dynamic_cast<EffectCullVisitor*>( cv );
EffectGeode::DrawablesIterator drawablesEnd = itr;
BOOST_FOREACH(ref_ptr<Pass>& pass, passes)
{
osg::ref_ptr<osg::StateSet> ss = pass;
if (ecv && ( ! pass->getBufferUnitList().empty() || ! pass->getPositionedUniformMap().empty() ) ) {
ss = static_cast<osg::StateSet*>(
pass->clone( osg::CopyOp( ( ! pass->getBufferUnitList().empty() ?
osg::CopyOp::DEEP_COPY_TEXTURES :
osg::CopyOp::SHALLOW_COPY ) |
( ! pass->getPositionedUniformMap().empty() ?
osg::CopyOp::DEEP_COPY_UNIFORMS :
osg::CopyOp::SHALLOW_COPY ) )
)
);
for (Pass::BufferUnitList::const_iterator ii = pass->getBufferUnitList().begin();
ii != pass->getBufferUnitList().end();
++ii) {
osg::Texture2D* tex = ecv->getBuffer(ii->second);
if (tex != 0)
ss->setTextureAttributeAndModes( ii->first, tex );
}
for (Pass::PositionedUniformMap::const_iterator ii = pass->getPositionedUniformMap().begin();
ii != pass->getPositionedUniformMap().end();
++ii) {
osg::RefMatrix* mv = cv->getModelViewMatrix();
osg::Vec4 v = ii->second * *mv;
ss->getUniform(ii->first)->set( v );
}
}
cv->pushStateSet(ss);
int i = 0;
for (itr = begin; itr != drawablesEnd; ++itr, ++i) {
if (depth[i] != FLT_MAX)
cv->addDrawableAndDepth(itr->get(), &matrix, depth[i]);
}
cv->popStateSet();
}
return drawablesEnd;
}
void Technique::resizeGLObjectBuffers(unsigned int maxSize)
{
if (_shadowingStateSet.valid())
_shadowingStateSet->resizeGLObjectBuffers(maxSize);
BOOST_FOREACH(ref_ptr<Pass>& pass, passes) {
pass->resizeGLObjectBuffers(maxSize);
}
_contextMap.resize(maxSize);
}
void Technique::releaseGLObjects(osg::State* state) const
{
if (_shadowingStateSet.valid())
_shadowingStateSet->releaseGLObjects(state);
BOOST_FOREACH(const ref_ptr<Pass>& pass, passes)
{
pass->releaseGLObjects(state);
}
if (state == 0) {
for (int i = 0; i < (int)_contextMap.size(); ++i) {
ContextInfo& info = _contextMap[i];
Status oldVal = info.valid();
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
} else {
ContextInfo& info = _contextMap[state->getContextID()];
Status oldVal = info.valid();
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
}
void Technique::setValidExpression(SGExpressionb* exp,
const simgear::expression
::BindingLayout& layout)
{
using namespace simgear::expression;
_validExpression = exp;
VariableBinding binding;
if (layout.findBinding("__contextId", binding))
_contextIdLocation = binding.location;
}
class GLVersionExpression : public SGExpression<float>
{
public:
void eval(float& value, const expression::Binding*) const
{
#ifdef TECHNIQUE_TEST_EXTENSIONS
value = 1.1;
#else
value = getGLVersionNumber();
#endif
}
};
Expression* glVersionParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
return new GLVersionExpression();
}
expression::ExpParserRegistrar glVersionRegistrar("glversion", glVersionParser);
class ExtensionSupportedExpression
: public GeneralNaryExpression<bool, int>
{
public:
ExtensionSupportedExpression() {}
ExtensionSupportedExpression(const std::string& extString)
: _extString(extString)
{
}
const std::string& getExtensionString() { return _extString; }
void setExtensionString(const std::string& extString) { _extString = extString; }
void eval(bool&value, const expression::Binding* b) const
{
int contextId = getOperand(0)->getValue(b);
value = isGLExtensionSupported((unsigned)contextId, _extString.c_str());
}
protected:
std::string _extString;
};
Expression* extensionSupportedParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
if (exp->getType() == props::STRING
|| exp->getType() == props::UNSPECIFIED) {
ExtensionSupportedExpression* esp
= new ExtensionSupportedExpression(exp->getStringValue());
int location = parser->getBindingLayout().addBinding("__contextId",
expression::INT);
VariableExpression<int>* contextExp
= new VariableExpression<int>(location);
esp->addOperand(contextExp);
return esp;
}
throw expression::ParseError("extension-supported expression has wrong type");
}
expression::ExpParserRegistrar
extensionSupportedRegistrar("extension-supported", extensionSupportedParser);
class GLShaderLanguageExpression : public GeneralNaryExpression<float, int>
{
public:
void eval(float& value, const expression::Binding* b) const
{
value = 0.0f;
int contextId = getOperand(0)->getValue(b);
GL2Extensions* extensions
= GL2Extensions::Get(static_cast<unsigned>(contextId), true);
if (!extensions)
return;
if (!extensions->isGlslSupported())
return;
value = extensions->getLanguageVersion();
}
};
Expression* shaderLanguageParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
GLShaderLanguageExpression* slexp = new GLShaderLanguageExpression;
int location = parser->getBindingLayout().addBinding("__contextId",
expression::INT);
VariableExpression<int>* contextExp = new VariableExpression<int>(location);
slexp->addOperand(contextExp);
return slexp;
}
expression::ExpParserRegistrar shaderLanguageRegistrar("shader-language",
glVersionParser);
void Technique::setGLExtensionsPred(float glVersion,
const std::vector<std::string>& extensions)
{
using namespace std;
using namespace expression;
BindingLayout layout;
int contextLoc = layout.addBinding("__contextId", INT);
VariableExpression<int>* contextExp
= new VariableExpression<int>(contextLoc);
SGExpression<bool>* versionTest
= makePredicate<std::less_equal>(new SGConstExpression<float>(glVersion),
new GLVersionExpression);
AndExpression* extensionsExp = 0;
for (vector<string>::const_iterator itr = extensions.begin(),
e = extensions.end();
itr != e;
++itr) {
if (!extensionsExp)
extensionsExp = new AndExpression;
ExtensionSupportedExpression* supported
= new ExtensionSupportedExpression(*itr);
supported->addOperand(contextExp);
extensionsExp->addOperand(supported);
}
SGExpressionb* predicate = 0;
if (extensionsExp) {
OrExpression* orExp = new OrExpression;
orExp->addOperand(versionTest);
orExp->addOperand(extensionsExp);
predicate = orExp;
} else {
predicate = versionTest;
}
setValidExpression(predicate, layout);
}
void Technique::refreshValidity()
{
for (int i = 0; i < (int)_contextMap.size(); ++i) {
ContextInfo& info = _contextMap[i];
Status oldVal = info.valid();
// What happens if we lose the race here?
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
}
bool Technique_writeLocalData(const Object& obj, osgDB::Output& fw)
{
const Technique& tniq = static_cast<const Technique&>(obj);
fw.indent() << "alwaysValid "
<< (tniq.getAlwaysValid() ? "TRUE\n" : "FALSE\n");
#if 0
fw.indent() << "glVersion " << tniq.getGLVersion() << "\n";
#endif
if (tniq.getShadowingStateSet()) {
fw.indent() << "shadowingStateSet\n";
fw.writeObject(*tniq.getShadowingStateSet());
}
fw.indent() << "num_passes " << tniq.passes.size() << "\n";
BOOST_FOREACH(const ref_ptr<Pass>& pass, tniq.passes) {
fw.writeObject(*pass);
}
return true;
}
namespace
{
osgDB::RegisterDotOsgWrapperProxy TechniqueProxy
(
new Technique,
"simgear::Technique",
"Object simgear::Technique",
0,
&Technique_writeLocalData
);
}
}
<commit_msg>Ensure type tag of contextId binding is set.<commit_after>
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include "Technique.hxx"
#include "Pass.hxx"
#include "EffectCullVisitor.hxx"
#include <boost/foreach.hpp>
#include <iterator>
#include <vector>
#include <string>
#include <osg/GLExtensions>
#include <osg/GL2Extensions>
#include <osg/Math>
#include <osg/Texture2D>
#include <osg/CopyOp>
#include <osgUtil/CullVisitor>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/ParameterOutput>
#include <simgear/props/props.hxx>
#include <simgear/structure/OSGUtils.hxx>
namespace simgear
{
using namespace osg;
using namespace osgUtil;
namespace
{
struct ValidateOperation : GraphicsOperation
{
ValidateOperation(Technique* technique_)
: GraphicsOperation(opName, false), technique(technique_)
{
}
virtual void operator() (GraphicsContext* gc);
osg::ref_ptr<Technique> technique;
static const std::string opName;
};
const std::string ValidateOperation::opName("ValidateOperation");
void ValidateOperation::operator() (GraphicsContext* gc)
{
technique->validateInContext(gc);
}
}
Technique::Technique(bool alwaysValid)
: _alwaysValid(alwaysValid), _contextIdLocation(-1)
{
}
Technique::Technique(const Technique& rhs, const osg::CopyOp& copyop) :
osg::Object(rhs,copyop),
_contextMap(rhs._contextMap), _alwaysValid(rhs._alwaysValid),
_shadowingStateSet(copyop(rhs._shadowingStateSet.get())),
_validExpression(rhs._validExpression),
_contextIdLocation(rhs._contextIdLocation)
{
for (std::vector<ref_ptr<Pass> >::const_iterator itr = rhs.passes.begin(),
end = rhs.passes.end();
itr != end;
++itr)
passes.push_back(static_cast<Pass*>(copyop(itr->get())));
}
Technique::~Technique()
{
}
Technique::Status Technique::valid(osg::RenderInfo* renderInfo)
{
if (_alwaysValid)
return VALID;
unsigned contextID = renderInfo->getContextID();
ContextInfo& contextInfo = _contextMap[contextID];
Status status = contextInfo.valid();
if (status != UNKNOWN)
return status;
Status newStatus = QUERY_IN_PROGRESS;
// lock and spawn validity check.
if (!contextInfo.valid.compareAndSwap(status, newStatus)) {
// Lost the race with another thread spawning a request
return contextInfo.valid();
}
ref_ptr<ValidateOperation> validOp = new ValidateOperation(this);
GraphicsContext* context = renderInfo->getState()->getGraphicsContext();
GraphicsThread* thread = context->getGraphicsThread();
if (thread)
thread->add(validOp.get());
else
context->add(validOp.get());
return newStatus;
}
Technique::Status Technique::getValidStatus(const RenderInfo* renderInfo) const
{
if (_alwaysValid)
return VALID;
ContextInfo& contextInfo = _contextMap[renderInfo->getContextID()];
return contextInfo.valid();
}
void Technique::validateInContext(GraphicsContext* gc)
{
unsigned int contextId = gc->getState()->getContextID();
ContextInfo& contextInfo = _contextMap[contextId];
Status oldVal = contextInfo.valid();
Status newVal = INVALID;
expression::FixedLengthBinding<1> binding;
binding.getBindings()[_contextIdLocation] = expression::Value((int) contextId);
if (_validExpression->getValue(&binding))
newVal = VALID;
contextInfo.valid.compareAndSwap(oldVal, newVal);
}
namespace
{
enum NumDrawables {NUM_DRAWABLES = 128};
}
EffectGeode::DrawablesIterator
Technique::processDrawables(const EffectGeode::DrawablesIterator& begin,
const EffectGeode::DrawablesIterator& end,
CullVisitor* cv,
bool isCullingActive)
{
RefMatrix& matrix = *cv->getModelViewMatrix();
float depth[NUM_DRAWABLES];
EffectGeode::DrawablesIterator itr = begin;
bool computeNearFar
= cv->getComputeNearFarMode() != CullVisitor::DO_NOT_COMPUTE_NEAR_FAR;
for (int i = 0; i < NUM_DRAWABLES && itr != end; ++itr, ++i) {
Drawable* drawable = itr->get();
const BoundingBox& bb = drawable->getBound();
if ((drawable->getCullCallback()
&& drawable->getCullCallback()->cull(cv, drawable,
&cv->getRenderInfo()))
|| (isCullingActive && cv->isCulled(bb))) {
depth[i] = FLT_MAX;
continue;
}
if (computeNearFar && bb.valid()) {
if (!cv->updateCalculatedNearFar(matrix, *drawable, false)) {
depth[i] = FLT_MAX;
continue;
}
}
depth[i] = (bb.valid()
? cv->getDistanceFromEyePoint(bb.center(), false)
: 0.0f);
if (isNaN(depth[i]))
depth[i] = FLT_MAX;
}
EffectCullVisitor* ecv = dynamic_cast<EffectCullVisitor*>( cv );
EffectGeode::DrawablesIterator drawablesEnd = itr;
BOOST_FOREACH(ref_ptr<Pass>& pass, passes)
{
osg::ref_ptr<osg::StateSet> ss = pass;
if (ecv && ( ! pass->getBufferUnitList().empty() || ! pass->getPositionedUniformMap().empty() ) ) {
ss = static_cast<osg::StateSet*>(
pass->clone( osg::CopyOp( ( ! pass->getBufferUnitList().empty() ?
osg::CopyOp::DEEP_COPY_TEXTURES :
osg::CopyOp::SHALLOW_COPY ) |
( ! pass->getPositionedUniformMap().empty() ?
osg::CopyOp::DEEP_COPY_UNIFORMS :
osg::CopyOp::SHALLOW_COPY ) )
)
);
for (Pass::BufferUnitList::const_iterator ii = pass->getBufferUnitList().begin();
ii != pass->getBufferUnitList().end();
++ii) {
osg::Texture2D* tex = ecv->getBuffer(ii->second);
if (tex != 0)
ss->setTextureAttributeAndModes( ii->first, tex );
}
for (Pass::PositionedUniformMap::const_iterator ii = pass->getPositionedUniformMap().begin();
ii != pass->getPositionedUniformMap().end();
++ii) {
osg::RefMatrix* mv = cv->getModelViewMatrix();
osg::Vec4 v = ii->second * *mv;
ss->getUniform(ii->first)->set( v );
}
}
cv->pushStateSet(ss);
int i = 0;
for (itr = begin; itr != drawablesEnd; ++itr, ++i) {
if (depth[i] != FLT_MAX)
cv->addDrawableAndDepth(itr->get(), &matrix, depth[i]);
}
cv->popStateSet();
}
return drawablesEnd;
}
void Technique::resizeGLObjectBuffers(unsigned int maxSize)
{
if (_shadowingStateSet.valid())
_shadowingStateSet->resizeGLObjectBuffers(maxSize);
BOOST_FOREACH(ref_ptr<Pass>& pass, passes) {
pass->resizeGLObjectBuffers(maxSize);
}
_contextMap.resize(maxSize);
}
void Technique::releaseGLObjects(osg::State* state) const
{
if (_shadowingStateSet.valid())
_shadowingStateSet->releaseGLObjects(state);
BOOST_FOREACH(const ref_ptr<Pass>& pass, passes)
{
pass->releaseGLObjects(state);
}
if (state == 0) {
for (int i = 0; i < (int)_contextMap.size(); ++i) {
ContextInfo& info = _contextMap[i];
Status oldVal = info.valid();
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
} else {
ContextInfo& info = _contextMap[state->getContextID()];
Status oldVal = info.valid();
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
}
void Technique::setValidExpression(SGExpressionb* exp,
const simgear::expression
::BindingLayout& layout)
{
using namespace simgear::expression;
_validExpression = exp;
VariableBinding binding;
if (layout.findBinding("__contextId", binding))
_contextIdLocation = binding.location;
}
class GLVersionExpression : public SGExpression<float>
{
public:
void eval(float& value, const expression::Binding*) const
{
#ifdef TECHNIQUE_TEST_EXTENSIONS
value = 1.1;
#else
value = getGLVersionNumber();
#endif
}
};
Expression* glVersionParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
return new GLVersionExpression();
}
expression::ExpParserRegistrar glVersionRegistrar("glversion", glVersionParser);
class ExtensionSupportedExpression
: public GeneralNaryExpression<bool, int>
{
public:
ExtensionSupportedExpression() {}
ExtensionSupportedExpression(const std::string& extString)
: _extString(extString)
{
}
const std::string& getExtensionString() { return _extString; }
void setExtensionString(const std::string& extString) { _extString = extString; }
void eval(bool&value, const expression::Binding* b) const
{
int contextId = getOperand(0)->getValue(b);
value = isGLExtensionSupported((unsigned)contextId, _extString.c_str());
}
protected:
std::string _extString;
};
Expression* extensionSupportedParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
if (exp->getType() == props::STRING
|| exp->getType() == props::UNSPECIFIED) {
ExtensionSupportedExpression* esp
= new ExtensionSupportedExpression(exp->getStringValue());
int location = parser->getBindingLayout().addBinding("__contextId",
expression::INT);
VariableExpression<int>* contextExp
= new VariableExpression<int>(location);
esp->addOperand(contextExp);
return esp;
}
throw expression::ParseError("extension-supported expression has wrong type");
}
expression::ExpParserRegistrar
extensionSupportedRegistrar("extension-supported", extensionSupportedParser);
class GLShaderLanguageExpression : public GeneralNaryExpression<float, int>
{
public:
void eval(float& value, const expression::Binding* b) const
{
value = 0.0f;
int contextId = getOperand(0)->getValue(b);
GL2Extensions* extensions
= GL2Extensions::Get(static_cast<unsigned>(contextId), true);
if (!extensions)
return;
if (!extensions->isGlslSupported())
return;
value = extensions->getLanguageVersion();
}
};
Expression* shaderLanguageParser(const SGPropertyNode* exp,
expression::Parser* parser)
{
GLShaderLanguageExpression* slexp = new GLShaderLanguageExpression;
int location = parser->getBindingLayout().addBinding("__contextId",
expression::INT);
VariableExpression<int>* contextExp = new VariableExpression<int>(location);
slexp->addOperand(contextExp);
return slexp;
}
expression::ExpParserRegistrar shaderLanguageRegistrar("shader-language",
glVersionParser);
void Technique::setGLExtensionsPred(float glVersion,
const std::vector<std::string>& extensions)
{
using namespace std;
using namespace expression;
BindingLayout layout;
int contextLoc = layout.addBinding("__contextId", INT);
VariableExpression<int>* contextExp
= new VariableExpression<int>(contextLoc);
SGExpression<bool>* versionTest
= makePredicate<std::less_equal>(new SGConstExpression<float>(glVersion),
new GLVersionExpression);
AndExpression* extensionsExp = 0;
for (vector<string>::const_iterator itr = extensions.begin(),
e = extensions.end();
itr != e;
++itr) {
if (!extensionsExp)
extensionsExp = new AndExpression;
ExtensionSupportedExpression* supported
= new ExtensionSupportedExpression(*itr);
supported->addOperand(contextExp);
extensionsExp->addOperand(supported);
}
SGExpressionb* predicate = 0;
if (extensionsExp) {
OrExpression* orExp = new OrExpression;
orExp->addOperand(versionTest);
orExp->addOperand(extensionsExp);
predicate = orExp;
} else {
predicate = versionTest;
}
setValidExpression(predicate, layout);
}
void Technique::refreshValidity()
{
for (int i = 0; i < (int)_contextMap.size(); ++i) {
ContextInfo& info = _contextMap[i];
Status oldVal = info.valid();
// What happens if we lose the race here?
info.valid.compareAndSwap(oldVal, UNKNOWN);
}
}
bool Technique_writeLocalData(const Object& obj, osgDB::Output& fw)
{
const Technique& tniq = static_cast<const Technique&>(obj);
fw.indent() << "alwaysValid "
<< (tniq.getAlwaysValid() ? "TRUE\n" : "FALSE\n");
#if 0
fw.indent() << "glVersion " << tniq.getGLVersion() << "\n";
#endif
if (tniq.getShadowingStateSet()) {
fw.indent() << "shadowingStateSet\n";
fw.writeObject(*tniq.getShadowingStateSet());
}
fw.indent() << "num_passes " << tniq.passes.size() << "\n";
BOOST_FOREACH(const ref_ptr<Pass>& pass, tniq.passes) {
fw.writeObject(*pass);
}
return true;
}
namespace
{
osgDB::RegisterDotOsgWrapperProxy TechniqueProxy
(
new Technique,
"simgear::Technique",
"Object simgear::Technique",
0,
&Technique_writeLocalData
);
}
}
<|endoftext|> |
<commit_before><commit_msg>Restore "magic resolve" as per code review.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 Stoned Xander
*
* 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.
*/
/*
* This example is not meant to simulate flocking, but only "almost"
* straight line going agents and how it affects the search tree.
*/
#include <iostream>
#include <random>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <headless-logic/searchtree.hpp>
#include "../common.hpp"
int loadTexture(sf::Texture &texture, std::string path) {
if(!texture.loadFromFile(path)) {
std::cerr << "Can't load texture '"
<< path << "' !" << std::endl;
return 0;
}
texture.setSmooth(true);
return 1;
}
class DisplayerVisitor {
private:
sf::Sprite *_sprite;
sf::RenderWindow *_window;
public:
DisplayerVisitor() : _sprite(nullptr), _window(nullptr) {}
void set(sf::Sprite *sprite, sf::RenderWindow *window) {
_sprite = sprite;
_window = window;
}
void init() {}
void enter(const Region& region) {
glm::vec4 boundary = region.boundary();
#ifdef DISPLAY_CENTER
_sprite->setPosition(boundary.x + (boundary.p / 2.0),
boundary.y + (boundary.q / 2.0));
_window->draw(*_sprite);
#else
_sprite->setPosition(boundary.x, boundary.y);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x + boundary.p, boundary.y);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x + boundary.p, boundary.y + boundary.q);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x, boundary.y + boundary.q);
_window->draw(*_sprite);
#endif
}
void exit(const Region&) {}
void inspect(Element **, unsigned int count) {
if(count == 0) {
// std::cout << "Empty leaf !" << std::endl;
}
if(count > 3) {
std::cout << "Node Overflow !" << std::endl;
}
}
};
#define AGENT_COUNT 256
/**
* Main procedure.
*/
int main(void) {
sf::Vector2f textureOffset(32, 32);
sf::Texture agentTexture;
if(!loadTexture(agentTexture, "resources/agent.png")) { return -1; }
sf::Texture boundaryTexture;
if(!loadTexture(boundaryTexture, "resources/cross.png")) { return -1; }
sf::Sprite sprite;
sf::RenderWindow window(sf::VideoMode(1024, 1024), "Crowd Control",
sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(60);
DisplayerVisitor visitor;
visitor.set(&sprite, &window);
Region region(glm::vec4(0.0, 0.0, 1024.0, 1024.0));
Headless::Logic::SearchTree::Node<glm::vec2, Region, Element> tree(®ion, 3);
Element **pool = new Element*[AGENT_COUNT];
Element **searchResult = new Element*[AGENT_COUNT];
std::random_device randomDevice;
std::mt19937 mt(randomDevice());
std::uniform_real_distribution<double> posDist(0.0, 1024.0);
std::uniform_real_distribution<double> velDist(-128.0, 128.0);
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
pool[i] = new Element(glm::vec2(posDist(mt), posDist(mt)),
std::string("Agent#").append(std::to_string(i)));
pool[i]->velocity(glm::vec2(velDist(mt), velDist(mt)));
tree.add(pool[i]);
}
sf::Clock clock;
sf::Time elapsed;
glm::vec2 target;
glm::vec2 velocity;
Disc searchDisc;
while (window.isOpen()) {
// Logic update
elapsed = clock.restart();
float sec = elapsed.asSeconds();
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
target = pool[i]->key();
velocity = pool[i]->velocity();
target.x += velocity.x * sec;
target.y += velocity.y * sec;
if(target.x < 0 || target.y < 0 || target.x > 1024.0 || target.y > 1024.0) {
target.x = posDist(mt);
target.y = posDist(mt);
velocity.x = velDist(mt);
velocity.y = velDist(mt);
pool[i]->velocity(velocity);
}
tree.move(pool[i], target);
// Search neighbor and take mean velocity.
searchDisc.set(target, 32.0);
unsigned int count = tree.retrieve(searchDisc, searchResult, AGENT_COUNT);
glm::vec2 meanVelocity(0.0, 0.0);
for(unsigned int j = 0; j < count; ++j) {
meanVelocity += searchResult[j]->velocity();
}
if(count > 0) {
meanVelocity.x /= (double) count;
meanVelocity.y /= (double) count;
pool[i]->velocity(meanVelocity);
}
}
// Event handling.
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
// Draw
window.clear(sf::Color::Black);
sf::Vector2i localPosition = sf::Mouse::getPosition(window);
sprite.setTexture(agentTexture);
sprite.setOrigin(textureOffset);
sprite.setColor(sf::Color(0, 255, 0));
sprite.setPosition(localPosition.x, localPosition.y);
sprite.setScale(sf::Vector2f(.5f, .5f));
window.draw(sprite);
sprite.setColor(sf::Color(0, 128, 255));
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
glm::vec2 pos = pool[i]->key();
sprite.setPosition(pos.x, pos.y);
window.draw(sprite);
}
sprite.setColor(sf::Color(255, 255, 255, 32));
sprite.setTexture(boundaryTexture);
tree.visit(visitor);
window.display();
}
// Clean Exit.
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
delete pool[i];
}
delete []pool;
delete []searchResult;
return 0;
}
<commit_msg>Added a parameter for world/window size in search tree crowd example.<commit_after>/*
* Copyright 2016 Stoned Xander
*
* 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.
*/
/*
* This example is not meant to simulate flocking, but only "almost"
* straight line going agents and how it affects the search tree.
*/
#include <iostream>
#include <random>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <headless-logic/searchtree.hpp>
#include "../common.hpp"
int loadTexture(sf::Texture &texture, std::string path) {
if(!texture.loadFromFile(path)) {
std::cerr << "Can't load texture '"
<< path << "' !" << std::endl;
return 0;
}
texture.setSmooth(true);
return 1;
}
class DisplayerVisitor {
private:
sf::Sprite *_sprite;
sf::RenderWindow *_window;
public:
DisplayerVisitor() : _sprite(nullptr), _window(nullptr) {}
void set(sf::Sprite *sprite, sf::RenderWindow *window) {
_sprite = sprite;
_window = window;
}
void init() {}
void enter(const Region& region) {
glm::vec4 boundary = region.boundary();
#ifdef DISPLAY_CENTER
_sprite->setPosition(boundary.x + (boundary.p / 2.0),
boundary.y + (boundary.q / 2.0));
_window->draw(*_sprite);
#else
_sprite->setPosition(boundary.x, boundary.y);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x + boundary.p, boundary.y);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x + boundary.p, boundary.y + boundary.q);
_window->draw(*_sprite);
_sprite->setPosition(boundary.x, boundary.y + boundary.q);
_window->draw(*_sprite);
#endif
}
void exit(const Region&) {}
void inspect(Element **, unsigned int count) {
if(count == 0) {
// std::cout << "Empty leaf !" << std::endl;
}
if(count > 3) {
std::cout << "Node Overflow !" << std::endl;
}
}
};
#define AGENT_COUNT 256
#define AREA_SIZE 800
/**
* Main procedure.
*/
int main(void) {
sf::Vector2f textureOffset(32, 32);
sf::Texture agentTexture;
if(!loadTexture(agentTexture, "resources/agent.png")) { return -1; }
sf::Texture boundaryTexture;
if(!loadTexture(boundaryTexture, "resources/cross.png")) { return -1; }
sf::Sprite sprite;
sf::RenderWindow window(sf::VideoMode(AREA_SIZE, AREA_SIZE), "Crowd Control",
sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(60);
DisplayerVisitor visitor;
visitor.set(&sprite, &window);
Region region(glm::vec4(0.0, 0.0, AREA_SIZE, AREA_SIZE));
Headless::Logic::SearchTree::Node<glm::vec2, Region, Element> tree(®ion, 3);
Element **pool = new Element*[AGENT_COUNT];
Element **searchResult = new Element*[AGENT_COUNT];
std::random_device randomDevice;
std::mt19937 mt(randomDevice());
std::uniform_real_distribution<double> posDist(0.0, AREA_SIZE);
std::uniform_real_distribution<double> velDist(-128.0, 128.0);
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
pool[i] = new Element(glm::vec2(posDist(mt), posDist(mt)),
std::string("Agent#").append(std::to_string(i)));
pool[i]->velocity(glm::vec2(velDist(mt), velDist(mt)));
tree.add(pool[i]);
}
sf::Clock clock;
sf::Time elapsed;
glm::vec2 target;
glm::vec2 velocity;
Disc searchDisc;
while (window.isOpen()) {
// Logic update
elapsed = clock.restart();
float sec = elapsed.asSeconds();
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
target = pool[i]->key();
velocity = pool[i]->velocity();
target.x += velocity.x * sec;
target.y += velocity.y * sec;
if(target.x < 0 || target.y < 0 || target.x > AREA_SIZE || target.y > AREA_SIZE) {
target.x = posDist(mt);
target.y = posDist(mt);
velocity.x = velDist(mt);
velocity.y = velDist(mt);
pool[i]->velocity(velocity);
}
tree.move(pool[i], target);
// Search neighbor and take mean velocity.
searchDisc.set(target, 32.0);
unsigned int count = tree.retrieve(searchDisc, searchResult, AGENT_COUNT);
glm::vec2 meanVelocity(0.0, 0.0);
for(unsigned int j = 0; j < count; ++j) {
meanVelocity += searchResult[j]->velocity();
}
if(count > 0) {
meanVelocity.x /= (double) count;
meanVelocity.y /= (double) count;
pool[i]->velocity(meanVelocity);
}
}
// Event handling.
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
// Draw
window.clear(sf::Color::Black);
sf::Vector2i localPosition = sf::Mouse::getPosition(window);
sprite.setTexture(agentTexture);
sprite.setOrigin(textureOffset);
sprite.setColor(sf::Color(0, 255, 0));
sprite.setPosition(localPosition.x, localPosition.y);
sprite.setScale(sf::Vector2f(.5f, .5f));
window.draw(sprite);
sprite.setColor(sf::Color(0, 128, 255));
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
glm::vec2 pos = pool[i]->key();
sprite.setPosition(pos.x, pos.y);
window.draw(sprite);
}
sprite.setColor(sf::Color(255, 255, 255, 32));
sprite.setTexture(boundaryTexture);
tree.visit(visitor);
window.display();
}
// Clean Exit.
for(unsigned int i = 0; i < AGENT_COUNT; ++i) {
delete pool[i];
}
delete []pool;
delete []searchResult;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 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.
*/
#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "HttpResponseHandler.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "PInstance.hxx"
#include "pool/pool.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/HeadIstream.hxx"
#include "istream/BlockIstream.hxx"
#include "istream/istream_catch.hxx"
#include "istream/Sink.hxx"
#include "fb_pool.hxx"
#include "fs/FilteredSocket.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include "util/Cancellable.hxx"
#include "util/PrintException.hxx"
#include <stdio.h>
#include <stdlib.h>
struct Instance final
: HttpServerConnectionHandler, Lease, HttpResponseHandler, IstreamSink, BufferedSocketHandler
{
struct pool *pool;
HttpServerConnection *connection = nullptr;
FilteredSocket client_fs;
CancellablePointer client_cancel_ptr;
std::exception_ptr response_error;
std::string response_body;
http_status_t status{};
bool client_fs_released = false;
bool response_eof = false;
Instance(struct pool &_pool, EventLoop &event_loop);
~Instance() noexcept {
CheckCloseConnection();
}
void RethrowResponseError() const {
if (response_error)
std::rethrow_exception(response_error);
}
bool IsClientDone() const noexcept {
return response_error || response_eof;
}
void CloseConnection() noexcept {
http_server_connection_close(connection);
connection = nullptr;
}
void CheckCloseConnection() noexcept {
if (connection != nullptr)
CloseConnection();
}
void SendRequest(http_method_t method, const char *uri,
HttpHeaders &&headers,
UnusedIstreamPtr body, bool expect_100=false) noexcept {
response_error = {};
status = {};
response_eof = false;
http_client_request(*pool, client_fs, *this,
"foo",
method, uri, std::move(headers),
std::move(body), expect_100,
*this, client_cancel_ptr);
}
void CloseClientSocket() noexcept {
if (client_fs.IsValid() && client_fs.IsConnected()) {
client_fs.Close();
client_fs.Destroy();
}
}
/* virtual methods from class HttpServerConnectionHandler */
void HandleHttpRequest(HttpServerRequest &request,
CancellablePointer &cancel_ptr) noexcept override;
void LogHttpRequest(HttpServerRequest &,
http_status_t, int64_t,
uint64_t, uint64_t) noexcept override {}
void HttpConnectionError(std::exception_ptr e) noexcept override;
void HttpConnectionClosed() noexcept override;
/* virtual methods from class HttpResponseHandler */
void ReleaseLease(bool reuse) noexcept override {
client_fs_released = true;
if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {
client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);
client_fs.UnscheduleWrite();
} else {
CloseClientSocket();
}
}
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t _status, StringMap &&headers,
UnusedIstreamPtr body) noexcept override {
status = _status;
(void)headers;
IstreamSink::SetInput(std::move(body));
input.Read();
}
void OnHttpError(std::exception_ptr ep) noexcept override {
response_error = std::move(ep);
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
response_body.append((const char *)data, length);
return length;
}
void OnEof() noexcept override {
IstreamSink::ClearInput();
response_eof = true;
}
void OnError(std::exception_ptr ep) noexcept override {
IstreamSink::ClearInput();
response_error = std::move(ep);
}
/* virtual methods from class BufferedSocketHandler */
BufferedResult OnBufferedData() override {
fprintf(stderr, "unexpected data in idle TCP connection");
CloseClientSocket();
return BufferedResult::CLOSED;
}
bool OnBufferedClosed() noexcept override {
CloseClientSocket();
return false;
}
gcc_noreturn
bool OnBufferedWrite() override {
/* should never be reached because we never schedule
writing */
gcc_unreachable();
}
void OnBufferedError(std::exception_ptr e) noexcept override {
PrintException(e);
CloseClientSocket();
}
};
Instance::Instance(struct pool &_pool, EventLoop &event_loop)
:pool(pool_new_libc(&_pool, "catch")),
client_fs(event_loop)
{
UniqueSocketDescriptor client_socket, server_socket;
if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,
client_socket, server_socket))
throw MakeErrno("socketpair() failed");
connection = http_server_connection_new(pool, event_loop,
std::move(server_socket),
FdType::FD_SOCKET,
nullptr,
nullptr, nullptr,
true, *this);
client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);
pool_unref(pool);
}
static std::exception_ptr
catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept
{
PrintException(ep);
return {};
}
void
Instance::HandleHttpRequest(HttpServerRequest &request,
gcc_unused CancellablePointer &cancel_ptr) noexcept
{
http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),
istream_catch_new(&request.pool,
std::move(request.body),
catch_callback, nullptr));
CloseConnection();
}
void
Instance::HttpConnectionError(std::exception_ptr e) noexcept
{
connection = nullptr;
PrintException(e);
}
void
Instance::HttpConnectionClosed() noexcept
{
connection = nullptr;
}
static void
test_catch(EventLoop &event_loop, struct pool *_pool)
{
Instance instance(*_pool, event_loop);
instance.SendRequest(HTTP_METHOD_POST, "/", HttpHeaders(*instance.pool),
istream_head_new(*instance.pool,
istream_block_new(*instance.pool),
1024, true));
while (!instance.IsClientDone())
event_loop.LoopOnce();
instance.CloseClientSocket();
instance.RethrowResponseError();
event_loop.Dispatch();
}
int
main(int argc, char **argv) noexcept
try {
(void)argc;
(void)argv;
direct_global_init();
const ScopeFbPoolInit fb_pool_init;
PInstance instance;
test_catch(instance.event_loop, instance.root_pool);
} catch (...) {
PrintException(std::current_exception());
return EXIT_FAILURE;
}
<commit_msg>test/t_http_server: add Instance::GetPool()<commit_after>/*
* Copyright 2007-2017 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.
*/
#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "HttpResponseHandler.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "PInstance.hxx"
#include "pool/pool.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/HeadIstream.hxx"
#include "istream/BlockIstream.hxx"
#include "istream/istream_catch.hxx"
#include "istream/Sink.hxx"
#include "fb_pool.hxx"
#include "fs/FilteredSocket.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include "util/Cancellable.hxx"
#include "util/PrintException.hxx"
#include <stdio.h>
#include <stdlib.h>
struct Instance final
: HttpServerConnectionHandler, Lease, HttpResponseHandler, IstreamSink, BufferedSocketHandler
{
struct pool *pool;
HttpServerConnection *connection = nullptr;
FilteredSocket client_fs;
CancellablePointer client_cancel_ptr;
std::exception_ptr response_error;
std::string response_body;
http_status_t status{};
bool client_fs_released = false;
bool response_eof = false;
Instance(struct pool &_pool, EventLoop &event_loop);
~Instance() noexcept {
CheckCloseConnection();
}
struct pool &GetPool() noexcept {
return *pool;
}
void RethrowResponseError() const {
if (response_error)
std::rethrow_exception(response_error);
}
bool IsClientDone() const noexcept {
return response_error || response_eof;
}
void CloseConnection() noexcept {
http_server_connection_close(connection);
connection = nullptr;
}
void CheckCloseConnection() noexcept {
if (connection != nullptr)
CloseConnection();
}
void SendRequest(http_method_t method, const char *uri,
HttpHeaders &&headers,
UnusedIstreamPtr body, bool expect_100=false) noexcept {
response_error = {};
status = {};
response_eof = false;
http_client_request(*pool, client_fs, *this,
"foo",
method, uri, std::move(headers),
std::move(body), expect_100,
*this, client_cancel_ptr);
}
void CloseClientSocket() noexcept {
if (client_fs.IsValid() && client_fs.IsConnected()) {
client_fs.Close();
client_fs.Destroy();
}
}
/* virtual methods from class HttpServerConnectionHandler */
void HandleHttpRequest(HttpServerRequest &request,
CancellablePointer &cancel_ptr) noexcept override;
void LogHttpRequest(HttpServerRequest &,
http_status_t, int64_t,
uint64_t, uint64_t) noexcept override {}
void HttpConnectionError(std::exception_ptr e) noexcept override;
void HttpConnectionClosed() noexcept override;
/* virtual methods from class HttpResponseHandler */
void ReleaseLease(bool reuse) noexcept override {
client_fs_released = true;
if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {
client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);
client_fs.UnscheduleWrite();
} else {
CloseClientSocket();
}
}
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t _status, StringMap &&headers,
UnusedIstreamPtr body) noexcept override {
status = _status;
(void)headers;
IstreamSink::SetInput(std::move(body));
input.Read();
}
void OnHttpError(std::exception_ptr ep) noexcept override {
response_error = std::move(ep);
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
response_body.append((const char *)data, length);
return length;
}
void OnEof() noexcept override {
IstreamSink::ClearInput();
response_eof = true;
}
void OnError(std::exception_ptr ep) noexcept override {
IstreamSink::ClearInput();
response_error = std::move(ep);
}
/* virtual methods from class BufferedSocketHandler */
BufferedResult OnBufferedData() override {
fprintf(stderr, "unexpected data in idle TCP connection");
CloseClientSocket();
return BufferedResult::CLOSED;
}
bool OnBufferedClosed() noexcept override {
CloseClientSocket();
return false;
}
gcc_noreturn
bool OnBufferedWrite() override {
/* should never be reached because we never schedule
writing */
gcc_unreachable();
}
void OnBufferedError(std::exception_ptr e) noexcept override {
PrintException(e);
CloseClientSocket();
}
};
Instance::Instance(struct pool &_pool, EventLoop &event_loop)
:pool(pool_new_libc(&_pool, "catch")),
client_fs(event_loop)
{
UniqueSocketDescriptor client_socket, server_socket;
if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,
client_socket, server_socket))
throw MakeErrno("socketpair() failed");
connection = http_server_connection_new(pool, event_loop,
std::move(server_socket),
FdType::FD_SOCKET,
nullptr,
nullptr, nullptr,
true, *this);
client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);
pool_unref(pool);
}
static std::exception_ptr
catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept
{
PrintException(ep);
return {};
}
void
Instance::HandleHttpRequest(HttpServerRequest &request,
gcc_unused CancellablePointer &cancel_ptr) noexcept
{
http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),
istream_catch_new(&request.pool,
std::move(request.body),
catch_callback, nullptr));
CloseConnection();
}
void
Instance::HttpConnectionError(std::exception_ptr e) noexcept
{
connection = nullptr;
PrintException(e);
}
void
Instance::HttpConnectionClosed() noexcept
{
connection = nullptr;
}
static void
test_catch(EventLoop &event_loop, struct pool *_pool)
{
Instance instance(*_pool, event_loop);
instance.SendRequest(HTTP_METHOD_POST, "/", HttpHeaders(instance.GetPool()),
istream_head_new(instance.GetPool(),
istream_block_new(instance.GetPool()),
1024, true));
while (!instance.IsClientDone())
event_loop.LoopOnce();
instance.CloseClientSocket();
instance.RethrowResponseError();
event_loop.Dispatch();
}
int
main(int argc, char **argv) noexcept
try {
(void)argc;
(void)argv;
direct_global_init();
const ScopeFbPoolInit fb_pool_init;
PInstance instance;
test_catch(instance.event_loop, instance.root_pool);
} catch (...) {
PrintException(std::current_exception());
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: keymapping.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:04:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_KEYMAPPING_HXX_
#include <accelerators/keymapping.hxx>
#endif
//_______________________________________________
// own includes
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_AWT_KEY_HPP_
#include <com/sun/star/awt/Key.hpp>
#endif
//_______________________________________________
// other includes
//_______________________________________________
// namespace
namespace framework
{
//_______________________________________________
// helper
KeyMapping::KeyIdentifierInfo KeyMapping::KeyIdentifierMap[] =
{
{css::awt::Key::NUM0 , "KEY_0" },
{css::awt::Key::NUM1 , "KEY_1" },
{css::awt::Key::NUM2 , "KEY_2" },
{css::awt::Key::NUM3 , "KEY_3" },
{css::awt::Key::NUM4 , "KEY_4" },
{css::awt::Key::NUM5 , "KEY_5" },
{css::awt::Key::NUM6 , "KEY_6" },
{css::awt::Key::NUM7 , "KEY_7" },
{css::awt::Key::NUM8 , "KEY_8" },
{css::awt::Key::NUM9 , "KEY_9" },
{css::awt::Key::A , "KEY_A" },
{css::awt::Key::B , "KEY_B" },
{css::awt::Key::C , "KEY_C" },
{css::awt::Key::D , "KEY_D" },
{css::awt::Key::E , "KEY_E" },
{css::awt::Key::F , "KEY_F" },
{css::awt::Key::G , "KEY_G" },
{css::awt::Key::H , "KEY_H" },
{css::awt::Key::I , "KEY_I" },
{css::awt::Key::J , "KEY_J" },
{css::awt::Key::K , "KEY_K" },
{css::awt::Key::L , "KEY_L" },
{css::awt::Key::M , "KEY_M" },
{css::awt::Key::N , "KEY_N" },
{css::awt::Key::O , "KEY_O" },
{css::awt::Key::P , "KEY_P" },
{css::awt::Key::Q , "KEY_Q" },
{css::awt::Key::R , "KEY_R" },
{css::awt::Key::S , "KEY_S" },
{css::awt::Key::T , "KEY_T" },
{css::awt::Key::U , "KEY_U" },
{css::awt::Key::V , "KEY_V" },
{css::awt::Key::W , "KEY_W" },
{css::awt::Key::X , "KEY_X" },
{css::awt::Key::Y , "KEY_Y" },
{css::awt::Key::Z , "KEY_Z" },
{css::awt::Key::F1 , "KEY_F1" },
{css::awt::Key::F2 , "KEY_F2" },
{css::awt::Key::F3 , "KEY_F3" },
{css::awt::Key::F4 , "KEY_F4" },
{css::awt::Key::F5 , "KEY_F5" },
{css::awt::Key::F6 , "KEY_F6" },
{css::awt::Key::F7 , "KEY_F7" },
{css::awt::Key::F8 , "KEY_F8" },
{css::awt::Key::F9 , "KEY_F9" },
{css::awt::Key::F10 , "KEY_F10" },
{css::awt::Key::F11 , "KEY_F11" },
{css::awt::Key::F12 , "KEY_F12" },
{css::awt::Key::F13 , "KEY_F13" },
{css::awt::Key::F14 , "KEY_F14" },
{css::awt::Key::F15 , "KEY_F15" },
{css::awt::Key::F16 , "KEY_F16" },
{css::awt::Key::F17 , "KEY_F17" },
{css::awt::Key::F18 , "KEY_F18" },
{css::awt::Key::F19 , "KEY_F19" },
{css::awt::Key::F20 , "KEY_F20" },
{css::awt::Key::F21 , "KEY_F21" },
{css::awt::Key::F22 , "KEY_F22" },
{css::awt::Key::F23 , "KEY_F23" },
{css::awt::Key::F24 , "KEY_F24" },
{css::awt::Key::F25 , "KEY_F25" },
{css::awt::Key::F26 , "KEY_F26" },
{css::awt::Key::DOWN , "KEY_DOWN" },
{css::awt::Key::UP , "KEY_UP" },
{css::awt::Key::LEFT , "KEY_LEFT" },
{css::awt::Key::RIGHT , "KEY_RIGHT" },
{css::awt::Key::HOME , "KEY_HOME" },
{css::awt::Key::END , "KEY_END" },
{css::awt::Key::PAGEUP , "KEY_PAGEUP" },
{css::awt::Key::PAGEDOWN , "KEY_PAGEDOWN" },
{css::awt::Key::RETURN , "KEY_RETURN" },
{css::awt::Key::ESCAPE , "KEY_ESCAPE" },
{css::awt::Key::TAB , "KEY_TAB" },
{css::awt::Key::BACKSPACE , "KEY_BACKSPACE" },
{css::awt::Key::SPACE , "KEY_SPACE" },
{css::awt::Key::INSERT , "KEY_INSERT" },
{css::awt::Key::DELETE , "KEY_DELETE" },
{css::awt::Key::ADD , "KEY_ADD" },
{css::awt::Key::SUBTRACT , "KEY_SUBTRACT" },
{css::awt::Key::MULTIPLY , "KEY_MULTIPLY" },
{css::awt::Key::DIVIDE , "KEY_DIVIDE" },
{css::awt::Key::POINT , "KEY_POINT" },
{css::awt::Key::COMMA , "KEY_COMMA" },
{css::awt::Key::LESS , "KEY_LESS" },
{css::awt::Key::GREATER , "KEY_GREATER" },
{css::awt::Key::EQUAL , "KEY_EQUAL" },
{css::awt::Key::OPEN , "KEY_OPEN" },
{css::awt::Key::CUT , "KEY_CUT" },
{css::awt::Key::COPY , "KEY_COPY" },
{css::awt::Key::PASTE , "KEY_PASTE" },
{css::awt::Key::UNDO , "KEY_UNDO" },
{css::awt::Key::REPEAT , "KEY_REPEAT" },
{css::awt::Key::FIND , "KEY_FIND" },
{css::awt::Key::PROPERTIES , "KEY_PROPERTIES" },
{css::awt::Key::FRONT , "KEY_FRONT" },
{css::awt::Key::CONTEXTMENU , "KEY_CONTEXTMENU"},
{css::awt::Key::HELP , "KEY_HELP" },
{0 , "" } // mark the end of this array!
};
//-----------------------------------------------
KeyMapping::KeyMapping()
{
sal_Int32 i = 0;
while(KeyIdentifierMap[i].Code != 0)
{
::rtl::OUString sIdentifier = ::rtl::OUString::createFromAscii(KeyIdentifierMap[i].Identifier);
sal_Int16 nCode = KeyIdentifierMap[i].Code;
m_lIdentifierHash[sIdentifier] = nCode ;
m_lCodeHash [nCode] = sIdentifier;
++i;
}
}
//-----------------------------------------------
KeyMapping::~KeyMapping()
{
}
//-----------------------------------------------
sal_uInt16 KeyMapping::mapIdentifierToCode(const ::rtl::OUString& sIdentifier)
throw(css::lang::IllegalArgumentException)
{
Identifier2CodeHash::const_iterator pIt = m_lIdentifierHash.find(sIdentifier);
if (pIt != m_lIdentifierHash.end())
return pIt->second;
// Its not well known identifier - but may be a pure key code formated as string ...
// Check and convert it!
sal_uInt16 nCode = 0;
if (!KeyMapping::impl_st_interpretIdentifierAsPureKeyCode(sIdentifier, nCode))
throw css::lang::IllegalArgumentException(
DECLARE_ASCII("Cant map given identifier to a valid key code value."),
css::uno::Reference< css::uno::XInterface >(),
0);
return (sal_uInt16)nCode;
}
//-----------------------------------------------
::rtl::OUString KeyMapping::mapCodeToIdentifier(sal_uInt16 nCode)
{
Code2IdentifierHash::const_iterator pIt = m_lCodeHash.find(nCode);
if (pIt != m_lCodeHash.end())
return pIt->second;
// If we have no well known identifier - use the pure code value!
return ::rtl::OUString::valueOf((sal_Int32)nCode);
}
//-----------------------------------------------
sal_Bool KeyMapping::impl_st_interpretIdentifierAsPureKeyCode(const ::rtl::OUString& sIdentifier,
sal_uInt16& rCode )
{
sal_Int32 nCode = sIdentifier.toInt32();
if (nCode > 0)
{
rCode = (sal_uInt16)nCode;
return sal_True;
}
// 0 is normaly an error of the called method toInt32() ...
// But we must be aware, that the identifier is "0"!
rCode = 0;
return sIdentifier.equalsAscii("0");
}
} // namespace framework
<commit_msg>INTEGRATION: CWS vcl49 (1.3.60); FILE MERGED 2005/12/05 17:02:34 pl 1.3.60.1: #i56194# add: MENU, HANGUL_HANJA, DECIMAL, TILDE, QUOTELEFT<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: keymapping.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-01-20 12:41:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_KEYMAPPING_HXX_
#include <accelerators/keymapping.hxx>
#endif
//_______________________________________________
// own includes
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_AWT_KEY_HPP_
#include <com/sun/star/awt/Key.hpp>
#endif
//_______________________________________________
// other includes
//_______________________________________________
// namespace
namespace framework
{
//_______________________________________________
// helper
KeyMapping::KeyIdentifierInfo KeyMapping::KeyIdentifierMap[] =
{
{css::awt::Key::NUM0 , "KEY_0" },
{css::awt::Key::NUM1 , "KEY_1" },
{css::awt::Key::NUM2 , "KEY_2" },
{css::awt::Key::NUM3 , "KEY_3" },
{css::awt::Key::NUM4 , "KEY_4" },
{css::awt::Key::NUM5 , "KEY_5" },
{css::awt::Key::NUM6 , "KEY_6" },
{css::awt::Key::NUM7 , "KEY_7" },
{css::awt::Key::NUM8 , "KEY_8" },
{css::awt::Key::NUM9 , "KEY_9" },
{css::awt::Key::A , "KEY_A" },
{css::awt::Key::B , "KEY_B" },
{css::awt::Key::C , "KEY_C" },
{css::awt::Key::D , "KEY_D" },
{css::awt::Key::E , "KEY_E" },
{css::awt::Key::F , "KEY_F" },
{css::awt::Key::G , "KEY_G" },
{css::awt::Key::H , "KEY_H" },
{css::awt::Key::I , "KEY_I" },
{css::awt::Key::J , "KEY_J" },
{css::awt::Key::K , "KEY_K" },
{css::awt::Key::L , "KEY_L" },
{css::awt::Key::M , "KEY_M" },
{css::awt::Key::N , "KEY_N" },
{css::awt::Key::O , "KEY_O" },
{css::awt::Key::P , "KEY_P" },
{css::awt::Key::Q , "KEY_Q" },
{css::awt::Key::R , "KEY_R" },
{css::awt::Key::S , "KEY_S" },
{css::awt::Key::T , "KEY_T" },
{css::awt::Key::U , "KEY_U" },
{css::awt::Key::V , "KEY_V" },
{css::awt::Key::W , "KEY_W" },
{css::awt::Key::X , "KEY_X" },
{css::awt::Key::Y , "KEY_Y" },
{css::awt::Key::Z , "KEY_Z" },
{css::awt::Key::F1 , "KEY_F1" },
{css::awt::Key::F2 , "KEY_F2" },
{css::awt::Key::F3 , "KEY_F3" },
{css::awt::Key::F4 , "KEY_F4" },
{css::awt::Key::F5 , "KEY_F5" },
{css::awt::Key::F6 , "KEY_F6" },
{css::awt::Key::F7 , "KEY_F7" },
{css::awt::Key::F8 , "KEY_F8" },
{css::awt::Key::F9 , "KEY_F9" },
{css::awt::Key::F10 , "KEY_F10" },
{css::awt::Key::F11 , "KEY_F11" },
{css::awt::Key::F12 , "KEY_F12" },
{css::awt::Key::F13 , "KEY_F13" },
{css::awt::Key::F14 , "KEY_F14" },
{css::awt::Key::F15 , "KEY_F15" },
{css::awt::Key::F16 , "KEY_F16" },
{css::awt::Key::F17 , "KEY_F17" },
{css::awt::Key::F18 , "KEY_F18" },
{css::awt::Key::F19 , "KEY_F19" },
{css::awt::Key::F20 , "KEY_F20" },
{css::awt::Key::F21 , "KEY_F21" },
{css::awt::Key::F22 , "KEY_F22" },
{css::awt::Key::F23 , "KEY_F23" },
{css::awt::Key::F24 , "KEY_F24" },
{css::awt::Key::F25 , "KEY_F25" },
{css::awt::Key::F26 , "KEY_F26" },
{css::awt::Key::DOWN , "KEY_DOWN" },
{css::awt::Key::UP , "KEY_UP" },
{css::awt::Key::LEFT , "KEY_LEFT" },
{css::awt::Key::RIGHT , "KEY_RIGHT" },
{css::awt::Key::HOME , "KEY_HOME" },
{css::awt::Key::END , "KEY_END" },
{css::awt::Key::PAGEUP , "KEY_PAGEUP" },
{css::awt::Key::PAGEDOWN , "KEY_PAGEDOWN" },
{css::awt::Key::RETURN , "KEY_RETURN" },
{css::awt::Key::ESCAPE , "KEY_ESCAPE" },
{css::awt::Key::TAB , "KEY_TAB" },
{css::awt::Key::BACKSPACE , "KEY_BACKSPACE" },
{css::awt::Key::SPACE , "KEY_SPACE" },
{css::awt::Key::INSERT , "KEY_INSERT" },
{css::awt::Key::DELETE , "KEY_DELETE" },
{css::awt::Key::ADD , "KEY_ADD" },
{css::awt::Key::SUBTRACT , "KEY_SUBTRACT" },
{css::awt::Key::MULTIPLY , "KEY_MULTIPLY" },
{css::awt::Key::DIVIDE , "KEY_DIVIDE" },
{css::awt::Key::POINT , "KEY_POINT" },
{css::awt::Key::COMMA , "KEY_COMMA" },
{css::awt::Key::LESS , "KEY_LESS" },
{css::awt::Key::GREATER , "KEY_GREATER" },
{css::awt::Key::EQUAL , "KEY_EQUAL" },
{css::awt::Key::OPEN , "KEY_OPEN" },
{css::awt::Key::CUT , "KEY_CUT" },
{css::awt::Key::COPY , "KEY_COPY" },
{css::awt::Key::PASTE , "KEY_PASTE" },
{css::awt::Key::UNDO , "KEY_UNDO" },
{css::awt::Key::REPEAT , "KEY_REPEAT" },
{css::awt::Key::FIND , "KEY_FIND" },
{css::awt::Key::PROPERTIES , "KEY_PROPERTIES" },
{css::awt::Key::FRONT , "KEY_FRONT" },
{css::awt::Key::CONTEXTMENU , "KEY_CONTEXTMENU"},
{css::awt::Key::HELP , "KEY_HELP" },
{css::awt::Key::MENU , "KEY_MENU" },
{css::awt::Key::HANGUL_HANJA , "KEY_HANGUL_HANJA"},
{css::awt::Key::DECIMAL , "KEY_DECIMAL" },
{css::awt::Key::TILDE , "KEY_TILDE" },
{css::awt::Key::QUOTELEFT , "KEY_QUOTELEFT" },
{0 , "" } // mark the end of this array!
};
//-----------------------------------------------
KeyMapping::KeyMapping()
{
sal_Int32 i = 0;
while(KeyIdentifierMap[i].Code != 0)
{
::rtl::OUString sIdentifier = ::rtl::OUString::createFromAscii(KeyIdentifierMap[i].Identifier);
sal_Int16 nCode = KeyIdentifierMap[i].Code;
m_lIdentifierHash[sIdentifier] = nCode ;
m_lCodeHash [nCode] = sIdentifier;
++i;
}
}
//-----------------------------------------------
KeyMapping::~KeyMapping()
{
}
//-----------------------------------------------
sal_uInt16 KeyMapping::mapIdentifierToCode(const ::rtl::OUString& sIdentifier)
throw(css::lang::IllegalArgumentException)
{
Identifier2CodeHash::const_iterator pIt = m_lIdentifierHash.find(sIdentifier);
if (pIt != m_lIdentifierHash.end())
return pIt->second;
// Its not well known identifier - but may be a pure key code formated as string ...
// Check and convert it!
sal_uInt16 nCode = 0;
if (!KeyMapping::impl_st_interpretIdentifierAsPureKeyCode(sIdentifier, nCode))
throw css::lang::IllegalArgumentException(
DECLARE_ASCII("Cant map given identifier to a valid key code value."),
css::uno::Reference< css::uno::XInterface >(),
0);
return (sal_uInt16)nCode;
}
//-----------------------------------------------
::rtl::OUString KeyMapping::mapCodeToIdentifier(sal_uInt16 nCode)
{
Code2IdentifierHash::const_iterator pIt = m_lCodeHash.find(nCode);
if (pIt != m_lCodeHash.end())
return pIt->second;
// If we have no well known identifier - use the pure code value!
return ::rtl::OUString::valueOf((sal_Int32)nCode);
}
//-----------------------------------------------
sal_Bool KeyMapping::impl_st_interpretIdentifierAsPureKeyCode(const ::rtl::OUString& sIdentifier,
sal_uInt16& rCode )
{
sal_Int32 nCode = sIdentifier.toInt32();
if (nCode > 0)
{
rCode = (sal_uInt16)nCode;
return sal_True;
}
// 0 is normaly an error of the called method toInt32() ...
// But we must be aware, that the identifier is "0"!
rCode = 0;
return sIdentifier.equalsAscii("0");
}
} // namespace framework
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "AccumulateReporter.h"
registerMooseObject("MooseApp", AccumulateReporter);
InputParameters
AccumulateReporter::validParams()
{
InputParameters params = GeneralReporter::validParams();
params.addClassDescription("Reporter the accumulates the value of a inputted reporter value over "
"time into a vector reporter value of the same type.");
params.addRequiredParam<std::vector<ReporterName>>("reporters", "The reporters to accumulate.");
params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END};
params.suppressParameter<ExecFlagEnum>("execute_on");
return params;
}
AccumulateReporter::AccumulateReporter(const InputParameters & parameters)
: GeneralReporter(parameters)
{
}
void
AccumulateReporter::initialSetup()
{
const ReporterData & rdata = _fe_problem.getReporterData();
for (const auto & rname : getParam<std::vector<ReporterName>>("reporters"))
{
if (!rdata.hasReporterValue(rname))
paramError("reporters", "Reporter ", rname, " does not exist.");
if (!declareAccumulateHelper<int>(rname) && !declareAccumulateHelper<Real>(rname) &&
!declareAccumulateHelper<std::string>(rname) &&
!declareAccumulateHelper<std::vector<int>>(rname) &&
!declareAccumulateHelper<std::vector<Real>>(rname) &&
!declareAccumulateHelper<std::vector<std::string>>(rname))
paramError("reporters",
"Reporter value ",
rname,
" is of unsupported type ",
rdata.getReporterContextBase(rname).type(),
".");
}
}
void
AccumulateReporter::execute()
{
unsigned int ind = static_cast<unsigned int>(_t_step);
for (auto & val : _accumulated_values)
val->accumulate(ind);
}
<commit_msg>added dof_id closes #20441<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "AccumulateReporter.h"
registerMooseObject("MooseApp", AccumulateReporter);
InputParameters
AccumulateReporter::validParams()
{
InputParameters params = GeneralReporter::validParams();
params.addClassDescription("Reporter the accumulates the value of a inputted reporter value over "
"time into a vector reporter value of the same type.");
params.addRequiredParam<std::vector<ReporterName>>("reporters", "The reporters to accumulate.");
params.set<ExecFlagEnum>("execute_on") = {EXEC_INITIAL, EXEC_TIMESTEP_END};
params.suppressParameter<ExecFlagEnum>("execute_on");
return params;
}
AccumulateReporter::AccumulateReporter(const InputParameters & parameters)
: GeneralReporter(parameters)
{
}
void
AccumulateReporter::initialSetup()
{
const ReporterData & rdata = _fe_problem.getReporterData();
for (const auto & rname : getParam<std::vector<ReporterName>>("reporters"))
{
if (!rdata.hasReporterValue(rname))
paramError("reporters", "Reporter ", rname, " does not exist.");
if (!declareAccumulateHelper<int>(rname) && !declareAccumulateHelper<Real>(rname) &&
!declareAccumulateHelper<std::string>(rname) &&
!declareAccumulateHelper<std::vector<int>>(rname) &&
!declareAccumulateHelper<std::vector<Real>>(rname) &&
!declareAccumulateHelper<std::vector<std::string>>(rname) &&
!declareAccumulateHelper<std::vector<dof_id_type>>(rname))
paramError("reporters",
"Reporter value ",
rname,
" is of unsupported type ",
rdata.getReporterContextBase(rname).type(),
".");
}
}
void
AccumulateReporter::execute()
{
unsigned int ind = static_cast<unsigned int>(_t_step);
for (auto & val : _accumulated_values)
val->accumulate(ind);
}
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/document/fieldvalue/fieldvalues.h>
#include <vespa/vsm/common/storagedocument.h>
#include <vespa/vespalib/stllike/asciistream.h>
using namespace document;
namespace vsm {
class DocumentTest : public vespalib::TestApp
{
private:
void testStorageDocument();
void testStringFieldIdTMap();
public:
int Main();
};
void
DocumentTest::testStorageDocument()
{
DocumentType dt("testdoc", 0);
Field fa("a", 0, *DataType::STRING, true);
Field fb("b", 1, *DataType::STRING, true);
dt.addField(fa);
dt.addField(fb);
document::Document::UP doc(new document::Document(dt, DocumentId()));
doc->setValue(fa, StringFieldValue("foo"));
doc->setValue(fb, StringFieldValue("bar"));
SharedFieldPathMap fpmap(new FieldPathMapT());
fpmap->push_back(*dt.buildFieldPath("a"));
fpmap->push_back(*dt.buildFieldPath("b"));
fpmap->push_back(FieldPath());
ASSERT_TRUE((*fpmap)[0].size() == 1);
ASSERT_TRUE((*fpmap)[1].size() == 1);
ASSERT_TRUE((*fpmap)[2].size() == 0);
StorageDocument sdoc(std::move(doc), fpmap, 3);
ASSERT_TRUE(sdoc.valid());
EXPECT_EQUAL(std::string("foo"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
// test caching
EXPECT_EQUAL(std::string("foo"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
// set new values
EXPECT_TRUE(sdoc.setField(0, FieldValue::UP(new StringFieldValue("baz"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
EXPECT_TRUE(sdoc.setField(1, FieldValue::UP(new StringFieldValue("qux"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("qux"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
EXPECT_TRUE(sdoc.setField(2, FieldValue::UP(new StringFieldValue("quux"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("qux"), sdoc.getField(1)->getAsString());
EXPECT_EQUAL(std::string("quux"), sdoc.getField(2)->getAsString());
EXPECT_EQUAL(std::string("foo"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
EXPECT_TRUE(!sdoc.setField(3, FieldValue::UP(new StringFieldValue("thud"))));
SharedFieldPathMap fim;
StorageDocument s2(std::make_unique<document::Document>(), fim, 0);
EXPECT_EQUAL(vespalib::string("null::"), s2.docDoc().getId().toString());
}
void DocumentTest::testStringFieldIdTMap()
{
StringFieldIdTMap m;
EXPECT_EQUAL(0u, m.highestFieldNo());
EXPECT_TRUE(StringFieldIdTMap::npos == m.fieldNo("unknown"));
m.add("f1");
EXPECT_EQUAL(0u, m.fieldNo("f1"));
EXPECT_EQUAL(1u, m.highestFieldNo());
m.add("f1");
EXPECT_EQUAL(0u, m.fieldNo("f1"));
EXPECT_EQUAL(1u, m.highestFieldNo());
m.add("f2");
EXPECT_EQUAL(1u, m.fieldNo("f2"));
EXPECT_EQUAL(2u, m.highestFieldNo());
m.add("f3", 7);
EXPECT_EQUAL(7u, m.fieldNo("f3"));
EXPECT_EQUAL(8u, m.highestFieldNo());
m.add("f3");
EXPECT_EQUAL(7u, m.fieldNo("f3"));
EXPECT_EQUAL(8u, m.highestFieldNo());
m.add("f2", 13);
EXPECT_EQUAL(13u, m.fieldNo("f2"));
EXPECT_EQUAL(14u, m.highestFieldNo());
m.add("f4");
EXPECT_EQUAL(3u, m.fieldNo("f4"));
EXPECT_EQUAL(14u, m.highestFieldNo());
{
vespalib::asciistream os;
StringFieldIdTMap t;
t.add("b");
t.add("a");
os << t;
EXPECT_EQUAL(vespalib::string("a = 1\nb = 0\n"), os.str());
}
}
int
DocumentTest::Main()
{
TEST_INIT("document_test");
testStorageDocument();
testStringFieldIdTMap();
TEST_DONE();
}
}
TEST_APPHOOK(vsm::DocumentTest);
<commit_msg>Update test due to removed functionality.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/document/fieldvalue/fieldvalues.h>
#include <vespa/vsm/common/storagedocument.h>
#include <vespa/vespalib/stllike/asciistream.h>
using namespace document;
namespace vsm {
class DocumentTest : public vespalib::TestApp
{
private:
void testStorageDocument();
void testStringFieldIdTMap();
public:
int Main();
};
void
DocumentTest::testStorageDocument()
{
DocumentType dt("testdoc", 0);
Field fa("a", 0, *DataType::STRING, true);
Field fb("b", 1, *DataType::STRING, true);
dt.addField(fa);
dt.addField(fb);
document::Document::UP doc(new document::Document(dt, DocumentId()));
doc->setValue(fa, StringFieldValue("foo"));
doc->setValue(fb, StringFieldValue("bar"));
SharedFieldPathMap fpmap(new FieldPathMapT());
fpmap->push_back(*dt.buildFieldPath("a"));
fpmap->push_back(*dt.buildFieldPath("b"));
fpmap->push_back(FieldPath());
ASSERT_TRUE((*fpmap)[0].size() == 1);
ASSERT_TRUE((*fpmap)[1].size() == 1);
ASSERT_TRUE((*fpmap)[2].size() == 0);
StorageDocument sdoc(std::move(doc), fpmap, 3);
ASSERT_TRUE(sdoc.valid());
EXPECT_EQUAL(std::string("foo"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
// test caching
EXPECT_EQUAL(std::string("foo"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
// set new values
EXPECT_TRUE(sdoc.setField(0, FieldValue::UP(new StringFieldValue("baz"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("bar"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
EXPECT_TRUE(sdoc.setField(1, FieldValue::UP(new StringFieldValue("qux"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("qux"), sdoc.getField(1)->getAsString());
EXPECT_TRUE(sdoc.getField(2) == NULL);
EXPECT_TRUE(sdoc.setField(2, FieldValue::UP(new StringFieldValue("quux"))));
EXPECT_EQUAL(std::string("baz"), sdoc.getField(0)->getAsString());
EXPECT_EQUAL(std::string("qux"), sdoc.getField(1)->getAsString());
EXPECT_EQUAL(std::string("quux"), sdoc.getField(2)->getAsString());
EXPECT_TRUE(!sdoc.setField(3, FieldValue::UP(new StringFieldValue("thud"))));
SharedFieldPathMap fim;
StorageDocument s2(std::make_unique<document::Document>(), fim, 0);
EXPECT_EQUAL(vespalib::string("null::"), s2.docDoc().getId().toString());
}
void DocumentTest::testStringFieldIdTMap()
{
StringFieldIdTMap m;
EXPECT_EQUAL(1u, m.highestFieldNo());
EXPECT_TRUE(StringFieldIdTMap::npos == m.fieldNo("unknown"));
m.add("f1");
EXPECT_EQUAL(0u, m.fieldNo("f1"));
EXPECT_EQUAL(1u, m.highestFieldNo());
m.add("f1");
EXPECT_EQUAL(0u, m.fieldNo("f1"));
EXPECT_EQUAL(1u, m.highestFieldNo());
m.add("f2");
EXPECT_EQUAL(1u, m.fieldNo("f2"));
EXPECT_EQUAL(2u, m.highestFieldNo());
m.add("f3", 7);
EXPECT_EQUAL(7u, m.fieldNo("f3"));
EXPECT_EQUAL(8u, m.highestFieldNo());
m.add("f3");
EXPECT_EQUAL(7u, m.fieldNo("f3"));
EXPECT_EQUAL(8u, m.highestFieldNo());
m.add("f2", 13);
EXPECT_EQUAL(13u, m.fieldNo("f2"));
EXPECT_EQUAL(14u, m.highestFieldNo());
m.add("f4");
EXPECT_EQUAL(3u, m.fieldNo("f4"));
EXPECT_EQUAL(14u, m.highestFieldNo());
{
vespalib::asciistream os;
StringFieldIdTMap t;
t.add("b");
t.add("a");
os << t;
EXPECT_EQUAL(vespalib::string("a = 1\nb = 0\n"), os.str());
}
}
int
DocumentTest::Main()
{
TEST_INIT("document_test");
testStorageDocument();
testStringFieldIdTMap();
TEST_DONE();
}
}
TEST_APPHOOK(vsm::DocumentTest);
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 <iostream>
#include "itkRealTimeClock.h"
#if defined(WIN32) || defined(_WIN32)
# include <windows.h>
#else
# include <sys/time.h>
#endif // defined(WIN32) || defined(_WIN32)
#include "itkMath.h"
namespace itk
{
RealTimeClock::RealTimeClock()
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER frequency;
::QueryPerformanceFrequency(&frequency);
m_Frequency = static_cast<FrequencyType>(frequency.QuadPart);
SYSTEMTIME st1;
SYSTEMTIME st2;
FILETIME ft1;
FILETIME ft2;
::memset(&st1, 0, sizeof(st1));
::memset(&st2, 0, sizeof(st2));
st1.wYear = 1601;
st1.wMonth = 1;
st1.wDay = 1;
st2.wYear = 1970;
st2.wMonth = 1;
st2.wDay = 1;
::SystemTimeToFileTime(&st1, &ft1);
::SystemTimeToFileTime(&st2, &ft2);
LARGE_INTEGER ui1;
LARGE_INTEGER ui2;
memcpy(&ui1, &ft1, sizeof(ui1));
memcpy(&ui2, &ft2, sizeof(ui2));
m_Difference = static_cast<TimeStampType>(ui2.QuadPart - ui1.QuadPart) / static_cast<TimeStampType>(1e7);
FILETIME currentTime;
LARGE_INTEGER intTime;
LARGE_INTEGER tick;
::GetSystemTimeAsFileTime(¤tTime);
::QueryPerformanceCounter(&tick);
memcpy(&intTime, ¤tTime, sizeof(intTime));
m_Origin = static_cast<TimeStampType>(intTime.QuadPart) / static_cast<TimeStampType>(1e7);
m_Origin -= static_cast<TimeStampType>(tick.QuadPart) / m_Frequency;
m_Origin -= m_Difference;
#else
m_Frequency = 1e6;
m_Difference = 0.0;
m_Origin = 0.0;
#endif // defined(WIN32) || defined(_WIN32)
}
RealTimeClock::~RealTimeClock() = default;
RealTimeClock::TimeStampType
RealTimeClock::GetTimeInSeconds() const
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER tick;
::QueryPerformanceCounter(&tick);
TimeStampType value = static_cast<TimeStampType>(tick.QuadPart) / m_Frequency;
value += m_Origin;
return value;
#else
struct timeval tval;
::gettimeofday(&tval, nullptr);
TimeStampType value =
static_cast<TimeStampType>(tval.tv_sec) + static_cast<TimeStampType>(tval.tv_usec) / m_Frequency;
return value;
#endif // defined(WIN32) || defined(_WIN32)
}
const TimeStamp &
RealTimeClock::GetTimeStamp() const
{
return this->Superclass::GetTimeStamp();
}
RealTimeStamp
RealTimeClock::GetRealTimeStamp() const
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER tick;
::QueryPerformanceCounter(&tick);
TimeStampType seconds = static_cast<TimeStampType>(tick.QuadPart) / m_Frequency;
seconds += m_Origin;
using SecondsCounterType = RealTimeStamp::SecondsCounterType;
using MicroSecondsCounterType = RealTimeStamp::MicroSecondsCounterType;
SecondsCounterType iseconds = std::floor(seconds);
MicroSecondsCounterType useconds = std::floor((seconds - iseconds) * 1e6);
RealTimeStamp value(iseconds, useconds);
return value;
#else
struct timeval tval;
::gettimeofday(&tval, nullptr);
RealTimeStamp value(static_cast<RealTimeStamp::SecondsCounterType>(tval.tv_sec),
static_cast<RealTimeStamp::MicroSecondsCounterType>(tval.tv_usec));
return value;
#endif // defined(WIN32) || defined(_WIN32)
}
void
RealTimeClock::PrintSelf(std::ostream & os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Frequency of the clock: " << m_Frequency << std::endl;
os << indent << "Difference : " << m_Difference << std::endl;
os << indent << "Origin : " << m_Origin << std::endl;
}
} // end namespace itk
<commit_msg>STYLE: Clean-up code Windows version default-constructor `RealTimeClock`<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 <iostream>
#include "itkRealTimeClock.h"
#if defined(WIN32) || defined(_WIN32)
# include <windows.h>
#else
# include <sys/time.h>
#endif // defined(WIN32) || defined(_WIN32)
#include "itkMath.h"
namespace itk
{
RealTimeClock::RealTimeClock()
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER frequency;
::QueryPerformanceFrequency(&frequency);
m_Frequency = static_cast<FrequencyType>(frequency.QuadPart);
// Converts a FILETIME to the number of seconds since January 1, 1601.
const auto convertToSeconds = [](const FILETIME fileTime) {
const auto numberOfIntervals =
uint64_t{ fileTime.dwHighDateTime } * (uint64_t{ UINT32_MAX } + 1) + uint64_t{ fileTime.dwLowDateTime };
return static_cast<TimeStampType>(numberOfIntervals) / TimeStampType{ 1e7 };
};
SYSTEMTIME systemTime{};
systemTime.wYear = 1970;
systemTime.wMonth = 1;
systemTime.wDay = 1;
FILETIME fileTime;
::SystemTimeToFileTime(&systemTime, &fileTime);
m_Difference = convertToSeconds(fileTime);
FILETIME currentTime;
LARGE_INTEGER tick;
::GetSystemTimeAsFileTime(¤tTime);
::QueryPerformanceCounter(&tick);
m_Origin = convertToSeconds(currentTime) - static_cast<TimeStampType>(tick.QuadPart) / m_Frequency - m_Difference;
#else
m_Frequency = 1e6;
m_Difference = 0.0;
m_Origin = 0.0;
#endif // defined(WIN32) || defined(_WIN32)
}
RealTimeClock::~RealTimeClock() = default;
RealTimeClock::TimeStampType
RealTimeClock::GetTimeInSeconds() const
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER tick;
::QueryPerformanceCounter(&tick);
TimeStampType value = static_cast<TimeStampType>(tick.QuadPart) / m_Frequency;
value += m_Origin;
return value;
#else
struct timeval tval;
::gettimeofday(&tval, nullptr);
TimeStampType value =
static_cast<TimeStampType>(tval.tv_sec) + static_cast<TimeStampType>(tval.tv_usec) / m_Frequency;
return value;
#endif // defined(WIN32) || defined(_WIN32)
}
const TimeStamp &
RealTimeClock::GetTimeStamp() const
{
return this->Superclass::GetTimeStamp();
}
RealTimeStamp
RealTimeClock::GetRealTimeStamp() const
{
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER tick;
::QueryPerformanceCounter(&tick);
TimeStampType seconds = static_cast<TimeStampType>(tick.QuadPart) / m_Frequency;
seconds += m_Origin;
using SecondsCounterType = RealTimeStamp::SecondsCounterType;
using MicroSecondsCounterType = RealTimeStamp::MicroSecondsCounterType;
SecondsCounterType iseconds = std::floor(seconds);
MicroSecondsCounterType useconds = std::floor((seconds - iseconds) * 1e6);
RealTimeStamp value(iseconds, useconds);
return value;
#else
struct timeval tval;
::gettimeofday(&tval, nullptr);
RealTimeStamp value(static_cast<RealTimeStamp::SecondsCounterType>(tval.tv_sec),
static_cast<RealTimeStamp::MicroSecondsCounterType>(tval.tv_usec));
return value;
#endif // defined(WIN32) || defined(_WIN32)
}
void
RealTimeClock::PrintSelf(std::ostream & os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Frequency of the clock: " << m_Frequency << std::endl;
os << indent << "Difference : " << m_Difference << std::endl;
os << indent << "Origin : " << m_Origin << std::endl;
}
} // end namespace itk
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-08-29
// Updated : 2009-08-29
// Licence : This source is under MIT License
// File : glm/gtx/matrix_operation.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm{
namespace gtc{
namespace matrix_operation
{
template <typename valType>
inline detail::tmat2x2<valType> diagonal2x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat2x3<valType> diagonal2x3
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat2x4<valType> diagonal2x4
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat3x2<valType> diagonal3x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat3x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat3x3<valType> diagonal3x3
(
detail::tvec3<valType> const & v
)
{
detail::tmat3x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat3x4<valType> diagonal3x4
(
detail::tvec3<valType> const & v
)
{
detail::tmat3x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat4x4<valType> diagonal4x4
(
detail::tvec4<valType> const & v
)
{
detail::tmat4x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
Result[3][3] = v[3];
return Result;
}
template <typename valType>
inline detail::tmat4x3<valType> diagonal4x3
(
detail::tvec3<valType> const & v
)
{
detail::tmat4x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat4x2<valType> diagonal4x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat4x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
}//namespace matrix_operation
}//namespace gtx
}//namespace glm
<commit_msg>Fixed namespace error<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-08-29
// Updated : 2009-08-29
// Licence : This source is under MIT License
// File : glm/gtx/matrix_operation.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm{
namespace gtx{
namespace matrix_operation
{
template <typename valType>
inline detail::tmat2x2<valType> diagonal2x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat2x3<valType> diagonal2x3
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat2x4<valType> diagonal2x4
(
detail::tvec2<valType> const & v
)
{
detail::tmat2x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat3x2<valType> diagonal3x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat3x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
template <typename valType>
inline detail::tmat3x3<valType> diagonal3x3
(
detail::tvec3<valType> const & v
)
{
detail::tmat3x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat3x4<valType> diagonal3x4
(
detail::tvec3<valType> const & v
)
{
detail::tmat3x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat4x4<valType> diagonal4x4
(
detail::tvec4<valType> const & v
)
{
detail::tmat4x4<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
Result[3][3] = v[3];
return Result;
}
template <typename valType>
inline detail::tmat4x3<valType> diagonal4x3
(
detail::tvec3<valType> const & v
)
{
detail::tmat4x3<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
Result[2][2] = v[2];
return Result;
}
template <typename valType>
inline detail::tmat4x2<valType> diagonal4x2
(
detail::tvec2<valType> const & v
)
{
detail::tmat4x2<valType> Result(valType(1));
Result[0][0] = v[0];
Result[1][1] = v[1];
return Result;
}
}//namespace matrix_operation
}//namespace gtx
}//namespace glm
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "browserservice.h"
#include "dbusadaptor.h"
#include <QDBusConnection>
#define SAILFISH_BROWSER_SERVICE QLatin1String("org.sailfishos.browser")
#define SAILFISH_BROWSER_UI_SERVICE QLatin1String("org.sailfishos.browser.ui")
BrowserService::BrowserService(QObject * parent)
: QObject(parent)
, m_registered(true)
{
new DBusAdaptor(this);
QDBusConnection connection = QDBusConnection::sessionBus();
if(!connection.registerService(SAILFISH_BROWSER_SERVICE) ||
!connection.registerObject("/", this)) {
m_registered = false;
}
}
bool BrowserService::registered() const
{
return m_registered;
}
QString BrowserService::serviceName() const
{
return SAILFISH_BROWSER_SERVICE;
}
void BrowserService::openUrl(QStringList args)
{
if(args.count() > 0) {
emit openUrlRequested(args.first());
} else {
emit openUrlRequested(QString());
}
}
void BrowserService::activateNewTabView()
{
emit activateNewTabViewRequested();
}
void BrowserService::cancelTransfer(int transferId)
{
emit cancelTransferRequested(transferId);
}
void BrowserService::restartTransfer(int transferId)
{
emit restartTransferRequested(transferId);
}
void BrowserService::dumpMemoryInfo(QString fileName)
{
emit dumpMemoryInfoRequested(fileName);
}
BrowserUIService::BrowserUIService(QObject * parent)
: QObject(parent)
, m_registered(true)
{
new UIServiceDBusAdaptor(this);
QDBusConnection connection = QDBusConnection::sessionBus();
if(!connection.registerService(SAILFISH_BROWSER_UI_SERVICE) ||
!connection.registerObject("/", this)) {
m_registered = false;
}
}
bool BrowserUIService::registered() const
{
return m_registered;
}
QString BrowserUIService::serviceName() const
{
return SAILFISH_BROWSER_UI_SERVICE;
}
void BrowserUIService::openUrl(QStringList args)
{
if(args.count() > 0) {
emit openUrlRequested(args.first());
} else {
emit openUrlRequested(QString());
}
}
void BrowserUIService::activateNewTabView()
{
emit activateNewTabViewRequested();
}
<commit_msg>[sailfish-browser] Use /ui dbus adaptor path for org.sailfishos.browser.ui service. Contributes to JB#31406<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "browserservice.h"
#include "dbusadaptor.h"
#include <QDBusConnection>
#define SAILFISH_BROWSER_SERVICE QLatin1String("org.sailfishos.browser")
#define SAILFISH_BROWSER_UI_SERVICE QLatin1String("org.sailfishos.browser.ui")
BrowserService::BrowserService(QObject * parent)
: QObject(parent)
, m_registered(true)
{
new DBusAdaptor(this);
QDBusConnection connection = QDBusConnection::sessionBus();
if(!connection.registerService(SAILFISH_BROWSER_SERVICE) ||
!connection.registerObject("/", this)) {
m_registered = false;
}
}
bool BrowserService::registered() const
{
return m_registered;
}
QString BrowserService::serviceName() const
{
return SAILFISH_BROWSER_SERVICE;
}
void BrowserService::openUrl(QStringList args)
{
if(args.count() > 0) {
emit openUrlRequested(args.first());
} else {
emit openUrlRequested(QString());
}
}
void BrowserService::activateNewTabView()
{
emit activateNewTabViewRequested();
}
void BrowserService::cancelTransfer(int transferId)
{
emit cancelTransferRequested(transferId);
}
void BrowserService::restartTransfer(int transferId)
{
emit restartTransferRequested(transferId);
}
void BrowserService::dumpMemoryInfo(QString fileName)
{
emit dumpMemoryInfoRequested(fileName);
}
BrowserUIService::BrowserUIService(QObject * parent)
: QObject(parent)
, m_registered(true)
{
new UIServiceDBusAdaptor(this);
QDBusConnection connection = QDBusConnection::sessionBus();
if(!connection.registerService(SAILFISH_BROWSER_UI_SERVICE) ||
!connection.registerObject("/ui", this)) {
m_registered = false;
}
}
bool BrowserUIService::registered() const
{
return m_registered;
}
QString BrowserUIService::serviceName() const
{
return SAILFISH_BROWSER_UI_SERVICE;
}
void BrowserUIService::openUrl(QStringList args)
{
if(args.count() > 0) {
emit openUrlRequested(args.first());
} else {
emit openUrlRequested(QString());
}
}
void BrowserUIService::activateNewTabView()
{
emit activateNewTabViewRequested();
}
<|endoftext|> |
<commit_before><commit_msg>The reliability tests are reporting lots of crashers in the CLD library. Temporarily disabling the CLD detection while investigating.<commit_after><|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <string>
#include <vector>
#include "StateMachine.hpp"
#include "StateMachineBuilder.hpp"
#include "RdUtils.hpp"
#include "DeadState.hpp"
#include "MockupNetworkManager.hpp"
#include "RdMockupImageManager.hpp"
#include "MockupInputManager.hpp"
#include "RdMentalMap.hpp"
#include "RdMockupRobotManager.hpp"
#include "MockupAudioManager.hpp"
#include <yarp/os/Network.h>
#include <yarp/os/Time.h>
using namespace rd;
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class DeadStateTest : public testing::Test
{
public:
virtual void SetUp()
{
//-- Start YARP network
yarp::os::Network::init();
//-- Register managers to be used:
MockupNetworkManager::RegisterManager();
RdMockupImageManager::RegisterManager();
MockupInputManager::RegisterManager();
MockupAudioManager::RegisterManager();
//-- Create managers
networkManager = RdNetworkManager::getNetworkManager("MOCKUP");
mockupNetworkManager = dynamic_cast<MockupNetworkManager *>(networkManager);
ASSERT_NE((RdNetworkManager*) NULL, networkManager);
ASSERT_NE((MockupNetworkManager*) NULL, mockupNetworkManager);
imageManager = RdImageManager::getImageManager("MOCKUP");
mockupImageManager = dynamic_cast<RdMockupImageManager *>(imageManager);
ASSERT_NE((RdImageManager*) NULL, imageManager);
ASSERT_NE((RdMockupImageManager*) NULL, mockupImageManager);
inputManager = RdInputManager::getInputManager("MOCKUP");
mockupInputManager = dynamic_cast<MockupInputManager *>(inputManager);
ASSERT_NE((RdInputManager*) NULL, inputManager);
ASSERT_NE((MockupInputManager*) NULL, mockupInputManager);
audioManager = AudioManager::getAudioManager("MOCKUP");
mockupAudioManager = dynamic_cast<MockupAudioManager *>(audioManager);
ASSERT_NE((AudioManager*) NULL, audioManager);
ASSERT_NE((MockupAudioManager*) NULL, mockupAudioManager);
mockupAudioManager->load("RD_THEME","RD_THEME", AudioManager::MUSIC);
mentalMap = RdMentalMap::getMentalMap();
ASSERT_NE((RdMentalMap*) NULL, mentalMap);
mockupRobotManager = new RdMockupRobotManager("MOCKUP");
robotManager = (RdRobotManager *) mockupRobotManager;
ASSERT_NE((RdMockupRobotManager*) NULL, mockupRobotManager);
ASSERT_NE((RdRobotManager*) NULL, robotManager);
}
virtual void TearDown()
{
//-- Close YARP network
yarp::os::Network::fini();
//-- Delete things
RdNetworkManager::destroyNetworkManager();
networkManager = NULL;
mockupNetworkManager = NULL;
RdImageManager::destroyImageManager();
imageManager = NULL;
mockupImageManager = NULL;
RdInputManager::destroyInputManager();
AudioManager::destroyAudioManager();
RdMentalMap::destroyMentalMap();
delete mockupRobotManager;
mockupRobotManager = NULL;
}
protected:
FiniteStateMachine *fsm;
RdNetworkManager * networkManager;
MockupNetworkManager * mockupNetworkManager;
RdImageManager * imageManager;
RdMockupImageManager * mockupImageManager;
RdInputManager * inputManager;
MockupInputManager * mockupInputManager;
AudioManager * audioManager;
MockupAudioManager * mockupAudioManager;
RdMentalMap * mentalMap;
RdMockupRobotManager * mockupRobotManager;
RdRobotManager * robotManager;
};
//--- Tests ------------------------------------------------------------------------------------------
TEST_F(DeadStateTest, DeadStateGoesToRespawn)
{
//-- Create fsm with DeadState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int dead_state_id = builder.addState(new DeadState(networkManager, imageManager, inputManager, mentalMap,
robotManager, audioManager));
int end_state_id = builder.addState(State::getEndState());
ASSERT_NE(-1, dead_state_id);
ASSERT_TRUE(builder.addTransition(dead_state_id, end_state_id, DeadState::RESPAWN_SELECTED));
ASSERT_TRUE(builder.addTransition(dead_state_id, end_state_id, DeadState::EXIT_SELECTED));
ASSERT_TRUE(builder.setInitialState(dead_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
// Player is dead
// Stuff is enabled
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME");
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_DEAD");
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_FALSE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(DeadStateTest.mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
//-- Check things that should happen in dead state before time runs out (setup):
//yarp::os::Time::delay(1);
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME");
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_DEAD");
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_FALSE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(DeadStateTest.mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_FALSE(mockupRobotManager->isConnected());
//-- When enter is pressed, the system should go to respawn state:
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ENTER));
yarp::os::Time::delay(0.5);
//-- Check that it has logged in and it is in the next state (cleanup):
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
}
TEST_F(DeadStateTest, DeadStateGoesToLogout)
{
}
<commit_msg>Add failing test for DeadState<commit_after>#include "gtest/gtest.h"
#include <string>
#include <vector>
#include "StateMachine.hpp"
#include "StateMachineBuilder.hpp"
#include "RdUtils.hpp"
#include "DeadState.hpp"
#include "MockupNetworkManager.hpp"
#include "RdMockupImageManager.hpp"
#include "MockupInputManager.hpp"
#include "RdMentalMap.hpp"
#include "RdMockupRobotManager.hpp"
#include "MockupAudioManager.hpp"
#include "MockupState.hpp"
#include <yarp/os/Network.h>
#include <yarp/os/Time.h>
using namespace rd;
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class DeadStateTest : public testing::Test
{
public:
virtual void SetUp()
{
//-- Start YARP network
yarp::os::Network::init();
//-- Register managers to be used:
MockupNetworkManager::RegisterManager();
RdMockupImageManager::RegisterManager();
MockupInputManager::RegisterManager();
MockupAudioManager::RegisterManager();
//-- Create managers
networkManager = RdNetworkManager::getNetworkManager("MOCKUP");
mockupNetworkManager = dynamic_cast<MockupNetworkManager *>(networkManager);
ASSERT_NE((RdNetworkManager*) NULL, networkManager);
ASSERT_NE((MockupNetworkManager*) NULL, mockupNetworkManager);
imageManager = RdImageManager::getImageManager("MOCKUP");
mockupImageManager = dynamic_cast<RdMockupImageManager *>(imageManager);
ASSERT_NE((RdImageManager*) NULL, imageManager);
ASSERT_NE((RdMockupImageManager*) NULL, mockupImageManager);
inputManager = RdInputManager::getInputManager("MOCKUP");
mockupInputManager = dynamic_cast<MockupInputManager *>(inputManager);
ASSERT_NE((RdInputManager*) NULL, inputManager);
ASSERT_NE((MockupInputManager*) NULL, mockupInputManager);
audioManager = AudioManager::getAudioManager("MOCKUP");
mockupAudioManager = dynamic_cast<MockupAudioManager *>(audioManager);
ASSERT_NE((AudioManager*) NULL, audioManager);
ASSERT_NE((MockupAudioManager*) NULL, mockupAudioManager);
mockupAudioManager->load("RD_THEME","RD_THEME", AudioManager::MUSIC);
mentalMap = RdMentalMap::getMentalMap();
ASSERT_NE((RdMentalMap*) NULL, mentalMap);
mockupRobotManager = new RdMockupRobotManager("MOCKUP");
robotManager = (RdRobotManager *) mockupRobotManager;
ASSERT_NE((RdMockupRobotManager*) NULL, mockupRobotManager);
ASSERT_NE((RdRobotManager*) NULL, robotManager);
}
virtual void TearDown()
{
//-- Close YARP network
yarp::os::Network::fini();
//-- Delete things
RdNetworkManager::destroyNetworkManager();
networkManager = NULL;
mockupNetworkManager = NULL;
RdImageManager::destroyImageManager();
imageManager = NULL;
mockupImageManager = NULL;
RdInputManager::destroyInputManager();
AudioManager::destroyAudioManager();
RdMentalMap::destroyMentalMap();
delete mockupRobotManager;
mockupRobotManager = NULL;
}
protected:
FiniteStateMachine *fsm;
RdNetworkManager * networkManager;
MockupNetworkManager * mockupNetworkManager;
RdImageManager * imageManager;
RdMockupImageManager * mockupImageManager;
RdInputManager * inputManager;
MockupInputManager * mockupInputManager;
AudioManager * audioManager;
MockupAudioManager * mockupAudioManager;
RdMentalMap * mentalMap;
RdMockupRobotManager * mockupRobotManager;
RdRobotManager * robotManager;
};
//--- Tests ------------------------------------------------------------------------------------------
TEST_F(DeadStateTest, DeadStateGoesToRespawn)
{
//-- Create fsm with DeadState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int dead_state_id = builder.addState(new DeadState(networkManager, imageManager, inputManager,
mentalMap, robotManager, audioManager));
ASSERT_NE(-1, dead_state_id);
int game_state_id = builder.addState(new MockupState(1));
ASSERT_NE(-1, game_state_id);
int exit_state_id = builder.addState(State::getEndState());
ASSERT_TRUE(builder.addTransition(dead_state_id, game_state_id, DeadState::RESPAWN_SELECTED));
ASSERT_TRUE(builder.addTransition(dead_state_id, exit_state_id, DeadState::EXIT_SELECTED));
ASSERT_TRUE(builder.setInitialState(dead_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
// Player is dead
// Stuff is enabled
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
//-- Check things that should happen in dead state before time runs out (setup):
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_TRUE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that deadState is active
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
//-- When enter is pressed, but the countdown is still active, input is ignored
yarp::os::Time::delay(0.5);
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ENTER));
yarp::os::Time::delay(0.5);
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
//-- When time is up, and enter is pressed, the system should go to respawn state:
yarp::os::Time::delay(10);
ASSERT_EQ(1, mockupInputManager->getNumListeners());
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ENTER));
yarp::os::Time::delay(0.5);
//-- Check that it has restored things (health, enable stuff)
//-- and it is in the game state (cleanup):
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that deadState is active
ASSERT_EQ(game_state_id, fsm->getCurrentState());
}
TEST_F(DeadStateTest, DeadStateGoesToLogout)
{
//-- Create fsm with DeadState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int dead_state_id = builder.addState(new DeadState(networkManager, imageManager, inputManager,
mentalMap, robotManager, audioManager));
ASSERT_NE(-1, dead_state_id);
int game_state_id = builder.addState(new MockupState(1));
ASSERT_NE(-1, game_state_id);
int exit_state_id = builder.addState(State::getEndState());
ASSERT_TRUE(builder.addTransition(dead_state_id, game_state_id, DeadState::RESPAWN_SELECTED));
ASSERT_TRUE(builder.addTransition(dead_state_id, exit_state_id, DeadState::EXIT_SELECTED));
ASSERT_TRUE(builder.setInitialState(dead_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
// Player is dead
// Stuff is enabled
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
//-- Check things that should happen in dead state before time runs out (setup):
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_TRUE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that deadState is active
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
//-- When enter is pressed, but the countdown is still active, input is ignored
yarp::os::Time::delay(0.5);
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ENTER));
yarp::os::Time::delay(0.5);
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
//-- When time is up, and esc is pressed, the system should exit the game:
yarp::os::Time::delay(10);
ASSERT_EQ(1, mockupInputManager->getNumListeners());
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ESCAPE));
yarp::os::Time::delay(0.5);
//-- Check that it has stopped things and it is in the final state (cleanup):
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_TRUE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
ASSERT_TRUE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_DEAD"));
ASSERT_TRUE(mockupNetworkManager->isStopped());
ASSERT_FALSE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that end state is active
ASSERT_EQ(exit_state_id, fsm->getCurrentState());
}
<|endoftext|> |
<commit_before>/*
* TTBlue Signal Crossfader Object
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTDSP.h"
#define thisTTClass TTCrossfade
#define thisTTClassName "crossfade"
#define thisTTClassTags "audio, processor, mixing"
static bool zeroed = false;
static TTSampleValue zeroVector1[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector2[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector3[2048]; //TODO: make this dynamically sized
/** TTCrossfade in an audio processor that crossfades between two input signals.
In fact, this processor can work on a number of channels, provided that the number of input
channels is twice the number of output channels. In this case the first N/2 input channels are
considered as the A source and the last N/2 input channels are considered the B source.
*/
class TTCrossfade : TTAudioObject {
TTCLASS_SETUP(TTCrossfade)
TTFloat64 position; ///< Use a range of 0.0 to 1.0 to specify a ratio of the B source to the A source.
TTSymbol* shape; ///< The shape attribute is set with a TTSymbol that is either "equalPower" (the default) or "linear"
TTSymbol* mode; ///< The mode attribute is set with a TTSymbol that is either "lookup" (the default) or "calculate"
/** Utility used by the setters for setting up the process routine. */
TTErr setProcessPointers();
/** The process method used when the shape attribute is set to "linear"
* This method will return an error if the input and output channels are not matched properly. */
TTErr processLinear(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
/** The process method used when the shape attribute is set to "equalPower" and the mode is set to "lookup"
* This method will return an error if the input and output channels are not matched properly. */
TTErr processEqualPowerLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
TTErr processEqualPowerCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs); // calculate
/** The process method used when the shape attribute is set to "squareRoot""
* This method will return an error if the input and output channels are not matched properly. */
TTErr processSquareRootCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
TTErr processSquareRootLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
/** Setter for the shape attribute. */
TTErr setshape(const TTValue& value);
/** Setter for the mode attribute. */
TTErr setmode(const TTValue& value);
};
TT_AUDIO_CONSTRUCTOR_EXPORT
{
registerAttributeSimple(position, kTypeFloat64);
addAttributeProperty(position, range, TTValue(0.0, 1.0));
addAttributeProperty(position, rangeChecking, TT("clip"));
registerAttributeWithSetter(shape, kTypeSymbol);
registerAttributeWithSetter(mode, kTypeSymbol);
if(!zeroed){
memset(zeroVector1, 0, sizeof(TTSampleValue) * 2048);
memset(zeroVector2, 0, sizeof(TTSampleValue) * 2048);
memset(zeroVector3, 0, sizeof(TTSampleValue) * 2048);
}
// Set Defaults (the attribute setters will set the process method for us)...
setAttributeValue(TT("position"), 0.5);
setAttributeValue(TT("shape"), TT("equalPower"));
setAttributeValue(TT("mode"), TT("lookup"));
}
TTCrossfade::~TTCrossfade()
{;}
TTErr TTCrossfade::setshape(const TTValue& newValue)
{
shape = newValue;
return setProcessPointers();
}
TTErr TTCrossfade::setmode(const TTValue& newValue)
{
mode = newValue;
return setProcessPointers();
}
TTErr TTCrossfade::setProcessPointers()
{
TTErr err = kTTErrNone;
if(shape == TT("equalPower") && mode == TT("lookup")){
err = setProcess((TTProcessMethod)&TTCrossfade::processEqualPowerLookup);
}
else if(shape == TT("equalPower") && mode == TT("calculate")){
err = setProcess((TTProcessMethod)&TTCrossfade::processEqualPowerCalc);
}
else if(shape == TT("squareRoot") && mode == TT("calculate")){
err = setProcess((TTProcessMethod)&TTCrossfade::processSquareRootCalc);
}
else if(shape == TT("squareRoot") && mode == TT("lookup")){
err = setProcess((TTProcessMethod)&TTCrossfade::processSquareRootLookup);
}
else{
err = setProcess((TTProcessMethod)&TTCrossfade::processLinear);
}
return err;
}
#if 0
#pragma mark -
#pragma mark Interleaved Process Methods
#endif
TTErr TTCrossfade::processLinear(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
// inSampleA = in1.sampleVectors[channel];
// inSampleB = in2.sampleVectors[channel];
// outSample = out.sampleVectors[channel];
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * position) + (*inSampleA++ * (1.0 - position));
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * position) + (*inSampleA++ * (1.0 - position));
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processEqualPowerLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
int index;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
}
}
return kTTErrNone;
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
}
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processSquareRootLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
int index;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupSquareRoot[511 - index]) + (*inSampleA++ * kTTLookupSquareRoot[index]);
}
}
return kTTErrNone;
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupSquareRoot[511 - index]) + (*inSampleA++ * kTTLookupSquareRoot[index]);
}
}
}
return kTTErrNone;
}
// TODO: Nils says that we should experiment here with (sin*sin) here so that we can sum to 1.0 in the center???
// It's worth experimenting with it....
TTErr TTCrossfade::processEqualPowerCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMinChannelCount(in, in2, out);
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in2.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sin(position * kTTPi_2))) + (*inSampleA++ * (cos(position * kTTPi_2)));
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sin(position * kTTPi_2))) + (*inSampleA++ * (cos(position * kTTPi_2)));
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processSquareRootCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMinChannelCount(in, in2, out);
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in2.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sqrt(position))) + (*inSampleA++ * (sqrt(1 - position)));
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sqrt(position))) + (*inSampleA++ * (sqrt(1 - position)));
}
}
return kTTErrNone;
}
<commit_msg>making equalPower Crossfade faster<commit_after>/*
* TTBlue Signal Crossfader Object
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTDSP.h"
#define thisTTClass TTCrossfade
#define thisTTClassName "crossfade"
#define thisTTClassTags "audio, processor, mixing"
static bool zeroed = false;
static TTSampleValue zeroVector1[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector2[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector3[2048]; //TODO: make this dynamically sized
/** TTCrossfade in an audio processor that crossfades between two input signals.
In fact, this processor can work on a number of channels, provided that the number of input
channels is twice the number of output channels. In this case the first N/2 input channels are
considered as the A source and the last N/2 input channels are considered the B source.
*/
class TTCrossfade : TTAudioObject {
TTCLASS_SETUP(TTCrossfade)
TTFloat64 position; ///< Use a range of 0.0 to 1.0 to specify a ratio of the B source to the A source.
TTSymbol* shape; ///< The shape attribute is set with a TTSymbol that is either "equalPower" (the default) or "linear"
TTSymbol* mode; ///< The mode attribute is set with a TTSymbol that is either "lookup" (the default) or "calculate"
/** Utility used by the setters for setting up the process routine. */
TTErr setProcessPointers();
/** The process method used when the shape attribute is set to "linear"
* This method will return an error if the input and output channels are not matched properly. */
TTErr processLinear(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
/** The process method used when the shape attribute is set to "equalPower" and the mode is set to "lookup"
* This method will return an error if the input and output channels are not matched properly. */
TTErr processEqualPowerLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
TTErr processEqualPowerCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs); // calculate
/** The process method used when the shape attribute is set to "squareRoot""
* This method will return an error if the input and output channels are not matched properly. */
TTErr processSquareRootCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
TTErr processSquareRootLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
/** Setter for the shape attribute. */
TTErr setshape(const TTValue& value);
/** Setter for the mode attribute. */
TTErr setmode(const TTValue& value);
};
TT_AUDIO_CONSTRUCTOR_EXPORT
{
registerAttributeSimple(position, kTypeFloat64);
addAttributeProperty(position, range, TTValue(0.0, 1.0));
addAttributeProperty(position, rangeChecking, TT("clip"));
registerAttributeWithSetter(shape, kTypeSymbol);
registerAttributeWithSetter(mode, kTypeSymbol);
if(!zeroed){
memset(zeroVector1, 0, sizeof(TTSampleValue) * 2048);
memset(zeroVector2, 0, sizeof(TTSampleValue) * 2048);
memset(zeroVector3, 0, sizeof(TTSampleValue) * 2048);
}
// Set Defaults (the attribute setters will set the process method for us)...
setAttributeValue(TT("position"), 0.5);
setAttributeValue(TT("shape"), TT("equalPower"));
setAttributeValue(TT("mode"), TT("lookup"));
}
TTCrossfade::~TTCrossfade()
{;}
TTErr TTCrossfade::setshape(const TTValue& newValue)
{
shape = newValue;
return setProcessPointers();
}
TTErr TTCrossfade::setmode(const TTValue& newValue)
{
mode = newValue;
return setProcessPointers();
}
TTErr TTCrossfade::setProcessPointers()
{
TTErr err = kTTErrNone;
if(shape == TT("equalPower") && mode == TT("lookup")){
err = setProcess((TTProcessMethod)&TTCrossfade::processEqualPowerLookup);
}
else if(shape == TT("equalPower") && mode == TT("calculate")){
err = setProcess((TTProcessMethod)&TTCrossfade::processEqualPowerCalc);
}
else if(shape == TT("squareRoot") && mode == TT("calculate")){
err = setProcess((TTProcessMethod)&TTCrossfade::processSquareRootCalc);
}
else if(shape == TT("squareRoot") && mode == TT("lookup")){
err = setProcess((TTProcessMethod)&TTCrossfade::processSquareRootLookup);
}
else{
err = setProcess((TTProcessMethod)&TTCrossfade::processLinear);
}
return err;
}
#if 0
#pragma mark -
#pragma mark Interleaved Process Methods
#endif
TTErr TTCrossfade::processLinear(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
// inSampleA = in1.sampleVectors[channel];
// inSampleB = in2.sampleVectors[channel];
// outSample = out.sampleVectors[channel];
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * position) + (*inSampleA++ * (1.0 - position));
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * position) + (*inSampleA++ * (1.0 - position));
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processEqualPowerLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
int index;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
}
}
return kTTErrNone;
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
}
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processSquareRootLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
int index;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMaxChannelCount(in, in2, out);;
for(channel=0; channel<numchannels; channel++){
if(channel < in.getNumChannels())
inSampleA = in.sampleVectors[channel];
else
inSampleA = zeroVector1;
if(channel < in2.getNumChannels())
inSampleB = in2.sampleVectors[channel];
else
inSampleB = zeroVector2;
if(channel < out.getNumChannels())
outSample = out.sampleVectors[channel];
else
outSample = zeroVector3;
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupSquareRoot[511 - index]) + (*inSampleA++ * kTTLookupSquareRoot[index]);
}
}
return kTTErrNone;
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--){
index = (int)(position * 511.0);
*outSample++ = (*inSampleB++ * kTTLookupSquareRoot[511 - index]) + (*inSampleA++ * kTTLookupSquareRoot[index]);
}
}
}
return kTTErrNone;
}
// TODO: Nils says that we should experiment here with (sin*sin) here so that we can sum to 1.0 in the center???
// It's worth experimenting with it....
TTErr TTCrossfade::processEqualPowerCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
TTFloat64 radPosition;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMinChannelCount(in, in2, out);
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in2.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
{
radPosition = position * kTTPi_2;
*outSample++ = (*inSampleB++ * (sin(radPosition))) + (*inSampleA++ * (cos(radPosition)));
}
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
{
radPosition = position * kTTPi_2;
*outSample++ = (*inSampleB++ * (sin(radPosition))) + (*inSampleA++ * (cos(radPosition)));
}
}
}
return kTTErrNone;
}
TTErr TTCrossfade::processSquareRootCalc(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs;
TTSampleValue *inSampleA,
*inSampleB,
*outSample;
TTUInt16 numchannels = out.getNumChannels();
TTUInt16 channel;
if(inputs->numAudioSignals > 1){
TTAudioSignal& in2 = inputs->getSignal(1);
numchannels = TTAudioSignal::getMinChannelCount(in, in2, out);
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in2.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sqrt(position))) + (*inSampleA++ * (sqrt(1 - position)));
}
}
else{
if(in.getNumChannels() != out.getNumChannels()*2)
return kTTErrBadChannelConfig;
for(channel=0; channel<numchannels; channel++){
inSampleA = in.sampleVectors[channel];
inSampleB = in.sampleVectors[numchannels+channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
while(vs--)
*outSample++ = (*inSampleB++ * (sqrt(position))) + (*inSampleA++ * (sqrt(1 - position)));
}
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/*
* $Id$
*/
#include <sys/time.h>
#include <stdio.h>
#include <fstream>
#include <map>
#include <list>
#include <iostream>
#include <sstream>
#include <cmath>
#include <set>
#include "crf.h"
#include "common.h"
using namespace std;
multimap<string, string> WNdic;
void tokenize(const string &s1, list<string> <);
string base_form(const string &s, const string &pos);
extern int push_stop_watch();
static string normalize(const string &s) {
string tmp(s);
for (size_t i = 0; i < tmp.size(); i++) {
tmp[i] = tolower(tmp[i]);
if (isdigit(tmp[i])) tmp[i] = '#';
}
return tmp;
}
static CRF_State crfstate(const vector<Token> &vt, int i) {
CRF_State sample;
string str = vt[i].str;
sample.label = vt[i].pos;
sample.add_feature("W0_" + vt[i].str);
sample.add_feature("NW0_" + normalize(str));
string prestr = "BOS";
if (i > 0) prestr = vt[i - 1].str;
string prestr2 = "BOS";
if (i > 1) prestr2 = vt[i - 2].str;
string poststr = "EOS";
if (i < (int)vt.size() - 1) poststr = vt[i + 1].str;
string poststr2 = "EOS";
if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str;
sample.add_feature("W-1_" + prestr);
sample.add_feature("W+1_" + poststr);
sample.add_feature("W-2_" + prestr2);
sample.add_feature("W+2_" + poststr2);
sample.add_feature("W-10_" + prestr + "_" + str);
sample.add_feature("W0+1_" + str + "_" + poststr);
sample.add_feature("W-1+1_" + prestr + "_" + poststr);
for (size_t j = 1; j <= 10; j++) {
char buf[1000];
if (str.size() >= j) {
sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str());
sample.add_feature(buf);
}
if (str.size() >= j) {
sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str());
sample.add_feature(buf);
}
}
for (size_t j = 0; j < str.size(); j++) {
if (isdigit(str[j])) {
sample.add_feature("CTN_NUM");
break;
}
}
for (size_t j = 0; j < str.size(); j++) {
if (isupper(str[j])) {
sample.add_feature("CTN_UPP");
break;
}
}
for (size_t j = 0; j < str.size(); j++) {
if (str[j] == '-') {
sample.add_feature("CTN_HPN");
break;
}
}
bool allupper = true;
for (size_t j = 0; j < str.size(); j++) {
if (!isupper(str[j])) {
allupper = false;
break;
}
}
if (allupper) sample.add_feature("ALL_UPP");
if (!WNdic.empty()) {
const string n = normalize(str);
for (map<string, string>::const_iterator i = WNdic.lower_bound(n);
i != WNdic.upper_bound(n); i++) {
sample.add_feature("WN_" + i->second);
}
}
return sample;
}
int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m,
const vector<Sentence> &vs, double gaussian, const bool use_l1) {
if (method != CRF_Model::BFGS && use_l1) {
cerr << "error: L1 regularization is currently not supported in this mode. "
"Please use other optimziation methods." << endl;
exit(1);
}
for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); i++) {
const Sentence &s = *i;
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.add_training_sample(cs);
}
if (use_l1)
m.train(method, 0, 0, 1.0);
else
m.train(method, 0, gaussian);
return 0;
}
void crf_decode_lookahead(Sentence &s, CRF_Model &m,
vector<map<string, double> > &tagp) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_lookahead(cs);
tagp.clear();
for (size_t k = 0; k < s.size(); k++) {
s[k].prd = cs.vs[k].label;
map<string, double> vp;
vp[s[k].prd] = 1.0;
tagp.push_back(vp);
}
}
void crf_decode_forward_backward(Sentence &s, CRF_Model &m,
vector<map<string, double> > &tagp) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_forward_backward(cs, tagp);
for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}
void crf_decode_nbest(Sentence &s, CRF_Model &m,
vector<pair<double, vector<string> > > &nbest_seqs,
int n) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_nbest(cs, nbest_seqs, n, 0);
for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}
/*
* $Log$
*/
<commit_msg>crfpos.cpp: prefer prefix ++operator for non-primitive types<commit_after>/*
* $Id$
*/
#include <sys/time.h>
#include <stdio.h>
#include <fstream>
#include <map>
#include <list>
#include <iostream>
#include <sstream>
#include <cmath>
#include <set>
#include "crf.h"
#include "common.h"
using namespace std;
multimap<string, string> WNdic;
void tokenize(const string &s1, list<string> <);
string base_form(const string &s, const string &pos);
extern int push_stop_watch();
static string normalize(const string &s) {
string tmp(s);
for (size_t i = 0; i < tmp.size(); i++) {
tmp[i] = tolower(tmp[i]);
if (isdigit(tmp[i])) tmp[i] = '#';
}
return tmp;
}
static CRF_State crfstate(const vector<Token> &vt, int i) {
CRF_State sample;
string str = vt[i].str;
sample.label = vt[i].pos;
sample.add_feature("W0_" + vt[i].str);
sample.add_feature("NW0_" + normalize(str));
string prestr = "BOS";
if (i > 0) prestr = vt[i - 1].str;
string prestr2 = "BOS";
if (i > 1) prestr2 = vt[i - 2].str;
string poststr = "EOS";
if (i < (int)vt.size() - 1) poststr = vt[i + 1].str;
string poststr2 = "EOS";
if (i < (int)vt.size() - 2) poststr2 = vt[i + 2].str;
sample.add_feature("W-1_" + prestr);
sample.add_feature("W+1_" + poststr);
sample.add_feature("W-2_" + prestr2);
sample.add_feature("W+2_" + poststr2);
sample.add_feature("W-10_" + prestr + "_" + str);
sample.add_feature("W0+1_" + str + "_" + poststr);
sample.add_feature("W-1+1_" + prestr + "_" + poststr);
for (size_t j = 1; j <= 10; j++) {
char buf[1000];
if (str.size() >= j) {
sprintf(buf, "SUF%d_%s", (int)j, str.substr(str.size() - j).c_str());
sample.add_feature(buf);
}
if (str.size() >= j) {
sprintf(buf, "PRE%d_%s", (int)j, str.substr(0, j).c_str());
sample.add_feature(buf);
}
}
for (size_t j = 0; j < str.size(); j++) {
if (isdigit(str[j])) {
sample.add_feature("CTN_NUM");
break;
}
}
for (size_t j = 0; j < str.size(); j++) {
if (isupper(str[j])) {
sample.add_feature("CTN_UPP");
break;
}
}
for (size_t j = 0; j < str.size(); j++) {
if (str[j] == '-') {
sample.add_feature("CTN_HPN");
break;
}
}
bool allupper = true;
for (size_t j = 0; j < str.size(); j++) {
if (!isupper(str[j])) {
allupper = false;
break;
}
}
if (allupper) sample.add_feature("ALL_UPP");
if (!WNdic.empty()) {
const string n = normalize(str);
for (map<string, string>::const_iterator i = WNdic.lower_bound(n);
i != WNdic.upper_bound(n); ++i) {
sample.add_feature("WN_" + i->second);
}
}
return sample;
}
int crftrain(const CRF_Model::OptimizationMethod method, CRF_Model &m,
const vector<Sentence> &vs, double gaussian, const bool use_l1) {
if (method != CRF_Model::BFGS && use_l1) {
cerr << "error: L1 regularization is currently not supported in this mode. "
"Please use other optimziation methods." << endl;
exit(1);
}
for (vector<Sentence>::const_iterator i = vs.begin(); i != vs.end(); ++i) {
const Sentence &s = *i;
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.add_training_sample(cs);
}
if (use_l1)
m.train(method, 0, 0, 1.0);
else
m.train(method, 0, gaussian);
return 0;
}
void crf_decode_lookahead(Sentence &s, CRF_Model &m,
vector<map<string, double> > &tagp) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_lookahead(cs);
tagp.clear();
for (size_t k = 0; k < s.size(); k++) {
s[k].prd = cs.vs[k].label;
map<string, double> vp;
vp[s[k].prd] = 1.0;
tagp.push_back(vp);
}
}
void crf_decode_forward_backward(Sentence &s, CRF_Model &m,
vector<map<string, double> > &tagp) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_forward_backward(cs, tagp);
for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}
void crf_decode_nbest(Sentence &s, CRF_Model &m,
vector<pair<double, vector<string> > > &nbest_seqs,
int n) {
CRF_Sequence cs;
for (size_t j = 0; j < s.size(); j++) cs.add_state(crfstate(s, j));
m.decode_nbest(cs, nbest_seqs, n, 0);
for (size_t k = 0; k < s.size(); k++) s[k].prd = cs.vs[k].label;
}
/*
* $Log$
*/
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_FEM_HH
#define DUNE_GDT_MAPPER_FEM_HH
#include <dune/common/dynvector.hh>
#include <dune/fem/space/mapper/dofmapper.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
//// forward, to be used in the traits and to allow for specialization
template< class FemDofMapperImp >
class FemDofWrapper;
template< class FemDofMapperImp >
class FemDofWrapperTraits
{
public:
typedef FemDofWrapper< FemDofMapperImp > derived_type;
typedef Dune::Fem::DofMapper< typename FemDofMapperImp::Traits > BackendType;
};
template< class FemDofMapperImp >
class FemDofWrapper
: public MapperInterface< FemDofWrapperTraits< FemDofMapperImp > >
{
typedef MapperInterface< FemDofWrapperTraits< FemDofMapperImp > > InterfaceType;
public:
typedef FemDofWrapperTraits< FemDofMapperImp > Traits;
typedef typename Traits::BackendType BackendType;
FemDofWrapper(const BackendType& femMapper)
: backend_(femMapper)
{}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return backend_.size();
}
template< class EntityType >
size_t numDofs(const EntityType& entity) const
{
return backend_.numDofs(entity);
}
size_t maxNumDofs() const
{
return backend_.maxNumDofs();
}
private:
class Functor
{
public:
Functor(Dune::DynamicVector< size_t >& globalIndices)
: globalIndices_(globalIndices)
{}
void operator()(int localDoF, int globalDoF)
{
assert(localDoF < int(globalIndices_.size()));
globalIndices_[localDoF] = globalDoF;
}
private:
Dune::DynamicVector< size_t >& globalIndices_;
};
public:
template< class EntityType >
void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
{
// some checks
const size_t numLocalDofs = numDofs(entity);
if (ret.size() < numLocalDofs)
ret.resize(numLocalDofs);
// compute
Functor functor(ret);
backend_.mapEachEntityDof(entity, functor);
}
using InterfaceType::globalIndices;
/**
* \attention This method is implemented using globalIndices() and thus not optimal!
*/
template< class EntityType >
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
const size_t numLocalDofs = numDofs(entity);
assert(localIndex < numLocalDofs);
Dune::DynamicVector< size_t > tmpGlobalIndices(numLocalDofs);
globalIndices(entity, tmpGlobalIndices);
return tmpGlobalIndices[localIndex];
}
private:
const BackendType& backend_;
}; // class FemDofWrapper
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_FEM_HH
<commit_msg>[mapper.fem] add proper guards and errors<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_FEM_HH
#define DUNE_GDT_MAPPER_FEM_HH
#include <type_traits>
#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>
#ifdef HAVE_DUNE_FEM
# include <dune/fem/space/mapper/dofmapper.hh>
#endif
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
#ifdef HAVE_DUNE_FEM
// forward, to be used in the traits and to allow for specialization
template< class FemDofMapperImp >
class FemDofWrapper;
template< class FemDofMapperImp >
class FemDofWrapperTraits
{
public:
typedef FemDofWrapper< FemDofMapperImp > derived_type;
typedef Dune::Fem::DofMapper< typename FemDofMapperImp::Traits > BackendType;
};
template< class FemDofMapperImp >
class FemDofWrapper
: public MapperInterface< FemDofWrapperTraits< FemDofMapperImp > >
{
typedef MapperInterface< FemDofWrapperTraits< FemDofMapperImp > > InterfaceType;
public:
typedef FemDofWrapperTraits< FemDofMapperImp > Traits;
typedef typename Traits::BackendType BackendType;
FemDofWrapper(const BackendType& femMapper)
: backend_(femMapper)
{}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return backend_.size();
}
template< class EntityType >
size_t numDofs(const EntityType& entity) const
{
return backend_.numDofs(entity);
}
size_t maxNumDofs() const
{
return backend_.maxNumDofs();
}
private:
class Functor
{
public:
Functor(Dune::DynamicVector< size_t >& globalIndices)
: globalIndices_(globalIndices)
{}
void operator()(int localDoF, int globalDoF)
{
assert(localDoF < int(globalIndices_.size()));
globalIndices_[localDoF] = globalDoF;
}
private:
Dune::DynamicVector< size_t >& globalIndices_;
};
public:
template< class EntityType >
void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
{
// some checks
const size_t numLocalDofs = numDofs(entity);
if (ret.size() < numLocalDofs)
ret.resize(numLocalDofs);
// compute
Functor functor(ret);
backend_.mapEachEntityDof(entity, functor);
}
using InterfaceType::globalIndices;
/**
* \attention This method is implemented using globalIndices() and thus not optimal!
*/
template< class EntityType >
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
const size_t numLocalDofs = numDofs(entity);
assert(localIndex < numLocalDofs);
Dune::DynamicVector< size_t > tmpGlobalIndices(numLocalDofs);
globalIndices(entity, tmpGlobalIndices);
return tmpGlobalIndices[localIndex];
}
private:
const BackendType& backend_;
}; // class FemDofWrapper
#else // HAVE_DUNE_FEM
template< class FemDofMapperImp >
class FemDofWrapper
{
static_assert(Dune::AlwaysFalse< FemDofMapperImp >::value, "You are missing dune-fem!");
};
#endif // HAVE_DUNE_FEM
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_FEM_HH
<|endoftext|> |
<commit_before>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** 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.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <fontconfig/fontconfig.h>
#include "SkDescriptor.h"
#include "SkFontHost.h"
#include "SkMMapStream.h"
#include "SkPaint.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkThread.h"
#include "SkTSearch.h"
// This is an extern from SkFontHost_FreeType
SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);
// -----------------------------------------------------------------------------
// The rest of Skia requires that fonts be identified by a unique unsigned id
// and that we be able to load them given the id. What we actually get from
// fontconfig is the filename of the font so we keep a locked map from
// filenames to fileid numbers and back.
//
// Note that there's also a unique id in the SkTypeface. This is unique over
// both filename and style. Thus we encode that id as (fileid << 8) | style.
// Although truetype fonts can support multiple faces in a single file, at the
// moment Skia doesn't.
// -----------------------------------------------------------------------------
static SkMutex global_fc_map_lock;
static std::map<std::string, unsigned> global_fc_map;
static std::map<unsigned, std::string> global_fc_map_inverted;
static unsigned global_fc_map_next_id = 0;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
static unsigned UniqueIdToFileId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileIdAndStyleToUniqueId(unsigned fileid,
SkTypeface::Style style)
{
// TODO(agl/brettw) bug 6291: This assertion fails for unknown reasons
// on ChromeFontTest.LoadArial. This should be fixed.
//SkASSERT(style & 0xff == style);
return (fileid << 8) | static_cast<int>(style);
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
};
// -----------------------------------------------------------------------------
// Find a matching font where @type (one of FC_*) is equal to @value. For a
// list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27.
// The variable arguments are a list of triples, just like the first three
// arguments, and must be NULL terminated.
//
// For example, FontMatchString(FC_FILE, FcTypeString,
// "/usr/share/fonts/myfont.ttf", NULL);
// -----------------------------------------------------------------------------
static FcPattern* FontMatch(const char* type, FcType vtype, const void* value,
...)
{
va_list ap;
va_start(ap, value);
FcPattern* pattern = FcPatternCreate();
bool family_requested = false;
for (;;) {
FcValue fcvalue;
fcvalue.type = vtype;
switch (vtype) {
case FcTypeString:
fcvalue.u.s = (FcChar8*) value;
break;
case FcTypeInteger:
fcvalue.u.i = (int) value;
break;
default:
SkASSERT(!"FontMatch unhandled type");
}
FcPatternAdd(pattern, type, fcvalue, 0);
if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)
family_requested = true;
type = va_arg(ap, const char *);
if (!type)
break;
// FcType is promoted to int when passed through ...
vtype = static_cast<FcType>(va_arg(ap, int));
value = va_arg(ap, const void *);
};
va_end(ap);
FcConfigSubstitute(0, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcPattern* match = FcFontMatch(0, pattern, &result);
if (!match) {
FcPatternDestroy(pattern);
return NULL;
}
FcChar8* post_match_family;
FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);
const bool family_names_match =
!family_requested ?
true :
strcasecmp((char *) post_config_family, (char *) post_match_family) == 0;
FcPatternDestroy(pattern);
if (!family_names_match) {
FcPatternDestroy(match);
return NULL;
}
return match;
}
// -----------------------------------------------------------------------------
// Check to see if the filename has already been assigned a fileid and, if so,
// use it. Otherwise, assign one. Return the resulting fileid.
// -----------------------------------------------------------------------------
static unsigned FileIdFromFilename(const char* filename)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
std::map<std::string, unsigned>::const_iterator i =
global_fc_map.find(filename);
if (i == global_fc_map.end()) {
const unsigned fileid = global_fc_map_next_id++;
global_fc_map[filename] = fileid;
global_fc_map_inverted[fileid] = filename;
return fileid;
} else {
return i->second;
}
}
SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace,
const char familyName[],
SkTypeface::Style style)
{
const char* resolved_family_name = NULL;
FcPattern* face_match = NULL;
if (familyFace) {
// Here we use the inverted global id map to find the filename from the
// SkTypeface object. Given the filename we can ask fontconfig for the
// familyname of the font.
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
FcInit();
face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(), NULL);
if (!face_match)
return NULL;
FcChar8* family;
if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {
FcPatternDestroy(face_match);
return NULL;
}
// At this point, @family is pointing into the @face_match object so we
// cannot release it yet.
resolved_family_name = reinterpret_cast<char*>(family);
} else if (familyName) {
resolved_family_name = familyName;
} else {
return NULL;
}
{
SkAutoMutexAcquire ac(global_fc_map_lock);
FcInit();
}
// At this point, we have a resolved_family_name from somewhere
SkASSERT(resolved_family_name);
const int bold = style & SkTypeface::kBold ?
FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;
const int italic = style & SkTypeface::kItalic ?
FC_SLANT_ITALIC : FC_SLANT_ROMAN;
FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,
FC_WEIGHT, FcTypeInteger, bold,
FC_SLANT, FcTypeInteger, italic,
NULL);
if (face_match)
FcPatternDestroy(face_match);
if (!match)
return NULL;
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename));
const unsigned id = FileIdAndStyleToUniqueId(fileid, style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
FcPatternDestroy(match);
return typeface;
}
SkTypeface* SkFontHost::ResolveTypeface(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const SkTypeface::Style style = UniqueIdToStyle(id);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(FontConfigTypeface, (style, id));
}
SkStream* SkFontHost::OpenStream(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));
}
void SkFontHost::CloseStream(uint32_t fontID, SkStream* stream)
{
}
SkTypeface* SkFontHost::CreateTypeface(SkStream* stream)
{
SkASSERT(!"SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkScalerContext* SkFontHost::CreateFallbackScalerContext
(const SkScalerContext::Rec& rec) {
FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, "serif",
NULL);
// This will fail when we have no fonts on the system.
SkASSERT(match);
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned id = FileIdFromFilename(reinterpret_cast<char*>(filename));
FcPatternDestroy(match);
SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1));
SkDescriptor* desc = ad.getDesc();
desc->init();
SkScalerContext::Rec* newRec =
(SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag,
sizeof(rec), &rec);
newRec->fFontID = id;
desc->computeChecksum();
return SkFontHost::CreateScalerContext(desc);
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)
{
if (sizeAllocatedSoFar > kFontCacheMemoryBudget)
return sizeAllocatedSoFar - kFontCacheMemoryBudget;
else
return 0; // nothing to do
}
<commit_msg>Linux: fix failure to find any fonts<commit_after>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** 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.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <fontconfig/fontconfig.h>
#include "SkDescriptor.h"
#include "SkFontHost.h"
#include "SkMMapStream.h"
#include "SkPaint.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkThread.h"
#include "SkTSearch.h"
// This is an extern from SkFontHost_FreeType
SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);
// -----------------------------------------------------------------------------
// The rest of Skia requires that fonts be identified by a unique unsigned id
// and that we be able to load them given the id. What we actually get from
// fontconfig is the filename of the font so we keep a locked map from
// filenames to fileid numbers and back.
//
// Note that there's also a unique id in the SkTypeface. This is unique over
// both filename and style. Thus we encode that id as (fileid << 8) | style.
// Although truetype fonts can support multiple faces in a single file, at the
// moment Skia doesn't.
// -----------------------------------------------------------------------------
static SkMutex global_fc_map_lock;
static std::map<std::string, unsigned> global_fc_map;
static std::map<unsigned, std::string> global_fc_map_inverted;
static unsigned global_fc_map_next_id = 0;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
static unsigned UniqueIdToFileId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileIdAndStyleToUniqueId(unsigned fileid,
SkTypeface::Style style)
{
// TODO(agl/brettw) bug 6291: This assertion fails for unknown reasons
// on ChromeFontTest.LoadArial. This should be fixed.
//SkASSERT(style & 0xff == style);
return (fileid << 8) | static_cast<int>(style);
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
};
// -----------------------------------------------------------------------------
// Find a matching font where @type (one of FC_*) is equal to @value. For a
// list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27.
// The variable arguments are a list of triples, just like the first three
// arguments, and must be NULL terminated.
//
// For example, FontMatchString(FC_FILE, FcTypeString,
// "/usr/share/fonts/myfont.ttf", NULL);
// -----------------------------------------------------------------------------
static FcPattern* FontMatch(bool is_fallback,
const char* type, FcType vtype, const void* value,
...)
{
va_list ap;
va_start(ap, value);
FcPattern* pattern = FcPatternCreate();
bool family_requested = false;
for (;;) {
FcValue fcvalue;
fcvalue.type = vtype;
switch (vtype) {
case FcTypeString:
fcvalue.u.s = (FcChar8*) value;
break;
case FcTypeInteger:
fcvalue.u.i = (int) value;
break;
default:
SkASSERT(!"FontMatch unhandled type");
}
FcPatternAdd(pattern, type, fcvalue, 0);
if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)
family_requested = true;
type = va_arg(ap, const char *);
if (!type)
break;
// FcType is promoted to int when passed through ...
vtype = static_cast<FcType>(va_arg(ap, int));
value = va_arg(ap, const void *);
};
va_end(ap);
FcConfigSubstitute(0, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcPattern* match = FcFontMatch(0, pattern, &result);
if (!match) {
FcPatternDestroy(pattern);
return NULL;
}
FcChar8* post_match_family;
FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);
const bool family_names_match =
!family_requested ?
true :
strcasecmp((char *) post_config_family, (char *) post_match_family) == 0;
FcPatternDestroy(pattern);
if (!family_names_match && !is_fallback) {
FcPatternDestroy(match);
return NULL;
}
return match;
}
// -----------------------------------------------------------------------------
// Check to see if the filename has already been assigned a fileid and, if so,
// use it. Otherwise, assign one. Return the resulting fileid.
// -----------------------------------------------------------------------------
static unsigned FileIdFromFilename(const char* filename)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
std::map<std::string, unsigned>::const_iterator i =
global_fc_map.find(filename);
if (i == global_fc_map.end()) {
const unsigned fileid = global_fc_map_next_id++;
global_fc_map[filename] = fileid;
global_fc_map_inverted[fileid] = filename;
return fileid;
} else {
return i->second;
}
}
SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace,
const char familyName[],
SkTypeface::Style style)
{
const char* resolved_family_name = NULL;
FcPattern* face_match = NULL;
if (familyFace) {
// Here we use the inverted global id map to find the filename from the
// SkTypeface object. Given the filename we can ask fontconfig for the
// familyname of the font.
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
FcInit();
face_match = FontMatch(false, FC_FILE, FcTypeString, i->second.c_str(),
NULL);
if (!face_match)
return NULL;
FcChar8* family;
if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {
FcPatternDestroy(face_match);
return NULL;
}
// At this point, @family is pointing into the @face_match object so we
// cannot release it yet.
resolved_family_name = reinterpret_cast<char*>(family);
} else if (familyName) {
resolved_family_name = familyName;
} else {
return NULL;
}
{
SkAutoMutexAcquire ac(global_fc_map_lock);
FcInit();
}
// At this point, we have a resolved_family_name from somewhere
SkASSERT(resolved_family_name);
const int bold = style & SkTypeface::kBold ?
FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;
const int italic = style & SkTypeface::kItalic ?
FC_SLANT_ITALIC : FC_SLANT_ROMAN;
FcPattern* match = FontMatch(false,
FC_FAMILY, FcTypeString, resolved_family_name,
FC_WEIGHT, FcTypeInteger, bold,
FC_SLANT, FcTypeInteger, italic,
NULL);
if (face_match)
FcPatternDestroy(face_match);
if (!match)
return NULL;
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename));
const unsigned id = FileIdAndStyleToUniqueId(fileid, style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
FcPatternDestroy(match);
return typeface;
}
SkTypeface* SkFontHost::ResolveTypeface(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const SkTypeface::Style style = UniqueIdToStyle(id);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(FontConfigTypeface, (style, id));
}
SkStream* SkFontHost::OpenStream(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));
}
void SkFontHost::CloseStream(uint32_t fontID, SkStream* stream)
{
}
SkTypeface* SkFontHost::CreateTypeface(SkStream* stream)
{
SkASSERT(!"SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkScalerContext* SkFontHost::CreateFallbackScalerContext
(const SkScalerContext::Rec& rec) {
FcPattern* match = FontMatch(true, FC_FAMILY, FcTypeString, "serif",
NULL);
// This will fail when we have no fonts on the system.
SkASSERT(match);
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned id = FileIdFromFilename(reinterpret_cast<char*>(filename));
FcPatternDestroy(match);
SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1));
SkDescriptor* desc = ad.getDesc();
desc->init();
SkScalerContext::Rec* newRec =
(SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag,
sizeof(rec), &rec);
newRec->fFontID = id;
desc->computeChecksum();
return SkFontHost::CreateScalerContext(desc);
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)
{
if (sizeAllocatedSoFar > kFontCacheMemoryBudget)
return sizeAllocatedSoFar - kFontCacheMemoryBudget;
else
return 0; // nothing to do
}
<|endoftext|> |
<commit_before>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// 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.
// * Neither the name of Southwest Research Institute® (SwRI®) nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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 <COPYRIGHT HOLDER> 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 <image_util/draw_util.h>
#include <cstdlib>
#include <algorithm>
#include <QPolygonF>
#include <QPointF>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <ros/ros.h>
#include <opencv_util/show.h>
namespace image_util
{
void RandomColor(int32_t seed, double& r, double& g, double& b)
{
std::srand(seed);
r = static_cast<double>(std::rand()) / RAND_MAX;
g = static_cast<double>(std::rand()) / RAND_MAX;
b = static_cast<double>(std::rand()) / RAND_MAX;
}
void JetColorMap(
unsigned char &r,
unsigned char &g,
unsigned char &b,
float value,
float min,
float max)
{
float max4 = (max - min) / 4.0;
value -= min;
if (value == HUGE_VAL)
{
r = g = b = 255;
}
else if (value < 0)
{
r = g = b = 0;
}
else if (value < max4)
{
unsigned char c1 = 144;
r = 0;
g = 0;
b = c1 + (unsigned char) ((255 - c1) * value / max4);
}
else if (value < 2 * max4)
{
r = 0;
g = (unsigned char) (255 * (value - max4) / max4);
b = 255;
}
else if (value < 3 * max4)
{
r = (unsigned char) (255 * (value - 2 * max4) / max4);
g = 255;
b = 255 - r;
}
else if (value < max)
{
r = 255;
g = (unsigned char) (255 - 255 * (value - 3 * max4) / max4);
b = 0;
}
else
{
r = 255;
g = 0;
b = 0;
}
}
void DrawOverlap(
const std::string& title,
const cv::Mat& image1,
const cv::Mat& image2,
const cv::Mat& transform)
{
if (image1.rows == image2.rows && image1.cols == image2.cols)
{
cv::Mat image2_warped;
cv::warpAffine(
image2,
image2_warped,
transform,
cv::Size(image2.cols, image2.rows));
cv::Mat sub = image1 - image2_warped;
opencv_util::ShowScaled(title, sub);
}
}
void DrawMatches(
cv::Mat& image_out,
const cv::Mat image1,
const cv::Mat image2,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color,
bool draw_image_borders)
{
cv::Size size(image1.cols + image2.cols, std::max(image1.rows, image2.rows));
image_out.create(size, CV_MAKETYPE(image1.depth(), 3));
cv::Mat draw_image1 = image_out(cv::Rect(0, 0, image1.cols, image1.rows));
cv::Mat draw_image2 = image_out(cv::Rect(image1.cols, 0, image2.cols, image2.rows));
if (image1.type() == CV_8U)
{
cvtColor(image1, draw_image1, CV_GRAY2BGR);
}
else
{
image1.copyTo(draw_image1);
}
if (image2.type() == CV_8U)
{
cvtColor(image2, draw_image2, CV_GRAY2BGR);
}
else
{
image2.copyTo(draw_image2);
}
if (draw_image_borders)
{
cv::rectangle(draw_image1,
cv::Point(0, 0),
cv::Point(image1.cols, image1.rows),
cv::Scalar(0, 0, 0),
2);
cv::rectangle(draw_image2,
cv::Point(0, 0),
cv::Point(image2.cols, image2.rows),
cv::Scalar(0, 0, 0),
2);
}
cv::RNG rng = cv::theRNG();
bool rand_color = color == cv::Scalar::all(-1);
for (int i = 0; i < points1.rows; i++)
{
cv::Scalar match_color = rand_color ? cv::Scalar(rng(256), rng(256), rng(256)) : color;
cv::Point2f center1(
cvRound(points1.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points1.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f center2(
cvRound(points2.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points2.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f dcenter2(
std::min(center2.x + draw_image1.cols * 16.0, (image_out.cols - 1) * 16.0),
center2.y);
circle(draw_image1, center1, 48, match_color2, 1, CV_AA, 4);
circle(draw_image2, center2, 48, match_color2, 1, CV_AA, 4);
line(image_out, center1, dcenter2, match_color, 1, CV_AA, 4);
}
}
void DrawMatches(
const std::string& title,
const cv::Mat image1,
const cv::Mat image2,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color,
bool draw_image_borders)
{
cv::Mat image_out;
DrawMatches(image_out,
image1,
image2,
points1,
points2,
color,
draw_image_borders);
opencv_util::ShowScaled(title, image_out);
}
void DrawMatches(
const std::string& title,
const cv::Mat image,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color1,
const cv::Scalar& color2,
bool draw_image_borders)
{
cv::Mat draw_image;
if (image.type() == CV_8U)
{
cvtColor(image, draw_image, CV_GRAY2BGR);
}
else
{
draw_image = image.clone();
}
for (int i = 0; i < points1.rows; i++)
{
cv::Point2f center1(
cvRound(points1.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points1.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f center2(cvRound(
points2.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points2.at<cv::Vec2f>(0, i)[1] * 16.0));
circle(draw_image, center1, 48, color1, 1, CV_AA, 4);
line(draw_image, center1, center2, color2, 1, CV_AA, 4);
}
opencv_util::ShowScaled(title, draw_image);
}
}
<commit_msg>fix merge error<commit_after>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// 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.
// * Neither the name of Southwest Research Institute® (SwRI®) nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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 <COPYRIGHT HOLDER> 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 <image_util/draw_util.h>
#include <cstdlib>
#include <algorithm>
#include <QPolygonF>
#include <QPointF>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <ros/ros.h>
#include <opencv_util/show.h>
namespace image_util
{
void RandomColor(int32_t seed, double& r, double& g, double& b)
{
std::srand(seed);
r = static_cast<double>(std::rand()) / RAND_MAX;
g = static_cast<double>(std::rand()) / RAND_MAX;
b = static_cast<double>(std::rand()) / RAND_MAX;
}
void JetColorMap(
unsigned char &r,
unsigned char &g,
unsigned char &b,
float value,
float min,
float max)
{
float max4 = (max - min) / 4.0;
value -= min;
if (value == HUGE_VAL)
{
r = g = b = 255;
}
else if (value < 0)
{
r = g = b = 0;
}
else if (value < max4)
{
unsigned char c1 = 144;
r = 0;
g = 0;
b = c1 + (unsigned char) ((255 - c1) * value / max4);
}
else if (value < 2 * max4)
{
r = 0;
g = (unsigned char) (255 * (value - max4) / max4);
b = 255;
}
else if (value < 3 * max4)
{
r = (unsigned char) (255 * (value - 2 * max4) / max4);
g = 255;
b = 255 - r;
}
else if (value < max)
{
r = 255;
g = (unsigned char) (255 - 255 * (value - 3 * max4) / max4);
b = 0;
}
else
{
r = 255;
g = 0;
b = 0;
}
}
void DrawOverlap(
const std::string& title,
const cv::Mat& image1,
const cv::Mat& image2,
const cv::Mat& transform)
{
if (image1.rows == image2.rows && image1.cols == image2.cols)
{
cv::Mat image2_warped;
cv::warpAffine(
image2,
image2_warped,
transform,
cv::Size(image2.cols, image2.rows));
cv::Mat sub = image1 - image2_warped;
opencv_util::ShowScaled(title, sub);
}
}
void DrawMatches(
cv::Mat& image_out,
const cv::Mat image1,
const cv::Mat image2,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color,
bool draw_image_borders)
{
cv::Size size(image1.cols + image2.cols, std::max(image1.rows, image2.rows));
image_out.create(size, CV_MAKETYPE(image1.depth(), 3));
cv::Mat draw_image1 = image_out(cv::Rect(0, 0, image1.cols, image1.rows));
cv::Mat draw_image2 = image_out(cv::Rect(image1.cols, 0, image2.cols, image2.rows));
if (image1.type() == CV_8U)
{
cvtColor(image1, draw_image1, CV_GRAY2BGR);
}
else
{
image1.copyTo(draw_image1);
}
if (image2.type() == CV_8U)
{
cvtColor(image2, draw_image2, CV_GRAY2BGR);
}
else
{
image2.copyTo(draw_image2);
}
if (draw_image_borders)
{
cv::rectangle(draw_image1,
cv::Point(0, 0),
cv::Point(image1.cols, image1.rows),
cv::Scalar(0, 0, 0),
2);
cv::rectangle(draw_image2,
cv::Point(0, 0),
cv::Point(image2.cols, image2.rows),
cv::Scalar(0, 0, 0),
2);
}
cv::RNG rng = cv::theRNG();
bool rand_color = color == cv::Scalar::all(-1);
for (int i = 0; i < points1.rows; i++)
{
cv::Scalar match_color = rand_color ? cv::Scalar(rng(256), rng(256), rng(256)) : color;
cv::Point2f center1(
cvRound(points1.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points1.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f center2(
cvRound(points2.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points2.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f dcenter2(
std::min(center2.x + draw_image1.cols * 16.0, (image_out.cols - 1) * 16.0),
center2.y);
circle(draw_image1, center1, 48, match_color, 1, CV_AA, 4);
circle(draw_image2, center2, 48, match_color, 1, CV_AA, 4);
line(image_out, center1, dcenter2, match_color, 1, CV_AA, 4);
}
}
void DrawMatches(
const std::string& title,
const cv::Mat image1,
const cv::Mat image2,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color,
bool draw_image_borders)
{
cv::Mat image_out;
DrawMatches(image_out,
image1,
image2,
points1,
points2,
color,
draw_image_borders);
opencv_util::ShowScaled(title, image_out);
}
void DrawMatches(
const std::string& title,
const cv::Mat image,
const cv::Mat points1,
const cv::Mat points2,
const cv::Scalar& color1,
const cv::Scalar& color2,
bool draw_image_borders)
{
cv::Mat draw_image;
if (image.type() == CV_8U)
{
cvtColor(image, draw_image, CV_GRAY2BGR);
}
else
{
draw_image = image.clone();
}
for (int i = 0; i < points1.rows; i++)
{
cv::Point2f center1(
cvRound(points1.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points1.at<cv::Vec2f>(0, i)[1] * 16.0));
cv::Point2f center2(cvRound(
points2.at<cv::Vec2f>(0, i)[0] * 16.0),
cvRound(points2.at<cv::Vec2f>(0, i)[1] * 16.0));
circle(draw_image, center1, 48, color1, 1, CV_AA, 4);
line(draw_image, center1, center2, color2, 1, CV_AA, 4);
}
opencv_util::ShowScaled(title, draw_image);
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <cstring>
#include <cstdlib>
#include <memory>
#include "CompileConfig.h"
#if defined(OUZEL_SUPPORTS_SSE)
#include <xmmintrin.h>
#endif
#include "MathUtils.h"
namespace ouzel
{
uint32_t calculateMipLevels(uint32_t width, uint32_t height)
{
uint32_t result = 1;
while (width > 1 || height > 1)
{
width >>= 1;
height >>= 1;
++result;
}
return result;
}
bool linesIntersect(const Vector2& p0, const Vector2& p1,
const Vector2& p2, const Vector2& p3)
{
Vector2 s1(p1.x - p0.x, p1.y - p0.y), s2(p3.x - p2.x, p3.y - p2.y);
float s, t;
s = (-s1.y * (p0.x - p2.x) + s1.x * (p0.y - p2.y)) / (-s2.x * s1.y + s1.x * s2.y);
t = ( s2.x * (p0.y - p2.y) - s2.y * (p0.x - p2.x)) / (-s2.x * s1.y + s1.x * s2.y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
return true;
}
return false; // No collision
}
}
<commit_msg>Remove unneeded SSE include from MathUtils.cpp<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <cstring>
#include <cstdlib>
#include <memory>
#include "MathUtils.h"
namespace ouzel
{
uint32_t calculateMipLevels(uint32_t width, uint32_t height)
{
uint32_t result = 1;
while (width > 1 || height > 1)
{
width >>= 1;
height >>= 1;
++result;
}
return result;
}
bool linesIntersect(const Vector2& p0, const Vector2& p1,
const Vector2& p2, const Vector2& p3)
{
Vector2 s1(p1.x - p0.x, p1.y - p0.y), s2(p3.x - p2.x, p3.y - p2.y);
float s, t;
s = (-s1.y * (p0.x - p2.x) + s1.x * (p0.y - p2.y)) / (-s2.x * s1.y + s1.x * s2.y);
t = ( s2.x * (p0.y - p2.y) - s2.y * (p0.x - p2.x)) / (-s2.x * s1.y + s1.x * s2.y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
return true;
}
return false; // No collision
}
}
<|endoftext|> |
<commit_before>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <vector>
#include <ctime>
#include <boost/algorithm/string/classification.hpp> // is_any_of
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccquvi>
#include <ccapplication>
#include <ccoptions>
#include <ccinput>
#include <ccutil>
#include <cclog>
#include <ccre>
namespace cc
{
static void handle_fetch(const quvi_word type, void*)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
print_done();
}
static void handle_resolve(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
#ifdef HAVE_LIBQUVI_0_9
static void status_callback_pt9(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVI_CALLBACK_STATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVI_CALLBACK_STATUS_HTTP_QUERY_METAINFO:
handle_verify(type);
break;
case QUVI_CALLBACK_STATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#else
static void status_callback_pt4(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVISTATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#endif
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
#ifdef HAVE_LIBQUVI_0_9
status_callback_pt9(status, type, ptr);
#else
status_callback_pt4(status, type, ptr);
#endif
cc::log << std::flush;
return QUVI_OK;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
namespace po = boost::program_options;
typedef std::vector<std::string> vst;
static application::exit_status
print_streams(const quvi::query& query, const quvi::options &qopts,
const vst& input_urls)
{
const size_t n = input_urls.size();
size_t i = 0;
foreach (const std::string& url, input_urls)
{
try
{
print_checking(++i,n);
query.setup_curl();
const std::string r = query.streams(url, qopts);
print_done();
if (cc::opts.flags.print_streams)
{
vst a;
boost::split(a, r, boost::is_any_of("|,"));
foreach (const std::string s, a)
{
cc::log << s << "\n";
}
}
else
cc::log << std::setw(10) << r << " : " << url << std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
return application::error;
}
}
return application::ok;
}
static void parse_prefer_format(const std::string& url, std::string& fmt,
const po::variables_map& map)
{
vst vb, va = map["prefer-format"].as<vst>();
foreach (const std::string s, va)
{
boost::split(vb, s, boost::is_any_of(":"));
if (vb.size() == 2)
{
// vb[0] = pattern
// vb[1] = format
if (cc::re::grep(vb[0], url))
{
fmt = vb[1];
return;
}
}
vb.clear();
}
}
static void set_stream(const std::string& url, quvi::options& qopts,
const po::variables_map& map)
{
std::string s = "default";
if (map.count("stream"))
s = map["stream"].as<std::string>();
else
{
if (map.count("prefer-format"))
parse_prefer_format(url, s, map);
}
qopts.stream = s;
}
static const char copyr[] =
"\n\nCopyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>\n"
"cclive comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of\n"
"cclive under the terms of the GNU Affero General Public License version\n"
"3 or later. For more information, see "
"<http://www.gnu.org/licenses/agpl.html>.\n\n"
"To contact the developers, please mail to "
"<cclive-devel@lists.sourceforge.net>";
static const application::exit_status print_version()
{
std::cout
<< "cclive "
#ifdef VN
<< VN
#else
<< PACKAGE_VERSION
#endif
<< "\n built on "
<< BUILD_TIME
<< " for " << CANONICAL_TARGET
<< "\n libquvi "
<< quvi::version()
<< "\n libquvi-scripts "
<< quvi_version(QUVI_VERSION_SCRIPTS)
<< copyr
<< std::endl;
return application::ok;
}
application::exit_status application::exec(int argc, char **argv)
{
try
{
opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return application::error;
}
const po::variables_map map = cc::opts.map();
// Dump and terminate options.
if (opts.flags.help)
{
std::cout << opts << std::flush;
return application::ok;
}
else if (opts.flags.print_config)
{
opts.dump();
return application::ok;
}
else if (opts.flags.version)
return print_version();
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (opts.flags.support)
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return application::ok;
}
// Parse input.
cc::input ci;
const vst input_urls = cc::input().urls();
if (input_urls.size() ==0)
{
std::clog << "error: no input URL" << std::endl;
return application::error;
}
// Set up quvi.
quvi::options qopts;
qopts.useragent = map["agent"].as<std::string>(); /* libquvi 0.9+ */
qopts.resolve = ! opts.flags.no_resolve;
qopts.statusfunc = status_callback;
// Omit flag.
bool omit = opts.flags.quiet;
// Go to background.
#ifdef HAVE_FORK
const bool background_given = opts.flags.background;
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Print streams.
if (opts.flags.print_streams)
return print_streams(query, qopts, input_urls);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
const size_t n = input_urls.size();
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
exit_status es = ok;
foreach(const std::string& url, input_urls)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
set_stream(url, qopts, map);
_curl = query.setup_curl();
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
if (e.cannot_retry())
throw e;
else
print_quvi_error(e);
}
cc::get(m, _curl);
break; // Stop retrying.
}
es = ok;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
es = application::error;
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
es = application::error;
}
}
return es;
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<commit_msg>FIX: Create cc::input instance once<commit_after>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <vector>
#include <ctime>
#include <boost/algorithm/string/classification.hpp> // is_any_of
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccquvi>
#include <ccapplication>
#include <ccoptions>
#include <ccinput>
#include <ccutil>
#include <cclog>
#include <ccre>
namespace cc
{
static void handle_fetch(const quvi_word type, void*)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
print_done();
}
static void handle_resolve(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
#ifdef HAVE_LIBQUVI_0_9
static void status_callback_pt9(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVI_CALLBACK_STATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVI_CALLBACK_STATUS_HTTP_QUERY_METAINFO:
handle_verify(type);
break;
case QUVI_CALLBACK_STATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#else
static void status_callback_pt4(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVISTATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#endif
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
#ifdef HAVE_LIBQUVI_0_9
status_callback_pt9(status, type, ptr);
#else
status_callback_pt4(status, type, ptr);
#endif
cc::log << std::flush;
return QUVI_OK;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
namespace po = boost::program_options;
typedef std::vector<std::string> vst;
static application::exit_status
print_streams(const quvi::query& query, const quvi::options &qopts,
const vst& input_urls)
{
const size_t n = input_urls.size();
size_t i = 0;
foreach (const std::string& url, input_urls)
{
try
{
print_checking(++i,n);
query.setup_curl();
const std::string r = query.streams(url, qopts);
print_done();
if (cc::opts.flags.print_streams)
{
vst a;
boost::split(a, r, boost::is_any_of("|,"));
foreach (const std::string s, a)
{
cc::log << s << "\n";
}
}
else
cc::log << std::setw(10) << r << " : " << url << std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
return application::error;
}
}
return application::ok;
}
static void parse_prefer_format(const std::string& url, std::string& fmt,
const po::variables_map& map)
{
vst vb, va = map["prefer-format"].as<vst>();
foreach (const std::string s, va)
{
boost::split(vb, s, boost::is_any_of(":"));
if (vb.size() == 2)
{
// vb[0] = pattern
// vb[1] = format
if (cc::re::grep(vb[0], url))
{
fmt = vb[1];
return;
}
}
vb.clear();
}
}
static void set_stream(const std::string& url, quvi::options& qopts,
const po::variables_map& map)
{
std::string s = "default";
if (map.count("stream"))
s = map["stream"].as<std::string>();
else
{
if (map.count("prefer-format"))
parse_prefer_format(url, s, map);
}
qopts.stream = s;
}
static const char copyr[] =
"\n\nCopyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>\n"
"cclive comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of\n"
"cclive under the terms of the GNU Affero General Public License version\n"
"3 or later. For more information, see "
"<http://www.gnu.org/licenses/agpl.html>.\n\n"
"To contact the developers, please mail to "
"<cclive-devel@lists.sourceforge.net>";
static const application::exit_status print_version()
{
std::cout
<< "cclive "
#ifdef VN
<< VN
#else
<< PACKAGE_VERSION
#endif
<< "\n built on "
<< BUILD_TIME
<< " for " << CANONICAL_TARGET
<< "\n libquvi "
<< quvi::version()
<< "\n libquvi-scripts "
<< quvi_version(QUVI_VERSION_SCRIPTS)
<< copyr
<< std::endl;
return application::ok;
}
application::exit_status application::exec(int argc, char **argv)
{
try
{
opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return application::error;
}
const po::variables_map map = cc::opts.map();
// Dump and terminate options.
if (opts.flags.help)
{
std::cout << opts << std::flush;
return application::ok;
}
else if (opts.flags.print_config)
{
opts.dump();
return application::ok;
}
else if (opts.flags.version)
return print_version();
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (opts.flags.support)
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return application::ok;
}
// Parse input.
const vst input_urls = cc::input().urls();
const size_t n = input_urls.size();
if (n == 0)
{
std::clog << "error: no input URL" << std::endl;
return application::error;
}
// Set up quvi.
quvi::options qopts;
qopts.useragent = map["agent"].as<std::string>(); /* libquvi 0.9+ */
qopts.resolve = ! opts.flags.no_resolve;
qopts.statusfunc = status_callback;
// Omit flag.
bool omit = opts.flags.quiet;
// Go to background.
#ifdef HAVE_FORK
const bool background_given = opts.flags.background;
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Print streams.
if (opts.flags.print_streams)
return print_streams(query, qopts, input_urls);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
exit_status es = ok;
foreach(const std::string& url, input_urls)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
set_stream(url, qopts, map);
_curl = query.setup_curl();
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
if (e.cannot_retry())
throw e;
else
print_quvi_error(e);
}
cc::get(m, _curl);
break; // Stop retrying.
}
es = ok;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
es = application::error;
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
es = application::error;
}
}
return es;
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<|endoftext|> |
<commit_before>// Copyright 2012 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 "config.h"
#include "ThrottledTextureUploader.h"
#include "Extensions3DChromium.h"
#include "TraceEvent.h"
#include <algorithm>
#include <public/Platform.h>
#include <public/WebGraphicsContext3D.h>
#include <vector>
namespace {
// How many previous uploads to use when predicting future throughput.
static const size_t uploadHistorySize = 100;
// Global estimated number of textures per second to maintain estimates across
// subsequent instances of ThrottledTextureUploader.
// More than one thread will not access this variable, so we do not need to synchronize access.
static double estimatedTexturesPerSecondGlobal = 48.0 * 60.0;
} // anonymous namespace
namespace cc {
ThrottledTextureUploader::Query::Query(WebKit::WebGraphicsContext3D* context)
: m_context(context)
, m_queryId(0)
, m_value(0)
, m_hasValue(false)
, m_isNonBlocking(false)
{
m_queryId = m_context->createQueryEXT();
}
ThrottledTextureUploader::Query::~Query()
{
m_context->deleteQueryEXT(m_queryId);
}
void ThrottledTextureUploader::Query::begin()
{
m_hasValue = false;
m_isNonBlocking = false;
m_context->beginQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM, m_queryId);
}
void ThrottledTextureUploader::Query::end()
{
m_context->endQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM);
}
bool ThrottledTextureUploader::Query::isPending()
{
unsigned available = 1;
m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_AVAILABLE_EXT, &available);
return !available;
}
void ThrottledTextureUploader::Query::wait()
{
value();
return;
}
unsigned ThrottledTextureUploader::Query::value()
{
if (!m_hasValue) {
m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_EXT, &m_value);
m_hasValue = true;
}
return m_value;
}
void ThrottledTextureUploader::Query::markAsNonBlocking()
{
m_isNonBlocking = true;
}
bool ThrottledTextureUploader::Query::isNonBlocking()
{
return m_isNonBlocking;
}
ThrottledTextureUploader::ThrottledTextureUploader(WebKit::WebGraphicsContext3D* context)
: m_context(context)
, m_texturesPerSecondHistory(uploadHistorySize, estimatedTexturesPerSecondGlobal)
, m_numBlockingTextureUploads(0)
{
}
ThrottledTextureUploader::~ThrottledTextureUploader()
{
}
size_t ThrottledTextureUploader::numBlockingUploads()
{
processQueries();
return m_numBlockingTextureUploads;
}
void ThrottledTextureUploader::markPendingUploadsAsNonBlocking()
{
for (Deque<OwnPtr<Query> >::iterator it = m_pendingQueries.begin();
it != m_pendingQueries.end(); ++it) {
if (it->get()->isNonBlocking())
continue;
m_numBlockingTextureUploads--;
it->get()->markAsNonBlocking();
}
ASSERT(!m_numBlockingTextureUploads);
}
double ThrottledTextureUploader::estimatedTexturesPerSecond()
{
processQueries();
// The history should never be empty because we initialize all elements with an estimate.
ASSERT(m_texturesPerSecondHistory.size() == uploadHistorySize);
// Sort the history and use the median as our estimate.
std::vector<double> sortedHistory(m_texturesPerSecondHistory.begin(),
m_texturesPerSecondHistory.end());
std::sort(sortedHistory.begin(), sortedHistory.end());
estimatedTexturesPerSecondGlobal = sortedHistory[sortedHistory.size() * 2 / 3];
TRACE_COUNTER1("cc", "estimatedTexturesPerSecond", estimatedTexturesPerSecondGlobal);
return estimatedTexturesPerSecondGlobal;
}
void ThrottledTextureUploader::beginQuery()
{
processQueries();
if (m_availableQueries.isEmpty())
m_availableQueries.append(Query::create(m_context));
m_availableQueries.first()->begin();
}
void ThrottledTextureUploader::endQuery()
{
m_availableQueries.first()->end();
m_pendingQueries.append(m_availableQueries.takeFirst());
m_numBlockingTextureUploads++;
}
void ThrottledTextureUploader::uploadTexture(CCResourceProvider* resourceProvider, Parameters upload)
{
bool isFullUpload = upload.destOffset.isZero() &&
upload.sourceRect.size() == upload.texture->texture()->size();
if (isFullUpload)
beginQuery();
upload.texture->updateRect(resourceProvider, upload.sourceRect, upload.destOffset);
if (isFullUpload)
endQuery();
}
void ThrottledTextureUploader::processQueries()
{
while (!m_pendingQueries.isEmpty()) {
if (m_pendingQueries.first()->isPending())
break;
unsigned usElapsed = m_pendingQueries.first()->value();
WebKit::Platform::current()->histogramCustomCounts("Renderer4.TextureGpuUploadTimeUS", usElapsed, 0, 100000, 50);
if (!m_pendingQueries.first()->isNonBlocking())
m_numBlockingTextureUploads--;
// Remove the oldest values from our history and insert the new one
double texturesPerSecond = 1.0 / (usElapsed * 1e-6);
m_texturesPerSecondHistory.pop_back();
m_texturesPerSecondHistory.push_front(texturesPerSecond);
m_availableQueries.append(m_pendingQueries.takeFirst());
}
}
}
<commit_msg>This gets rid of the implicit flushes processQueries was inserting between most texture uploads.<commit_after>// Copyright 2012 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 "config.h"
#include "ThrottledTextureUploader.h"
#include "Extensions3DChromium.h"
#include "TraceEvent.h"
#include <algorithm>
#include <public/Platform.h>
#include <public/WebGraphicsContext3D.h>
#include <vector>
namespace {
// How many previous uploads to use when predicting future throughput.
static const size_t uploadHistorySize = 100;
// Global estimated number of textures per second to maintain estimates across
// subsequent instances of ThrottledTextureUploader.
// More than one thread will not access this variable, so we do not need to synchronize access.
static double estimatedTexturesPerSecondGlobal = 48.0 * 60.0;
} // anonymous namespace
namespace cc {
ThrottledTextureUploader::Query::Query(WebKit::WebGraphicsContext3D* context)
: m_context(context)
, m_queryId(0)
, m_value(0)
, m_hasValue(false)
, m_isNonBlocking(false)
{
m_queryId = m_context->createQueryEXT();
}
ThrottledTextureUploader::Query::~Query()
{
m_context->deleteQueryEXT(m_queryId);
}
void ThrottledTextureUploader::Query::begin()
{
m_hasValue = false;
m_isNonBlocking = false;
m_context->beginQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM, m_queryId);
}
void ThrottledTextureUploader::Query::end()
{
m_context->endQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM);
}
bool ThrottledTextureUploader::Query::isPending()
{
unsigned available = 1;
m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_AVAILABLE_EXT, &available);
return !available;
}
void ThrottledTextureUploader::Query::wait()
{
value();
return;
}
unsigned ThrottledTextureUploader::Query::value()
{
if (!m_hasValue) {
m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_EXT, &m_value);
m_hasValue = true;
}
return m_value;
}
void ThrottledTextureUploader::Query::markAsNonBlocking()
{
m_isNonBlocking = true;
}
bool ThrottledTextureUploader::Query::isNonBlocking()
{
return m_isNonBlocking;
}
ThrottledTextureUploader::ThrottledTextureUploader(WebKit::WebGraphicsContext3D* context)
: m_context(context)
, m_texturesPerSecondHistory(uploadHistorySize, estimatedTexturesPerSecondGlobal)
, m_numBlockingTextureUploads(0)
{
}
ThrottledTextureUploader::~ThrottledTextureUploader()
{
}
size_t ThrottledTextureUploader::numBlockingUploads()
{
processQueries();
return m_numBlockingTextureUploads;
}
void ThrottledTextureUploader::markPendingUploadsAsNonBlocking()
{
for (Deque<OwnPtr<Query> >::iterator it = m_pendingQueries.begin();
it != m_pendingQueries.end(); ++it) {
if (it->get()->isNonBlocking())
continue;
m_numBlockingTextureUploads--;
it->get()->markAsNonBlocking();
}
ASSERT(!m_numBlockingTextureUploads);
}
double ThrottledTextureUploader::estimatedTexturesPerSecond()
{
processQueries();
// The history should never be empty because we initialize all elements with an estimate.
ASSERT(m_texturesPerSecondHistory.size() == uploadHistorySize);
// Sort the history and use the median as our estimate.
std::vector<double> sortedHistory(m_texturesPerSecondHistory.begin(),
m_texturesPerSecondHistory.end());
std::sort(sortedHistory.begin(), sortedHistory.end());
estimatedTexturesPerSecondGlobal = sortedHistory[sortedHistory.size() * 2 / 3];
TRACE_COUNTER1("cc", "estimatedTexturesPerSecond", estimatedTexturesPerSecondGlobal);
return estimatedTexturesPerSecondGlobal;
}
void ThrottledTextureUploader::beginQuery()
{
if (m_availableQueries.isEmpty())
m_availableQueries.append(Query::create(m_context));
m_availableQueries.first()->begin();
}
void ThrottledTextureUploader::endQuery()
{
m_availableQueries.first()->end();
m_pendingQueries.append(m_availableQueries.takeFirst());
m_numBlockingTextureUploads++;
}
void ThrottledTextureUploader::uploadTexture(CCResourceProvider* resourceProvider, Parameters upload)
{
bool isFullUpload = upload.destOffset.isZero() &&
upload.sourceRect.size() == upload.texture->texture()->size();
if (isFullUpload)
beginQuery();
upload.texture->updateRect(resourceProvider, upload.sourceRect, upload.destOffset);
if (isFullUpload)
endQuery();
}
void ThrottledTextureUploader::processQueries()
{
while (!m_pendingQueries.isEmpty()) {
if (m_pendingQueries.first()->isPending())
break;
unsigned usElapsed = m_pendingQueries.first()->value();
WebKit::Platform::current()->histogramCustomCounts("Renderer4.TextureGpuUploadTimeUS", usElapsed, 0, 100000, 50);
if (!m_pendingQueries.first()->isNonBlocking())
m_numBlockingTextureUploads--;
// Remove the oldest values from our history and insert the new one
double texturesPerSecond = 1.0 / (usElapsed * 1e-6);
m_texturesPerSecondHistory.pop_back();
m_texturesPerSecondHistory.push_front(texturesPerSecond);
m_availableQueries.append(m_pendingQueries.takeFirst());
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupevent.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2007-07-17 15:20:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX
#define INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX
#include <canvas/elapsedtime.hxx>
#include "event.hxx"
#include "activitiesqueue.hxx"
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
namespace slideshow {
namespace internal {
/** Little helper class, used to set Activities active again
after some sleep period.
Clients can use this class to schedule wakeup events at
the EventQueue, to avoid busy-waiting for the next
discrete time instant.
*/
class WakeupEvent : public Event,
private ::boost::noncopyable
{
public:
WakeupEvent(
::boost::shared_ptr< ::canvas::tools::ElapsedTime > const& pTimeBase,
ActivitiesQueue & rActivityQueue );
virtual void dispose();
virtual bool fire();
virtual bool isCharged() const;
virtual double getActivationTime( double nCurrentTime ) const;
/// Start the internal timer
void start();
/** Set the next timeout this object should generate.
@param nextTime
Absolute time, measured from the last start() call,
when this event should wakeup the Activity again. If
your time is relative, simply call start() just before
every setNextTimeout() call.
*/
void setNextTimeout( double nextTime );
/** Set activity to wakeup.
The activity given here will be reinserted into the
ActivitiesQueue, once the timeout is reached.
*/
void setActivity( const ActivitySharedPtr& rActivity );
private:
::canvas::tools::ElapsedTime maTimer;
double mnNextTime;
ActivitySharedPtr mpActivity;
ActivitiesQueue& mrActivityQueue;
};
typedef ::boost::shared_ptr< WakeupEvent > WakeupEventSharedPtr;
} // namespace internal
} // namespace presentation
#endif /* INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.8.46); FILE MERGED 2008/03/31 14:00:32 rt 1.8.46.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupevent.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX
#define INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX
#include <canvas/elapsedtime.hxx>
#include "event.hxx"
#include "activitiesqueue.hxx"
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
namespace slideshow {
namespace internal {
/** Little helper class, used to set Activities active again
after some sleep period.
Clients can use this class to schedule wakeup events at
the EventQueue, to avoid busy-waiting for the next
discrete time instant.
*/
class WakeupEvent : public Event,
private ::boost::noncopyable
{
public:
WakeupEvent(
::boost::shared_ptr< ::canvas::tools::ElapsedTime > const& pTimeBase,
ActivitiesQueue & rActivityQueue );
virtual void dispose();
virtual bool fire();
virtual bool isCharged() const;
virtual double getActivationTime( double nCurrentTime ) const;
/// Start the internal timer
void start();
/** Set the next timeout this object should generate.
@param nextTime
Absolute time, measured from the last start() call,
when this event should wakeup the Activity again. If
your time is relative, simply call start() just before
every setNextTimeout() call.
*/
void setNextTimeout( double nextTime );
/** Set activity to wakeup.
The activity given here will be reinserted into the
ActivitiesQueue, once the timeout is reached.
*/
void setActivity( const ActivitySharedPtr& rActivity );
private:
::canvas::tools::ElapsedTime maTimer;
double mnNextTime;
ActivitySharedPtr mpActivity;
ActivitiesQueue& mrActivityQueue;
};
typedef ::boost::shared_ptr< WakeupEvent > WakeupEventSharedPtr;
} // namespace internal
} // namespace presentation
#endif /* INCLUDED_SLIDESHOW_WAKEUPEVENT_HXX */
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file rdortp.cpp
\authors
\authors (rdo@rk9.bmstu.ru)
\date 11.06.2006
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/runtime/calc/resource/calc_resource.h"
// --------------------------------------------------------------------------------
OPEN_RDO_PARSER_NAMESPACE
int rtplex(PTR(YYSTYPE) lpval, PTR(YYLTYPE) llocp, PTR(void) lexer)
{
LEXER->m_lpval = lpval;
LEXER->m_lploc = llocp;
return LEXER->yylex();
}
void rtperror(PTR(char) message)
{
UNUSED(message);
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPResType
// --------------------------------------------------------------------------------
RDORTPResType::RDORTPResType(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, rbool permanent, TypeRDOResType type)
: RDOParserSrcInfo(src_info )
, m_number (pParser->getRTP_id())
, m_permanent (permanent )
, m_type (type )
{
pParser->insertRTPResType(LPRDORTPResType(this));
}
RDORTPResType::~RDORTPResType()
{}
LPRDORSSResource RDORTPResType::createRes(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info)
{
return rdo::Factory<RDORSSResource>::create(pParser, src_info, this);
}
void RDORTPResType::addParam(CREF(LPRDORTPParam) param)
{
if (findRTPParam(param->name()))
{
RDOParser::s_parser()->error().error(param->src_info(), rdo::format(_T(" : %s"), param->name().c_str()));
}
m_params.push_back(param);
}
void RDORTPResType::addParam(CREF(tstring) param_name, rdo::runtime::RDOType::TypeID param_typeID)
{
UNUSED(param_name );
UNUSED(param_typeID);
}
LPRDORTPParam RDORTPResType::findRTPParam(CREF(tstring) paramName) const
{
ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
return it != m_params.end() ? *it : LPRDORTPParam();
}
ruint RDORTPResType::getRTPParamNumber(CREF(tstring) paramName) const
{
ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
return it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;
}
void RDORTPResType::writeModelStructure(REF(rdo::ostream) stream) const
{
stream << getNumber() << " " << name() << " " << getParams().size() << std::endl;
for (ruint i = 0; i < getParams().size(); i++)
{
stream << " " << (i+1) << " ";
getParams().at(i)->writeModelStructure(stream);
}
}
tstring RDORTPResType::name() const
{
static tstring s_name;
s_name = src_text();
return s_name;
}
LPRDOType RDORTPResType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
UNUSED(from_src_info);
switch (pFrom->typeID())
{
case rdo::runtime::RDOType::t_pointer:
{
LPRDOType pThisRTPType(const_cast<PTR(RDORTPResType)>(this));
//!
if (pThisRTPType == pFrom)
return pThisRTPType;
//! ,
parser::g_error().push_only(src_info, _T(" "));
parser::g_error().push_only(to_src_info, to_src_info.src_text());
parser::g_error().push_done();
break;
}
default:
{
parser::g_error().push_only(src_info, rdo::format(_T(" , : %s"), from_src_info.src_text().c_str()));
parser::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
parser::g_error().push_done();
break;
}
}
return LPRDOType(NULL);
}
LPRDOValue RDORTPResType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
ASSERT(pFrom);
LPRDORTPResType pRTPResType = pFrom->typeInfo()->type().object_dynamic_cast<RDORTPResType>();
if (pRTPResType)
{
LPRDOType pThisType = const_cast<PTR(RDORTPResType)>(this);
//!
if (pThisType == pRTPResType.object_parent_cast<RDOType>())
return pFrom;
//! ,
parser::g_error().push_only(src_info, _T(" "));
parser::g_error().push_only(to_src_info, rdo::format( _T(": %s"), to_src_info.src_text().c_str()));
parser::g_error().push_only(src_info, rdo::format( _T(": %s"), pFrom->src_text().c_str()));
parser::g_error().push_only(to_src_info, to_src_info.src_text());
parser::g_error().push_done();
}
parser::g_error().push_only(src_info, rdo::format(_T(" , : %s"), pFrom->src_text().c_str()));
parser::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
parser::g_error().push_done();
return LPRDOValue(NULL);
}
rdo::runtime::LPRDOCalc RDORTPResType::calc_cast(CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
return RDOType::calc_cast(pCalc, pType);
}
rdo::runtime::RDOValue RDORTPResType::get_default() const
{
NEVER_REACH_HERE;
return rdo::runtime::RDOValue();
//return rdo::runtime::RDOValue (pResourceType,pResource);
}
Context::FindResult RDORTPResType::onSwitchContext(CREF(LPExpression) pSwitchExpression, CREF(LPRDOValue) pValue) const
{
ASSERT(pSwitchExpression);
ASSERT(pValue );
ruint parNumb = getRTPParamNumber(pValue->value().getIdentificator());
if (parNumb == RDORTPResType::UNDEFINED_PARAM)
{
RDOParser::s_parser()->error().error(pValue->src_info(), rdo::format(_T(" : %s"), pValue->value().getIdentificator().c_str()));
}
LPRDORTPParam pParam = findRTPParam(pValue->value().getIdentificator());
ASSERT(pParam);
LPExpression pExpression = rdo::Factory<Expression>::create(
pParam->getTypeInfo(),
rdo::Factory<rdo::runtime::RDOCalcGetResourceParam>::create(pSwitchExpression->calc(), parNumb),
pValue->src_info()
);
ASSERT(pExpression);
return Context::FindResult(const_cast<PTR(RDORTPResType)>(this), pExpression, pValue);
}
/*
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyMembershiftFun - -
// --------------------------------------------------------------------------------
RDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(CREF(LPRDOParser) pParser):
RDOParserObject(pParser)
{
/* for (ruint i = 0; i < m_points.size(); i++)
{
// double x = m_points[i]->getX();
}
Items::iterator it = m_points.begin();
while (it != m_points.end())
{
double x = (*it)->getX();
it++;
}
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyTerm -
// --------------------------------------------------------------------------------
RDORTPFuzzyTerm::RDORTPFuzzyTerm(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, PTR(RDORTPFuzzyMembershiftFun) pMembersfift_fun):
RDOParserObject(pParser)
{
}*/
CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - добавлена ошибка на недопустимое использование типа ресурса<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file rdortp.cpp
\authors
\authors (rdo@rk9.bmstu.ru)
\date 11.06.2006
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/runtime/calc/resource/calc_resource.h"
// --------------------------------------------------------------------------------
OPEN_RDO_PARSER_NAMESPACE
int rtplex(PTR(YYSTYPE) lpval, PTR(YYLTYPE) llocp, PTR(void) lexer)
{
LEXER->m_lpval = lpval;
LEXER->m_lploc = llocp;
return LEXER->yylex();
}
void rtperror(PTR(char) message)
{
UNUSED(message);
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPResType
// --------------------------------------------------------------------------------
RDORTPResType::RDORTPResType(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, rbool permanent, TypeRDOResType type)
: RDOParserSrcInfo(src_info )
, m_number (pParser->getRTP_id())
, m_permanent (permanent )
, m_type (type )
{
pParser->insertRTPResType(LPRDORTPResType(this));
}
RDORTPResType::~RDORTPResType()
{}
LPRDORSSResource RDORTPResType::createRes(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info)
{
return rdo::Factory<RDORSSResource>::create(pParser, src_info, this);
}
void RDORTPResType::addParam(CREF(LPRDORTPParam) param)
{
if (findRTPParam(param->name()))
{
RDOParser::s_parser()->error().error(param->src_info(), rdo::format(_T(" : %s"), param->name().c_str()));
}
m_params.push_back(param);
}
void RDORTPResType::addParam(CREF(tstring) param_name, rdo::runtime::RDOType::TypeID param_typeID)
{
UNUSED(param_name );
UNUSED(param_typeID);
}
LPRDORTPParam RDORTPResType::findRTPParam(CREF(tstring) paramName) const
{
ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
return it != m_params.end() ? *it : LPRDORTPParam();
}
ruint RDORTPResType::getRTPParamNumber(CREF(tstring) paramName) const
{
ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
return it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;
}
void RDORTPResType::writeModelStructure(REF(rdo::ostream) stream) const
{
stream << getNumber() << " " << name() << " " << getParams().size() << std::endl;
for (ruint i = 0; i < getParams().size(); i++)
{
stream << " " << (i+1) << " ";
getParams().at(i)->writeModelStructure(stream);
}
}
tstring RDORTPResType::name() const
{
static tstring s_name;
s_name = src_text();
return s_name;
}
LPRDOType RDORTPResType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
UNUSED(from_src_info);
switch (pFrom->typeID())
{
case rdo::runtime::RDOType::t_pointer:
{
LPRDOType pThisRTPType(const_cast<PTR(RDORTPResType)>(this));
//!
if (pThisRTPType == pFrom)
return pThisRTPType;
//! ,
parser::g_error().push_only(src_info, _T(" "));
parser::g_error().push_only(to_src_info, to_src_info.src_text());
parser::g_error().push_done();
break;
}
default:
{
parser::g_error().push_only(src_info, rdo::format(_T(" , : %s"), from_src_info.src_text().c_str()));
parser::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
parser::g_error().push_done();
break;
}
}
return LPRDOType(NULL);
}
LPRDOValue RDORTPResType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
ASSERT(pFrom);
LPRDORTPResType pRTPResType = pFrom->typeInfo()->type().object_dynamic_cast<RDORTPResType>();
if (pRTPResType)
{
LPRDOType pThisType = const_cast<PTR(RDORTPResType)>(this);
//!
if (pThisType == pRTPResType.object_parent_cast<RDOType>())
return pFrom;
//! ,
parser::g_error().push_only(src_info, _T(" "));
parser::g_error().push_only(to_src_info, rdo::format( _T(": %s"), to_src_info.src_text().c_str()));
parser::g_error().push_only(src_info, rdo::format( _T(": %s"), pFrom->src_text().c_str()));
parser::g_error().push_only(to_src_info, to_src_info.src_text());
parser::g_error().push_done();
}
parser::g_error().push_only(src_info, rdo::format(_T(" , : %s"), pFrom->src_text().c_str()));
parser::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
parser::g_error().push_done();
return LPRDOValue(NULL);
}
rdo::runtime::LPRDOCalc RDORTPResType::calc_cast(CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
return RDOType::calc_cast(pCalc, pType);
}
rdo::runtime::RDOValue RDORTPResType::get_default() const
{
NEVER_REACH_HERE;
return rdo::runtime::RDOValue();
//return rdo::runtime::RDOValue (pResourceType,pResource);
}
Context::FindResult RDORTPResType::onSwitchContext(CREF(LPExpression) pSwitchExpression, CREF(LPRDOValue) pValue) const
{
ASSERT(pSwitchExpression);
ASSERT(pValue );
if (!pSwitchExpression->calc())
{
RDOParser::s_parser()->error().error(
pSwitchExpression->src_info(),
rdo::format(_T(" : %s"), src_text().c_str())
);
}
ruint parNumb = getRTPParamNumber(pValue->value().getIdentificator());
if (parNumb == RDORTPResType::UNDEFINED_PARAM)
{
RDOParser::s_parser()->error().error(pValue->src_info(), rdo::format(_T(" : %s"), pValue->value().getIdentificator().c_str()));
}
LPRDORTPParam pParam = findRTPParam(pValue->value().getIdentificator());
ASSERT(pParam);
LPExpression pExpression = rdo::Factory<Expression>::create(
pParam->getTypeInfo(),
rdo::Factory<rdo::runtime::RDOCalcGetResourceParam>::create(pSwitchExpression->calc(), parNumb),
pValue->src_info()
);
ASSERT(pExpression);
return Context::FindResult(const_cast<PTR(RDORTPResType)>(this), pExpression, pValue);
}
/*
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyMembershiftFun - -
// --------------------------------------------------------------------------------
RDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(CREF(LPRDOParser) pParser):
RDOParserObject(pParser)
{
/* for (ruint i = 0; i < m_points.size(); i++)
{
// double x = m_points[i]->getX();
}
Items::iterator it = m_points.begin();
while (it != m_points.end())
{
double x = (*it)->getX();
it++;
}
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyTerm -
// --------------------------------------------------------------------------------
RDORTPFuzzyTerm::RDORTPFuzzyTerm(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, PTR(RDORTPFuzzyMembershiftFun) pMembersfift_fun):
RDOParserObject(pParser)
{
}*/
CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|> |
<commit_before>/************************************************************************
filename: CEGUIGroupBox.cpp
created: 03/23/2004
author: Lars 'Levia' Wesselius (Content Pane based on Tomas Lindquist Olsen's code)
purpose: Implementation of base class for the groupbox
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/WindowManager.h"
#include "CEGUI/elements/GroupBox.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const String GroupBox::EventNamespace("GroupBox");
const String GroupBox::WidgetTypeName("CEGUI/GroupBox");
const String GroupBox::ContentPaneName("__auto_contentpane__");
/*************************************************************************
Base class constructor
*************************************************************************/
GroupBox::GroupBox(const String& type, const String& name) :
Window(type, name)
{
// When clicked, don't rise. Required because a Groupbox does not have an actual parent child
// relation with the widgets which appear inside it.
d_riseOnClick = false;
}
GroupBox::~GroupBox()
{
}
void GroupBox::initialiseComponents()
{ // Add the auto-child which got defined in the looknfeel
Window::addChild_impl(getContentPane());
Window::initialiseComponents();
}
void GroupBox::addChild_impl(Element* element)
{
Window* wnd = dynamic_cast<Window*>(element);
if (!wnd)
{
CEGUI_THROW(AlreadyExistsException("GroupBox::addChild_impl - You can't add elements of different types than 'Window' to a Window (Window path: " + getNamePath() + ") attached."));
}
// Only add it when it's not the __auto_contentpane__ (auto-child) itself
if (wnd && wnd->getName() == ContentPaneName)
{
Window* pane = getContentPane();
if (pane)
{
pane->addChild(wnd);
}
else
{
Window::addChild_impl(wnd);
}
}
}
void GroupBox::removeChild_impl(Element* element)
{
Window* wnd = static_cast<Window*>(wnd);
if (wnd)
{ // Auto pane itself?
if (wnd->getName() == ContentPaneName)
{ // Yes
Window::removeChild_impl(wnd);
WindowManager::getSingleton().destroyWindow(wnd);
}
else
{ // Remove child from out auto pane
Window* wndPane = getContentPane();
if (wndPane)
{
wndPane->removeChild(wnd);
if (wnd->isDestroyedByParent())
{
WindowManager::getSingleton().destroyWindow(wnd);
}
}
}
}
}
Window * GroupBox::getContentPane() const
{
if (isChild(ContentPaneName))
return getChild(ContentPaneName);
return 0;
}
bool GroupBox::drawAroundWidget(const CEGUI::Window*)
{
Logger::getSingleton().logEvent("TODO: GroupBox::drawAroundWidget");
return true;
/*if (!wnd)
{
return false;
}
UVector2 widgetSize = wnd->getSize();
UVector2 widgetPosition = wnd->getPosition();
UVector2 newSize = widgetSize;
newSize.d_x.d_scale = widgetSize.d_x.d_scale + 0.04f;
newSize.d_y.d_scale = widgetSize.d_y.d_scale + 0.06f;
UVector2 newPos = widgetPosition;
newPos.d_x.d_scale = widgetPosition.d_x.d_scale - 0.02f;
newPos.d_y.d_scale = widgetPosition.d_y.d_scale - 0.04f;
this->setSize(newSize);
this->setPosition(newPos);
return true;*/
}
bool GroupBox::drawAroundWidget(const String& name)
{
return drawAroundWidget(getChild(name));
}
} // End of CEGUI namespace section
<commit_msg>Fixing quite a serious messup of mine, removing children from GroupBox works now<commit_after>/************************************************************************
filename: CEGUIGroupBox.cpp
created: 03/23/2004
author: Lars 'Levia' Wesselius (Content Pane based on Tomas Lindquist Olsen's code)
purpose: Implementation of base class for the groupbox
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/WindowManager.h"
#include "CEGUI/elements/GroupBox.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const String GroupBox::EventNamespace("GroupBox");
const String GroupBox::WidgetTypeName("CEGUI/GroupBox");
const String GroupBox::ContentPaneName("__auto_contentpane__");
/*************************************************************************
Base class constructor
*************************************************************************/
GroupBox::GroupBox(const String& type, const String& name) :
Window(type, name)
{
// When clicked, don't rise. Required because a Groupbox does not have an actual parent child
// relation with the widgets which appear inside it.
d_riseOnClick = false;
}
GroupBox::~GroupBox()
{
}
void GroupBox::initialiseComponents()
{ // Add the auto-child which got defined in the looknfeel
Window::addChild_impl(getContentPane());
Window::initialiseComponents();
}
void GroupBox::addChild_impl(Element* element)
{
Window* wnd = dynamic_cast<Window*>(element);
if (!wnd)
{
CEGUI_THROW(AlreadyExistsException("GroupBox::addChild_impl - You can't add elements of different types than 'Window' to a Window (Window path: " + getNamePath() + ") attached."));
}
// Only add it when it's not the __auto_contentpane__ (auto-child) itself
if (wnd && wnd->getName() == ContentPaneName)
{
Window* pane = getContentPane();
if (pane)
{
pane->addChild(wnd);
}
else
{
Window::addChild_impl(wnd);
}
}
}
void GroupBox::removeChild_impl(Element* element)
{
Window* wnd = static_cast<Window*>(element);
if (wnd)
{ // Auto pane itself?
if (wnd->getName() == ContentPaneName)
{ // Yes
Window::removeChild_impl(wnd);
WindowManager::getSingleton().destroyWindow(wnd);
}
else
{ // Remove child from out auto pane
Window* wndPane = getContentPane();
if (wndPane)
{
wndPane->removeChild(wnd);
if (wnd->isDestroyedByParent())
{
WindowManager::getSingleton().destroyWindow(wnd);
}
}
}
}
}
Window * GroupBox::getContentPane() const
{
if (isChild(ContentPaneName))
return getChild(ContentPaneName);
return 0;
}
bool GroupBox::drawAroundWidget(const CEGUI::Window*)
{
Logger::getSingleton().logEvent("TODO: GroupBox::drawAroundWidget");
return true;
/*if (!wnd)
{
return false;
}
UVector2 widgetSize = wnd->getSize();
UVector2 widgetPosition = wnd->getPosition();
UVector2 newSize = widgetSize;
newSize.d_x.d_scale = widgetSize.d_x.d_scale + 0.04f;
newSize.d_y.d_scale = widgetSize.d_y.d_scale + 0.06f;
UVector2 newPos = widgetPosition;
newPos.d_x.d_scale = widgetPosition.d_x.d_scale - 0.02f;
newPos.d_y.d_scale = widgetPosition.d_y.d_scale - 0.04f;
this->setSize(newSize);
this->setPosition(newPos);
return true;*/
}
bool GroupBox::drawAroundWidget(const String& name)
{
return drawAroundWidget(getChild(name));
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: collect.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-02-27 11:53:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_COLLECT_HXX
#define SC_COLLECT_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#define MAXCOLLECTIONSIZE 16384
#define MAXDELTA 1024
#define SCPOS_INVALID USHRT_MAX
#define SC_STRTYPE_VALUE 0
#define SC_STRTYPE_STANDARD 1
class ScDocument;
class DataObject
{
public:
DataObject() {}
virtual ~DataObject();
virtual DataObject* Clone() const = 0;
};
class SC_DLLPUBLIC Collection : public DataObject
{
protected:
USHORT nCount;
USHORT nLimit;
USHORT nDelta;
DataObject** pItems;
public:
Collection(USHORT nLim = 4, USHORT nDel = 4);
Collection(const Collection& rCollection);
virtual ~Collection();
virtual DataObject* Clone() const;
void AtFree(USHORT nIndex);
void Free(DataObject* pDataObject);
void FreeAll();
BOOL AtInsert(USHORT nIndex, DataObject* pDataObject);
virtual BOOL Insert(DataObject* pDataObject);
DataObject* At(USHORT nIndex) const;
virtual USHORT IndexOf(DataObject* pDataObject) const;
USHORT GetCount() const { return nCount; }
DataObject* operator[]( const USHORT nIndex) const {return At(nIndex);}
Collection& operator=( const Collection& rCol );
};
class SC_DLLPUBLIC SortedCollection : public Collection
{
private:
BOOL bDuplicates;
protected:
// fuer StrCollection Load/Store
void SetDups( BOOL bVal ) { bDuplicates = bVal; }
BOOL IsDups() const { return bDuplicates; }
public:
SortedCollection(USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE);
SortedCollection(const SortedCollection& rSortedCollection) :
Collection(rSortedCollection),
bDuplicates(rSortedCollection.bDuplicates) {}
virtual USHORT IndexOf(DataObject* pDataObject) const;
virtual short Compare(DataObject* pKey1, DataObject* pKey2) const = 0;
virtual BOOL IsEqual(DataObject* pKey1, DataObject* pKey2) const;
BOOL Search(DataObject* pDataObject, USHORT& rIndex) const;
virtual BOOL Insert(DataObject* pDataObject);
virtual BOOL InsertPos(DataObject* pDataObject, USHORT& nIndex);
BOOL operator==(const SortedCollection& rCmp) const;
};
//------------------------------------------------------------------------
class StrData : public DataObject
{
friend class StrCollection;
String aStr;
public:
StrData(const String& rStr) : aStr(rStr) {}
StrData(const StrData& rData) : DataObject(), aStr(rData.aStr) {}
virtual DataObject* Clone() const;
const String& GetString() const { return aStr; }
// SetString nur, wenn StrData nicht in StrCollection ist! !!!
// z.B. fuer Searcher
void SetString( const String& rNew ) { aStr = rNew; }
};
//------------------------------------------------------------------------
class SvStream;
class SC_DLLPUBLIC StrCollection : public SortedCollection
{
public:
StrCollection(USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE) :
SortedCollection ( nLim, nDel, bDup ) {}
StrCollection(const StrCollection& rStrCollection) :
SortedCollection ( rStrCollection ) {}
virtual DataObject* Clone() const;
StrData* operator[]( const USHORT nIndex) const {return (StrData*)At(nIndex);}
virtual short Compare(DataObject* pKey1, DataObject* pKey2) const;
void Load( SvStream& );
void Store( SvStream& ) const;
};
//------------------------------------------------------------------------
// TypedStrCollection: wie StrCollection, nur, dass Zahlen vor Strings
// sortiert werden
class TypedStrData : public DataObject
{
public:
TypedStrData( const String& rStr, double nVal = 0.0,
USHORT nType = SC_STRTYPE_STANDARD )
: aStrValue(rStr),
nValue(nVal),
nStrType(nType) {}
TypedStrData( ScDocument* pDoc, SCCOL nCol, SCROW nRow, SCTAB nTab,
BOOL bAllStrings );
TypedStrData( const TypedStrData& rCpy )
: DataObject(),
aStrValue(rCpy.aStrValue),
nValue(rCpy.nValue),
nStrType(rCpy.nStrType) {}
virtual DataObject* Clone() const;
BOOL IsStrData() const { return nStrType != 0; }
const String& GetString() const { return aStrValue; }
double GetValue () const { return nValue; }
private:
friend class TypedStrCollection;
friend class PivotStrCollection;
String aStrValue;
double nValue;
USHORT nStrType; // 0 = Value
};
class SC_DLLPUBLIC TypedStrCollection : public SortedCollection
{
private:
BOOL bCaseSensitive;
public:
TypedStrCollection( USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE )
: SortedCollection( nLim, nDel, bDup ) { bCaseSensitive = FALSE; }
TypedStrCollection( const TypedStrCollection& rCpy )
: SortedCollection( rCpy ) { bCaseSensitive = rCpy.bCaseSensitive; }
virtual DataObject* Clone() const;
virtual short Compare( DataObject* pKey1, DataObject* pKey2 ) const;
TypedStrData* operator[]( const USHORT nIndex) const
{ return (TypedStrData*)At(nIndex); }
void SetCaseSensitive( BOOL bSet ) { bCaseSensitive = bSet; }
BOOL FindText( const String& rStart, String& rResult, USHORT& rPos, BOOL bBack ) const;
BOOL GetExactMatch( String& rString ) const;
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.330); FILE MERGED 2008/04/01 15:29:21 thb 1.5.330.3: #i85898# Stripping all external header guards 2008/04/01 12:35:52 thb 1.5.330.2: #i85898# Stripping all external header guards 2008/03/31 17:13:27 rt 1.5.330.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: collect.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_COLLECT_HXX
#define SC_COLLECT_HXX
#include "address.hxx"
#include <tools/string.hxx>
#ifndef INCLUDED_LIMITS_H
#include <limits.h>
#define INCLUDED_LIMITS_H
#endif
#include "scdllapi.h"
#define MAXCOLLECTIONSIZE 16384
#define MAXDELTA 1024
#define SCPOS_INVALID USHRT_MAX
#define SC_STRTYPE_VALUE 0
#define SC_STRTYPE_STANDARD 1
class ScDocument;
class DataObject
{
public:
DataObject() {}
virtual ~DataObject();
virtual DataObject* Clone() const = 0;
};
class SC_DLLPUBLIC Collection : public DataObject
{
protected:
USHORT nCount;
USHORT nLimit;
USHORT nDelta;
DataObject** pItems;
public:
Collection(USHORT nLim = 4, USHORT nDel = 4);
Collection(const Collection& rCollection);
virtual ~Collection();
virtual DataObject* Clone() const;
void AtFree(USHORT nIndex);
void Free(DataObject* pDataObject);
void FreeAll();
BOOL AtInsert(USHORT nIndex, DataObject* pDataObject);
virtual BOOL Insert(DataObject* pDataObject);
DataObject* At(USHORT nIndex) const;
virtual USHORT IndexOf(DataObject* pDataObject) const;
USHORT GetCount() const { return nCount; }
DataObject* operator[]( const USHORT nIndex) const {return At(nIndex);}
Collection& operator=( const Collection& rCol );
};
class SC_DLLPUBLIC SortedCollection : public Collection
{
private:
BOOL bDuplicates;
protected:
// fuer StrCollection Load/Store
void SetDups( BOOL bVal ) { bDuplicates = bVal; }
BOOL IsDups() const { return bDuplicates; }
public:
SortedCollection(USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE);
SortedCollection(const SortedCollection& rSortedCollection) :
Collection(rSortedCollection),
bDuplicates(rSortedCollection.bDuplicates) {}
virtual USHORT IndexOf(DataObject* pDataObject) const;
virtual short Compare(DataObject* pKey1, DataObject* pKey2) const = 0;
virtual BOOL IsEqual(DataObject* pKey1, DataObject* pKey2) const;
BOOL Search(DataObject* pDataObject, USHORT& rIndex) const;
virtual BOOL Insert(DataObject* pDataObject);
virtual BOOL InsertPos(DataObject* pDataObject, USHORT& nIndex);
BOOL operator==(const SortedCollection& rCmp) const;
};
//------------------------------------------------------------------------
class StrData : public DataObject
{
friend class StrCollection;
String aStr;
public:
StrData(const String& rStr) : aStr(rStr) {}
StrData(const StrData& rData) : DataObject(), aStr(rData.aStr) {}
virtual DataObject* Clone() const;
const String& GetString() const { return aStr; }
// SetString nur, wenn StrData nicht in StrCollection ist! !!!
// z.B. fuer Searcher
void SetString( const String& rNew ) { aStr = rNew; }
};
//------------------------------------------------------------------------
class SvStream;
class SC_DLLPUBLIC StrCollection : public SortedCollection
{
public:
StrCollection(USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE) :
SortedCollection ( nLim, nDel, bDup ) {}
StrCollection(const StrCollection& rStrCollection) :
SortedCollection ( rStrCollection ) {}
virtual DataObject* Clone() const;
StrData* operator[]( const USHORT nIndex) const {return (StrData*)At(nIndex);}
virtual short Compare(DataObject* pKey1, DataObject* pKey2) const;
void Load( SvStream& );
void Store( SvStream& ) const;
};
//------------------------------------------------------------------------
// TypedStrCollection: wie StrCollection, nur, dass Zahlen vor Strings
// sortiert werden
class TypedStrData : public DataObject
{
public:
TypedStrData( const String& rStr, double nVal = 0.0,
USHORT nType = SC_STRTYPE_STANDARD )
: aStrValue(rStr),
nValue(nVal),
nStrType(nType) {}
TypedStrData( ScDocument* pDoc, SCCOL nCol, SCROW nRow, SCTAB nTab,
BOOL bAllStrings );
TypedStrData( const TypedStrData& rCpy )
: DataObject(),
aStrValue(rCpy.aStrValue),
nValue(rCpy.nValue),
nStrType(rCpy.nStrType) {}
virtual DataObject* Clone() const;
BOOL IsStrData() const { return nStrType != 0; }
const String& GetString() const { return aStrValue; }
double GetValue () const { return nValue; }
private:
friend class TypedStrCollection;
friend class PivotStrCollection;
String aStrValue;
double nValue;
USHORT nStrType; // 0 = Value
};
class SC_DLLPUBLIC TypedStrCollection : public SortedCollection
{
private:
BOOL bCaseSensitive;
public:
TypedStrCollection( USHORT nLim = 4, USHORT nDel = 4, BOOL bDup = FALSE )
: SortedCollection( nLim, nDel, bDup ) { bCaseSensitive = FALSE; }
TypedStrCollection( const TypedStrCollection& rCpy )
: SortedCollection( rCpy ) { bCaseSensitive = rCpy.bCaseSensitive; }
virtual DataObject* Clone() const;
virtual short Compare( DataObject* pKey1, DataObject* pKey2 ) const;
TypedStrData* operator[]( const USHORT nIndex) const
{ return (TypedStrData*)At(nIndex); }
void SetCaseSensitive( BOOL bSet ) { bCaseSensitive = bSet; }
BOOL FindText( const String& rStart, String& rResult, USHORT& rPos, BOOL bBack ) const;
BOOL GetExactMatch( String& rString ) const;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximppage.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2007-08-28 13:34:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XIMPPAGE_HXX
#define _XIMPPAGE_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef _XIMPSHAPE_HXX
#include "ximpshap.hxx"
#endif
//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)
class SdXMLGenericPageContext : public SvXMLImportContext
{
// the shape group this group is working on
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;
protected:
rtl::OUString maPageLayoutName;
rtl::OUString maUseHeaderDeclName;
rtl::OUString maUseFooterDeclName;
rtl::OUString maUseDateTimeDeclName;
rtl::OUString msNavOrder;
void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
{ mxShapes = rNew; }
/** sets the page style on this page */
void SetStyle( rtl::OUString& rStyleName );
/** sets the presentation layout at this page. It is used for drawing pages and for the handout master */
void SetLayout();
/** deletes all shapes on this drawing page */
void DeleteAllShapes();
const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }
/** sets the properties from a page master style with the given name on this contexts page */
void SetPageMaster( rtl::OUString& rsPageMasterName );
void SetNavigationOrder();
public:
TYPEINFO();
SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
virtual ~SdXMLGenericPageContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual SvXMLImportContext *CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
{ return mxShapes; }
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
{ return mxShapes; }
};
#endif // _XIMPGROUP_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.9.120); FILE MERGED 2008/04/01 16:09:43 thb 1.9.120.3: #i85898# Stripping all external header guards 2008/04/01 13:04:46 thb 1.9.120.2: #i85898# Stripping all external header guards 2008/03/31 16:28:08 rt 1.9.120.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ximppage.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XIMPPAGE_HXX
#define _XIMPPAGE_HXX
#include <xmloff/xmlictxt.hxx>
#include "sdxmlimp_impl.hxx"
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/drawing/XShapes.hpp>
#include <tools/rtti.hxx>
#include "ximpshap.hxx"
//////////////////////////////////////////////////////////////////////////////
// draw:g context (RECURSIVE)
class SdXMLGenericPageContext : public SvXMLImportContext
{
// the shape group this group is working on
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;
protected:
rtl::OUString maPageLayoutName;
rtl::OUString maUseHeaderDeclName;
rtl::OUString maUseFooterDeclName;
rtl::OUString maUseDateTimeDeclName;
rtl::OUString msNavOrder;
void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)
{ mxShapes = rNew; }
/** sets the page style on this page */
void SetStyle( rtl::OUString& rStyleName );
/** sets the presentation layout at this page. It is used for drawing pages and for the handout master */
void SetLayout();
/** deletes all shapes on this drawing page */
void DeleteAllShapes();
const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }
SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }
/** sets the properties from a page master style with the given name on this contexts page */
void SetPageMaster( rtl::OUString& rsPageMasterName );
void SetNavigationOrder();
public:
TYPEINFO();
SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);
virtual ~SdXMLGenericPageContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual SvXMLImportContext *CreateChildContext(
USHORT nPrefix, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const
{ return mxShapes; }
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()
{ return mxShapes; }
};
#endif // _XIMPGROUP_HXX
<|endoftext|> |
<commit_before>#pragma once
#include <xcb/xcb.h>
#include <string>
#include <unordered_map>
#include "common.hpp"
POLYBAR_NS
// fwd
struct randr_output;
using monitor_t = shared_ptr<randr_output>;
struct enum_hash {
template <typename T>
inline typename std::enable_if<std::is_enum<T>::value, size_t>::type operator()(T const value) const {
return static_cast<size_t>(value);
}
};
enum class edge : uint8_t { NONE = 0U, TOP, BOTTOM, LEFT, RIGHT, ALL };
enum class alignment : uint8_t { NONE = 0U, LEFT, CENTER, RIGHT };
enum class attribute : uint8_t { NONE = 0U, UNDERLINE, OVERLINE };
enum class syntaxtag : uint8_t {
NONE = 0U,
A, // mouse action
B, // background color
F, // foreground color
T, // font index
O, // pixel offset
R, // flip colors
o, // overline color
u, // underline color
};
enum class mousebtn : uint8_t {
NONE = 0U,
LEFT,
MIDDLE,
RIGHT,
SCROLL_UP,
SCROLL_DOWN,
DOUBLE_LEFT,
DOUBLE_MIDDLE,
DOUBLE_RIGHT
};
enum class strut : uint16_t {
LEFT = 0U,
RIGHT,
TOP,
BOTTOM,
LEFT_START_Y,
LEFT_END_Y,
RIGHT_START_Y,
RIGHT_END_Y,
TOP_START_X,
TOP_END_X,
BOTTOM_START_X,
BOTTOM_END_X,
};
struct position {
int16_t x{0};
int16_t y{0};
};
struct size {
uint16_t w{1U};
uint16_t h{1U};
};
struct side_values {
uint16_t left{0U};
uint16_t right{0U};
};
struct edge_values {
uint16_t left{0U};
uint16_t right{0U};
uint16_t top{0U};
uint16_t bottom{0U};
};
struct border_settings {
uint32_t color{0xFF000000};
uint16_t size{0U};
};
struct line_settings {
uint32_t color{0xFF000000};
uint16_t size{0U};
};
struct action {
mousebtn button{mousebtn::NONE};
string command{};
};
struct action_block : public action {
alignment align{alignment::NONE};
double start_x{0.0};
double end_x{0.0};
bool active{true};
uint16_t width() const {
return static_cast<uint16_t>(end_x - start_x + 0.5);
}
bool test(int16_t point) const {
return static_cast<int16_t>(start_x) < point && static_cast<int16_t>(end_x) >= point;
}
};
struct bar_settings {
explicit bar_settings() = default;
bar_settings(const bar_settings& other) = default;
xcb_window_t window{XCB_NONE};
monitor_t monitor{};
edge origin{edge::TOP};
struct size size {
1U, 1U
};
position pos{0, 0};
position offset{0, 0};
position center{0, 0};
side_values padding{0U, 0U};
side_values margin{0U, 0U};
side_values module_margin{0U, 2U};
edge_values strut{0U, 0U, 0U, 0U};
uint32_t background{0xFFFFFFFF};
uint32_t foreground{0xFF000000};
line_settings underline{};
line_settings overline{};
std::unordered_map<edge, border_settings, enum_hash> borders{};
uint8_t spacing{0};
string separator{};
string wmname{};
string locale{};
bool override_redirect{false};
vector<action> actions{};
bool dimmed{false};
double dimvalue{1.0};
bool shaded{false};
struct size shade_size {
1U, 1U
};
position shade_pos{1U, 1U};
const xcb_rectangle_t inner_area(bool abspos = false) const {
xcb_rectangle_t rect{0, 0, size.w, size.h};
if (abspos) {
rect.x = pos.x;
rect.y = pos.y;
}
if (borders.find(edge::TOP) != borders.end()) {
rect.y += borders.at(edge::TOP).size;
rect.height -= borders.at(edge::TOP).size;
}
if (borders.find(edge::BOTTOM) != borders.end()) {
rect.height -= borders.at(edge::BOTTOM).size;
}
if (borders.find(edge::LEFT) != borders.end()) {
rect.x += borders.at(edge::LEFT).size;
rect.width -= borders.at(edge::LEFT).size;
}
if (borders.find(edge::RIGHT) != borders.end()) {
rect.width -= borders.at(edge::RIGHT).size;
}
return rect;
}
};
struct event_timer {
xcb_timestamp_t event{0L};
xcb_timestamp_t offset{1L};
bool allow(xcb_timestamp_t time) {
bool pass = time >= event + offset;
event = time;
return pass;
};
bool deny(xcb_timestamp_t time) {
return !allow(time);
};
};
POLYBAR_NS_END
<commit_msg>fix(config): Remove default value for module-margin-right<commit_after>#pragma once
#include <xcb/xcb.h>
#include <string>
#include <unordered_map>
#include "common.hpp"
POLYBAR_NS
// fwd
struct randr_output;
using monitor_t = shared_ptr<randr_output>;
struct enum_hash {
template <typename T>
inline typename std::enable_if<std::is_enum<T>::value, size_t>::type operator()(T const value) const {
return static_cast<size_t>(value);
}
};
enum class edge : uint8_t { NONE = 0U, TOP, BOTTOM, LEFT, RIGHT, ALL };
enum class alignment : uint8_t { NONE = 0U, LEFT, CENTER, RIGHT };
enum class attribute : uint8_t { NONE = 0U, UNDERLINE, OVERLINE };
enum class syntaxtag : uint8_t {
NONE = 0U,
A, // mouse action
B, // background color
F, // foreground color
T, // font index
O, // pixel offset
R, // flip colors
o, // overline color
u, // underline color
};
enum class mousebtn : uint8_t {
NONE = 0U,
LEFT,
MIDDLE,
RIGHT,
SCROLL_UP,
SCROLL_DOWN,
DOUBLE_LEFT,
DOUBLE_MIDDLE,
DOUBLE_RIGHT
};
enum class strut : uint16_t {
LEFT = 0U,
RIGHT,
TOP,
BOTTOM,
LEFT_START_Y,
LEFT_END_Y,
RIGHT_START_Y,
RIGHT_END_Y,
TOP_START_X,
TOP_END_X,
BOTTOM_START_X,
BOTTOM_END_X,
};
struct position {
int16_t x{0};
int16_t y{0};
};
struct size {
uint16_t w{1U};
uint16_t h{1U};
};
struct side_values {
uint16_t left{0U};
uint16_t right{0U};
};
struct edge_values {
uint16_t left{0U};
uint16_t right{0U};
uint16_t top{0U};
uint16_t bottom{0U};
};
struct border_settings {
uint32_t color{0xFF000000};
uint16_t size{0U};
};
struct line_settings {
uint32_t color{0xFF000000};
uint16_t size{0U};
};
struct action {
mousebtn button{mousebtn::NONE};
string command{};
};
struct action_block : public action {
alignment align{alignment::NONE};
double start_x{0.0};
double end_x{0.0};
bool active{true};
uint16_t width() const {
return static_cast<uint16_t>(end_x - start_x + 0.5);
}
bool test(int16_t point) const {
return static_cast<int16_t>(start_x) < point && static_cast<int16_t>(end_x) >= point;
}
};
struct bar_settings {
explicit bar_settings() = default;
bar_settings(const bar_settings& other) = default;
xcb_window_t window{XCB_NONE};
monitor_t monitor{};
edge origin{edge::TOP};
struct size size {
1U, 1U
};
position pos{0, 0};
position offset{0, 0};
position center{0, 0};
side_values padding{0U, 0U};
side_values margin{0U, 0U};
side_values module_margin{0U, 0U};
edge_values strut{0U, 0U, 0U, 0U};
uint32_t background{0xFFFFFFFF};
uint32_t foreground{0xFF000000};
line_settings underline{};
line_settings overline{};
std::unordered_map<edge, border_settings, enum_hash> borders{};
uint8_t spacing{0};
string separator{};
string wmname{};
string locale{};
bool override_redirect{false};
vector<action> actions{};
bool dimmed{false};
double dimvalue{1.0};
bool shaded{false};
struct size shade_size {
1U, 1U
};
position shade_pos{1U, 1U};
const xcb_rectangle_t inner_area(bool abspos = false) const {
xcb_rectangle_t rect{0, 0, size.w, size.h};
if (abspos) {
rect.x = pos.x;
rect.y = pos.y;
}
if (borders.find(edge::TOP) != borders.end()) {
rect.y += borders.at(edge::TOP).size;
rect.height -= borders.at(edge::TOP).size;
}
if (borders.find(edge::BOTTOM) != borders.end()) {
rect.height -= borders.at(edge::BOTTOM).size;
}
if (borders.find(edge::LEFT) != borders.end()) {
rect.x += borders.at(edge::LEFT).size;
rect.width -= borders.at(edge::LEFT).size;
}
if (borders.find(edge::RIGHT) != borders.end()) {
rect.width -= borders.at(edge::RIGHT).size;
}
return rect;
}
};
struct event_timer {
xcb_timestamp_t event{0L};
xcb_timestamp_t offset{1L};
bool allow(xcb_timestamp_t time) {
bool pass = time >= event + offset;
event = time;
return pass;
};
bool deny(xcb_timestamp_t time) {
return !allow(time);
};
};
POLYBAR_NS_END
<|endoftext|> |
<commit_before>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com
Copyright(c) 2014 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include <UnitTest++/UnitTest++.h>
#include "../observer.h"
//*****************************************************************************
// Notification1
//*****************************************************************************
struct Notification1
{
};
//*****************************************************************************
// Notification2
//*****************************************************************************
struct Notification2
{
};
//*****************************************************************************
// Notification3
//*****************************************************************************
struct Notification3
{
};
//*****************************************************************************
// Generic notification.
//*****************************************************************************
template <const int ID>
struct Notification
{
};
//*****************************************************************************
// The observer base type.
// Declare what notifications you want to observe and how they are passed to 'notification'.
// The Notification1 is passed by value.
// The Notification2 is passed by reference.
// The Notification3 is passed by const reference.
//*****************************************************************************
typedef etl::observer<Notification1, Notification2&, const Notification3&> ObserverType;
//*****************************************************************************
// The concrete observable 1 class.
//*****************************************************************************
class Observable1 : public etl::observable<ObserverType, 2>
{
public:
Notification1 data1;
Notification2 data2;
//*********************************
// Notify all of the observers.
//*********************************
void send_notifications()
{
notify_observers(data1);
notify_observers(data2);
}
};
//*****************************************************************************
// The concrete observable 2 class.
//*****************************************************************************
class Observable2 : public etl::observable<ObserverType, 2>
{
public:
Notification3 data3;
//*********************************
// Notify all of the observers.
//*********************************
void send_notifications()
{
notify_observers(data3);
}
};
//*****************************************************************************
// The first observer type.
// If any one of the overloads is missing or a parameter declaration is incorrect
// then the class will be 'abstract' and will not compile.
//*****************************************************************************
class Observer1 : public ObserverType
{
public:
Observer1()
: data1_count(0),
data2_count(0),
data3_count(0)
{
}
//*******************************************
// Notification1 is passed by value.
//*******************************************
void notification(Notification1 data1)
{
++data1_count;
}
//*******************************************
// Notification2 is passed by reference.
//*******************************************
void notification(Notification2& data2)
{
++data2_count;
}
//*******************************************
// Notification3 is passed by const reference.
//*******************************************
void notification(const Notification3& data3)
{
++data3_count;
}
int data1_count;
int data2_count;
int data3_count;
};
//*****************************************************************************
// The second observer type.
// If any one of the overloads is missing or a parameter declaration is incorrect
// then the class will be 'abstract' and will not compile.
//*****************************************************************************
class Observer2 : public ObserverType
{
public:
Observer2()
: data1_count(0),
data2_count(0),
data3_count(0)
{
}
//*******************************************
// Notification1 is passed by value.
//*******************************************
void notification(Notification1 data1)
{
++data1_count;
}
//*******************************************
// Notification2 is passed by reference.
//*******************************************
void notification(Notification2& data2)
{
++data2_count;
}
//*******************************************
// Notification3 is passed by const reference.
//*******************************************
void notification(const Notification3& data3)
{
++data3_count;
}
int data1_count;
int data2_count;
int data3_count;
};
namespace
{
SUITE(test_observer)
{
//*************************************************************************
TEST(test_2_observables_2_observers_3_notifications)
{
// The observable objects.
Observable1 observable1;
Observable2 observable2;
// The observer objects.
Observer1 observer1;
Observer2 observer2;
observable1.add_observer(observer1);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(1, observer1.data1_count);
CHECK_EQUAL(1, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(0, observer2.data1_count);
CHECK_EQUAL(0, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
observable2.send_notifications(); // Updates data3. observeable2 has no observers yet.
CHECK_EQUAL(1, observer1.data1_count);
CHECK_EQUAL(1, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(0, observer2.data1_count);
CHECK_EQUAL(0, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
// Add an observer to both.
observable1.add_observer(observer2);
observable2.add_observer(observer2);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(1, observer2.data1_count);
CHECK_EQUAL(1, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
observable2.send_notifications(); // Updates data3.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(1, observer2.data1_count);
CHECK_EQUAL(1, observer2.data2_count);
CHECK_EQUAL(1, observer2.data3_count);
observable1.remove_observer(observer1);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(2, observer2.data1_count);
CHECK_EQUAL(2, observer2.data2_count);
CHECK_EQUAL(1, observer2.data3_count);
observable2.send_notifications(); // Updates data3.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(2, observer2.data1_count);
CHECK_EQUAL(2, observer2.data2_count);
CHECK_EQUAL(2, observer2.data3_count);
}
//*************************************************************************
TEST(test_8_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6>, Notification<7>, Notification<8> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_7_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6>, Notification<7> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_6_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_5_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_4_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_3_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_2_notifications)
{
typedef etl::observer<Notification<1>, Notification<2> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_1_notification)
{
typedef etl::observer<Notification<1> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_observer_list)
{
class Observer : public etl::observer<Notification1>
{
void notification(Notification1) {}
};
class Observable : public etl::observable<Observer, 4>
{
};
Observable observable;
Observer observer1;
Observer observer2;
Observer observer3;
Observer observer4;
Observer observer5;
observable.add_observer(observer1);
CHECK_EQUAL(1, observable.number_of_observers());
observable.add_observer(observer2);
CHECK_EQUAL(2, observable.number_of_observers());
observable.add_observer(observer3);
CHECK_EQUAL(3, observable.number_of_observers());
observable.add_observer(observer2);
CHECK_EQUAL(3, observable.number_of_observers());
observable.add_observer(observer4);
CHECK_EQUAL(4, observable.number_of_observers());
CHECK_THROW(observable.add_observer(observer5), etl::observer_list_full);
observable.remove_observer(observer3);
CHECK_EQUAL(3, observable.number_of_observers());
observable.clear_observers();
CHECK_EQUAL(0, observable.number_of_observers());
}
}
}
<commit_msg>Fixed signed/unsigned warnings for GCC<commit_after>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com
Copyright(c) 2014 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include <UnitTest++/UnitTest++.h>
#include "../observer.h"
//*****************************************************************************
// Notification1
//*****************************************************************************
struct Notification1
{
};
//*****************************************************************************
// Notification2
//*****************************************************************************
struct Notification2
{
};
//*****************************************************************************
// Notification3
//*****************************************************************************
struct Notification3
{
};
//*****************************************************************************
// Generic notification.
//*****************************************************************************
template <const int ID>
struct Notification
{
};
//*****************************************************************************
// The observer base type.
// Declare what notifications you want to observe and how they are passed to 'notification'.
// The Notification1 is passed by value.
// The Notification2 is passed by reference.
// The Notification3 is passed by const reference.
//*****************************************************************************
typedef etl::observer<Notification1, Notification2&, const Notification3&> ObserverType;
//*****************************************************************************
// The concrete observable 1 class.
//*****************************************************************************
class Observable1 : public etl::observable<ObserverType, 2>
{
public:
Notification1 data1;
Notification2 data2;
//*********************************
// Notify all of the observers.
//*********************************
void send_notifications()
{
notify_observers(data1);
notify_observers(data2);
}
};
//*****************************************************************************
// The concrete observable 2 class.
//*****************************************************************************
class Observable2 : public etl::observable<ObserverType, 2>
{
public:
Notification3 data3;
//*********************************
// Notify all of the observers.
//*********************************
void send_notifications()
{
notify_observers(data3);
}
};
//*****************************************************************************
// The first observer type.
// If any one of the overloads is missing or a parameter declaration is incorrect
// then the class will be 'abstract' and will not compile.
//*****************************************************************************
class Observer1 : public ObserverType
{
public:
Observer1()
: data1_count(0),
data2_count(0),
data3_count(0)
{
}
//*******************************************
// Notification1 is passed by value.
//*******************************************
void notification(Notification1 data1)
{
++data1_count;
}
//*******************************************
// Notification2 is passed by reference.
//*******************************************
void notification(Notification2& data2)
{
++data2_count;
}
//*******************************************
// Notification3 is passed by const reference.
//*******************************************
void notification(const Notification3& data3)
{
++data3_count;
}
int data1_count;
int data2_count;
int data3_count;
};
//*****************************************************************************
// The second observer type.
// If any one of the overloads is missing or a parameter declaration is incorrect
// then the class will be 'abstract' and will not compile.
//*****************************************************************************
class Observer2 : public ObserverType
{
public:
Observer2()
: data1_count(0),
data2_count(0),
data3_count(0)
{
}
//*******************************************
// Notification1 is passed by value.
//*******************************************
void notification(Notification1 data1)
{
++data1_count;
}
//*******************************************
// Notification2 is passed by reference.
//*******************************************
void notification(Notification2& data2)
{
++data2_count;
}
//*******************************************
// Notification3 is passed by const reference.
//*******************************************
void notification(const Notification3& data3)
{
++data3_count;
}
int data1_count;
int data2_count;
int data3_count;
};
namespace
{
SUITE(test_observer)
{
//*************************************************************************
TEST(test_2_observables_2_observers_3_notifications)
{
// The observable objects.
Observable1 observable1;
Observable2 observable2;
// The observer objects.
Observer1 observer1;
Observer2 observer2;
observable1.add_observer(observer1);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(1, observer1.data1_count);
CHECK_EQUAL(1, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(0, observer2.data1_count);
CHECK_EQUAL(0, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
observable2.send_notifications(); // Updates data3. observeable2 has no observers yet.
CHECK_EQUAL(1, observer1.data1_count);
CHECK_EQUAL(1, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(0, observer2.data1_count);
CHECK_EQUAL(0, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
// Add an observer to both.
observable1.add_observer(observer2);
observable2.add_observer(observer2);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(1, observer2.data1_count);
CHECK_EQUAL(1, observer2.data2_count);
CHECK_EQUAL(0, observer2.data3_count);
observable2.send_notifications(); // Updates data3.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(1, observer2.data1_count);
CHECK_EQUAL(1, observer2.data2_count);
CHECK_EQUAL(1, observer2.data3_count);
observable1.remove_observer(observer1);
// Send the notifications.
observable1.send_notifications(); // Updates data1 & data2.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(2, observer2.data1_count);
CHECK_EQUAL(2, observer2.data2_count);
CHECK_EQUAL(1, observer2.data3_count);
observable2.send_notifications(); // Updates data3.
CHECK_EQUAL(2, observer1.data1_count);
CHECK_EQUAL(2, observer1.data2_count);
CHECK_EQUAL(0, observer1.data3_count);
CHECK_EQUAL(2, observer2.data1_count);
CHECK_EQUAL(2, observer2.data2_count);
CHECK_EQUAL(2, observer2.data3_count);
}
//*************************************************************************
TEST(test_8_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6>, Notification<7>, Notification<8> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_7_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6>, Notification<7> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_6_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5>, Notification<6> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_5_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4>, Notification<5> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_4_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3>, Notification<4> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_3_notifications)
{
typedef etl::observer<Notification<1>, Notification<2>, Notification<3> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_2_notifications)
{
typedef etl::observer<Notification<1>, Notification<2> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_1_notification)
{
typedef etl::observer<Notification<1> > Observer;
class Observable : public etl::observable<Observer, 1>
{
};
// This test just needs to compile without errors.
CHECK(true);
}
//*************************************************************************
TEST(test_observer_list)
{
class Observer : public etl::observer<Notification1>
{
void notification(Notification1) {}
};
class Observable : public etl::observable<Observer, 4>
{
};
Observable observable;
Observer observer1;
Observer observer2;
Observer observer3;
Observer observer4;
Observer observer5;
observable.add_observer(observer1);
CHECK_EQUAL(size_t(1), observable.number_of_observers());
observable.add_observer(observer2);
CHECK_EQUAL(size_t(2), observable.number_of_observers());
observable.add_observer(observer3);
CHECK_EQUAL(size_t(3), observable.number_of_observers());
observable.add_observer(observer2);
CHECK_EQUAL(size_t(3), observable.number_of_observers());
observable.add_observer(observer4);
CHECK_EQUAL(size_t(4), observable.number_of_observers());
CHECK_THROW(observable.add_observer(observer5), etl::observer_list_full);
observable.remove_observer(observer3);
CHECK_EQUAL(size_t(3), observable.number_of_observers());
observable.clear_observers();
CHECK_EQUAL(size_t(0), observable.number_of_observers());
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlwrap.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2004-10-04 20:04:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XMLWRAP_HXX
#define SC_XMLWRAP_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
class ScDocument;
class SfxMedium;
class ScMySharedData;
#include <tools/errcode.hxx>
namespace com { namespace sun { namespace star {
namespace beans { class PropertyValue; }
namespace frame { class XModel; }
namespace task { class XStatusIndicator; }
namespace lang { class XMultiServiceFactory; }
namespace uno { class XInterface; }
namespace embed { class XStorage; }
namespace xml {
namespace sax { struct InputSource; } }
} } }
class ScXMLImportWrapper
{
ScDocument& rDoc;
SfxMedium* pMedium;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(
com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();
sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,
com::sun::star::xml::sax::InputSource& aParserInput,
const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,
com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
sal_Bool bMustBeSuccessfull);
sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,
com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,
const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,
const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
ScMySharedData*& pSharedData);
public:
ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);
BOOL Import(sal_Bool bStylesOnly, ErrCode& );
BOOL Export(sal_Bool bStylesOnly);
};
#endif
<commit_msg>INTEGRATION: CWS calc28 (1.13.142); FILE MERGED 2005/01/21 10:03:42 dr 1.13.142.1: #i10000# class/struct usage<commit_after>/*************************************************************************
*
* $RCSfile: xmlwrap.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2005-01-28 17:19:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XMLWRAP_HXX
#define SC_XMLWRAP_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
class ScDocument;
class SfxMedium;
class ScMySharedData;
#include <tools/errcode.hxx>
namespace com { namespace sun { namespace star {
namespace beans { struct PropertyValue; }
namespace frame { class XModel; }
namespace task { class XStatusIndicator; }
namespace lang { class XMultiServiceFactory; }
namespace uno { class XInterface; }
namespace embed { class XStorage; }
namespace xml {
namespace sax { struct InputSource; } }
} } }
class ScXMLImportWrapper
{
ScDocument& rDoc;
SfxMedium* pMedium;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(
com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);
com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();
sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,
com::sun::star::xml::sax::InputSource& aParserInput,
const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,
com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
sal_Bool bMustBeSuccessfull);
sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,
com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,
const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,
const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
ScMySharedData*& pSharedData);
public:
ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);
BOOL Import(sal_Bool bStylesOnly, ErrCode& );
BOOL Export(sal_Bool bStylesOnly);
};
#endif
<|endoftext|> |
<commit_before>#ifndef HEAPQUEUE_H
#define HEAPQUEUE_H
#include "detail/common.hpp"
#include <iomanip>
#include <tuple>
#include <vector>
#include <queue>
#include <numeric>
#include <iterator>
namespace ndtess {
namespace heap {
template <typename T>
static pqueue<T> build(const T* _lab,
const std::vector<std::size_t>& _shape,
const float* _dist){
using local_item = item<T>;
using queue = pqueue<T>;
using valloc = typename std::vector<local_item>::allocator_type;
const std::size_t len = std::accumulate(std::begin(_shape),
std::end(_shape),
1,
std::multiplies<std::size_t>()
);
const T nil = 0;
//FOR LATER: check if this cache miss due to first jumping in y and then jumping in x
// needs some attention
static constexpr int offsets_y[4] = {-1,1,0,0};
static constexpr int offsets_x[4] = {0,0,-1,1};
std::int64_t x2 = 0;
std::int64_t y2 = 0;
static constexpr T epsilon = std::numeric_limits<T>::epsilon();
pvec<T> under_heap;
queue q;
std::cout.precision(1);
for(std::int64_t y = 0;y < _shape[1];++y){
for(std::int64_t x = 0;x < _shape[0];++x){
std::size_t pix_offset = y*_shape[1] + x;
if(std::abs(_lab[pix_offset]) < epsilon)
continue;
for(int off = 0;off < 4;++off){
x2 = x + offsets_x[off];
y2 = y + offsets_y[off];
if(!( x2 >= 0 && x2 < _shape[1] && y2 >= 0 && y2 < _shape[0] ))
continue;
float res = 1. + std::abs(_dist[pix_offset] + _dist[(y2)*_shape[1] + (x2)]);
std::cout << "<> "
<< "(" << std::setw(3) << y
<< std::setw(3) << x
<< ")"
<< std::setw(4) << _dist[pix_offset] << " "
<< "(" << std::setw(3) << y2
<< std::setw(3) << x2
<< ")"
<< std::setw(4) << _dist[(y2)*_shape[1] + (x2)]
<< " " << _lab[pix_offset];
q.push(std::make_tuple(res,
x2,
y2,
_lab[pix_offset]));
auto t = q.top();
std::cout << " -> "
<< std::get<0>(t) << ", "
<< std::get<1>(t) << ", "
<< std::get<2>(t) << ", "
<< std::get<3>(t) << " " << q.size()
<< "\n";
}
}
}
return q;
}
template <typename T>
static pqueue<T> build(const T* _lab,
const std::vector<std::size_t>& _shape){
const std::size_t len = std::accumulate(std::begin(_shape),
std::end(_shape),
1,
std::multiplies<std::size_t>()
);
std::vector<float> dist(len,0.f);
return build<T>(_lab, _shape,dist.data());
}
}
}
#endif /* HEAPQUEUE_H */
<commit_msg>added traces<commit_after>#ifndef HEAPQUEUE_H
#define HEAPQUEUE_H
#include "detail/common.hpp"
#include <iomanip>
#include <tuple>
#include <vector>
#include <queue>
#include <numeric>
#include <iterator>
namespace ndtess {
namespace heap {
template <typename T>
static pqueue<T> build(const T* _lab,
const std::vector<std::size_t>& _shape,
const float* _dist){
using local_item = item<T>;
using queue = pqueue<T>;
using valloc = typename std::vector<local_item>::allocator_type;
const std::size_t len = std::accumulate(std::begin(_shape),
std::end(_shape),
1,
std::multiplies<std::size_t>()
);
std::int64_t x2 = 0;
std::int64_t y2 = 0;
static constexpr T epsilon = std::numeric_limits<T>::epsilon();
pvec<T> under_heap;
queue q;
#ifdef NDTESS_TRACE
std::cout.precision(1);
#endif
for(std::int64_t y = 0;y < _shape[ndtess::in_y];++y){
for(std::int64_t x = 0;x < _shape[ndtess::in_x];++x){
std::size_t pix_offset = y*_shape[ndtess::in_x] + x;
if(std::abs(_lab[pix_offset]) < epsilon)
continue;
for(int off = 0;off < 4;++off){
x2 = x + ndtess::offsets_x[off];
y2 = y + ndtess::offsets_y[off];
if(!( x2 >= 0 && x2 < _shape[ndtess::in_x] && y2 >= 0 && y2 < _shape[ndtess::in_y] ))
continue;
auto d1 = _dist[pix_offset];
auto d2 = _dist[(y2)*_shape[ndtess::in_x] + (x2)];
auto res = std::abs(d1 + d2) + 1.f;
#ifdef NDTESS_TRACE
std::cout << "<> "
<< "(" << std::setw(3) << y
<< std::setw(3) << x
<< ")"
<< std::setw(4) << d1 << " "
<< "(" << std::setw(3) << y2
<< std::setw(3) << x2
<< ")"
<< std::setw(4) << d2
<< " " << _lab[pix_offset];
#endif
q.push(std::make_tuple(res,
x2,
y2,
_lab[pix_offset]));
#ifdef NDTESS_TRACE
auto t = q.top();
std::cout << " -> "
<< std::get<0>(t) << ", "
<< std::get<1>(t) << ", "
<< std::get<2>(t) << ", "
<< std::get<3>(t) << " " << q.size()
<< "\n";
#endif
}
}
}
return q;
}
template <typename T>
static pqueue<T> build(const T* _lab,
const std::vector<std::size_t>& _shape){
const std::size_t len = std::accumulate(std::begin(_shape),
std::end(_shape),
1,
std::multiplies<std::size_t>()
);
std::vector<float> dist(len,0.f);
return build<T>(_lab, _shape,dist.data());
}
}
}
#endif /* HEAPQUEUE_H */
<|endoftext|> |
<commit_before>struct edge {int v, f, w, c; };
int n, m, k, s, t, f, c, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];
void add_edge(int u, int v, int w, int c) {
int k = e.size();
g[u].push_back(k);
g[v].push_back(k+1);
e.push_back({ v, 0, w, c });
e.push_back({ u, 0, -w, 0 });
}
void min_cost_max_flow() {
f = 0, c = 0;
while (f < k) {
memset(et, 0, n * sizeof et[0]);
memset(d, 63, n * sizeof d[0]);
deque<int> q;
q.push_back(s), d[s] = 0;
while (!q.empty()) {
int u = q.front(); q.pop_front();
et[u] = 2;
for(int i : g[u]) {
edge &dir = e[i];
int v = dir.v;
if (dir.f < dir.c and d[u] + dir.w < d[v]) {
d[v] = d[u] + dir.w;
if (et[v] == 0) q.push_back(v);
else if (et[v] == 2) q.push_front(v);
et[v] = 1;
p[v] = i;
}
}
}
if (d[t] > INF) break;
int inc = k - f;
for (int u=t; u != s; u = e[p[u]^1].v) {
edge &dir = e[p[u]];
inc = min(inc, dir.c - dir.f);
}
for (int u=t; u != s; u = e[p[u]^1].v) {
edge &dir = e[p[u]], &rev = e[p[u]^1];
dir.f += inc;
rev.f -= inc;
c += inc * dir.w;
}
f += inc;
}
}
<commit_msg>Made min cost flow code clearer and easier to use.<commit_after>// w: weight or cost, c : capacity
struct edge {int v, f, w, c; };
int node_count, flw_lmt=INF, src, snk, flw, cst, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];
void add_edge(int u, int v, int w, int c) {
int k = e.size();
node_count = max(node_count, u+1);
node_count = max(node_count, v+1);
g[u].push_back(k);
g[v].push_back(k+1);
e.push_back({ v, 0, w, c });
e.push_back({ u, 0, -w, 0 });
}
void clear() {
flw_lmt = INF;
for(int i=0; i<node_count; ++i) g[i].clear();
e.clear();
node_count = 0;
}
void min_cost_max_flow() {
flw = 0, cst = 0;
while (flw < flw_lmt) {
memset(et, 0, node_count * sizeof et[0]);
memset(d, 63, node_count * sizeof d[0]);
deque<int> q;
q.push_back(src), d[src] = 0;
while (!q.empty()) {
int u = q.front(); q.pop_front();
et[u] = 2;
for(int i : g[u]) {
edge &dir = e[i];
int v = dir.v;
if (dir.f < dir.c and d[u] + dir.w < d[v]) {
d[v] = d[u] + dir.w;
if (et[v] == 0) q.push_back(v);
else if (et[v] == 2) q.push_front(v);
et[v] = 1;
p[v] = i;
}
}
}
if (d[snk] > INF) break;
int inc = flw_lmt - flw;
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]];
inc = min(inc, dir.c - dir.f);
}
for (int u=snk; u != src; u = e[p[u]^1].v) {
edge &dir = e[p[u]], &rev = e[p[u]^1];
dir.f += inc;
rev.f -= inc;
cst += inc * dir.w;
}
if (!inc) break;
flw += inc;
}
}
<|endoftext|> |
<commit_before>/**
* @file disk_index.tcc
* @author Sean Massung
*/
#include <cstdio>
#include <numeric>
#include <queue>
#include <iostream>
#include <utility>
#include <sys/stat.h>
#include "index/disk_index.h"
#include "index/chunk.h"
#include "parallel/thread_pool.h"
#include "util/common.h"
#include "util/optional.h"
namespace meta {
namespace index {
template <class Index, class... Args>
Index make_index(const std::string & config_file, Args &&... args)
{
auto config = cpptoml::parse_file(config_file);
// check if we have paths specified for either kind of index
if (!(config.contains("forward-index")
&& config.contains("inverted-index"))) {
throw typename Index::disk_index_exception{
"forward-index or inverted-index missing from configuration file"
};
}
Index idx{config, std::forward<Args>(args)...};
// if index has already been made, load it
if(mkdir(idx._index_name.c_str(), 0755) == -1)
idx.load_index();
else
idx.create_index(config_file);
return idx;
}
template <class Index, template <class, class> class Cache, class... Args>
cached_index<Index, Cache> make_index(const std::string & config_file,
Args &&... args) {
return make_index<cached_index<Index, Cache>>(config_file,
std::forward<Args>(args)...);
}
template <class PrimaryKey, class SecondaryKey>
disk_index<PrimaryKey, SecondaryKey>::disk_index(
const cpptoml::toml_group & config,
const std::string & index_path):
_tokenizer{ tokenizers::tokenizer::load_tokenizer(config) },
_index_name{ index_path }
{ /* nothing */ }
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::index_name() const
{
return _index_name;
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::unique_terms(doc_id d_id) const
{
return _unique_terms.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::unique_terms() const
{
return _tokenizer->num_terms();
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::create_index(
const std::string & config_file)
{
// save the config file so we can recreate the tokenizer
std::ifstream source_config{config_file.c_str(), std::ios::binary};
std::ofstream dest_config{_index_name + "/config.toml", std::ios::binary};
dest_config << source_config.rdbuf();
// load the documents from the corpus
auto docs = corpus::corpus::load(config_file);
// reserve space for all the vectors
uint64_t num_docs = docs->size();
_doc_id_mapping.reserve(num_docs);
_doc_sizes.reserve(num_docs);
_term_bit_locations.reserve(num_docs * 3); // guess 3x
_labels.reserve(num_docs);
_unique_terms.reserve(num_docs); // guess 1x
// create postings file
uint32_t num_chunks = tokenize_docs(docs);
merge_chunks(num_chunks, _index_name + "/postings.index");
compress(_index_name + "/postings.index");
save_mapping(_doc_id_mapping, _index_name + "/docids.mapping");
save_mapping(_doc_sizes, _index_name + "/docsizes.counts");
save_mapping(_term_bit_locations, _index_name + "/lexicon.index");
save_mapping(_labels, _index_name + "/docs.labels");
save_mapping(_unique_terms, _index_name + "/docs.uniqueterms");
save_mapping(_compression_mapping, _index_name + "/keys.compressedmapping");
_tokenizer->save_term_id_mapping(_index_name + "/termids.mapping");
set_label_ids();
_postings = std::unique_ptr<io::mmap_file>{
new io::mmap_file{_index_name + "/postings.index"}
};
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::calc_compression_mapping(
const std::string & filename)
{
std::ifstream in{filename};
PostingsData pdata{PrimaryKey{0}};
std::unordered_map<uint64_t, uint64_t> freqs;
while(in >> pdata)
{
for(auto & c: pdata.counts())
{
++freqs[c.first];
++freqs[*reinterpret_cast<const uint64_t*>(&c.second)];
}
}
using pair_t = std::pair<uint64_t, uint64_t>;
std::vector<pair_t> sorted{freqs.begin(), freqs.end()};
std::sort(sorted.begin(), sorted.end(),
[](const pair_t & a, const pair_t & b) {
return a.second > b.second;
}
);
_compression_mapping.clear();
// have to know what the delimiter is, and can't use 0
uint64_t delim = std::numeric_limits<uint64_t>::max();
_compression_mapping.insert(delim, 1);
// 2 is the first valid compressed char after the delimiter 1
uint64_t counter = 2;
for(auto & p: sorted)
_compression_mapping.insert(p.first, counter++);
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::compress(
const std::string & filename)
{
std::cerr << "Calculating optimal compression mapping..." << std::endl;
calc_compression_mapping(filename);
std::string cfilename{filename + ".compressed"};
std::cerr << "Creating compressed postings file..." << std::endl;
// create scope so the writer closes and we can calculate the size of the
// file as well as rename it
{
io::compressed_file_writer out{cfilename, _compression_mapping};
PostingsData pdata{PrimaryKey{0}};
std::ifstream in{filename};
// note: we will be accessing pdata in sorted order
while(in >> pdata)
{
_term_bit_locations.push_back(out.bit_location());
pdata.write_compressed(out);
}
}
struct stat st;
stat(cfilename.c_str(), &st);
std::cerr << "Created compressed postings file ("
<< common::bytes_to_units(st.st_size) << ")" << std::endl;
remove(filename.c_str());
rename(cfilename.c_str(), filename.c_str());
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::load_index()
{
std::cerr << "Loading index from disk ("
<< _index_name << ")..." << std::endl;
auto config = cpptoml::parse_file(_index_name + "/config.toml");
load_mapping(_doc_id_mapping, _index_name + "/docids.mapping");
load_mapping(_doc_sizes, _index_name + "/docsizes.counts");
load_mapping(_term_bit_locations, _index_name + "/lexicon.index");
load_mapping(_labels, _index_name + "/docs.labels");
load_mapping(_unique_terms, _index_name + "/docs.uniqueterms");
load_mapping(_compression_mapping, _index_name + "/keys.compressedmapping");
_tokenizer = tokenizers::tokenizer::load_tokenizer(config);
_tokenizer->set_term_id_mapping(_index_name + "/termids.mapping");
set_label_ids();
_postings = std::unique_ptr<io::mmap_file>{
new io::mmap_file{_index_name + "/postings.index"}
};
}
template <class PrimaryKey, class SecondaryKey>
class_label disk_index<PrimaryKey, SecondaryKey>::label(doc_id d_id) const
{
return _labels.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
class_label
disk_index<PrimaryKey, SecondaryKey>::class_label_from_id(label_id l_id) const
{
return _label_ids.get_key(l_id);
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::set_label_ids()
{
std::unordered_set<class_label> labels;
for(auto & lbl: _labels)
labels.insert(lbl);
label_id i{0};
for(auto & lbl: labels)
_label_ids.insert(lbl, i++);
}
template <class PrimaryKey, class SecondaryKey>
label_id
disk_index<PrimaryKey, SecondaryKey>::label_id_from_doc(doc_id d_id) const
{
return _label_ids.get_value(_labels.at(d_id));
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::write_chunk(
uint32_t chunk_num,
std::vector<postings_data<PrimaryKey, SecondaryKey>> & pdata)
{
std::sort(pdata.begin(), pdata.end());
std::ofstream outfile{"chunk-" + common::to_string(chunk_num)};
for(auto & p: pdata)
outfile << p;
outfile.close();
pdata.clear();
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::merge_chunks(
uint32_t num_chunks,
const std::string & filename)
{
using chunk_t = chunk<PrimaryKey, SecondaryKey>;
// create priority queue of all chunks based on size
std::priority_queue<chunk_t> chunks;
for(uint32_t i = 0; i < num_chunks; ++i)
{
std::string filename = "chunk-" + common::to_string(i);
chunks.push(chunk_t{filename});
}
// merge the smallest two chunks together until there is only one left
// done in parallel
std::mutex mutex;
parallel::thread_pool pool;
auto thread_ids = pool.thread_ids();
std::vector<std::future<void>> futures;
std::function<void()> task;
task = [&]() {
util::optional<chunk_t> first;
util::optional<chunk_t> second;
{
std::lock_guard<std::mutex> lock{mutex};
if (chunks.size() < 2)
return;
first = util::optional<chunk_t>{chunks.top()};
chunks.pop();
second = util::optional<chunk_t>{chunks.top()};
chunks.pop();
std::cerr << " Merging " << first->path() << " ("
<< common::bytes_to_units(first->size())
<< ") and " << second->path() << " ("
<< common::bytes_to_units(second->size())
<< "), " << chunks.size() << " remaining \r";
}
first->merge_with(*second);
mutex.lock();
chunks.push(*first);
if (chunks.size() > 1) {
mutex.unlock();
task();
} else {
mutex.unlock();
}
};
for (size_t i = 0; i < thread_ids.size(); ++i) {
futures.emplace_back(pool.submit_task(task));
}
for (auto & fut : futures)
fut.get();
std::cerr << std::endl;
rename(chunks.top().path().c_str(), filename.c_str());
std::cerr << "Created uncompressed postings file " << filename
<< " (" << common::bytes_to_units(chunks.top().size()) << ")"
<< std::endl;
}
template <class PrimaryKey, class SecondaryKey>
template <class Key, class Value>
void disk_index<PrimaryKey, SecondaryKey>::save_mapping(
const util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & p: map)
outfile << p.first << " " << p.second << "\n";
}
template <class PrimaryKey, class SecondaryKey>
template <class T>
void disk_index<PrimaryKey, SecondaryKey>::save_mapping(
const std::vector<T> & vec, const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & v: vec)
outfile << v << "\n";
}
template <class PrimaryKey, class SecondaryKey>
template <class Key, class Value>
void disk_index<PrimaryKey, SecondaryKey>::load_mapping(
util::invertible_map<Key, Value> & map, const std::string & filename)
{
std::ifstream input{filename};
Key k;
Value v;
while((input >> k) && (input >> v))
map.insert(std::make_pair(k, v));
}
template <class PrimaryKey, class SecondaryKey>
template <class T>
void disk_index<PrimaryKey, SecondaryKey>::load_mapping(
std::vector<T> & vec, const std::string & filename)
{
std::ifstream input{filename};
uint64_t size = common::num_lines(filename);
vec.reserve(size);
T val;
while(input >> val)
vec.push_back(val);
}
template <class PrimaryKey, class SecondaryKey>
double disk_index<PrimaryKey, SecondaryKey>::doc_size(doc_id d_id) const
{
return _doc_sizes.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::num_docs() const
{
return _doc_sizes.size();
}
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::doc_name(doc_id d_id) const
{
auto path = doc_path(d_id);
return path.substr(path.find_last_of("/") + 1);
}
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::doc_path(doc_id d_id) const
{
return _doc_id_mapping.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
std::vector<doc_id> disk_index<PrimaryKey, SecondaryKey>::docs() const
{
std::vector<doc_id> ret(_doc_id_mapping.size());
std::iota(ret.begin(), ret.end(), 0);
return ret;
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::tokenize(corpus::document & doc)
{
_tokenizer->tokenize(doc);
}
template <class PrimaryKey, class SecondaryKey>
std::shared_ptr<postings_data<PrimaryKey, SecondaryKey>>
disk_index<PrimaryKey, SecondaryKey>::search_primary(PrimaryKey p_id) const
{
uint64_t idx{p_id};
// if the term doesn't exist in the index, return an empty postings_data
if(idx >= _term_bit_locations.size())
return std::make_shared<PostingsData>(p_id);
io::compressed_file_reader reader{*_postings, _compression_mapping};
reader.seek(_term_bit_locations.at(idx));
auto pdata = std::make_shared<PostingsData>(p_id);
pdata->read_compressed(reader);
return pdata;
}
}
}
<commit_msg>Fix progress indicator for parallel merging of chunks.<commit_after>/**
* @file disk_index.tcc
* @author Sean Massung
*/
#include <cstdio>
#include <numeric>
#include <queue>
#include <iostream>
#include <utility>
#include <sys/stat.h>
#include "index/disk_index.h"
#include "index/chunk.h"
#include "parallel/thread_pool.h"
#include "util/common.h"
#include "util/optional.h"
namespace meta {
namespace index {
template <class Index, class... Args>
Index make_index(const std::string & config_file, Args &&... args)
{
auto config = cpptoml::parse_file(config_file);
// check if we have paths specified for either kind of index
if (!(config.contains("forward-index")
&& config.contains("inverted-index"))) {
throw typename Index::disk_index_exception{
"forward-index or inverted-index missing from configuration file"
};
}
Index idx{config, std::forward<Args>(args)...};
// if index has already been made, load it
if(mkdir(idx._index_name.c_str(), 0755) == -1)
idx.load_index();
else
idx.create_index(config_file);
return idx;
}
template <class Index, template <class, class> class Cache, class... Args>
cached_index<Index, Cache> make_index(const std::string & config_file,
Args &&... args) {
return make_index<cached_index<Index, Cache>>(config_file,
std::forward<Args>(args)...);
}
template <class PrimaryKey, class SecondaryKey>
disk_index<PrimaryKey, SecondaryKey>::disk_index(
const cpptoml::toml_group & config,
const std::string & index_path):
_tokenizer{ tokenizers::tokenizer::load_tokenizer(config) },
_index_name{ index_path }
{ /* nothing */ }
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::index_name() const
{
return _index_name;
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::unique_terms(doc_id d_id) const
{
return _unique_terms.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::unique_terms() const
{
return _tokenizer->num_terms();
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::create_index(
const std::string & config_file)
{
// save the config file so we can recreate the tokenizer
std::ifstream source_config{config_file.c_str(), std::ios::binary};
std::ofstream dest_config{_index_name + "/config.toml", std::ios::binary};
dest_config << source_config.rdbuf();
// load the documents from the corpus
auto docs = corpus::corpus::load(config_file);
// reserve space for all the vectors
uint64_t num_docs = docs->size();
_doc_id_mapping.reserve(num_docs);
_doc_sizes.reserve(num_docs);
_term_bit_locations.reserve(num_docs * 3); // guess 3x
_labels.reserve(num_docs);
_unique_terms.reserve(num_docs); // guess 1x
// create postings file
uint32_t num_chunks = tokenize_docs(docs);
merge_chunks(num_chunks, _index_name + "/postings.index");
compress(_index_name + "/postings.index");
save_mapping(_doc_id_mapping, _index_name + "/docids.mapping");
save_mapping(_doc_sizes, _index_name + "/docsizes.counts");
save_mapping(_term_bit_locations, _index_name + "/lexicon.index");
save_mapping(_labels, _index_name + "/docs.labels");
save_mapping(_unique_terms, _index_name + "/docs.uniqueterms");
save_mapping(_compression_mapping, _index_name + "/keys.compressedmapping");
_tokenizer->save_term_id_mapping(_index_name + "/termids.mapping");
set_label_ids();
_postings = std::unique_ptr<io::mmap_file>{
new io::mmap_file{_index_name + "/postings.index"}
};
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::calc_compression_mapping(
const std::string & filename)
{
std::ifstream in{filename};
PostingsData pdata{PrimaryKey{0}};
std::unordered_map<uint64_t, uint64_t> freqs;
while(in >> pdata)
{
for(auto & c: pdata.counts())
{
++freqs[c.first];
++freqs[*reinterpret_cast<const uint64_t*>(&c.second)];
}
}
using pair_t = std::pair<uint64_t, uint64_t>;
std::vector<pair_t> sorted{freqs.begin(), freqs.end()};
std::sort(sorted.begin(), sorted.end(),
[](const pair_t & a, const pair_t & b) {
return a.second > b.second;
}
);
_compression_mapping.clear();
// have to know what the delimiter is, and can't use 0
uint64_t delim = std::numeric_limits<uint64_t>::max();
_compression_mapping.insert(delim, 1);
// 2 is the first valid compressed char after the delimiter 1
uint64_t counter = 2;
for(auto & p: sorted)
_compression_mapping.insert(p.first, counter++);
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::compress(
const std::string & filename)
{
std::cerr << "Calculating optimal compression mapping..." << std::endl;
calc_compression_mapping(filename);
std::string cfilename{filename + ".compressed"};
std::cerr << "Creating compressed postings file..." << std::endl;
// create scope so the writer closes and we can calculate the size of the
// file as well as rename it
{
io::compressed_file_writer out{cfilename, _compression_mapping};
PostingsData pdata{PrimaryKey{0}};
std::ifstream in{filename};
// note: we will be accessing pdata in sorted order
while(in >> pdata)
{
_term_bit_locations.push_back(out.bit_location());
pdata.write_compressed(out);
}
}
struct stat st;
stat(cfilename.c_str(), &st);
std::cerr << "Created compressed postings file ("
<< common::bytes_to_units(st.st_size) << ")" << std::endl;
remove(filename.c_str());
rename(cfilename.c_str(), filename.c_str());
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::load_index()
{
std::cerr << "Loading index from disk ("
<< _index_name << ")..." << std::endl;
auto config = cpptoml::parse_file(_index_name + "/config.toml");
load_mapping(_doc_id_mapping, _index_name + "/docids.mapping");
load_mapping(_doc_sizes, _index_name + "/docsizes.counts");
load_mapping(_term_bit_locations, _index_name + "/lexicon.index");
load_mapping(_labels, _index_name + "/docs.labels");
load_mapping(_unique_terms, _index_name + "/docs.uniqueterms");
load_mapping(_compression_mapping, _index_name + "/keys.compressedmapping");
_tokenizer = tokenizers::tokenizer::load_tokenizer(config);
_tokenizer->set_term_id_mapping(_index_name + "/termids.mapping");
set_label_ids();
_postings = std::unique_ptr<io::mmap_file>{
new io::mmap_file{_index_name + "/postings.index"}
};
}
template <class PrimaryKey, class SecondaryKey>
class_label disk_index<PrimaryKey, SecondaryKey>::label(doc_id d_id) const
{
return _labels.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
class_label
disk_index<PrimaryKey, SecondaryKey>::class_label_from_id(label_id l_id) const
{
return _label_ids.get_key(l_id);
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::set_label_ids()
{
std::unordered_set<class_label> labels;
for(auto & lbl: _labels)
labels.insert(lbl);
label_id i{0};
for(auto & lbl: labels)
_label_ids.insert(lbl, i++);
}
template <class PrimaryKey, class SecondaryKey>
label_id
disk_index<PrimaryKey, SecondaryKey>::label_id_from_doc(doc_id d_id) const
{
return _label_ids.get_value(_labels.at(d_id));
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::write_chunk(
uint32_t chunk_num,
std::vector<postings_data<PrimaryKey, SecondaryKey>> & pdata)
{
std::sort(pdata.begin(), pdata.end());
std::ofstream outfile{"chunk-" + common::to_string(chunk_num)};
for(auto & p: pdata)
outfile << p;
outfile.close();
pdata.clear();
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::merge_chunks(
uint32_t num_chunks,
const std::string & filename)
{
using chunk_t = chunk<PrimaryKey, SecondaryKey>;
// create priority queue of all chunks based on size
std::priority_queue<chunk_t> chunks;
for(uint32_t i = 0; i < num_chunks; ++i)
{
std::string filename = "chunk-" + common::to_string(i);
chunks.push(chunk_t{filename});
}
// merge the smallest two chunks together until there is only one left
// done in parallel
// this represents the number of merge steps needed---it is equivalent
// to the number of internal nodes in a binary tree with n leaf nodes
size_t remaining = chunks.size() - 1;
std::mutex mutex;
parallel::thread_pool pool;
auto thread_ids = pool.thread_ids();
std::vector<std::future<void>> futures;
std::function<void()> task;
task = [&]() {
util::optional<chunk_t> first;
util::optional<chunk_t> second;
{
std::lock_guard<std::mutex> lock{mutex};
if (chunks.size() < 2)
return;
first = util::optional<chunk_t>{chunks.top()};
chunks.pop();
second = util::optional<chunk_t>{chunks.top()};
chunks.pop();
std::cerr << " Merging " << first->path() << " ("
<< common::bytes_to_units(first->size())
<< ") and " << second->path() << " ("
<< common::bytes_to_units(second->size())
<< "), " << --remaining << " remaining \r";
}
first->merge_with(*second);
mutex.lock();
chunks.push(*first);
if (chunks.size() > 1) {
mutex.unlock();
task();
} else {
mutex.unlock();
}
};
for (size_t i = 0; i < thread_ids.size(); ++i) {
futures.emplace_back(pool.submit_task(task));
}
for (auto & fut : futures)
fut.get();
std::cerr << std::endl;
rename(chunks.top().path().c_str(), filename.c_str());
std::cerr << "Created uncompressed postings file " << filename
<< " (" << common::bytes_to_units(chunks.top().size()) << ")"
<< std::endl;
}
template <class PrimaryKey, class SecondaryKey>
template <class Key, class Value>
void disk_index<PrimaryKey, SecondaryKey>::save_mapping(
const util::invertible_map<Key, Value> & map,
const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & p: map)
outfile << p.first << " " << p.second << "\n";
}
template <class PrimaryKey, class SecondaryKey>
template <class T>
void disk_index<PrimaryKey, SecondaryKey>::save_mapping(
const std::vector<T> & vec, const std::string & filename)
{
std::ofstream outfile{filename};
for(auto & v: vec)
outfile << v << "\n";
}
template <class PrimaryKey, class SecondaryKey>
template <class Key, class Value>
void disk_index<PrimaryKey, SecondaryKey>::load_mapping(
util::invertible_map<Key, Value> & map, const std::string & filename)
{
std::ifstream input{filename};
Key k;
Value v;
while((input >> k) && (input >> v))
map.insert(std::make_pair(k, v));
}
template <class PrimaryKey, class SecondaryKey>
template <class T>
void disk_index<PrimaryKey, SecondaryKey>::load_mapping(
std::vector<T> & vec, const std::string & filename)
{
std::ifstream input{filename};
uint64_t size = common::num_lines(filename);
vec.reserve(size);
T val;
while(input >> val)
vec.push_back(val);
}
template <class PrimaryKey, class SecondaryKey>
double disk_index<PrimaryKey, SecondaryKey>::doc_size(doc_id d_id) const
{
return _doc_sizes.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
uint64_t disk_index<PrimaryKey, SecondaryKey>::num_docs() const
{
return _doc_sizes.size();
}
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::doc_name(doc_id d_id) const
{
auto path = doc_path(d_id);
return path.substr(path.find_last_of("/") + 1);
}
template <class PrimaryKey, class SecondaryKey>
std::string disk_index<PrimaryKey, SecondaryKey>::doc_path(doc_id d_id) const
{
return _doc_id_mapping.at(d_id);
}
template <class PrimaryKey, class SecondaryKey>
std::vector<doc_id> disk_index<PrimaryKey, SecondaryKey>::docs() const
{
std::vector<doc_id> ret(_doc_id_mapping.size());
std::iota(ret.begin(), ret.end(), 0);
return ret;
}
template <class PrimaryKey, class SecondaryKey>
void disk_index<PrimaryKey, SecondaryKey>::tokenize(corpus::document & doc)
{
_tokenizer->tokenize(doc);
}
template <class PrimaryKey, class SecondaryKey>
std::shared_ptr<postings_data<PrimaryKey, SecondaryKey>>
disk_index<PrimaryKey, SecondaryKey>::search_primary(PrimaryKey p_id) const
{
uint64_t idx{p_id};
// if the term doesn't exist in the index, return an empty postings_data
if(idx >= _term_bit_locations.size())
return std::make_shared<PostingsData>(p_id);
io::compressed_file_reader reader{*_postings, _compression_mapping};
reader.seek(_term_bit_locations.at(idx));
auto pdata = std::make_shared<PostingsData>(p_id);
pdata->read_compressed(reader);
return pdata;
}
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2014 Micah C Chambers (micahc.vt@gmail.com)
*
* 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.
*
* @file lbfgs.cpp Implemenation of the LBFGSOpt class which implements
* a LBFGS optimization (energy minimization) algorithm.
*
*****************************************************************************/
#include "lbfgs.h"
#ifdef DEBUG
#include <iterator>
#include <iostream>
#include <iomanip>
using std::cerr;
using std::endl;
using std::setw;
using std::setprecision;
#endif //DEBUG
namespace npl {
/**
* @brief Constructor for optimizer function.
*
* @param dim Dimension of state variable
* @param valfunc Function which computes the energy of the underlying
* mathematical function
* @param gradfunc Function which computes the gradient of energy in the
* underlying mathematical function
* @param callback Function which should be called at the end of each
* iteration (for instance, to debug)
*/
LBFGSOpt::LBFGSOpt(size_t dim, const ValFunc& valfunc,
const GradFunc& gradfunc, const CallBackFunc& callback)
: Optimizer(dim, valfunc, gradfunc, callback),
m_lsearch(valfunc)
{
m_hist.clear();
opt_H0inv = VectorXd::Ones(dim);
opt_histsize = 6;
opt_ls_s = 1;
opt_ls_beta = 0.5;
opt_ls_sigma = 1e-5;
};
/**
* @brief Constructor for optimizer function.
*
* @param dim Dimension of state variable
* @param valfunc Function which computes the energy of the underlying
* mathematical function
* @param gradfunc Function which computes the gradient of energy in the
* underlying mathematical function
* @param gradAndValFunc
* Function which computes the energy and gradient in the
* underlying mathematical function
* @param callback Function which should be called at the end of each
* iteration (for instance, to debug)
*/
LBFGSOpt::LBFGSOpt(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc,
const ValGradFunc& gradAndValFunc, const CallBackFunc& callback)
: Optimizer(dim, valfunc, gradfunc, gradAndValFunc, callback),
m_lsearch(valfunc)
{
m_hist.clear();
opt_H0inv = VectorXd::Ones(dim);
opt_histsize = 6;
opt_ls_s = 1;
opt_ls_beta = 0.5;
opt_ls_sigma = 1e-5;
};
/**
* @brief Function for computing the hessian recursively
* Based on the algorithm from Numerical Optimization (Nocedal)
*
* @param gamma Scale of initial (H0)
* @param g Direction from right multiplication so far
* @param it Position in history list
*
* @return Direction (d) after right multiplying d by H_k, the hessian
* estimate for position it,
*/
VectorXd LBFGSOpt::hessFuncTwoLoop(double gamma, const VectorXd& g)
{
VectorXd q = g;
VectorXd alpha(m_hist.size());
// iterate backward in time (forward in list)
int ii = 0;
for(auto it = m_hist.cbegin(); it != m_hist.cend(); ++it, ++ii) {
double rho = std::get<0>(*it);
const VectorXd& y = std::get<1>(*it); // or q
const VectorXd& s = std::get<2>(*it); // or p
alpha[ii] = rho*s.dot(q);
q -= alpha[ii]*y;
}
VectorXd r = opt_H0inv.cwiseProduct(q)*gamma;
// oldest first
ii = m_hist.size()-1;
for(auto it = m_hist.crbegin(); it != m_hist.crend(); ++it, --ii) {
double rho = std::get<0>(*it);
const VectorXd& y = std::get<1>(*it); // or q
const VectorXd& s = std::get<2>(*it); // or p
double beta = rho*y.dot(r);
r += s*(alpha[ii]-beta);
}
return r;
}
/**
* @brief Function for computing the hessian recursively
*
* @param gamma Scale of initial (H0)
* @param d Direction from right multiplication so far
* @param it Position in history list
*
* @return Direction (d) after right multiplying d by H_k, the hessian
* estimate for position it,
*/
/**
* @brief Optimize Based on a value function and gradient function
* separately. When both gradient and value are needed it will call update,
* when it needs just the gradient it will call gradFunc, and when it just
* needs the value it will cal valFunc. This is always the most efficient,
* assuming there is additional cost of computing the gradient or value, but
* its obviously more complicated.
*
* Paper: On the limited memory BFGS method for large scale optimization
* By: Liu, Dong C., Nocedal, Jorge
*
* @return StopReason
*/
StopReason LBFGSOpt::optimize()
{
double gradstop = this->stop_G >= 0 ? this->stop_G : 0;
double stepstop = this->stop_X >= 0 ? this->stop_X : 0;
double valstop = this->stop_F >= 0 ? this->stop_F : -1;
// update linesearch with minimum step, an options
m_lsearch.opt_s = opt_ls_s;
m_lsearch.opt_minstep = stepstop;
m_lsearch.opt_beta = opt_ls_beta;
m_lsearch.opt_sigma = opt_ls_sigma;
VectorXd gk(state_x.rows()); // gradient
double f_xk; // value at current position
double f_xkm1; // value at previous position
VectorXd pk, qk, dk, vk;
VectorXd H0 = VectorXd::Ones(state_x.rows());
double gamma = 1;
//D(k+1) += p(k)p(k)' - D(k)q(k)q(k)'D(k) + Z(k)T(k)v(k)v(k)'
// ---------- -----------------
// (p(k)'q(k)) q(k)'D(k)q(k)
m_compFG(state_x, f_xk, gk);
dk = -gk;
for(int iter = 0; stop_Its <= 0 || iter < stop_Its; iter++) {
// compute step size
double alpha = m_lsearch.search(f_xk, state_x, gk, dk);
pk = alpha*dk;
if(alpha == 0 || pk.squaredNorm() < stepstop*stepstop) {
return ENDSTEP;
}
// step
state_x += pk;
// update gradient, value
qk = -gk;
f_xkm1 = f_xk;
m_compFG(state_x, f_xk, gk);
qk += gk;
if(gk.squaredNorm() < gradstop*gradstop)
return ENDGRAD;
if(abs(f_xk - f_xkm1) < valstop)
return ENDVALUE;
if(f_xk < this->stop_F_under || f_xk > this->stop_F_over)
return ENDABSVALUE;
// update history
m_hist.push_front(std::make_tuple(1./qk.dot(pk), qk, pk));
if(m_hist.size() > opt_histsize)
m_hist.pop_back();
/*
* update direction
* qk - change in gradient (yk in original paper)
* pk - change in x (sk in original paper)
*/
gamma = qk.dot(pk)/qk.squaredNorm();
dk = -hessFuncTwoLoop(gamma, gk);
m_callback(dk, f_xk, gk, iter);
}
return ENDFAIL;
}
}
<commit_msg>added direction constraint to armijo<commit_after>/******************************************************************************
* Copyright 2014 Micah C Chambers (micahc.vt@gmail.com)
*
* 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.
*
* @file lbfgs.cpp Implemenation of the LBFGSOpt class which implements
* a LBFGS optimization (energy minimization) algorithm.
*
*****************************************************************************/
#include "lbfgs.h"
#ifdef DEBUG
#include <iterator>
#include <iostream>
#include <iomanip>
using std::cerr;
using std::endl;
using std::setw;
using std::setprecision;
#endif //DEBUG
namespace npl {
/**
* @brief Constructor for optimizer function.
*
* @param dim Dimension of state variable
* @param valfunc Function which computes the energy of the underlying
* mathematical function
* @param gradfunc Function which computes the gradient of energy in the
* underlying mathematical function
* @param callback Function which should be called at the end of each
* iteration (for instance, to debug)
*/
LBFGSOpt::LBFGSOpt(size_t dim, const ValFunc& valfunc,
const GradFunc& gradfunc, const CallBackFunc& callback)
: Optimizer(dim, valfunc, gradfunc, callback),
m_lsearch(valfunc)
{
m_hist.clear();
opt_H0inv = VectorXd::Ones(dim);
opt_histsize = 6;
opt_ls_s = 1;
opt_ls_beta = 0.5;
opt_ls_sigma = 1e-5;
};
/**
* @brief Constructor for optimizer function.
*
* @param dim Dimension of state variable
* @param valfunc Function which computes the energy of the underlying
* mathematical function
* @param gradfunc Function which computes the gradient of energy in the
* underlying mathematical function
* @param gradAndValFunc
* Function which computes the energy and gradient in the
* underlying mathematical function
* @param callback Function which should be called at the end of each
* iteration (for instance, to debug)
*/
LBFGSOpt::LBFGSOpt(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc,
const ValGradFunc& gradAndValFunc, const CallBackFunc& callback)
: Optimizer(dim, valfunc, gradfunc, gradAndValFunc, callback),
m_lsearch(valfunc)
{
m_hist.clear();
opt_H0inv = VectorXd::Ones(dim);
opt_histsize = 6;
opt_ls_s = 1;
opt_ls_beta = 0.5;
opt_ls_sigma = 1e-5;
};
/**
* @brief Function for computing the hessian recursively
* Based on the algorithm from Numerical Optimization (Nocedal)
*
* @param gamma Scale of initial (H0)
* @param g Direction from right multiplication so far
* @param it Position in history list
*
* @return Direction (d) after right multiplying d by H_k, the hessian
* estimate for position it,
*/
VectorXd LBFGSOpt::hessFuncTwoLoop(double gamma, const VectorXd& g)
{
VectorXd q = g;
VectorXd alpha(m_hist.size());
// iterate backward in time (forward in list)
int ii = 0;
for(auto it = m_hist.cbegin(); it != m_hist.cend(); ++it, ++ii) {
double rho = std::get<0>(*it);
const VectorXd& y = std::get<1>(*it); // or q
const VectorXd& s = std::get<2>(*it); // or p
alpha[ii] = rho*s.dot(q);
q -= alpha[ii]*y;
}
VectorXd r = opt_H0inv.cwiseProduct(q)*gamma;
// oldest first
ii = m_hist.size()-1;
for(auto it = m_hist.crbegin(); it != m_hist.crend(); ++it, --ii) {
double rho = std::get<0>(*it);
const VectorXd& y = std::get<1>(*it); // or q
const VectorXd& s = std::get<2>(*it); // or p
double beta = rho*y.dot(r);
r += s*(alpha[ii]-beta);
}
return r;
}
/**
* @brief Function for computing the hessian recursively
*
* @param gamma Scale of initial (H0)
* @param d Direction from right multiplication so far
* @param it Position in history list
*
* @return Direction (d) after right multiplying d by H_k, the hessian
* estimate for position it,
*/
/**
* @brief Optimize Based on a value function and gradient function
* separately. When both gradient and value are needed it will call update,
* when it needs just the gradient it will call gradFunc, and when it just
* needs the value it will cal valFunc. This is always the most efficient,
* assuming there is additional cost of computing the gradient or value, but
* its obviously more complicated.
*
* Paper: On the limited memory BFGS method for large scale optimization
* By: Liu, Dong C., Nocedal, Jorge
*
* @return StopReason
*/
StopReason LBFGSOpt::optimize()
{
double gradstop = this->stop_G >= 0 ? this->stop_G : 0;
double stepstop = this->stop_X >= 0 ? this->stop_X : 0;
double valstop = this->stop_F >= 0 ? this->stop_F : -1;
// update linesearch with minimum step, an options
m_lsearch.opt_s = opt_ls_s;
m_lsearch.opt_minstep = stepstop;
m_lsearch.opt_beta = opt_ls_beta;
m_lsearch.opt_sigma = opt_ls_sigma;
VectorXd gk(state_x.rows()); // gradient
double f_xk; // value at current position
double f_xkm1; // value at previous position
VectorXd pk, qk, dk, vk;
VectorXd H0 = VectorXd::Ones(state_x.rows());
double gamma = 1;
//D(k+1) += p(k)p(k)' - D(k)q(k)q(k)'D(k) + Z(k)T(k)v(k)v(k)'
// ---------- -----------------
// (p(k)'q(k)) q(k)'D(k)q(k)
m_compFG(state_x, f_xk, gk);
dk = -gk;
for(int iter = 0; stop_Its <= 0 || iter < stop_Its; iter++) {
// reset history if grad . gk > 0 (ie they go the same direction)
if(gk.dot(dk) >= 0) {
dk = -gk;
m_hist.clear();
}
// compute step size
double alpha = m_lsearch.search(f_xk, state_x, gk, dk);
pk = alpha*dk;
if(alpha == 0 || pk.squaredNorm() < stepstop*stepstop) {
return ENDSTEP;
}
// step
state_x += pk;
// update gradient, value
qk = -gk;
f_xkm1 = f_xk;
m_compFG(state_x, f_xk, gk);
qk += gk;
if(gk.squaredNorm() < gradstop*gradstop)
return ENDGRAD;
if(abs(f_xk - f_xkm1) < valstop)
return ENDVALUE;
if(f_xk < this->stop_F_under || f_xk > this->stop_F_over)
return ENDABSVALUE;
// update history
m_hist.push_front(std::make_tuple(1./qk.dot(pk), qk, pk));
if(m_hist.size() > opt_histsize)
m_hist.pop_back();
/*
* update direction
* qk - change in gradient (yk in original paper)
* pk - change in x (sk in original paper)
*/
gamma = qk.dot(pk)/qk.squaredNorm();
dk = -hessFuncTwoLoop(gamma, gk);
m_callback(dk, f_xk, gk, iter);
}
return ENDFAIL;
}
}
<|endoftext|> |
<commit_before>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/FileSystem.h"
using namespace llvm;
static cl::opt<int> Offset(
"offset", cl::desc("Format a range starting at this file offset."),
cl::init(0));
static cl::opt<int> Length(
"length", cl::desc("Format a range of this length, -1 for end of file."),
cl::init(-1));
static cl::opt<std::string> Style(
"style", cl::desc("Coding style, currently supports: LLVM, Google."),
cl::init("LLVM"));
namespace clang {
namespace format {
static FileID createInMemoryFile(const MemoryBuffer *Source,
SourceManager &Sources,
FileManager &Files) {
const FileEntry *Entry =
Files.getVirtualFile("<stdio>", Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
static void format() {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(IntrusiveRefCntPtr<DiagnosticIDs>(
new DiagnosticIDs), new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
OwningPtr<MemoryBuffer> Code;
if (error_code ec = MemoryBuffer::getSTDIN(Code)) {
llvm::errs() << ec.message() << "\n";
return;
}
FileID ID = createInMemoryFile(Code.get(), Sources, Files);
// FIXME: Pull this out into a common method and use here and in the tests.
LangOptions LangOpts;
LangOpts.CPlusPlus = 1;
LangOpts.CPlusPlus11 = 1;
LangOpts.ObjC1 = 1;
Lexer Lex(ID, Sources.getBuffer(ID), Sources, LangOpts);
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
SourceLocation End = Sources.getLocForEndOfFile(ID);
if (Length != -1)
End = Start.getLocWithOffset(Length);
std::vector<CharSourceRange> Ranges(
1, CharSourceRange::getCharRange(Start, End));
FormatStyle FStyle = Style == "LLVM" ? getLLVMStyle() : getGoogleStyle();
tooling::Replacements Replaces = reformat(FStyle, Lex, Sources, Ranges);
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
Rewrite.getEditBuffer(ID).write(outs());
}
} // namespace format
} // namespace clang
int main(int argc, const char **argv) {
cl::ParseCommandLineOptions(argc, argv);
clang::format::format();
return 0;
}
<commit_msg>Enabled ObjC2 in clang-format for @package. Matches r171766.<commit_after>//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/FileSystem.h"
using namespace llvm;
static cl::opt<int> Offset(
"offset", cl::desc("Format a range starting at this file offset."),
cl::init(0));
static cl::opt<int> Length(
"length", cl::desc("Format a range of this length, -1 for end of file."),
cl::init(-1));
static cl::opt<std::string> Style(
"style", cl::desc("Coding style, currently supports: LLVM, Google."),
cl::init("LLVM"));
namespace clang {
namespace format {
static FileID createInMemoryFile(const MemoryBuffer *Source,
SourceManager &Sources,
FileManager &Files) {
const FileEntry *Entry =
Files.getVirtualFile("<stdio>", Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
static void format() {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(IntrusiveRefCntPtr<DiagnosticIDs>(
new DiagnosticIDs), new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
OwningPtr<MemoryBuffer> Code;
if (error_code ec = MemoryBuffer::getSTDIN(Code)) {
llvm::errs() << ec.message() << "\n";
return;
}
FileID ID = createInMemoryFile(Code.get(), Sources, Files);
// FIXME: Pull this out into a common method and use here and in the tests.
LangOptions LangOpts;
LangOpts.CPlusPlus = 1;
LangOpts.CPlusPlus11 = 1;
LangOpts.ObjC1 = 1;
LangOpts.ObjC2 = 1;
Lexer Lex(ID, Sources.getBuffer(ID), Sources, LangOpts);
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
SourceLocation End = Sources.getLocForEndOfFile(ID);
if (Length != -1)
End = Start.getLocWithOffset(Length);
std::vector<CharSourceRange> Ranges(
1, CharSourceRange::getCharRange(Start, End));
FormatStyle FStyle = Style == "LLVM" ? getLLVMStyle() : getGoogleStyle();
tooling::Replacements Replaces = reformat(FStyle, Lex, Sources, Ranges);
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
Rewrite.getEditBuffer(ID).write(outs());
}
} // namespace format
} // namespace clang
int main(int argc, const char **argv) {
cl::ParseCommandLineOptions(argc, argv);
clang::format::format();
return 0;
}
<|endoftext|> |
<commit_before>AliEmcalJetTask* AddTaskEmcalJet(
const UInt_t type = AliEmcalJetTask::kAKT | AliEmcalJetTask::kFullJet | AliEmcalJetTask::kR040Jet,
const char *nTracks = "Tracks",
const char *nClusters = "CaloClusters",
const Double_t minTrPt = 0.15,
const Double_t minClPt = 0.30,
const Double_t ghostArea = 0.005,
const Double_t radius = 0.4,
const Int_t recombScheme = 1,
const char *tag = "Jet",
const Double_t minJetPt = 0.,
const Bool_t selectPhysPrim = kFALSE,
const Int_t useExchangeCont = 0,
const Bool_t lockTask = kTRUE
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskAliEmcalJet", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskAliEmcalJet", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
char *algoString;
if ((type & AliEmcalJetTask::kKT) != 0) {
algoString = "KT";
// minJetPt = 0.1;
} else if ((type & AliEmcalJetTask::kAKT) != 0) {
algoString = "AKT";
// minJetPt = 1.0;
}
char *typeString;
if ((type & AliEmcalJetTask::kFullJet) != 0)
typeString = "Full";
else if ((type & AliEmcalJetTask::kChargedJet) != 0)
typeString = "Charged";
else if ((type & AliEmcalJetTask::kNeutralJet) != 0)
typeString = "Neutral";
char radiusString[200];
if ((type & AliEmcalJetTask::kR020Jet) != 0)
sprintf(radiusString,"R020");
else if ((type & AliEmcalJetTask::kR030Jet) != 0)
sprintf(radiusString,"R030");
else if ((type & AliEmcalJetTask::kR040Jet) != 0)
sprintf(radiusString,"R040");
else
sprintf(radiusString,"R0%2.0f",radius*100.0);
char pTString[200];
if (minTrPt==0)
sprintf(pTString,"pT0000");
else if (minTrPt<1.0)
sprintf(pTString,"pT0%3.0f",minTrPt*1000.0);
else if (minTrPt>=1.0)
sprintf(pTString,"pT%4.0f",minTrPt*1000.0);
char ETString[200];
if (minClPt==0)
sprintf(ETString,"ET0000");
else if (minClPt<1.0)
sprintf(ETString,"ET0%3.0f",minClPt*1000.0);
else if (minClPt>=1.0)
sprintf(ETString,"ET%4.0f",minClPt*1000.0);
char recombSchemeString[200];
if(recombScheme==0)
sprintf(recombSchemeString,"%s","E_scheme");
else if(recombScheme==1)
sprintf(recombSchemeString,"%s","pt_scheme");
else if(recombScheme==2)
sprintf(recombSchemeString,"%s","pt2_scheme");
else if(recombScheme==3)
sprintf(recombSchemeString,"%s","Et_scheme");
else if(recombScheme==4)
sprintf(recombSchemeString,"%s","Et2_scheme");
else if(recombScheme==5)
sprintf(recombSchemeString,"%s","BIpt_scheme");
else if(recombScheme==6)
sprintf(recombSchemeString,"%s","BIpt2_scheme");
else if(recombScheme==99)
sprintf(recombSchemeString,"%s","ext_scheme");
else {
::Error("AddTaskAliEmcalJet", "Recombination scheme not recognized.");
return NULL;
}
TString name;
if (*nTracks && *nClusters)
name = TString(Form("%s_%s%s%s_%s_%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString,recombSchemeString));
else if (!*nClusters)
name = TString(Form("%s_%s%s%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nTracks,pTString,recombSchemeString));
else if (!*nTracks)
name = TString(Form("%s_%s%s%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nClusters,ETString,recombSchemeString));
std::cout << "Jet task name: " << name.Data() << std::endl;
AliEmcalJetTask* mgrTask = mgr->GetTask(name.Data());
if (mgrTask) return mgrTask;
AliEmcalJetTask* jetTask = new AliEmcalJetTask(name, useExchangeCont);
jetTask->SetTracksName(nTracks);
jetTask->SetClusName(nClusters);
jetTask->SetJetsName(name);
jetTask->SetJetType(type);
jetTask->SetMinJetTrackPt(minTrPt);
jetTask->SetMinJetClusPt(minClPt);
jetTask->SetMinJetPt(minJetPt);
if ((type & (AliEmcalJetTask::kRX1Jet|AliEmcalJetTask::kRX2Jet|AliEmcalJetTask::kRX3Jet)) != 0)
jetTask->SetRadius(radius);
jetTask->SetGhostArea(ghostArea);
jetTask->SetRecombScheme(recombScheme);
jetTask->SelectPhysicalPrimaries(selectPhysPrim);
if (lockTask) jetTask->SetLocked();
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(jetTask, 0, cinput);
if (useExchangeCont > 0) {
TObjArray* cnt = mgr->GetContainers();
if (strcmp(nTracks, "") != 0) {
AliAnalysisDataContainer* trackCont = static_cast<AliAnalysisDataContainer*>(cnt->FindObject(nTracks));
if (trackCont) {
mgr->ConnectInput(jetTask, 1, trackCont);
}
else {
::Error("AddTaskEmcalJet", "Could not find input container '%s'!", nTracks);
}
}
}
if (useExchangeCont > 1) {
if (strcmp(nClusters, "") != 0) {
AliAnalysisDataContainer* clusCont = static_cast<AliAnalysisDataContainer*>(cnt->FindObject(nClusters));
if (clusCont) {
mgr->ConnectInput(jetTask, 2, clusCont);
}
else {
::Error("AddTaskEmcalJet", "Could not find input container '%s'!", nClusters);
}
}
}
return jetTask;
}
AliEmcalJetTask* AddTaskEmcalJet(
const char *nTracks = "Tracks",
const char *nClusters = "CaloClusters",
const Int_t algo = 1,
const Double_t radius = 0.4,
const Int_t type = 0,
const Double_t minTrPt = 0.15,
const Double_t minClPt = 0.30,
const Double_t ghostArea = 0.005,
const Int_t recombScheme = 1,
const char *tag = "Jet",
const Double_t minJetPt = 0.,
const Bool_t selectPhysPrim = kFALSE,
const Int_t useExchangeCont = 0,
const Bool_t lockTask = kTRUE
)
{
UInt_t jetType = 0;
if (algo == 0)
jetType |= AliEmcalJetTask::kKT;
else
jetType |= AliEmcalJetTask::kAKT;
if (type==0)
jetType |= AliEmcalJetTask::kFullJet;
else if (type==1)
jetType |= AliEmcalJetTask::kChargedJet;
else if (type==2)
jetType |= AliEmcalJetTask::kNeutralJet;
if (radius==0.2)
jetType |= AliEmcalJetTask::kR020Jet;
else if (radius==0.3)
jetType |= AliEmcalJetTask::kR030Jet;
else if (radius==0.4)
jetType |= AliEmcalJetTask::kR040Jet;
else
jetType |= AliEmcalJetTask::kRX1Jet;
if (ghostArea<=0) {
::Error("AddTaskEmcalJet","Ghost area set to 0, check your settings (try 0.005)");
return NULL;
}
return AddTaskEmcalJet(jetType, nTracks, nClusters, minTrPt, minClPt, ghostArea, radius, recombScheme, tag, minJetPt, selectPhysPrim, useExchangeCont, lockTask);
}
<commit_msg>move useExchangeCont variable to end<commit_after>AliEmcalJetTask* AddTaskEmcalJet(
const UInt_t type = AliEmcalJetTask::kAKT | AliEmcalJetTask::kFullJet | AliEmcalJetTask::kR040Jet,
const char *nTracks = "Tracks",
const char *nClusters = "CaloClusters",
const Double_t minTrPt = 0.15,
const Double_t minClPt = 0.30,
const Double_t ghostArea = 0.005,
const Double_t radius = 0.4,
const Int_t recombScheme = 1,
const char *tag = "Jet",
const Double_t minJetPt = 0.,
const Bool_t selectPhysPrim = kFALSE,
const Bool_t lockTask = kTRUE,
const Int_t useExchangeCont = 0
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskAliEmcalJet", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskAliEmcalJet", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
char *algoString;
if ((type & AliEmcalJetTask::kKT) != 0) {
algoString = "KT";
// minJetPt = 0.1;
} else if ((type & AliEmcalJetTask::kAKT) != 0) {
algoString = "AKT";
// minJetPt = 1.0;
}
char *typeString;
if ((type & AliEmcalJetTask::kFullJet) != 0)
typeString = "Full";
else if ((type & AliEmcalJetTask::kChargedJet) != 0)
typeString = "Charged";
else if ((type & AliEmcalJetTask::kNeutralJet) != 0)
typeString = "Neutral";
char radiusString[200];
if ((type & AliEmcalJetTask::kR020Jet) != 0)
sprintf(radiusString,"R020");
else if ((type & AliEmcalJetTask::kR030Jet) != 0)
sprintf(radiusString,"R030");
else if ((type & AliEmcalJetTask::kR040Jet) != 0)
sprintf(radiusString,"R040");
else
sprintf(radiusString,"R0%2.0f",radius*100.0);
char pTString[200];
if (minTrPt==0)
sprintf(pTString,"pT0000");
else if (minTrPt<1.0)
sprintf(pTString,"pT0%3.0f",minTrPt*1000.0);
else if (minTrPt>=1.0)
sprintf(pTString,"pT%4.0f",minTrPt*1000.0);
char ETString[200];
if (minClPt==0)
sprintf(ETString,"ET0000");
else if (minClPt<1.0)
sprintf(ETString,"ET0%3.0f",minClPt*1000.0);
else if (minClPt>=1.0)
sprintf(ETString,"ET%4.0f",minClPt*1000.0);
char recombSchemeString[200];
if(recombScheme==0)
sprintf(recombSchemeString,"%s","E_scheme");
else if(recombScheme==1)
sprintf(recombSchemeString,"%s","pt_scheme");
else if(recombScheme==2)
sprintf(recombSchemeString,"%s","pt2_scheme");
else if(recombScheme==3)
sprintf(recombSchemeString,"%s","Et_scheme");
else if(recombScheme==4)
sprintf(recombSchemeString,"%s","Et2_scheme");
else if(recombScheme==5)
sprintf(recombSchemeString,"%s","BIpt_scheme");
else if(recombScheme==6)
sprintf(recombSchemeString,"%s","BIpt2_scheme");
else if(recombScheme==99)
sprintf(recombSchemeString,"%s","ext_scheme");
else {
::Error("AddTaskAliEmcalJet", "Recombination scheme not recognized.");
return NULL;
}
TString name;
if (*nTracks && *nClusters)
name = TString(Form("%s_%s%s%s_%s_%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString,recombSchemeString));
else if (!*nClusters)
name = TString(Form("%s_%s%s%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nTracks,pTString,recombSchemeString));
else if (!*nTracks)
name = TString(Form("%s_%s%s%s_%s_%s_%s",
tag,algoString,typeString,radiusString,nClusters,ETString,recombSchemeString));
std::cout << "Jet task name: " << name.Data() << std::endl;
AliEmcalJetTask* mgrTask = mgr->GetTask(name.Data());
if (mgrTask) return mgrTask;
AliEmcalJetTask* jetTask = new AliEmcalJetTask(name, useExchangeCont);
jetTask->SetTracksName(nTracks);
jetTask->SetClusName(nClusters);
jetTask->SetJetsName(name);
jetTask->SetJetType(type);
jetTask->SetMinJetTrackPt(minTrPt);
jetTask->SetMinJetClusPt(minClPt);
jetTask->SetMinJetPt(minJetPt);
if ((type & (AliEmcalJetTask::kRX1Jet|AliEmcalJetTask::kRX2Jet|AliEmcalJetTask::kRX3Jet)) != 0)
jetTask->SetRadius(radius);
jetTask->SetGhostArea(ghostArea);
jetTask->SetRecombScheme(recombScheme);
jetTask->SelectPhysicalPrimaries(selectPhysPrim);
if (lockTask) jetTask->SetLocked();
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(jetTask);
// Create containers for input/output
AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(jetTask, 0, cinput);
if (useExchangeCont > 0) {
TObjArray* cnt = mgr->GetContainers();
if (strcmp(nTracks, "") != 0) {
AliAnalysisDataContainer* trackCont = static_cast<AliAnalysisDataContainer*>(cnt->FindObject(nTracks));
if (trackCont) {
mgr->ConnectInput(jetTask, 1, trackCont);
}
else {
::Error("AddTaskEmcalJet", "Could not find input container '%s'!", nTracks);
}
}
}
if (useExchangeCont > 1) {
if (strcmp(nClusters, "") != 0) {
AliAnalysisDataContainer* clusCont = static_cast<AliAnalysisDataContainer*>(cnt->FindObject(nClusters));
if (clusCont) {
mgr->ConnectInput(jetTask, 2, clusCont);
}
else {
::Error("AddTaskEmcalJet", "Could not find input container '%s'!", nClusters);
}
}
}
return jetTask;
}
AliEmcalJetTask* AddTaskEmcalJet(
const char *nTracks = "Tracks",
const char *nClusters = "CaloClusters",
const Int_t algo = 1,
const Double_t radius = 0.4,
const Int_t type = 0,
const Double_t minTrPt = 0.15,
const Double_t minClPt = 0.30,
const Double_t ghostArea = 0.005,
const Int_t recombScheme = 1,
const char *tag = "Jet",
const Double_t minJetPt = 0.,
const Bool_t selectPhysPrim = kFALSE,
const Bool_t lockTask = kTRUE,
const Int_t useExchangeCont = 0
)
{
UInt_t jetType = 0;
if (algo == 0)
jetType |= AliEmcalJetTask::kKT;
else
jetType |= AliEmcalJetTask::kAKT;
if (type==0)
jetType |= AliEmcalJetTask::kFullJet;
else if (type==1)
jetType |= AliEmcalJetTask::kChargedJet;
else if (type==2)
jetType |= AliEmcalJetTask::kNeutralJet;
if (radius==0.2)
jetType |= AliEmcalJetTask::kR020Jet;
else if (radius==0.3)
jetType |= AliEmcalJetTask::kR030Jet;
else if (radius==0.4)
jetType |= AliEmcalJetTask::kR040Jet;
else
jetType |= AliEmcalJetTask::kRX1Jet;
if (ghostArea<=0) {
::Error("AddTaskEmcalJet","Ghost area set to 0, check your settings (try 0.005)");
return NULL;
}
return AddTaskEmcalJet(jetType, nTracks, nClusters, minTrPt, minClPt, ghostArea, radius, recombScheme, tag, minJetPt, selectPhysPrim, lockTask, useExchangeCont);
}
<|endoftext|> |
<commit_before>/* Siconos-sample , Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
//-----------------------------------------------------------------------
//
// DiodeBridgeCapFilter : sample of an electrical circuit involving :
// - a 1st linear dynamical system LSDiodeBridge1 consisting of
// an LC oscillator (1 F , 10 mH)
// - a non smooth system : a 4 diodes bridge used as a full wave rectifier
// of the supplied voltage across the LC oscillator, providing power
// to the resistor load of the 2nd dynamical system
// - a 2nd linear dynamical system LSDiodeBridge2 consisting of
// a filtering capacitor in parallel with a load resistor
//
// Expected behavior :
// The initial state (Vc = 10 V , IL = 0) of the oscillator provides
// an initial energy.
// The oscillator period is 2 Pi sqrt(LC) ~ 0,628 ms.
// The non smooth system is a full wave rectifier :
// each phase (positive and negative) of the oscillation allows current
// to flow in a constant direction through the load.
// The capacitor filter acts as a tank providing energy to the load resistor
// when the voltage across the oscillator weakens.
// The load resistor consumes energy : the oscillation damps.
//
// State variables LSDiodeBridge1:
// - the voltage across the capacitor (or inductor)
// - the current through the inductor
//
// State variable LSDiodeBridge2:
// - the voltage across the filtering capacitor
//
// The interaction between the two dynamical systems is defined by :
// - complementarity laws between diodes current and voltage. Depending on
// the diode position in the bridge, y stands for the reverse voltage across
// the diode or for the diode current (see figure in the template file)
// - a linear time invariant relation between the state variables and y and
// lambda (derived from the Kirchhoff laws)
//
//-----------------------------------------------------------------------
#include "SiconosKernel.hpp"
using namespace std;
int main(int argc, char* argv[])
{
double t0 = 0.0;
double T = 5e-3; // Total simulation time
double h_step = 1e-6; // Time step
double Lvalue = 1e-2; // inductance
double Cvalue = 1e-6; // capacitance LC oscillator
double Rvalue = 1e3; // load resistance
double Cfilt = 300.0e-9; // filtering capacitor
double VinitLS1 = 10.0; // initial voltage LC oscillator
double VinitLS2 = 0.0; // initial voltage Cfilt
string Modeltitle = "DiodeBridgeCapFilter";
try
{
// --- Linear system 1 (LC oscillator) specification ---
SP::SiconosVector init_stateLS1(new SiconosVector(2));
(*init_stateLS1)(0) = VinitLS1;
SP::SimpleMatrix LS1_A(new SimpleMatrix(2, 2));
(*LS1_A)(0 , 1) = -1.0 / Cvalue;
(*LS1_A)(1 , 0) = 1.0 / Lvalue;
cout << " LS1 matrice A = " << endl;
LS1_A->display();
SP::FirstOrderLinearDS LS1DiodeBridgeCapFilter(new FirstOrderLinearDS(init_stateLS1, LS1_A));
// --- Linear system 2 (load and filter) specification ---
SP::SiconosVector init_stateLS2(new SiconosVector(1));
(*init_stateLS2)(0) = VinitLS2;
SP::SimpleMatrix LS2_A(new SimpleMatrix(1, 1));
(*LS2_A)(0 , 0) = -1.0 / (Rvalue * Cfilt);
cout << " LS2 matrice A = " << endl;
LS2_A->display();
SP::FirstOrderLinearDS LS2DiodeBridgeCapFilter(new FirstOrderLinearDS(init_stateLS2, LS2_A));
// --- Interaction between linear systems and non smooth system ---
SP::SimpleMatrix Int_C(new SimpleMatrix(4, 3));
(*Int_C)(0 , 2) = 1.0;
(*Int_C)(2 , 0) = -1.0;
(*Int_C)(2 , 2) = 1.0;
(*Int_C)(3 , 0) = 1.0;
SP::SimpleMatrix Int_D(new SimpleMatrix(4, 4));
(*Int_D)(0 , 1) = -1.0;
(*Int_D)(1 , 0) = 1.0;
(*Int_D)(1 , 2) = 1.0;
(*Int_D)(1 , 3) = -1.0;
(*Int_D)(2 , 1) = -1.0;
(*Int_D)(3 , 1) = 1.0;
SP::SimpleMatrix Int_B(new SimpleMatrix(3, 4));
(*Int_B)(0 , 2) = -1.0 / Cvalue;
(*Int_B)(0 , 3) = 1.0 / Cvalue;
(*Int_B)(2 , 0) = 1.0 / Cfilt;
(*Int_B)(2 , 2) = 1.0 / Cfilt;
SP::FirstOrderLinearTIR LTIRDiodeBridgeCapFilter(new FirstOrderLinearTIR(Int_C, Int_B));
LTIRDiodeBridgeCapFilter->setDPtr(Int_D);
SP::NonSmoothLaw nslaw(new ComplementarityConditionNSL(4));
SP::Interaction InterDiodeBridgeCapFilter(new Interaction(4, nslaw, LTIRDiodeBridgeCapFilter));
// --- Model creation ---
SP::Model DiodeBridgeCapFilter(new Model(t0, T, Modeltitle));
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->insertDynamicalSystem(LS1DiodeBridgeCapFilter);
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->insertDynamicalSystem(LS2DiodeBridgeCapFilter);
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->link(InterDiodeBridgeCapFilter, LS1DiodeBridgeCapFilter, LS2DiodeBridgeCapFilter);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
double theta = 0.5;
double gamma = 0.5;
SP::EulerMoreauOSI aOSI(new EulerMoreauOSI(theta, gamma));
aOSI->insertDynamicalSystem(LS1DiodeBridgeCapFilter);
aOSI->insertDynamicalSystem(LS2DiodeBridgeCapFilter);
aOSI->setUseGammaForRelation(true);
// -- (2) Time discretisation --
SP::TimeDiscretisation aTiDisc(new TimeDiscretisation(t0, h_step));
// -- (3) Non smooth problem
SP::LCP aLCP(new LCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping aTS(new TimeStepping(aTiDisc, aOSI, aLCP));
// Initialization
cout << "====> Initialisation ..." << endl << endl;
DiodeBridgeCapFilter->initialize(aTS);
cout << " ---> End of initialization." << endl;
int k = 0;
double h = aTS->timeStep();
int N = ceil((T - t0) / h); // Number of time steps
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
SimpleMatrix dataPlot(N, 7);
// For the initial time step:
// time
dataPlot(k, 0) = DiodeBridgeCapFilter->t0();
// inductor voltage
dataPlot(k, 1) = (*LS1DiodeBridgeCapFilter->x())(0);
// inductor current
dataPlot(k, 2) = (*LS1DiodeBridgeCapFilter->x())(1);
// diode R1 current
dataPlot(k, 3) = (InterDiodeBridgeCapFilter->getLambda(0))(0);
// diode R1 voltage
dataPlot(k, 4) = -(*InterDiodeBridgeCapFilter->y(0))(0);
// diode F2 voltage
dataPlot(k, 5) = -(InterDiodeBridgeCapFilter->getLambda(0))(1);
// diode F1 current
dataPlot(k, 6) = (InterDiodeBridgeCapFilter->getLambda(0))(2);
// --- Compute elapsed time ---
boost::timer t;
t.restart();
// --- Time loop ---
while (k < N - 1)
{
// get current time step
k++;
// solve ...
aTS->computeOneStep();
// --- Get values to be plotted ---
// time
dataPlot(k, 0) = aTS->nextTime();
// inductor voltage
dataPlot(k, 1) = (*LS1DiodeBridgeCapFilter->x())(0);
// inductor current
dataPlot(k, 2) = (*LS1DiodeBridgeCapFilter->x())(1);
// diode R1 current
dataPlot(k, 3) = (InterDiodeBridgeCapFilter->getLambda(0))(0);
// diode R1 voltage
dataPlot(k, 4) = -(*InterDiodeBridgeCapFilter->y(0))(0);
// diode F2 voltage
dataPlot(k, 5) = -(InterDiodeBridgeCapFilter->getLambda(0))(1);
// diode F1 current
dataPlot(k, 6) = (InterDiodeBridgeCapFilter->getLambda(0))(2);
aTS->nextStep();
}
// --- elapsed time computing ---
cout << "time = " << t.elapsed() << endl;
// Number of time iterations
cout << "Number of iterations done: " << k << endl;
// dataPlot (ascii) output
dataPlot.resize(k, 10);
ioMatrix::write("DiodeBridgeCapFilter.dat", "ascii", dataPlot, "noDim");
cout << "Comparison with a reference file ..."<< endl;
SimpleMatrix dataPlotRef(dataPlot);
dataPlotRef.zero();
ioMatrix::read("DiodeBridgeCapFilter.ref", "ascii", dataPlotRef);
SP::SiconosVector err(new SiconosVector(dataPlot.size(1)));
(dataPlot - dataPlotRef).normInfByColumn(err);
err->display();
double error = 0.0;
for (unsigned int i = 0; i < 3; ++i)
{
if (error < (*err)(i))
error = (*err)(i);
}
cout << "error ="<<error << endl;
if (error > 1e-12)
{
(dataPlot - dataPlotRef).display();
std::cout << "Warning. The results is rather different from the reference file." << std::endl;
cout << "error ="<<error << endl;
return 1;
}
}
// --- Exceptions handling ---
catch (SiconosException e)
{
cout << "SiconosException" << endl;
cout << e.report() << endl;
}
catch (std::exception& e)
{
cout << "Exception: " << e.what() << endl;
exit(-1);
}
catch (...)
{
cout << "Exception caught " << endl;
}
}
<commit_msg>[examples] add plot of the phase portrait<commit_after>/* Siconos-sample , Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
//-----------------------------------------------------------------------
//
// DiodeBridgeCapFilter : sample of an electrical circuit involving :
// - a 1st linear dynamical system LSDiodeBridge1 consisting of
// an LC oscillator (1 F , 10 mH)
// - a non smooth system : a 4 diodes bridge used as a full wave rectifier
// of the supplied voltage across the LC oscillator, providing power
// to the resistor load of the 2nd dynamical system
// - a 2nd linear dynamical system LSDiodeBridge2 consisting of
// a filtering capacitor in parallel with a load resistor
//
// Expected behavior :
// The initial state (Vc = 10 V , IL = 0) of the oscillator provides
// an initial energy.
// The oscillator period is 2 Pi sqrt(LC) ~ 0,628 ms.
// The non smooth system is a full wave rectifier :
// each phase (positive and negative) of the oscillation allows current
// to flow in a constant direction through the load.
// The capacitor filter acts as a tank providing energy to the load resistor
// when the voltage across the oscillator weakens.
// The load resistor consumes energy : the oscillation damps.
//
// State variables LSDiodeBridge1:
// - the voltage across the capacitor (or inductor)
// - the current through the inductor
//
// State variable LSDiodeBridge2:
// - the voltage across the filtering capacitor
//
// The interaction between the two dynamical systems is defined by :
// - complementarity laws between diodes current and voltage. Depending on
// the diode position in the bridge, y stands for the reverse voltage across
// the diode or for the diode current (see figure in the template file)
// - a linear time invariant relation between the state variables and y and
// lambda (derived from the Kirchhoff laws)
//
//-----------------------------------------------------------------------
#include "SiconosKernel.hpp"
using namespace std;
int main(int argc, char* argv[])
{
double t0 = 0.0;
double T = 5e-3; // Total simulation time
double h_step = 1e-6; // Time step
double Lvalue = 1e-2; // inductance
double Cvalue = 1e-6; // capacitance LC oscillator
double Rvalue = 1e3; // load resistance
double Cfilt = 300.0e-9; // filtering capacitor
double VinitLS1 = 10.0; // initial voltage LC oscillator
double VinitLS2 = 0.0; // initial voltage Cfilt
string Modeltitle = "DiodeBridgeCapFilter";
try
{
// --- Linear system 1 (LC oscillator) specification ---
SP::SiconosVector init_stateLS1(new SiconosVector(2));
(*init_stateLS1)(0) = VinitLS1;
SP::SimpleMatrix LS1_A(new SimpleMatrix(2, 2));
(*LS1_A)(0 , 1) = -1.0 / Cvalue;
(*LS1_A)(1 , 0) = 1.0 / Lvalue;
cout << " LS1 matrice A = " << endl;
LS1_A->display();
SP::FirstOrderLinearDS LS1DiodeBridgeCapFilter(new FirstOrderLinearDS(init_stateLS1, LS1_A));
// --- Linear system 2 (load and filter) specification ---
SP::SiconosVector init_stateLS2(new SiconosVector(1));
(*init_stateLS2)(0) = VinitLS2;
SP::SimpleMatrix LS2_A(new SimpleMatrix(1, 1));
(*LS2_A)(0 , 0) = -1.0 / (Rvalue * Cfilt);
cout << " LS2 matrice A = " << endl;
LS2_A->display();
SP::FirstOrderLinearDS LS2DiodeBridgeCapFilter(new FirstOrderLinearDS(init_stateLS2, LS2_A));
// --- Interaction between linear systems and non smooth system ---
SP::SimpleMatrix Int_C(new SimpleMatrix(4, 3));
(*Int_C)(0 , 2) = 1.0;
(*Int_C)(2 , 0) = -1.0;
(*Int_C)(2 , 2) = 1.0;
(*Int_C)(3 , 0) = 1.0;
SP::SimpleMatrix Int_D(new SimpleMatrix(4, 4));
(*Int_D)(0 , 1) = -1.0;
(*Int_D)(1 , 0) = 1.0;
(*Int_D)(1 , 2) = 1.0;
(*Int_D)(1 , 3) = -1.0;
(*Int_D)(2 , 1) = -1.0;
(*Int_D)(3 , 1) = 1.0;
SP::SimpleMatrix Int_B(new SimpleMatrix(3, 4));
(*Int_B)(0 , 2) = -1.0 / Cvalue;
(*Int_B)(0 , 3) = 1.0 / Cvalue;
(*Int_B)(2 , 0) = 1.0 / Cfilt;
(*Int_B)(2 , 2) = 1.0 / Cfilt;
SP::FirstOrderLinearTIR LTIRDiodeBridgeCapFilter(new FirstOrderLinearTIR(Int_C, Int_B));
LTIRDiodeBridgeCapFilter->setDPtr(Int_D);
SP::NonSmoothLaw nslaw(new ComplementarityConditionNSL(4));
SP::Interaction InterDiodeBridgeCapFilter(new Interaction(4, nslaw, LTIRDiodeBridgeCapFilter));
// --- Model creation ---
SP::Model DiodeBridgeCapFilter(new Model(t0, T, Modeltitle));
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->insertDynamicalSystem(LS1DiodeBridgeCapFilter);
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->insertDynamicalSystem(LS2DiodeBridgeCapFilter);
DiodeBridgeCapFilter->nonSmoothDynamicalSystem()->link(InterDiodeBridgeCapFilter, LS1DiodeBridgeCapFilter, LS2DiodeBridgeCapFilter);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
double theta = 0.5;
double gamma = 0.5;
SP::EulerMoreauOSI aOSI(new EulerMoreauOSI(theta, gamma));
aOSI->insertDynamicalSystem(LS1DiodeBridgeCapFilter);
aOSI->insertDynamicalSystem(LS2DiodeBridgeCapFilter);
aOSI->setUseGammaForRelation(true);
// -- (2) Time discretisation --
SP::TimeDiscretisation aTiDisc(new TimeDiscretisation(t0, h_step));
// -- (3) Non smooth problem
SP::LCP aLCP(new LCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping aTS(new TimeStepping(aTiDisc, aOSI, aLCP));
// Initialization
cout << "====> Initialisation ..." << endl << endl;
DiodeBridgeCapFilter->initialize(aTS);
cout << " ---> End of initialization." << endl;
int k = 0;
double h = aTS->timeStep();
int N = ceil((T - t0) / h); // Number of time steps
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
SimpleMatrix dataPlot(N, 8);
// For the initial time step:
// time
dataPlot(k, 0) = DiodeBridgeCapFilter->t0();
// inductor voltage
dataPlot(k, 1) = (*LS1DiodeBridgeCapFilter->x())(0);
// inductor current
dataPlot(k, 2) = (*LS1DiodeBridgeCapFilter->x())(1);
// diode R1 current
dataPlot(k, 3) = (InterDiodeBridgeCapFilter->getLambda(0))(0);
// diode R1 voltage
dataPlot(k, 4) = -(*InterDiodeBridgeCapFilter->y(0))(0);
// diode F2 voltage
dataPlot(k, 5) = -(InterDiodeBridgeCapFilter->getLambda(0))(1);
// diode F1 current
dataPlot(k, 6) = (InterDiodeBridgeCapFilter->getLambda(0))(2);
// load voltage
dataPlot(k, 7) = (*LS2DiodeBridgeCapFilter->x())(0);
// --- Compute elapsed time ---
boost::timer t;
t.restart();
// --- Time loop ---
while (k < N - 1)
{
// get current time step
k++;
// solve ...
aTS->computeOneStep();
// --- Get values to be plotted ---
// time
dataPlot(k, 0) = aTS->nextTime();
// inductor voltage
dataPlot(k, 1) = (*LS1DiodeBridgeCapFilter->x())(0);
// inductor current
dataPlot(k, 2) = (*LS1DiodeBridgeCapFilter->x())(1);
// diode R1 current
dataPlot(k, 3) = (InterDiodeBridgeCapFilter->getLambda(0))(0);
// diode R1 voltage
dataPlot(k, 4) = -(*InterDiodeBridgeCapFilter->y(0))(0);
// diode F2 voltage
dataPlot(k, 5) = -(InterDiodeBridgeCapFilter->getLambda(0))(1);
// diode F1 current
dataPlot(k, 6) = (InterDiodeBridgeCapFilter->getLambda(0))(2);
// load voltage
dataPlot(k, 7) = (*LS2DiodeBridgeCapFilter->x())(0);
aTS->nextStep();
}
// --- elapsed time computing ---
cout << "time = " << t.elapsed() << endl;
// Number of time iterations
cout << "Number of iterations done: " << k << endl;
// dataPlot (ascii) output
dataPlot.resize(k, 10);
ioMatrix::write("DiodeBridgeCapFilter.dat", "ascii", dataPlot, "noDim");
cout << "Comparison with a reference file ..."<< endl;
SimpleMatrix dataPlotRef(dataPlot);
dataPlotRef.zero();
ioMatrix::read("DiodeBridgeCapFilter.ref", "ascii", dataPlotRef);
SP::SiconosVector err(new SiconosVector(dataPlot.size(1)));
(dataPlot - dataPlotRef).normInfByColumn(err);
err->display();
double error = 0.0;
for (unsigned int i = 0; i < 3; ++i)
{
if (error < (*err)(i))
error = (*err)(i);
}
cout << "error ="<<error << endl;
if (error > 1e-12)
{
(dataPlot - dataPlotRef).display();
std::cout << "Warning. The results is rather different from the reference file." << std::endl;
cout << "error ="<<error << endl;
return 1;
}
}
// --- Exceptions handling ---
catch (SiconosException e)
{
cout << "SiconosException" << endl;
cout << e.report() << endl;
}
catch (std::exception& e)
{
cout << "Exception: " << e.what() << endl;
exit(-1);
}
catch (...)
{
cout << "Exception caught " << endl;
}
}
<|endoftext|> |
<commit_before><commit_msg>Increase the default quota for extensions to 1GB.<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.