text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include "data/GraphSerializer.hpp"
#include "data/PathSerializer.hpp"
#include "data/ConfigSerializer.hpp"
#include "genetic/GeneticSolver.hpp"
#include "genetic/GeneticAnalyser.hpp"
#include "utils/Random.hpp"
#include "net/PopulationExchanger.hpp"
namespace po = boost::program_options;
tsp::Graph graph;
tsp::GeneticSolver solver(graph);
tsp::Config cfg;
tsp::PopulationExchanger *ex;
int parseArguments(int argc, char **argv)
{
po::variables_map vm;
po::options_description desc("Allowed Options");
desc.add_options()
("help,h", "show help text")
("config,c", po::value<std::string>(), "config file")
("infile,i", po::value<std::string>(), "graph definition file")
("outfile,o", po::value<std::string>(), "path output file")
("generations,g", po::value<unsigned int>(),
"amount of generations to be calculated")
("population,p", po::value<unsigned int>(), "population size")
("start,s", po::value<unsigned int>(), "start node")
("elitism,e", po::value<double>(), "elitism rate")
("mutation,m", po::value<double>(), "mutation chance")
("fitness,f", po::value<unsigned int>(), "fitness power")
("exchange,x", po::value<double>(), "exchange rate")
("network,n", "activate MPI network mode")
;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch(std::exception &e) {
std::cout << e.what() << "\n";
return 1;
}
bool hasConfig = vm.count("config");
bool hasOpt = vm.count("infile") &&
vm.count("outfile") &&
vm.count("generations") &&
vm.count("population") &&
vm.count("start") &&
vm.count("elitism") &&
vm.count("mutation") &&
vm.count("fitness");
bool hasHelp = vm.count("help");
if(hasHelp || !(hasConfig || hasOpt)) {
std::cout << desc << "\n";
return 1;
}
if(hasConfig) {
std::cout << "Loading Config from '" << vm["config"].as<std::string>() <<
"' ...";
std::cout.flush();
if(!tsp::ConfigSerializer::load(cfg, vm["config"].as<std::string>())) {
std::cout << " Failed\n";
return 1;
}
std::cout << " Done\n";
}
if(vm.count("infile"))
cfg.graphFile = vm["infile"].as<std::string>();
if(vm.count("outfile"))
cfg.pathFile = vm["outfile"].as<std::string>();
if(vm.count("generations"))
cfg.generationCount = vm["generations"].as<unsigned int>();
if(vm.count("population"))
cfg.gaSettings.populationSize = vm["population"].as<unsigned int>();
if(vm.count("start"))
cfg.gaSettings.startNode = vm["start"].as<unsigned int>();
if(vm.count("elitism"))
cfg.gaSettings.elitismRate = vm["elitism"].as<double>();
if(vm.count("mutation"))
cfg.gaSettings.mutationChance = vm["mutation"].as<double>();
if(vm.count("fitness"))
cfg.gaSettings.fitnessPow = vm["fitness"].as<unsigned int>();
if(vm.count("exchange"))
cfg.exchangeRate = vm["exchange"].as<double>();
if(vm.count("network")) {
ex = new tsp::PopulationExchanger(argc, argv);
ex->setExchangeCount(cfg.exchangeRate * cfg.gaSettings.populationSize);
}
return 0;
}
int main(int argc, char **argv)
{
tsp::Random::shakeRNG();
ex = NULL;
int ret = parseArguments(argc, argv);
if(ret)
return ret;
std::cout << "Parameters\n";
std::cout << " graph file: " << cfg.graphFile << "\n";
std::cout << " path file: " << cfg.pathFile << "\n";
std::cout << " generation count: " << cfg.generationCount << "\n";
std::cout << " population size: " << cfg.gaSettings.populationSize << "\n";
std::cout << " start node: " << cfg.gaSettings.startNode << "\n";
std::cout << " elitism rate: " << cfg.gaSettings.elitismRate << "\n";
std::cout << " mutation chance: " << cfg.gaSettings.mutationChance << "\n";
std::cout << " fitness power: " << cfg.gaSettings.fitnessPow << "\n";
std::cout << "Loading Graph ...";
std::cout.flush();
if(!tsp::GraphSerializer::load(graph, cfg.graphFile)) {
std::cout << " Failed\n";
return 1;
}
std::cout << " Done\n";
std::cout << "Initializing solver...";
std::cout.flush();
solver.setSettings(cfg.gaSettings);
solver.init();
std::cout << " Done\n";
tsp::GeneticAnalyser analyser(graph);
for(unsigned int i = 0; i < cfg.generationCount; ++i) {
std::cout << "Calculating Generation " << i + 1 << "... ";
std::cout.flush();
solver.nextGeneration();
if(ex != NULL) {
ex->exchange(solver.getPopulation());
solver.updateFitness();
}
std::cout << " Done\n";
std::cout << " Best Distance: " << analyser.getBestDistance(
solver.getPopulation()) << "\n";
std::cout << " Mean Distance: " << analyser.getMeanDistance(
solver.getPopulation()) << "\n";
std::cout << " Best Fitness: " << analyser.getBestFitness(
solver.getPopulation()) << "\n";
std::cout << " Mean Fitness: " << analyser.getMeanFitness(
solver.getPopulation()) << "\n";
std::cout << " Best Norm. Fitness: " << analyser.getBestNormalizedFitness(
solver.getPopulation()) << "\n";
}
std::cout << "Saving Path ...";
std::cout.flush();
tsp::PathSerializer::save(solver.getPopulation().getBestIndividual().getPath(),
cfg.pathFile);
std::cout << " Done\n";
if(ex != NULL)
delete ex;
return 0;
}
<commit_msg>Refactor simplega main<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include "data/GraphSerializer.hpp"
#include "data/PathSerializer.hpp"
#include "data/ConfigSerializer.hpp"
#include "genetic/GeneticSolver.hpp"
#include "genetic/GeneticAnalyser.hpp"
#include "net/PopulationExchanger.hpp"
#include "utils/Random.hpp"
namespace po = boost::program_options;
tsp::Graph graph;
tsp::GeneticSolver solver(graph);
tsp::Config cfg;
tsp::PopulationExchanger *ex = NULL;
static int parseArguments(int argc, char **argv)
{
po::variables_map vm;
po::options_description desc("Allowed Options");
desc.add_options()
("help,h", "show help text")
("config,c", po::value<std::string>(), "config file")
("infile,i", po::value<std::string>(), "graph definition file")
("outfile,o", po::value<std::string>(), "path output file")
("generations,g", po::value<unsigned int>(),
"amount of generations to be calculated")
("population,p", po::value<unsigned int>(), "population size")
("start,s", po::value<unsigned int>(), "start node")
("elitism,e", po::value<double>(), "elitism rate")
("mutation,m", po::value<double>(), "mutation chance")
("fitness,f", po::value<unsigned int>(), "fitness power")
("exchange,x", po::value<double>(), "exchange rate")
("network,n", "activate MPI network mode")
;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch(std::exception &e) {
std::cout << e.what() << "\n";
return 1;
}
bool hasConfig = vm.count("config");
bool hasOpt = vm.count("infile") &&
vm.count("outfile") &&
vm.count("generations") &&
vm.count("population") &&
vm.count("start") &&
vm.count("elitism") &&
vm.count("mutation") &&
vm.count("fitness");
bool hasHelp = vm.count("help");
if(hasHelp || !(hasConfig || hasOpt)) {
std::cout << desc << "\n";
return 1;
}
// load config file if specified
if(hasConfig) {
std::cout << "Loading Config from '" << vm["config"].as<std::string>() <<
"' ...";
std::cout.flush();
if(!tsp::ConfigSerializer::load(cfg, vm["config"].as<std::string>())) {
std::cout << " Failed\n";
return 1;
}
std::cout << " Done\n";
}
if(vm.count("exchange"))
cfg.exchangeRate = vm["exchange"].as<double>();
if(vm.count("network")) {
ex = new tsp::PopulationExchanger(argc, argv);
ex->setExchangeCount(cfg.exchangeRate * cfg.gaSettings.populationSize);
}
if(vm.count("infile"))
cfg.graphFile = vm["infile"].as<std::string>();
if(vm.count("outfile"))
cfg.pathFile = vm["outfile"].as<std::string>();
if(vm.count("generations"))
cfg.generationCount = vm["generations"].as<unsigned int>();
if(vm.count("population"))
cfg.gaSettings.populationSize = vm["population"].as<unsigned int>();
if(vm.count("start"))
cfg.gaSettings.startNode = vm["start"].as<unsigned int>();
if(vm.count("elitism"))
cfg.gaSettings.elitismRate = vm["elitism"].as<double>();
if(vm.count("mutation"))
cfg.gaSettings.mutationChance = vm["mutation"].as<double>();
if(vm.count("fitness"))
cfg.gaSettings.fitnessPow = vm["fitness"].as<unsigned int>();
return 0;
}
static int exchangeConfig()
{
// TODO Process 0 send config to all other processes
// only if network is activated
return 0;
}
static void printParameters()
{
std::cout << "Parameters\n";
std::cout << " graph file: " << cfg.graphFile << "\n";
std::cout << " path file: " << cfg.pathFile << "\n";
std::cout << " generation count: " << cfg.generationCount << "\n";
std::cout << " population size: " << cfg.gaSettings.populationSize << "\n";
std::cout << " start node: " << cfg.gaSettings.startNode << "\n";
std::cout << " elitism rate: " << cfg.gaSettings.elitismRate << "\n";
std::cout << " mutation chance: " << cfg.gaSettings.mutationChance << "\n";
std::cout << " fitness power: " << cfg.gaSettings.fitnessPow << "\n";
std::cout << " exchange rate: " << cfg.exchangeRate << "\n";
}
static int loadGraph()
{
std::cout << "Loading Graph ...";
std::cout.flush();
if(!tsp::GraphSerializer::load(graph, cfg.graphFile)) {
std::cout << " Failed\n";
return 1;
}
std::cout << " Done\n";
return 0;
}
static void runAlgorithm()
{
std::cout << "Initializing solver...";
std::cout.flush();
solver.setSettings(cfg.gaSettings);
solver.init();
std::cout << " Done\n";
tsp::GeneticAnalyser analyser(graph);
for(unsigned int i = 0; i < cfg.generationCount; ++i) {
std::cout << "Calculating Generation " << i + 1 << "... ";
std::cout.flush();
solver.nextGeneration();
if(ex != NULL) {
ex->exchange(solver.getPopulation());
solver.updateFitness();
}
std::cout << " Done\n";
std::cout << " Best Distance: " << analyser.getBestDistance(
solver.getPopulation()) << "\n";
std::cout << " Mean Distance: " << analyser.getMeanDistance(
solver.getPopulation()) << "\n";
std::cout << " Best Fitness: " << analyser.getBestFitness(
solver.getPopulation()) << "\n";
std::cout << " Mean Fitness: " << analyser.getMeanFitness(
solver.getPopulation()) << "\n";
std::cout << " Best Norm. Fitness: " << analyser.getBestNormalizedFitness(
solver.getPopulation()) << "\n";
}
}
static int gatherResults()
{
// TODO Process 0 should gather best individuals from all processes
// select best from those
// only gather if network is activated
return 0;
}
static int savePath()
{
std::cout << "Saving Path ...";
std::cout.flush();
if(!tsp::PathSerializer::save(solver.getPopulation().getBestIndividual().getPath(),
cfg.pathFile))
{
std::cout << " Failed\n";
return 1;
}
std::cout << " Done\n";
return 0;
}
int main(int argc, char **argv)
{
tsp::Random::shakeRNG();
int ret = parseArguments(argc, argv);
if(ret)
return ret;
ret = exchangeConfig();
if(ret)
return ret;
printParameters();
ret = loadGraph();
if(ret)
return ret;
runAlgorithm();
ret = gatherResults();
if(ret)
return ret;
ret = savePath();
if(ret)
return ret;
if(ex != NULL)
delete ex;
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 the author 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 "libtorrent/pch.hpp"
#include "libtorrent/socks5_stream.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
void socks5_stream::name_lookup(asio::error_code const& e, tcp::resolver::iterator i
, boost::shared_ptr<handler_type> h)
{
if (e || i == tcp::resolver::iterator())
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_sock.async_connect(i->endpoint(), boost::bind(
&socks5_stream::connected, this, _1, h));
}
void socks5_stream::connected(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
m_buffer.resize(m_user.empty()?3:4);
char* p = &m_buffer[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_user.empty())
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake1, this, _1, h));
}
void socks5_stream::handshake1(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(2);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake2, this, _1, h));
}
void socks5_stream::handshake2(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
char* p = &m_buffer[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
if (method == 0)
{
socks_connect(h);
}
else if (method == 2)
{
if (m_user.empty())
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
// start sub-negotiation
m_buffer.resize(m_user.size() + m_password.size() + 3);
char* p = &m_buffer[0];
write_uint8(1, p);
write_uint8(m_user.size(), p);
write_string(m_user, p);
write_uint8(m_password.size(), p);
write_string(m_password, p);
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake3, this, _1, h));
}
else
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
}
void socks5_stream::handshake3(asio::error_code const& e
, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(2);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake4, this, _1, h));
}
void socks5_stream::handshake4(asio::error_code const& e
, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
char* p = &m_buffer[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
if (status != 0)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
std::vector<char>().swap(m_buffer);
(*h)(e);
}
void socks5_stream::socks_connect(boost::shared_ptr<handler_type> h)
{
using namespace libtorrent::detail;
// send SOCKS5 connect command
m_buffer.resize(6 + (m_remote_endpoint.address().is_v4()?4:16));
char* p = &m_buffer[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(1, p); // CONNECT command
write_uint8(0, p); // reserved
write_uint8(m_remote_endpoint.address().is_v4()?1:4, p); // address type
write_address(m_remote_endpoint.address(), p);
write_uint16(m_remote_endpoint.port(), p);
TORRENT_ASSERT(p - &m_buffer[0] == int(m_buffer.size()));
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect1, this, _1, h));
}
void socks5_stream::connect1(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(6 + 4); // assume an IPv4 address
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect2, this, _1, h));
}
void socks5_stream::connect2(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
// send SOCKS5 connect command
char* p = &m_buffer[0];
int version = read_uint8(p);
if (version < 5)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
int response = read_uint8(p);
if (response != 0)
{
asio::error_code e = asio::error::fault;
switch (response)
{
case 1: e = asio::error::fault; break;
case 2: e = asio::error::no_permission; break;
case 3: e = asio::error::network_unreachable; break;
case 4: e = asio::error::host_unreachable; break;
case 5: e = asio::error::connection_refused; break;
case 6: e = asio::error::timed_out; break;
case 7: e = asio::error::operation_not_supported; break;
case 8: e = asio::error::address_family_not_supported; break;
}
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
p += 1; // reserved
int atyp = read_uint8(p);
// we ignore the proxy IP it was bound to
if (atyp == 1)
{
std::vector<char>().swap(m_buffer);
(*h)(e);
return;
}
int skip_bytes = 0;
if (atyp == 4)
{
skip_bytes = 12;
}
else if (atyp == 3)
{
skip_bytes = read_uint8(p) - 3;
}
else
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(skip_bytes);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect3, this, _1, h));
}
void socks5_stream::connect3(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
std::vector<char>().swap(m_buffer);
(*h)(e);
}
}
<commit_msg>fixed bug in socks5 implementation when using user/pass authentication<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 the author 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 "libtorrent/pch.hpp"
#include "libtorrent/socks5_stream.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
void socks5_stream::name_lookup(asio::error_code const& e, tcp::resolver::iterator i
, boost::shared_ptr<handler_type> h)
{
if (e || i == tcp::resolver::iterator())
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_sock.async_connect(i->endpoint(), boost::bind(
&socks5_stream::connected, this, _1, h));
}
void socks5_stream::connected(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
m_buffer.resize(m_user.empty()?3:4);
char* p = &m_buffer[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_user.empty())
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake1, this, _1, h));
}
void socks5_stream::handshake1(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(2);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake2, this, _1, h));
}
void socks5_stream::handshake2(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
char* p = &m_buffer[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
if (method == 0)
{
socks_connect(h);
}
else if (method == 2)
{
if (m_user.empty())
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
// start sub-negotiation
m_buffer.resize(m_user.size() + m_password.size() + 3);
char* p = &m_buffer[0];
write_uint8(1, p);
write_uint8(m_user.size(), p);
write_string(m_user, p);
write_uint8(m_password.size(), p);
write_string(m_password, p);
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake3, this, _1, h));
}
else
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
}
void socks5_stream::handshake3(asio::error_code const& e
, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(2);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::handshake4, this, _1, h));
}
void socks5_stream::handshake4(asio::error_code const& e
, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
char* p = &m_buffer[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
if (status != 0)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
std::vector<char>().swap(m_buffer);
socks_connect(h);
}
void socks5_stream::socks_connect(boost::shared_ptr<handler_type> h)
{
using namespace libtorrent::detail;
// send SOCKS5 connect command
m_buffer.resize(6 + (m_remote_endpoint.address().is_v4()?4:16));
char* p = &m_buffer[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(1, p); // CONNECT command
write_uint8(0, p); // reserved
write_uint8(m_remote_endpoint.address().is_v4()?1:4, p); // address type
write_address(m_remote_endpoint.address(), p);
write_uint16(m_remote_endpoint.port(), p);
TORRENT_ASSERT(p - &m_buffer[0] == int(m_buffer.size()));
asio::async_write(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect1, this, _1, h));
}
void socks5_stream::connect1(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(6 + 4); // assume an IPv4 address
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect2, this, _1, h));
}
void socks5_stream::connect2(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
using namespace libtorrent::detail;
// send SOCKS5 connect command
char* p = &m_buffer[0];
int version = read_uint8(p);
if (version < 5)
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
int response = read_uint8(p);
if (response != 0)
{
asio::error_code e = asio::error::fault;
switch (response)
{
case 1: e = asio::error::fault; break;
case 2: e = asio::error::no_permission; break;
case 3: e = asio::error::network_unreachable; break;
case 4: e = asio::error::host_unreachable; break;
case 5: e = asio::error::connection_refused; break;
case 6: e = asio::error::timed_out; break;
case 7: e = asio::error::operation_not_supported; break;
case 8: e = asio::error::address_family_not_supported; break;
}
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
p += 1; // reserved
int atyp = read_uint8(p);
// we ignore the proxy IP it was bound to
if (atyp == 1)
{
std::vector<char>().swap(m_buffer);
(*h)(e);
return;
}
int skip_bytes = 0;
if (atyp == 4)
{
skip_bytes = 12;
}
else if (atyp == 3)
{
skip_bytes = read_uint8(p) - 3;
}
else
{
(*h)(asio::error::operation_not_supported);
asio::error_code ec;
close(ec);
return;
}
m_buffer.resize(skip_bytes);
asio::async_read(m_sock, asio::buffer(m_buffer)
, boost::bind(&socks5_stream::connect3, this, _1, h));
}
void socks5_stream::connect3(asio::error_code const& e, boost::shared_ptr<handler_type> h)
{
if (e)
{
(*h)(e);
asio::error_code ec;
close(ec);
return;
}
std::vector<char>().swap(m_buffer);
(*h)(e);
}
}
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#ifndef SET_HPP
#define SET_HPP
#include "coloredkdbio.hpp"
#include <command.hpp>
#include <kdb.hpp>
class SetCommand : public Command
{
kdb::KDB kdb;
public:
SetCommand ();
~SetCommand ();
virtual std::string getShortOptions () override
{
return "qN";
}
virtual std::string getSynopsis () override
{
return "<name> [<value>]";
}
virtual std::string getShortHelpText () override
{
return "Set the value of an individual key.";
}
virtual std::string getLongHelpText () override
{
return "If no value is given, it will be set to a null-value\n"
"To get an empty value you need to quote like \"\" (depending on shell)\n"
"To set a negative value you need to use '--' to stop option processing.\n"
"(e.g. 'kdb set -- /tests/neg -3')\n";
}
virtual int execute (Cmdline const & cmdline) override;
};
#endif
<commit_msg>kdb: remove null key setting in header file<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#ifndef SET_HPP
#define SET_HPP
#include "coloredkdbio.hpp"
#include <command.hpp>
#include <kdb.hpp>
class SetCommand : public Command
{
kdb::KDB kdb;
public:
SetCommand ();
~SetCommand ();
virtual std::string getShortOptions () override
{
return "qN";
}
virtual std::string getSynopsis () override
{
return "<name> <value>";
}
virtual std::string getShortHelpText () override
{
return "Set the value of an individual key.";
}
virtual std::string getLongHelpText () override
{
return "To get an empty value you need to quote like \"\" (depending on shell)\n"
"To set a negative value you need to use '--' to stop option processing.\n"
"(e.g. 'kdb set -- /tests/neg -3')\n";
}
virtual int execute (Cmdline const & cmdline) override;
};
#endif
<|endoftext|>
|
<commit_before>/* Copyright (C) 2016 INRA
*
* 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 <fstream>
#include <iostream>
#include <limits>
#include <lpcore>
#include <sstream>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <getopt.h>
void help() noexcept;
double to_double(const char* s, double bad_value) noexcept;
long to_long(const char* s, long bad_value) noexcept;
std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept;
const char* file_format_error_format(lp::file_format_error::tag) noexcept;
const char* problem_definition_error_format(
lp::problem_definition_error::tag) noexcept;
const char* solver_error_format(lp::solver_error::tag) noexcept;
int
main(int argc, char* argv[])
{
const char* const short_opts = "hp:l:qv:";
const struct option long_opts[] = {
{ "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' },
{ "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 },
{ "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 }
};
int opt_index;
int verbose = 1;
bool fail = false;
bool quiet = false;
std::map<std::string, lp::parameter> parameters;
while (not fail) {
const auto opt =
getopt_long(argc, argv, short_opts, long_opts, &opt_index);
if (opt == -1)
break;
switch (opt) {
case 0:
break;
case 'l':
parameters["limit"] = to_long(::optarg, 1000l);
break;
case 'h':
help();
return EXIT_SUCCESS;
case 'p': {
std::string name;
lp::parameter value;
std::tie(name, value) = split_param(::optarg);
parameters[name] = value;
} break;
case '?':
default:
fail = true;
std::fprintf(stderr, "Unknown command line option\n");
break;
};
}
if (fail)
return EXIT_FAILURE;
(void)verbose;
(void)quiet;
for (int i = ::optind; i < argc; ++i) {
try {
auto pb = lp::make_problem(argv[i]);
auto ret = lp::solve(pb, parameters);
if (ret.solution_found and
lp::is_valid_solution(pb, ret.variable_value)) {
std::fprintf(stdout, "Solution found: %f\n", ret.value);
for (std::size_t i{ 0 }, e{ ret.variable_name.size() }; i != e;
++i)
std::fprintf(stdout,
"%s = %d",
ret.variable_name[i].c_str(),
ret.variable_value[i]);
} else {
std::fprintf(stdout, "No solution found\n");
}
} catch (const lp::precondition_error& e) {
std::fprintf(stderr, "internal failure\n");
} catch (const lp::postcondition_error& e) {
std::fprintf(stderr, "internal failure\n");
} catch (const lp::numeric_cast_error& e) {
std::fprintf(stderr, "numeric cast interal failure\n");
} catch (const lp::file_access_error& e) {
std::fprintf(stderr,
"file `%s' fail %d: %s\n",
e.file().c_str(),
e.error(),
std::strerror(e.error()));
} catch (const lp::file_format_error& e) {
std::fprintf(stderr,
"file format error at line %d column %d "
"%s\n",
e.line(),
e.column(),
file_format_error_format(e.failure()));
} catch (const lp::problem_definition_error& e) {
std::fprintf(stderr,
"definition problem error at %s: %s\n",
e.element().c_str(),
problem_definition_error_format(e.failure()));
} catch (const lp::solver_error& e) {
std::fprintf(
stderr, "solver error: %s\n", solver_error_format(e.failure()));
} catch (const std::exception& e) {
std::fprintf(stderr, "failure: %s.\n", e.what());
}
}
return EXIT_SUCCESS;
}
void
help() noexcept
{
std::fprintf(stdout,
"--help|-h This help message\n"
"--param|-p [name]:[value] Add a new parameter (name is"
" [a-z][A-Z]_ value can be a double, an integer otherwise a"
" string.\n"
"--limit int Set limit\n"
"--quiet Remove any verbose message\n"
"--verbose|-v int Set verbose level\n");
}
const char*
file_format_error_format(lp::file_format_error::tag failure) noexcept
{
static const char* const tag[] = {
"end of file", "unknown",
"already defined", "incomplete",
"bad name", "bad operator",
"bad integer", "bad objective function type",
"bad bound", "bad function element",
"bad constraint"
};
switch (failure) {
case lp::file_format_error::tag::end_of_file:
return tag[0];
case lp::file_format_error::tag::unknown:
return tag[1];
case lp::file_format_error::tag::already_defined:
return tag[2];
case lp::file_format_error::tag::incomplete:
return tag[3];
case lp::file_format_error::tag::bad_name:
return tag[4];
case lp::file_format_error::tag::bad_operator:
return tag[5];
case lp::file_format_error::tag::bad_integer:
return tag[6];
case lp::file_format_error::tag::bad_objective_function_type:
return tag[7];
case lp::file_format_error::tag::bad_bound:
return tag[8];
case lp::file_format_error::tag::bad_function_element:
return tag[9];
case lp::file_format_error::tag::bad_constraint:
return tag[10];
}
return nullptr;
}
const char*
problem_definition_error_format(
lp::problem_definition_error::tag failure) noexcept
{
static const char* const tag[] = {
"empty variables",
"empty objective function",
"variable not used",
"bad bound",
"multiple constraints with different value"
};
switch (failure) {
case lp::problem_definition_error::tag::empty_variables:
return tag[0];
case lp::problem_definition_error::tag::empty_objective_function:
return tag[1];
case lp::problem_definition_error::tag::variable_not_used:
return tag[2];
case lp::problem_definition_error::tag::bad_bound:
return tag[3];
case lp::problem_definition_error::tag::multiple_constraint:
return tag[4];
}
return nullptr;
}
const char*
solver_error_format(lp::solver_error::tag failure) noexcept
{
static const char* const tag[] = { "no solver available",
"unrealisable constraint",
"not enough memory" };
switch (failure) {
case lp::solver_error::tag::no_solver_available:
return tag[0];
case lp::solver_error::tag::unrealisable_constraint:
return tag[1];
case lp::solver_error::tag::not_enough_memory:
return tag[2];
}
return nullptr;
}
double
to_double(const char* s, double bad_value) noexcept
{
char* c;
errno = 0;
double value = std::strtof(s, &c);
if ((errno == ERANGE and (value == std::numeric_limits<double>::lowest() or
value == -std::numeric_limits<double>::max())) or
(errno != 0 and value == 0) or (c == ::optarg))
return bad_value;
return value;
}
long
to_long(const char* s, long bad_value) noexcept
{
char* c;
errno = 0;
long value = std::strtol(s, &c, 10);
if ((errno == ERANGE and (value == std::numeric_limits<long>::lowest() or
value == std::numeric_limits<long>::max())) or
(errno != 0 and value == 0) or (c == ::optarg))
return bad_value;
return value;
}
std::tuple<std::string, lp::parameter>
split_param(const char* param) noexcept
{
std::string name, value;
while (*param) {
if (isalpha(*param) or *param == '_' or *param == '-')
name += *param;
else
break;
param++;
}
if (*param and (*param == ':' or *param == '=')) {
param++;
while (*param) {
if (isalnum(*param) or *param == '.')
value += *param;
else
break;
param++;
}
}
auto valuel = to_long(value.c_str(), std::numeric_limits<long>::min());
auto valued = to_double(value.c_str(), std::numeric_limits<double>::min());
double tmp;
if (valued != std::numeric_limits<double>::min() and
std::modf(valued, &tmp))
return std::make_tuple(name, lp::parameter(valued));
if (valuel != std::numeric_limits<long>::min())
return std::make_tuple(name, lp::parameter(valuel));
return std::make_tuple(name, lp::parameter(value));
}
<commit_msg>main: fix detection of bad long or double<commit_after>/* Copyright (C) 2016 INRA
*
* 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 <fstream>
#include <iostream>
#include <limits>
#include <lpcore>
#include <sstream>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <getopt.h>
void help() noexcept;
double to_double(const char* s, double bad_value) noexcept;
long to_long(const char* s, long bad_value) noexcept;
std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept;
const char* file_format_error_format(lp::file_format_error::tag) noexcept;
const char* problem_definition_error_format(
lp::problem_definition_error::tag) noexcept;
const char* solver_error_format(lp::solver_error::tag) noexcept;
int
main(int argc, char* argv[])
{
const char* const short_opts = "hp:l:qv:";
const struct option long_opts[] = {
{ "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' },
{ "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 },
{ "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 }
};
int opt_index;
int verbose = 1;
bool fail = false;
bool quiet = false;
std::map<std::string, lp::parameter> parameters;
while (not fail) {
const auto opt =
getopt_long(argc, argv, short_opts, long_opts, &opt_index);
if (opt == -1)
break;
switch (opt) {
case 0:
break;
case 'l':
parameters["limit"] = to_long(::optarg, 1000l);
break;
case 'h':
help();
return EXIT_SUCCESS;
case 'p': {
std::string name;
lp::parameter value;
std::tie(name, value) = split_param(::optarg);
parameters[name] = value;
} break;
case '?':
default:
fail = true;
std::fprintf(stderr, "Unknown command line option\n");
break;
};
}
if (fail)
return EXIT_FAILURE;
(void)verbose;
(void)quiet;
for (int i = ::optind; i < argc; ++i) {
try {
auto pb = lp::make_problem(argv[i]);
auto ret = lp::solve(pb, parameters);
if (ret.solution_found and
lp::is_valid_solution(pb, ret.variable_value)) {
std::fprintf(stdout, "Solution found: %f\n", ret.value);
for (std::size_t i{ 0 }, e{ ret.variable_name.size() }; i != e;
++i)
std::fprintf(stdout,
"%s = %d",
ret.variable_name[i].c_str(),
ret.variable_value[i]);
} else {
std::fprintf(stdout, "No solution found\n");
}
} catch (const lp::precondition_error& e) {
std::fprintf(stderr, "internal failure\n");
} catch (const lp::postcondition_error& e) {
std::fprintf(stderr, "internal failure\n");
} catch (const lp::numeric_cast_error& e) {
std::fprintf(stderr, "numeric cast interal failure\n");
} catch (const lp::file_access_error& e) {
std::fprintf(stderr,
"file `%s' fail %d: %s\n",
e.file().c_str(),
e.error(),
std::strerror(e.error()));
} catch (const lp::file_format_error& e) {
std::fprintf(stderr,
"file format error at line %d column %d "
"%s\n",
e.line(),
e.column(),
file_format_error_format(e.failure()));
} catch (const lp::problem_definition_error& e) {
std::fprintf(stderr,
"definition problem error at %s: %s\n",
e.element().c_str(),
problem_definition_error_format(e.failure()));
} catch (const lp::solver_error& e) {
std::fprintf(
stderr, "solver error: %s\n", solver_error_format(e.failure()));
} catch (const std::exception& e) {
std::fprintf(stderr, "failure: %s.\n", e.what());
}
}
return EXIT_SUCCESS;
}
void
help() noexcept
{
std::fprintf(stdout,
"--help|-h This help message\n"
"--param|-p [name]:[value] Add a new parameter (name is"
" [a-z][A-Z]_ value can be a double, an integer otherwise a"
" string.\n"
"--limit int Set limit\n"
"--quiet Remove any verbose message\n"
"--verbose|-v int Set verbose level\n");
}
const char*
file_format_error_format(lp::file_format_error::tag failure) noexcept
{
static const char* const tag[] = {
"end of file", "unknown",
"already defined", "incomplete",
"bad name", "bad operator",
"bad integer", "bad objective function type",
"bad bound", "bad function element",
"bad constraint"
};
switch (failure) {
case lp::file_format_error::tag::end_of_file:
return tag[0];
case lp::file_format_error::tag::unknown:
return tag[1];
case lp::file_format_error::tag::already_defined:
return tag[2];
case lp::file_format_error::tag::incomplete:
return tag[3];
case lp::file_format_error::tag::bad_name:
return tag[4];
case lp::file_format_error::tag::bad_operator:
return tag[5];
case lp::file_format_error::tag::bad_integer:
return tag[6];
case lp::file_format_error::tag::bad_objective_function_type:
return tag[7];
case lp::file_format_error::tag::bad_bound:
return tag[8];
case lp::file_format_error::tag::bad_function_element:
return tag[9];
case lp::file_format_error::tag::bad_constraint:
return tag[10];
}
return nullptr;
}
const char*
problem_definition_error_format(
lp::problem_definition_error::tag failure) noexcept
{
static const char* const tag[] = {
"empty variables",
"empty objective function",
"variable not used",
"bad bound",
"multiple constraints with different value"
};
switch (failure) {
case lp::problem_definition_error::tag::empty_variables:
return tag[0];
case lp::problem_definition_error::tag::empty_objective_function:
return tag[1];
case lp::problem_definition_error::tag::variable_not_used:
return tag[2];
case lp::problem_definition_error::tag::bad_bound:
return tag[3];
case lp::problem_definition_error::tag::multiple_constraint:
return tag[4];
}
return nullptr;
}
const char*
solver_error_format(lp::solver_error::tag failure) noexcept
{
static const char* const tag[] = { "no solver available",
"unrealisable constraint",
"not enough memory" };
switch (failure) {
case lp::solver_error::tag::no_solver_available:
return tag[0];
case lp::solver_error::tag::unrealisable_constraint:
return tag[1];
case lp::solver_error::tag::not_enough_memory:
return tag[2];
}
return nullptr;
}
double
to_double(const char* s, double bad_value) noexcept
{
char* c;
errno = 0;
double value = std::strtod(s, &c);
if ((errno == ERANGE and (value == HUGE_VAL or value == -HUGE_VAL)) or
(value == 0.0 and c == s))
return bad_value;
return value;
}
long
to_long(const char* s, long bad_value) noexcept
{
char* c;
errno = 0;
long value = std::strtol(s, &c, 10);
if ((errno == ERANGE and (value == LONG_MIN or value == LONG_MAX)) or
(value == 0 and c == s))
return bad_value;
return value;
}
std::tuple<std::string, lp::parameter>
split_param(const char* param) noexcept
{
std::string name, value;
while (*param) {
if (isalpha(*param) or *param == '_' or *param == '-')
name += *param;
else
break;
param++;
}
if (*param and (*param == ':' or *param == '=')) {
param++;
while (*param)
value += *param++;
}
auto valuel = to_long(value.c_str(), LONG_MIN);
auto valued = to_double(value.c_str(), -HUGE_VAL);
double tmp;
if (valued != -HUGE_VAL and std::modf(valued, &tmp))
return std::make_tuple(name, lp::parameter(valued));
if (valuel != LONG_MIN)
return std::make_tuple(name, lp::parameter(valuel));
return std::make_tuple(name, lp::parameter(value));
}
<|endoftext|>
|
<commit_before>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "OpcodeBase.hpp"
#include <algorithm>
#include <cmath>
#include <dirent.h>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace csound;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
// MYFLT* trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
iftsamplebank() {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
numberOfFiles = 0;
sDirectory = NULL;
}
// init-pass
int init(CSOUND *csound) {
*numberOfFiles = loadSamplesToTables(
csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *) { return OK; }
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
MYFLT *trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
int internalCounter;
kftsamplebank() : internalCounter(0) {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
trigger = 0;
}
// init-pass
int init(CSOUND *csound) {
IGN(csound);
*numberOfFiles = 0;
// loadSamplesToTables(csound, *index, fileNames,
// (char* )sDirectory->data, *skiptime, *format, *channel);
// csound->Message(csound, (char* )sDirectory->data);
*trigger = 0;
return OK;
}
int noteoff(CSOUND *) { return OK; }
int kontrol(CSOUND *csound) {
// if directry changes update tables..
if (*trigger == 1) {
*numberOfFiles =
loadSamplesToTables(csound, *index, (char *)sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel) {
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
// only use supported file types
for (int i = 0; (size_t)i < fileExtensions.size(); i++)
{
std::string fname = ent->d_name;
std::string extension;
if(fname.find_last_of(".") != std::string::npos)
extension = fname.substr(fname.find_last_of(".")+1);
if(extension == fileExtensions[i])
{
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
// push statements to score, starting with table number 'index'
for (int y = 0; (size_t)y < fileNames.size(); y++) {
std::ostringstream statement;
statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" "
<< skiptime << " " << format << " " << channel << "\n";
// csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
closedir(dir);
} else {
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
// return number of files
return noOfFiles;
} else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT *outArr;
STRINGDAT *directoryName;
MYFLT *extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory
*/
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension);
#include "arrays.h"
#if 0
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) {
p->data = (MYFLT*)csound->Calloc(csound, ss);
p->allocated = ss;
}
else if (ss > p->allocated) {
p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->allocated = ss;
}
if (p->dimensions==0) {
p->dimensions = 1;
p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));
}
}
p->sizes[0] = size;
}
#endif
static int directory(CSOUND *csound, DIR_STRUCT *p) {
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount == 0)
return csound->InitError(
csound, "%s", Str("Error: you must pass a directory as a string."));
if (inArgCount == 1) {
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if (inArgCount == 2) {
CS_TYPE *argType = csound->GetTypeForArg(p->extension);
if (strcmp("S", argType->varTypeName) == 0) {
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
} else
return csound->InitError(csound,
"%s", Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabinit(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *)p->outArr->data;
for (int i = 0; i < numberOfFiles; i++) {
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension) {
std::vector<std::string> fileNames;
if (directory) {
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
std::string fname = ent->d_name;
size_t lastPos = fname.find_last_of(".");
if (fname.length() > 2 && (fileExtension.empty() ||
(lastPos != std::string::npos &&
fname.substr(lastPos) == fileExtension))) {
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
} else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
} else {
csound->Message(csound, Str("Cannot find directory. "
"Error opening directory: %s\n"),
directory);
}
closedir(dir);
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {
int status = csound->AppendOpcode(
csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3,
(char *)"k", (char *)"Skkkkk",
(int (*)(CSOUND *, void *))kftsamplebank::init_,
(int (*)(CSOUND *, void *))kftsamplebank::kontrol_,
(int (*)(CSOUND *, void *))0);
status |= csound->AppendOpcode(
csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1,
(char *)"i", (char *)"Siiii",
(int (*)(CSOUND *, void *))iftsamplebank::init_,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(
csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]",
(char *)"SN", (int (*)(CSOUND *, void *))directory,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
return status;
}
#ifndef INIT_STATIC_MODULES
PUBLIC int csoundModuleCreate(CSOUND *csound) {
IGN(csound);
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound) {
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound) {
IGN(csound);
return 0;
}
#endif
}
<commit_msg>rory's changes<commit_after>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "OpcodeBase.hpp"
#include <algorithm>
#include <cmath>
#include <dirent.h>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace csound;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
// MYFLT* trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
iftsamplebank() {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
numberOfFiles = 0;
sDirectory = NULL;
}
// init-pass
int init(CSOUND *csound) {
*numberOfFiles = loadSamplesToTables(
csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *) { return OK; }
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
MYFLT *trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
int internalCounter;
kftsamplebank() : internalCounter(0) {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
trigger = 0;
}
// init-pass
int init(CSOUND *csound) {
IGN(csound);
*numberOfFiles =
loadSamplesToTables(csound, *index, (char *)sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
return OK;
}
int noteoff(CSOUND *) { return OK; }
int kontrol(CSOUND *csound) {
// if directry changes update tables..
if (*trigger == 1) {
*numberOfFiles =
loadSamplesToTables(csound, *index, (char *)sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel) {
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
// only use supported file types
for (int i = 0; (size_t)i < fileExtensions.size(); i++)
{
std::string fname = ent->d_name;
std::string extension;
if(fname.find_last_of(".") != std::string::npos)
extension = fname.substr(fname.find_last_of("."));
csound->Message(csound, "Extension: %s", extension.c_str());
if(extension == fileExtensions[i])
{
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
// push statements to score, starting with table number 'index'
for (int y = 0; (size_t)y < fileNames.size(); y++) {
std::ostringstream statement;
statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" "
<< skiptime << " " << format << " " << channel << "\n";
// csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
closedir(dir);
} else {
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
// return number of files
return noOfFiles;
} else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT *outArr;
STRINGDAT *directoryName;
MYFLT *extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory
*/
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension);
#include "arrays.h"
#if 0
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) {
p->data = (MYFLT*)csound->Calloc(csound, ss);
p->allocated = ss;
}
else if (ss > p->allocated) {
p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->allocated = ss;
}
if (p->dimensions==0) {
p->dimensions = 1;
p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));
}
}
p->sizes[0] = size;
}
#endif
static int directory(CSOUND *csound, DIR_STRUCT *p) {
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount == 0)
return csound->InitError(
csound, "%s", Str("Error: you must pass a directory as a string."));
if (inArgCount == 1) {
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if (inArgCount == 2) {
CS_TYPE *argType = csound->GetTypeForArg(p->extension);
if (strcmp("S", argType->varTypeName) == 0) {
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
} else
return csound->InitError(csound,
"%s", Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabinit(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *)p->outArr->data;
for (int i = 0; i < numberOfFiles; i++) {
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension) {
std::vector<std::string> fileNames;
if (directory) {
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
std::string fname = ent->d_name;
size_t lastPos = fname.find_last_of(".");
if (fname.length() > 2 && (fileExtension.empty() ||
(lastPos != std::string::npos &&
fname.substr(lastPos) == fileExtension))) {
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
} else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
} else {
csound->Message(csound, Str("Cannot find directory. "
"Error opening directory: %s\n"),
directory);
}
closedir(dir);
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {
int status = csound->AppendOpcode(
csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3,
(char *)"k", (char *)"Skkkkk",
(int (*)(CSOUND *, void *))kftsamplebank::init_,
(int (*)(CSOUND *, void *))kftsamplebank::kontrol_,
(int (*)(CSOUND *, void *))0);
status |= csound->AppendOpcode(
csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1,
(char *)"i", (char *)"Siiii",
(int (*)(CSOUND *, void *))iftsamplebank::init_,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(
csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]",
(char *)"SN", (int (*)(CSOUND *, void *))directory,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
return status;
}
#ifndef INIT_STATIC_MODULES
PUBLIC int csoundModuleCreate(CSOUND *csound) {
IGN(csound);
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound) {
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound) {
IGN(csound);
return 0;
}
#endif
}
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <catch/catch.hpp>
#include "plant_generator.h"
#include "from_json.h"
using namespace std;
using namespace plantgen;
namespace
{
constexpr size_t num_range_rng_tests = 1000;
}
TEST_CASE("Testing the Test Framework")
{
SECTION("Variant Comparators")
{
SECTION("Value Comparators")
{
string std_string = "string";
variant_value_t variant_string = "string";
REQUIRE(variant_string == std_string);
REQUIRE(std_string == variant_string);
std::string other_str = "something else entirely";
variant_value_t other_variant_str = "something_else_entirely";
REQUIRE(std_string != other_str);
REQUIRE(variant_string != other_variant_str);
REQUIRE(variant_string != other_str);
//REQUIRE(other_str != variant_string);
REQUIRE(other_variant_str != std_string);
//REQUIRE(std_string != other_variant_str);
}
SECTION("Value List Comparators")
{
std::vector<std::string> string_list = {"A", "B", "C", "D"};
value_list_t variant_list = {"A", "B", "C", "D"};
CHECK(string_list == variant_list);
CHECK(variant_list == string_list);
auto auto_strings = {"A","B","C","D"};
REQUIRE(variant_list == auto_strings);
std::vector<std::string> wrong_strings = {"X", "Y", "Z", "W"};
REQUIRE(variant_list != wrong_strings);
}
}
SECTION("Basic Node")
{
pregen_node_t node = node_from_json("data/basic_node.json");
REQUIRE(node.name == "Basic Node");
REQUIRE(node.values.size() == 4);
REQUIRE(node.children.size() == 1); //properties
REQUIRE(node.children[0].name == "Property");
REQUIRE(node.children[0].values.size() == 4);
std::vector<std::string> expected_node_value_strings = {"A", "B", "C", "D"};
CHECK(node.values == expected_node_value_strings);
expected_node_value_strings = {"1 A", "1 B", "1 C", "1 D"};
CHECK(node.children[0].values == expected_node_value_strings);
}
SECTION("Fancy Node")
{
pregen_node_t node = node_from_json("data/fancy_node.json");
REQUIRE(node.name == "Fancy Node");
/// Properties
REQUIRE(node.children.size() == 2);
auto const& p1 = node.children[0];
REQUIRE(p1.children.size() == 0);
auto const& p2 = node.children[1];
REQUIRE(p2.children.size() == 2);
auto const& p2a = p2.children[0];
auto const& p2b = p2.children[1];
REQUIRE(p2a.children.size() == 0);
REQUIRE(p2a.children.size() == 1);
auto const& p2b_1 = p2b.children[0];
REQUIRE(p2b_1.children.size() == 0);
/// Values
REQUIRE(node.values.size() == 2);
REQUIRE(node.value_nodes.size() == 1);
auto node_value_strings = {"ValueString A", "ValueString B"};
CHECK(node.values == node_value_strings);
auto const& vn = node.value_nodes[0];
CHECK(vn.name == "ValueObj A");
REQUIRE(vn.children.size() == 1);
REQUIRE(vn.values.size() == 4);
REQUIRE(vn.value_nodes.size() == 1);
auto vn_value_strings = {"ValueObj Value A", "ValueObj Value B", "ValueObj Value C", "ValueObj Value D"};
CHECK(vn.values == vn_value_strings);
REQUIRE(vn.value_nodes[0].name == "Value Obj Value Obj");
auto const& vn_p1 = vn.children[0];
REQUIRE(vn_p1.name == "ValueObj Property One");
auto vn_p1_value_strings = {"VObj P1 A", "VObj P1 B", "VObj P1 C", "VObj P1 D"};
REQUIRE(vn_p1.values == vn_p1_value_strings);
auto p1_value_strings = {"1 A", "1 B"};
CHECK(p1.values == p1_value_strings);
CHECK(p1.value_nodes[0].name == "ValueObj 1 A");
CHECK(p1.value_nodes[1].name == "ValueObj 1 B");
auto p2a_value_strings = {"2A - A", "2A - B", "2A - C", "2A - D"};
CHECK(p2a.values == p2a_value_strings);
REQUIRE(p2b_1.value_nodes.size() == 1);
auto const& p2b_1_vnode = p2b_1.value_nodes[0];
CHECK(p2b_1_vnode.name == "P2B_1 Value Node A");
auto p2b_1_vnode_value_strings = {"Value Node Value A", "Value Node Value B", "Value Node Value C", "Value Node Value D"};
REQUIRE(p2b_1_vnode.values == p2b_1_vnode_value_strings);
}
SECTION("Range Value")
{
pregen_node_t node = node_from_json("data/range_value.json");
REQUIRE(node.name == "Range Value");
REQUIRE(node.children.size() == 1);
REQUIRE(node.values.size() == 2);
REQUIRE(node.value_nodes.size() == 0);
REQUIRE(std::holds_alternative<range_value_t>(node.values[0]));
REQUIRE(std::holds_alternative<range_value_t>(node.values[1]));
range_value_t r0 = std::get<range_value_t>(node.values[0]);
std::vector<std::string> r0_strings = {"1 A", "1 B", "1 C", "1 D"};
REQUIRE(r0 == r0_strings);
range_value_t r1 = std::get<range_value_t>(node.values[1]);
std::vector<std::string> r1_strings = {"2 A", "2 B", "2 C", "2 D"};
REQUIRE(r1 == r1_strings);
auto const& p1 = node.children[0];
REQUIRE(p1.children.size() == 0);
REQUIRE(p1.values.size() == 5);
REQUIRE(p1.value_nodes.size() == 1);
CHECK(p1.values[0] == std::string("NotRange A"));
CHECK(p1.values[1] == std::string("NotRange B"));
CHECK(p1.values[2] == std::string("NotRange C"));
REQUIRE(std::holds_alternative<range_value_t>(p1.values[3]));
REQUIRE(std::holds_alternative<range_value_t>(p1.values[4]));
range_value_t p1r0 = std::get<range_value_t>(p1.values[3]);
std::vector<std::string> p1r0_strings = {"P1R1 A", "P1R1 B", "P1R1 C", "P1R1 D"};
REQUIRE(p1r0 == p1r0_strings);
range_value_t p1r1 = std::get<range_value_t>(p1.values[4]);
std::vector<std::string> p1r1_strings = {"P1R2 A", "P1R2 B", "P1R2 C", "P1R2 D"};
REQUIRE(p1r1 == p1r1_strings);
SECTION("Range Generation")
{
auto generated = generate_node(node);
REQUIRE(generated.name == node.name);
REQUIRE(generated.generated_values.size() == node.children.size());
auto get_total = [](std::vector<std::string> const& gend_vals) -> uint32_t
{
uint32_t total = 0;
for(auto const& v : gend_vals)
{
total += stoi(v);
}
};
REQUIRE(get_total(generated.generated_values) == 100);
bool all_range_rng_passed = true;
for(size_t i = 0; i < num_range_rng_tests; ++i)
all_range_rng_passed &= (get_total(generated.generated_values) == 100);
REQUIRE(all_range_rng_passed);
}
}
}<commit_msg>weight tests<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <catch/catch.hpp>
#include "plant_generator.h"
#include "from_json.h"
using namespace std;
using namespace plantgen;
namespace
{
constexpr size_t num_range_rng_tests = 1000;
}
TEST_CASE("Testing the Test Framework")
{
SECTION("Variant Comparators")
{
SECTION("Value Comparators")
{
string std_string = "string";
variant_value_t variant_string = "string";
REQUIRE(variant_string == std_string);
REQUIRE(std_string == variant_string);
std::string other_str = "something else entirely";
variant_value_t other_variant_str = "something_else_entirely";
REQUIRE(std_string != other_str);
REQUIRE(variant_string != other_variant_str);
REQUIRE(variant_string != other_str);
//REQUIRE(other_str != variant_string);
REQUIRE(other_variant_str != std_string);
//REQUIRE(std_string != other_variant_str);
}
SECTION("Value List Comparators")
{
std::vector<std::string> string_list = {"A", "B", "C", "D"};
value_list_t variant_list = {"A", "B", "C", "D"};
CHECK(string_list == variant_list);
CHECK(variant_list == string_list);
auto auto_strings = {"A","B","C","D"};
REQUIRE(variant_list == auto_strings);
std::vector<std::string> wrong_strings = {"X", "Y", "Z", "W"};
REQUIRE(variant_list != wrong_strings);
}
}
SECTION("Basic Node")
{
pregen_node_t node = node_from_json("data/basic_node.json");
REQUIRE(node.name == "Basic Node");
REQUIRE(node.values.size() == 4);
REQUIRE(node.children.size() == 1); //properties
REQUIRE(node.children[0].name == "Property");
REQUIRE(node.children[0].values.size() == 4);
std::vector<std::string> expected_node_value_strings = {"A", "B", "C", "D"};
CHECK(node.values == expected_node_value_strings);
expected_node_value_strings = {"1 A", "1 B", "1 C", "1 D"};
CHECK(node.children[0].values == expected_node_value_strings);
}
SECTION("Fancy Node")
{
pregen_node_t node = node_from_json("data/fancy_node.json");
REQUIRE(node.name == "Fancy Node");
/// Properties
REQUIRE(node.children.size() == 2);
auto const& p1 = node.children[0];
REQUIRE(p1.children.size() == 0);
auto const& p2 = node.children[1];
REQUIRE(p2.children.size() == 2);
auto const& p2a = p2.children[0];
auto const& p2b = p2.children[1];
REQUIRE(p2a.children.size() == 0);
REQUIRE(p2a.children.size() == 1);
auto const& p2b_1 = p2b.children[0];
REQUIRE(p2b_1.children.size() == 0);
/// Values
REQUIRE(node.values.size() == 2);
REQUIRE(node.value_nodes.size() == 1);
auto node_value_strings = {"ValueString A", "ValueString B"};
CHECK(node.values == node_value_strings);
auto const& vn = node.value_nodes[0];
CHECK(vn.name == "ValueObj A");
REQUIRE(vn.children.size() == 1);
REQUIRE(vn.values.size() == 4);
REQUIRE(vn.value_nodes.size() == 1);
auto vn_value_strings = {"ValueObj Value A", "ValueObj Value B", "ValueObj Value C", "ValueObj Value D"};
CHECK(vn.values == vn_value_strings);
REQUIRE(vn.value_nodes[0].name == "Value Obj Value Obj");
auto const& vn_p1 = vn.children[0];
REQUIRE(vn_p1.name == "ValueObj Property One");
auto vn_p1_value_strings = {"VObj P1 A", "VObj P1 B", "VObj P1 C", "VObj P1 D"};
REQUIRE(vn_p1.values == vn_p1_value_strings);
auto p1_value_strings = {"1 A", "1 B"};
CHECK(p1.values == p1_value_strings);
CHECK(p1.value_nodes[0].name == "ValueObj 1 A");
CHECK(p1.value_nodes[1].name == "ValueObj 1 B");
auto p2a_value_strings = {"2A - A", "2A - B", "2A - C", "2A - D"};
CHECK(p2a.values == p2a_value_strings);
REQUIRE(p2b_1.value_nodes.size() == 1);
auto const& p2b_1_vnode = p2b_1.value_nodes[0];
CHECK(p2b_1_vnode.name == "P2B_1 Value Node A");
auto p2b_1_vnode_value_strings = {"Value Node Value A", "Value Node Value B", "Value Node Value C", "Value Node Value D"};
REQUIRE(p2b_1_vnode.values == p2b_1_vnode_value_strings);
}
SECTION("Range Value")
{
pregen_node_t node = node_from_json("data/range_value.json");
REQUIRE(node.name == "Range Value");
REQUIRE(node.children.size() == 1);
REQUIRE(node.values.size() == 2);
REQUIRE(node.value_nodes.size() == 0);
REQUIRE(std::holds_alternative<range_value_t>(node.values[0]));
REQUIRE(std::holds_alternative<range_value_t>(node.values[1]));
range_value_t r0 = std::get<range_value_t>(node.values[0]);
std::vector<std::string> r0_strings = {"1 A", "1 B", "1 C", "1 D"};
REQUIRE(r0 == r0_strings);
range_value_t r1 = std::get<range_value_t>(node.values[1]);
std::vector<std::string> r1_strings = {"2 A", "2 B", "2 C", "2 D"};
REQUIRE(r1 == r1_strings);
auto const& p1 = node.children[0];
REQUIRE(p1.children.size() == 0);
REQUIRE(p1.values.size() == 5);
REQUIRE(p1.value_nodes.size() == 1);
CHECK(p1.values[0] == std::string("NotRange A"));
CHECK(p1.values[1] == std::string("NotRange B"));
CHECK(p1.values[2] == std::string("NotRange C"));
REQUIRE(std::holds_alternative<range_value_t>(p1.values[3]));
REQUIRE(std::holds_alternative<range_value_t>(p1.values[4]));
range_value_t p1r0 = std::get<range_value_t>(p1.values[3]);
std::vector<std::string> p1r0_strings = {"P1R1 A", "P1R1 B", "P1R1 C", "P1R1 D"};
REQUIRE(p1r0 == p1r0_strings);
range_value_t p1r1 = std::get<range_value_t>(p1.values[4]);
std::vector<std::string> p1r1_strings = {"P1R2 A", "P1R2 B", "P1R2 C", "P1R2 D"};
REQUIRE(p1r1 == p1r1_strings);
SECTION("Range Generation")
{
auto generated = generate_node(node);
REQUIRE(generated.name == node.name);
REQUIRE(generated.generated_values.size() == node.children.size());
auto get_total = [](std::vector<std::string> const& gend_vals) -> uint32_t
{
uint32_t total = 0;
for(auto const& v : gend_vals)
{
total += stoi(v);
}
};
REQUIRE(get_total(generated.generated_values) == 100);
bool all_range_rng_passed = true;
for(size_t i = 0; i < num_range_rng_tests; ++i)
all_range_rng_passed &= (get_total(generated.generated_values) == 100);
REQUIRE(all_range_rng_passed);
}
}
SECTION("Multi Value")
{
//TODO
}
/*
SECTION("Weights")
{
pregen_node_t node = node_from_json("data/weights.json");
REQUIRE(node.name == "Weights");
REQUIRE(node.children.size() == 4);
REQUIRE(node.values.size() == 5);
CHECK(node.values[0].weight == 100);
CHECK(node.values[0] == "A");
CHECK(node.values[1].weight == 20);
CHECK(node.values[1] == "B");
CHECK(node.values[2].weight == 1);
CHECK(node.values[2] == "C");
CHECK(node.values[3].weight == 1);
CHECK(node.values[3] == "D");
CHECK(node.values[4].weight == 0);
CHECK(node.values[4] == "E");
CHECK(node.value_nodes[0].name == "ValueNode A");
CHECK(node.value_nodes[0].weight == 25);
CHECK(node.value_nodes[1].name == "ValueNode B");
CHECK(node.value_nodes[1].weight == 250);
CHECK(node.value_nodes[2].name == "ValueNode C");
CHECK(node.value_nodes[2].weight == 4);
CHECK(node.value_nodes[2].values.size() == 4);
SECTION("Normal Weights")
{
auto const& n = node.children[0];
REQUIRE(n.name == "Normal Weights");
REQUIRE(n.values.size() == 0);
REQUIRE(n.values_nodes.size() == 3);
CHECK(n.values_nodes[0].name == "Normal A");
CHECK(n.values_nodes[0].weight == 123)
CHECK(n.values_nodes[1].name == "Normal B");
CHECK(n.values_nodes[1].weight == 456)
CHECK(n.values_nodes[2].name == "Normal C");
CHECK(n.values_nodes[2].weight == 789)
}
SECTION("Inline Weights")
{
auto const& n = node.children[1];
REQUIRE(n.name == "Inline Weights");
REQUIRE(n.values.size() == 3);
REQUIRE(n.values_nodes.size() == 0);
CHECK(n.values_nodes[0].name == "Inline A");
CHECK(n.values_nodes[0].weight == 123)
CHECK(n.values_nodes[1].name == "Inline B");
CHECK(n.values_nodes[1].weight == 456)
CHECK(n.values_nodes[2].name == "Inline C");
CHECK(n.values_nodes[2].weight == 789)
}
SECTION("Inline Normal Mix")
{
auto const& n = node.children[2];
REQUIRE(n.name == "Inline Normal Mix");
REQUIRE(n.values.size() == 3);
REQUIRE(n.values_nodes.size() == 3);
//lazy copypaste
CHECK(n.values_nodes[0].name == "Normal A");
CHECK(n.values_nodes[0].weight == 123)
CHECK(n.values_nodes[1].name == "Normal B");
CHECK(n.values_nodes[1].weight == 456)
CHECK(n.values_nodes[2].name == "Normal C");
CHECK(n.values_nodes[2].weight == 789)
//lazy copypaste
CHECK(n.values_nodes[0].name == "Inline A");
CHECK(n.values_nodes[0].weight == 123)
CHECK(n.values_nodes[1].name == "Inline B");
CHECK(n.values_nodes[1].weight == 456)
CHECK(n.values_nodes[2].name == "Inline C");
CHECK(n.values_nodes[2].weight == 789)
}
SECTION("Weight of Values")
{
auto const& n = node.children[3];
REQUIRE(n.name == "Weight of Values");
REQUIRE(n.values.size() == 0);
REQUIRE(n.values_nodes.size() == 1);
auto const& vn = node.value_nodes[0];
auto sum = total_weight(vn);
REQUIRE(vn.weight == sum);
}
}
*/
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: roadmapentry.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-05-19 13:42:54 $
*
* 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 _TOOLKIT_ROADMAPENTRY_HXX_
#define _TOOLKIT_ROADMAPENTRY_HXX_
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#define RM_PROPERTY_ID_LABEL 1
#define RM_PROPERTY_ID_ID 2
#define RM_PROPERTY_ID_ENABLED 4
#define RM_PROPERTY_ID_INTERACTIVE 5
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::lang::XServiceInfo
> ORoadmapEntry_Base;
class ORoadmapEntry :public ORoadmapEntry_Base
,public ::comphelper::OMutexAndBroadcastHelper
,public ::comphelper::OPropertyContainer
,public ::comphelper::OPropertyArrayUsageHelper< ORoadmapEntry >
{
public:
ORoadmapEntry();
protected:
DECLARE_XINTERFACE() // merge XInterface implementations
DECLARE_XTYPEPROVIDER() // merge XTypeProvider implementations
/// @see ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
// other stuff
// ...
// (e.g. DECLARE_SERVICE_INFO();)
protected:
// <properties>
::rtl::OUString m_sLabel;
sal_Int32 m_nID;
sal_Bool m_bEnabled;
sal_Bool m_bInteractive;
// </properties>
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.152); FILE MERGED 2005/09/05 16:57:41 rt 1.2.152.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: roadmapentry.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:49:57 $
*
* 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 _TOOLKIT_ROADMAPENTRY_HXX_
#define _TOOLKIT_ROADMAPENTRY_HXX_
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#define RM_PROPERTY_ID_LABEL 1
#define RM_PROPERTY_ID_ID 2
#define RM_PROPERTY_ID_ENABLED 4
#define RM_PROPERTY_ID_INTERACTIVE 5
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::lang::XServiceInfo
> ORoadmapEntry_Base;
class ORoadmapEntry :public ORoadmapEntry_Base
,public ::comphelper::OMutexAndBroadcastHelper
,public ::comphelper::OPropertyContainer
,public ::comphelper::OPropertyArrayUsageHelper< ORoadmapEntry >
{
public:
ORoadmapEntry();
protected:
DECLARE_XINTERFACE() // merge XInterface implementations
DECLARE_XTYPEPROVIDER() // merge XTypeProvider implementations
/// @see ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo()
throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
// other stuff
// ...
// (e.g. DECLARE_SERVICE_INFO();)
protected:
// <properties>
::rtl::OUString m_sLabel;
sal_Int32 m_nID;
sal_Bool m_bEnabled;
sal_Bool m_bInteractive;
// </properties>
};
#endif
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include "utl/Logger.h"
#include "db.h"
using namespace odb;
dbMaster* createMaster2X1(dbLib* lib,
const char* name,
uint width,
uint height,
const char* in1,
const char* in2,
const char* out)
{
dbMaster* master = dbMaster::create(lib, name);
master->setWidth(width);
master->setHeight(height);
master->setType(dbMasterType::CORE);
dbMTerm::create(master, in1, dbIoType::INPUT, dbSigType::SIGNAL);
dbMTerm::create(master, in2, dbIoType::INPUT, dbSigType::SIGNAL);
dbMTerm::create(master, out, dbIoType::OUTPUT, dbSigType::SIGNAL);
master->setFrozen();
return master;
}
dbDatabase* createSimpleDB()
{
utl::Logger* logger = new utl::Logger();
dbDatabase* db = dbDatabase::create();
db->setLogger(logger);
dbTech* tech = dbTech::create(db);
dbTechLayer* layer
= dbTechLayer::create(tech, "L1", dbTechLayerType::MASTERSLICE);
dbLib* lib = dbLib::create(db, "lib1", ',');
dbChip* chip = dbChip::create(db);
dbBlock* block = dbBlock::create(chip, "simple_block");
dbMaster* and2 = createMaster2X1(lib, "and2", 1000, 1000, "a", "b", "o");
dbMaster* or2 = createMaster2X1(lib, "or2", 500, 500, "a", "b", "o");
return db;
}
// # (n1) +-----
// # --------|a \ (n5)
// # (n2) | (i1)o|-----------+
// # --------|b / | +-------
// # +----- +--------\a \ (n7)
// # ) (i3)o|---------------
// # (n3) +----- +--------/b /
// # --------|a \ (n6) | +-------
// # (n4) | (i2)o|-----------+
// # --------|b /
// # +-----
dbDatabase* create2LevetDbNoBTerms()
{
dbDatabase* db = createSimpleDB();
dbLib* lib = db->findLib("lib1");
dbChip* chip = db->getChip();
dbBlock* block = chip->getBlock();
auto and2 = lib->findMaster("and2");
auto or2 = lib->findMaster("or2");
dbInst* i1 = dbInst::create(block, and2, "i1");
dbInst* i2 = dbInst::create(block, and2, "i2");
dbInst* i3 = dbInst::create(block, or2, "i3");
dbNet* n1 = dbNet::create(block, "n1");
dbNet* n2 = dbNet::create(block, "n2");
dbNet* n3 = dbNet::create(block, "n3");
dbNet* n4 = dbNet::create(block, "n4");
dbNet* n5 = dbNet::create(block, "n5");
dbNet* n6 = dbNet::create(block, "n6");
dbNet* n7 = dbNet::create(block, "n7");
dbITerm::connect(i1->findITerm("a"), n1);
dbITerm::connect(i1->findITerm("b"), n2);
dbITerm::connect(i2->findITerm("a"), n3);
dbITerm::connect(i2->findITerm("b"), n4);
dbITerm::connect(i3->findITerm("a"), n5);
dbITerm::connect(i3->findITerm("b"), n6);
dbITerm::connect(i1->findITerm("o"), n5);
dbITerm::connect(i2->findITerm("o"), n6);
dbITerm::connect(i3->findITerm("o"), n7);
return db;
}
dbDatabase* create2LevetDbWithBTerms()
{
dbDatabase* db = create2LevetDbNoBTerms();
dbBlock* block = db->getChip()->getBlock();
auto n1 = block->findNet("n1");
auto n2 = block->findNet("n2");
auto n7 = block->findNet("n7");
dbBTerm* IN1 = dbBTerm::create(n1, "IN1");
IN1->setIoType(dbIoType::INPUT);
dbBTerm* IN2 = dbBTerm::create(n2, "IN2");
IN1->setIoType(dbIoType::INPUT);
dbBTerm* OUT = dbBTerm::create(n7, "IN3");
IN1->setIoType(dbIoType::OUTPUT);
return db;
}
dbDatabase* create3LevetDbNoBTerms()
{
dbDatabase* db = createSimpleDB();
dbLib* lib = db->findLib("lib1");
dbChip* chip = db->getChip();
dbBlock* block = chip->getBlock();
auto and2 = lib->findMaster("and2");
auto or2 = lib->findMaster("or2");
dbInst* i1 = dbInst::create(block, and2, "i1");
dbInst* i2 = dbInst::create(block, and2, "i2");
dbInst* i3 = dbInst::create(block, or2, "i3");
dbInst* i4 = dbInst::create(block, or2, "i4");
dbNet* n1 = dbNet::create(block, "n1");
dbNet* n2 = dbNet::create(block, "n2");
dbNet* n3 = dbNet::create(block, "n3");
dbNet* n4 = dbNet::create(block, "n4");
dbNet* n5 = dbNet::create(block, "n5");
dbNet* n6 = dbNet::create(block, "n6");
dbNet* n7 = dbNet::create(block, "n7");
dbNet* n8 = dbNet::create(block, "n8");
dbNet* n9 = dbNet::create(block, "n9");
dbITerm::connect(i1->findITerm("a"), n1);
dbITerm::connect(i1->findITerm("b"), n2);
dbITerm::connect(i2->findITerm("a"), n3);
dbITerm::connect(i2->findITerm("b"), n4);
dbITerm::connect(i3->findITerm("a"), n5);
dbITerm::connect(i3->findITerm("b"), n6);
dbITerm::connect(i1->findITerm("o"), n5);
dbITerm::connect(i2->findITerm("o"), n6);
dbITerm::connect(i3->findITerm("o"), n7);
dbITerm::connect(i4->findITerm("a"), n7);
dbITerm::connect(i4->findITerm("b"), n8);
dbITerm::connect(i4->findITerm("o"), n9);
return db;
}
<commit_msg>remove outdated db test helper method<commit_after>#include <stdio.h>
#include "utl/Logger.h"
#include "db.h"
using namespace odb;
dbMaster* createMaster2X1(dbLib* lib,
const char* name,
uint width,
uint height,
const char* in1,
const char* in2,
const char* out)
{
dbMaster* master = dbMaster::create(lib, name);
master->setWidth(width);
master->setHeight(height);
master->setType(dbMasterType::CORE);
dbMTerm::create(master, in1, dbIoType::INPUT, dbSigType::SIGNAL);
dbMTerm::create(master, in2, dbIoType::INPUT, dbSigType::SIGNAL);
dbMTerm::create(master, out, dbIoType::OUTPUT, dbSigType::SIGNAL);
master->setFrozen();
return master;
}
dbDatabase* createSimpleDB()
{
utl::Logger* logger = new utl::Logger();
dbDatabase* db = dbDatabase::create();
db->setLogger(logger);
dbTech* tech = dbTech::create(db);
dbTechLayer* layer
= dbTechLayer::create(tech, "L1", dbTechLayerType::MASTERSLICE);
dbLib* lib = dbLib::create(db, "lib1", ',');
dbChip* chip = dbChip::create(db);
dbBlock* block = dbBlock::create(chip, "simple_block");
dbMaster* and2 = createMaster2X1(lib, "and2", 1000, 1000, "a", "b", "o");
dbMaster* or2 = createMaster2X1(lib, "or2", 500, 500, "a", "b", "o");
return db;
}
// # (n1) +-----
// # --------|a \ (n5)
// # (n2) | (i1)o|-----------+
// # --------|b / | +-------
// # +----- +--------\a \ (n7)
// # ) (i3)o|---------------
// # (n3) +----- +--------/b /
// # --------|a \ (n6) | +-------
// # (n4) | (i2)o|-----------+
// # --------|b /
// # +-----
dbDatabase* create2LevetDbNoBTerms()
{
dbDatabase* db = createSimpleDB();
dbLib* lib = db->findLib("lib1");
dbChip* chip = db->getChip();
dbBlock* block = chip->getBlock();
auto and2 = lib->findMaster("and2");
auto or2 = lib->findMaster("or2");
dbInst* i1 = dbInst::create(block, and2, "i1");
dbInst* i2 = dbInst::create(block, and2, "i2");
dbInst* i3 = dbInst::create(block, or2, "i3");
dbNet* n1 = dbNet::create(block, "n1");
dbNet* n2 = dbNet::create(block, "n2");
dbNet* n3 = dbNet::create(block, "n3");
dbNet* n4 = dbNet::create(block, "n4");
dbNet* n5 = dbNet::create(block, "n5");
dbNet* n6 = dbNet::create(block, "n6");
dbNet* n7 = dbNet::create(block, "n7");
dbITerm::connect(i1->findITerm("a"), n1);
dbITerm::connect(i1->findITerm("b"), n2);
dbITerm::connect(i2->findITerm("a"), n3);
dbITerm::connect(i2->findITerm("b"), n4);
dbITerm::connect(i3->findITerm("a"), n5);
dbITerm::connect(i3->findITerm("b"), n6);
dbITerm::connect(i1->findITerm("o"), n5);
dbITerm::connect(i2->findITerm("o"), n6);
dbITerm::connect(i3->findITerm("o"), n7);
return db;
}
dbDatabase* create2LevetDbWithBTerms()
{
dbDatabase* db = create2LevetDbNoBTerms();
dbBlock* block = db->getChip()->getBlock();
auto n1 = block->findNet("n1");
auto n2 = block->findNet("n2");
auto n7 = block->findNet("n7");
dbBTerm* IN1 = dbBTerm::create(n1, "IN1");
IN1->setIoType(dbIoType::INPUT);
dbBTerm* IN2 = dbBTerm::create(n2, "IN2");
IN1->setIoType(dbIoType::INPUT);
dbBTerm* OUT = dbBTerm::create(n7, "IN3");
IN1->setIoType(dbIoType::OUTPUT);
return db;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2022 The Orbit 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 <gtest/gtest.h>
#include <random>
#include "GlCanvas.h"
#include "MockBatcher.h"
#include "MockTextRenderer.h"
#include "MockTimelineInfo.h"
#include "TimelineUi.h"
#include "Viewport.h"
namespace orbit_gl {
class TimelineUiTest : public TimelineUi {
public:
static constexpr int kBigScreenPixelsWidth = 2000;
static constexpr int kSmallScreenMaxPixelsWidth = 700;
static constexpr int kTinyScreenMaxPixelsWidth = 200;
explicit TimelineUiTest(MockTimelineInfo* mock_timeline_info, Viewport* viewport,
TimeGraphLayout* layout)
: TimelineUi(nullptr /*parent*/, mock_timeline_info, viewport, layout),
primitive_assembler_(&mock_batcher_),
viewport_(viewport),
mock_timeline_info_(mock_timeline_info) {
viewport->SetWorldSize(viewport->GetWorldWidth(), TimelineUi::GetHeight());
}
void TestUpdatePrimitives(uint64_t min_tick, uint64_t max_tick) {
mock_text_renderer_.Clear();
mock_batcher_.ResetElements();
mock_timeline_info_->SetMinMax(min_tick, max_tick);
UpdatePrimitives(primitive_assembler_, mock_text_renderer_, min_tick, max_tick,
PickingMode::kNone);
int num_labels = mock_text_renderer_.GetNumAddTextCalls();
int num_boxes = mock_batcher_.GetNumBoxes();
int num_major_ticks = mock_batcher_.GetNumLinesByColor(kTimelineMajorTickColor);
int num_minor_ticks = mock_batcher_.GetNumLinesByColor(kTimelineMinorTickColor);
// Lines should be only major and minor ticks.
EXPECT_EQ(mock_batcher_.GetNumLines(), num_major_ticks + num_minor_ticks);
// Major ticks should always be between 2 and 10, given scale set. In extremely small screens
// (Width < 200), we don't force a minimum number of major ticks.
if (viewport_->GetWorldWidth() > kTinyScreenMaxPixelsWidth) {
EXPECT_GE(num_major_ticks, 2);
}
EXPECT_LE(num_major_ticks, 10);
// Depending on the scale, there should be 1 minor ticks or 4 between each major tick, which
// means that (calling MT to the number of major ticks, and mt to the number of minor ticks)
// mt is between (MT-1, MT+1) or mt is between (4x(MT-1), 4x(MT+1)).
EXPECT_GE(num_minor_ticks, num_major_ticks - 1);
EXPECT_LE(num_minor_ticks, 4 * (num_major_ticks + 1));
EXPECT_THAT(num_minor_ticks, testing::AnyOf(testing::Le(num_major_ticks + 1),
testing::Ge(4 * (num_major_ticks - 1))));
// Labels should all have the same number of digits, start at the same vertical position and
// they will appear at the right of each major tick.
EXPECT_TRUE(mock_text_renderer_.HasAddTextsSameLength());
EXPECT_TRUE(mock_text_renderer_.AreAddTextsAlignedVertically());
// TODO(b/218311326): In some cases, small screens (Width < 700) failed in the condition between
// #labels and #major_ticks, since we are drawing major_ticks anyways when labels intersect.
if (viewport_->GetWorldWidth() > kSmallScreenMaxPixelsWidth) {
EXPECT_GE(num_labels, num_major_ticks - 1);
}
EXPECT_LE(num_labels, num_major_ticks + 1);
// Boxes: One box per each label + Background box + margin box.
EXPECT_EQ(num_boxes, num_labels + 2);
// Everything should be between kZValueTimeBar and kZValueTimeBarMouseLabel.
EXPECT_TRUE(mock_text_renderer_.IsTextBetweenZLayers(GlCanvas::kZValueTimeBar,
GlCanvas::kZValueTimeBarMouseLabel));
EXPECT_TRUE(mock_batcher_.IsEverythingBetweenZLayers(GlCanvas::kZValueTimeBar,
GlCanvas::kZValueTimeBarMouseLabel));
}
private:
MockBatcher mock_batcher_;
MockTextRenderer mock_text_renderer_;
PrimitiveAssembler primitive_assembler_;
Viewport* viewport_;
MockTimelineInfo* mock_timeline_info_;
};
static void TestUpdatePrimitivesWithSeveralRanges(int world_width) {
MockTimelineInfo mock_timeline_info;
mock_timeline_info.SetWorldWidth(world_width);
TimeGraphLayout layout;
Viewport viewport(world_width, 0);
TimelineUiTest timeline_ui_test(&mock_timeline_info, &viewport, &layout);
timeline_ui_test.TestUpdatePrimitives(0, 100);
timeline_ui_test.TestUpdatePrimitives(1'000'000'000, 1'000'000'100);
timeline_ui_test.TestUpdatePrimitives(0, 999'999'000);
timeline_ui_test.TestUpdatePrimitives(0, 999'999'999);
timeline_ui_test.TestUpdatePrimitives(0, 1'000'000'000);
// Maximum supported timestamp: 1 Month.
std::mt19937 gen;
std::uniform_int_distribution<> distrib(0, kNanosecondsPerMonth);
for (int i = 0; i < 100; i++) {
uint64_t timestamp_1 = distrib(gen);
uint64_t timestamp_2 = distrib(gen);
timeline_ui_test.TestUpdatePrimitives(std::min(timestamp_1, timestamp_2),
std::max(timestamp_1, timestamp_2));
}
}
TEST(TimelineUI, UpdatePrimitives) {
TestUpdatePrimitivesWithSeveralRanges(TimelineUiTest::kBigScreenPixelsWidth);
TestUpdatePrimitivesWithSeveralRanges(TimelineUiTest::kTinyScreenMaxPixelsWidth);
}
} // namespace orbit_gl<commit_msg>Fix timeline's visual tests (#3625)<commit_after>// Copyright (c) 2022 The Orbit 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 <gtest/gtest.h>
#include <random>
#include "GlCanvas.h"
#include "MockBatcher.h"
#include "MockTextRenderer.h"
#include "MockTimelineInfo.h"
#include "TimelineUi.h"
#include "Viewport.h"
namespace orbit_gl {
class TimelineUiTest : public TimelineUi {
public:
static constexpr int kBigScreenPixelsWidth = 2000;
static constexpr int kSmallScreenMaxPixelsWidth = 700;
static constexpr int kTinyScreenMaxPixelsWidth = 200;
explicit TimelineUiTest(MockTimelineInfo* mock_timeline_info, Viewport* viewport,
TimeGraphLayout* layout)
: TimelineUi(nullptr /*parent*/, mock_timeline_info, viewport, layout),
primitive_assembler_(&mock_batcher_),
viewport_(viewport),
mock_timeline_info_(mock_timeline_info) {
viewport->SetWorldSize(viewport->GetWorldWidth(), TimelineUi::GetHeight());
}
void TestUpdatePrimitives(uint64_t min_tick, uint64_t max_tick) {
mock_text_renderer_.Clear();
mock_batcher_.ResetElements();
mock_timeline_info_->SetMinMax(min_tick, max_tick);
UpdatePrimitives(primitive_assembler_, mock_text_renderer_, min_tick, max_tick,
PickingMode::kNone);
int num_labels = mock_text_renderer_.GetNumAddTextCalls();
int num_boxes = mock_batcher_.GetNumBoxes();
int num_major_ticks = mock_batcher_.GetNumLinesByColor(kTimelineMajorTickColor);
int num_minor_ticks = mock_batcher_.GetNumLinesByColor(kTimelineMinorTickColor);
// Lines should be only major and minor ticks.
EXPECT_EQ(mock_batcher_.GetNumLines(), num_major_ticks + num_minor_ticks);
// Major ticks should always be between 2 and 10, given scale set. In extremely small screens
// (Width < 200), we don't force a minimum number of major ticks.
if (viewport_->GetWorldWidth() > kTinyScreenMaxPixelsWidth) {
EXPECT_GE(num_major_ticks, 2);
}
EXPECT_LE(num_major_ticks, 10);
// Depending on the scale, there should be 1, 2 or 4 minor ticks between each major tick, which
// means that (calling MT to the number of major ticks, and mt to the number of minor ticks)
// mt is between (MT-1, MT+1), (2*(MT-1), 2*(MT+1)) or (4*(MT-1), 4*(MT+1)).
EXPECT_GE(num_minor_ticks, num_major_ticks - 1);
EXPECT_LE(num_minor_ticks, 4 * (num_major_ticks + 1));
EXPECT_THAT(num_minor_ticks,
testing::AnyOf(testing::Le(num_major_ticks + 1),
testing::AllOf(testing::Ge(2 * (num_major_ticks - 1)),
testing::Le(2 * (num_major_ticks + 1))),
testing::Ge(4 * (num_major_ticks - 1))));
// Generally, labels should all have the same number of digits, start at the same vertical
// position and they will appear at the right of each major tick. The only exception is about
// labels with the same number of digits when the number of hours is greater than 100. The hour
// part of the iso timestamp will have 2 digits when it's smaller than 100.
if (max_tick < 100 * kNanosecondsPerHour) {
EXPECT_TRUE(mock_text_renderer_.HasAddTextsSameLength());
}
EXPECT_TRUE(mock_text_renderer_.AreAddTextsAlignedVertically());
// TODO(b/218311326): In some cases, small screens (Width < 700) failed in the condition between
// #labels and #major_ticks, since we are drawing major_ticks anyways when labels intersect.
if (viewport_->GetWorldWidth() > kSmallScreenMaxPixelsWidth) {
EXPECT_GE(num_labels, num_major_ticks - 1);
}
EXPECT_LE(num_labels, num_major_ticks + 1);
// Boxes: One box per each label + Background box + margin box.
EXPECT_EQ(num_boxes, num_labels + 2);
// Everything should be between kZValueTimeBar and kZValueTimeBarMouseLabel.
EXPECT_TRUE(mock_text_renderer_.IsTextBetweenZLayers(GlCanvas::kZValueTimeBar,
GlCanvas::kZValueTimeBarMouseLabel));
EXPECT_TRUE(mock_batcher_.IsEverythingBetweenZLayers(GlCanvas::kZValueTimeBar,
GlCanvas::kZValueTimeBarMouseLabel));
}
private:
MockBatcher mock_batcher_;
MockTextRenderer mock_text_renderer_;
PrimitiveAssembler primitive_assembler_;
Viewport* viewport_;
MockTimelineInfo* mock_timeline_info_;
};
static void TestUpdatePrimitivesWithSeveralRanges(int world_width) {
MockTimelineInfo mock_timeline_info;
mock_timeline_info.SetWorldWidth(world_width);
TimeGraphLayout layout;
Viewport viewport(world_width, 0);
TimelineUiTest timeline_ui_test(&mock_timeline_info, &viewport, &layout);
timeline_ui_test.TestUpdatePrimitives(0, 100);
timeline_ui_test.TestUpdatePrimitives(kNanosecondsPerSecond, kNanosecondsPerSecond + 100);
timeline_ui_test.TestUpdatePrimitives(0, kNanosecondsPerSecond - 100);
timeline_ui_test.TestUpdatePrimitives(0, kNanosecondsPerSecond - 1);
timeline_ui_test.TestUpdatePrimitives(0, kNanosecondsPerSecond);
timeline_ui_test.TestUpdatePrimitives(0, 59 * kNanosecondsPerMinute);
timeline_ui_test.TestUpdatePrimitives(90 * kNanosecondsPerHour, 100 * kNanosecondsPerHour);
// Maximum supported timestamp: 1 Month.
std::mt19937 gen;
std::uniform_int_distribution<uint64_t> distrib(0, kNanosecondsPerMonth);
for (int i = 0; i < 100; i++) {
uint64_t timestamp_1 = distrib(gen);
uint64_t timestamp_2 = distrib(gen);
timeline_ui_test.TestUpdatePrimitives(std::min(timestamp_1, timestamp_2),
std::max(timestamp_1, timestamp_2));
}
}
TEST(TimelineUI, UpdatePrimitives) {
TestUpdatePrimitivesWithSeveralRanges(TimelineUiTest::kBigScreenPixelsWidth);
TestUpdatePrimitivesWithSeveralRanges(TimelineUiTest::kTinyScreenMaxPixelsWidth);
}
} // namespace orbit_gl<|endoftext|>
|
<commit_before><commit_msg>Fixed getSemanticSortedColumn for both modes: zoom and grid<commit_after><|endoftext|>
|
<commit_before><commit_msg>getSortedColumns aware of hideColumns option active or not<commit_after><|endoftext|>
|
<commit_before>/ /
/ / R e m o t e P h o t o T o o l - r e m o t e c a m e r a c o n t r o l s o f t w a r e
/ / C o p y r i g h t ( C ) 2 0 0 8 - 2 0 1 8 M i c h a e l F i n k
/ /
/ / / \ f i l e L o c a t i o n \ s t d a f x . c p p P r e c o m p i l e d h e a d e r s u p p o r t
/ /
/ / i n c l u d e s
# i n c l u d e " s t d a f x . h "
<commit_msg>converted file from UTF-16 to UTF-8; cppcheck reported an error<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file Location\stdafx.cpp Precompiled header support
//
// includes
#include "stdafx.h"
<|endoftext|>
|
<commit_before>/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of Teapotnet. *
* *
* Teapotnet 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. *
* *
* Teapotnet 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 Teapotnet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#ifndef TPN_INCLUDE_H
#define TPN_INCLUDE_H
//#define DEBUG 1
#define APPNAME "Teapotnet"
#define APPVERSION "0.9.5"
#define APPMAGIC 0x54504f54 // "TPOT"
#define APPAUTHOR "Paul-Louis Ageneau"
#define APPLINK "https://teapotnet.org/"
#define SOURCELINK "https://teapotnet.org/source"
#define HELPLINK "https://teapotnet.org/help"
#define DOWNLOADURL "https://teapotnet.org/download"
#define BUGSLINK "mailto:bugs@teapotnet.org"
#include "pla/include.hpp"
#include "pla/string.hpp"
#include "pla/binarystring.hpp"
using namespace pla;
namespace tpn
{
typedef BinaryString Identifier;
typedef std::pair<Identifier, Identifier> IdentifierPair;
}
#endif
<commit_msg>Version 0.10.1<commit_after>/*************************************************************************
* Copyright (C) 2011-2013 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of Teapotnet. *
* *
* Teapotnet 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. *
* *
* Teapotnet 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 Teapotnet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#ifndef TPN_INCLUDE_H
#define TPN_INCLUDE_H
//#define DEBUG 1
#define APPNAME "Teapotnet"
#define APPVERSION "0.10.1"
#define APPMAGIC 0x54504f54 // "TPOT"
#define APPAUTHOR "Paul-Louis Ageneau"
#define APPLINK "https://teapotnet.org/"
#define SOURCELINK "https://teapotnet.org/source"
#define HELPLINK "https://teapotnet.org/help"
#define DOWNLOADURL "https://teapotnet.org/download"
#define BUGSLINK "mailto:bugs@teapotnet.org"
#include "pla/include.hpp"
#include "pla/string.hpp"
#include "pla/binarystring.hpp"
using namespace pla;
namespace tpn
{
typedef BinaryString Identifier;
typedef std::pair<Identifier, Identifier> IdentifierPair;
}
#endif
<|endoftext|>
|
<commit_before>#ifndef HMLIB_TYPETRAITS_INC
#define HMLIB_TYPETRAITS_INC 100
#
#include<type_traits>
#include<iterator>
namespace hmLib{
template<typename type1, typename type2>
struct select_derived{
template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value>
struct check{
using ans_type = void;
};
template<typename type>
struct check<type, true, false>{
using ans_type = type2;
};
template<typename type>
struct check<type, false, true>{
using ans_type = type1;
};
using type = typename check<void>::ans_type;
};
template<typename terget, typename... others>
struct near_base_of{
template<typename terget_, typename candidate_>
struct check{
using ans_type = candidate_;
};
using type = typename check<terget, void>::ans_type;
};
template<typename terget, typename try_type, typename... others>
struct near_base_of<terget, try_type, others...>{
template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value>
struct check{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type;
};
template<typename terget_, typename candidate_>
struct check<terget_, candidate_, true>{
using new_candidate = typename select_derived<candidate_, try_type>::type;
using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type;
};
template<typename terget_>
struct check<terget_, void, true>{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type;
};
using type = typename check<terget, void>::ans_type;
};
template <typename T>
struct has_begin_and_end {
private:
template <class U>
static auto check(U&& x)->decltype(x.begin(), x.end(), std::true_type{});
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<typename std::decay<T>::type>()));
constexpr static bool value = type::value;
};
template<typename T>
struct is_iterator{
private:
template<typename U>
static auto check(U&&)->decltype(typename std::iterator_traits<U>::iterator_category{}, std::true_type{});
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<typename std::decay<T>::type>()));
constexpr static bool value = type::value;
};
template<typename T, bool is_iterator_ = is_iterator<T>::value>
struct is_const_iterator: public std::false_type {};
template<typename T>
struct is_const_iterator<T, true> {
public:
using type = std::integral_constant<bool, std::is_assignable<decltype(*std::declval<T>()), typename std::iterator_traits<T>::value_type>::value>;
constexpr static bool value = type::value;
};
namespace detail {
struct result_of_impl {
template < class Result, class ... Args >
static Result Func(Result(*)(Args ...));
template < class T, class Result, class ... Args >
static Result Func(Result(T::*)(Args ...));
template < class T, class Result, class ... Args >
static Result Func(Result(T::*)(Args ...) const);
template < class T, class FuncType = decltype(&T::operator()) >
static decltype(Func(std::declval<FuncType>())) Func(T*);
};
}
template < typename Fn >
struct result_of {
using type = decltype(detail::result_of_impl::Func(std::declval<std::remove_pointer_t<Fn>*>()));
};
template<typename Fn, typename T>
struct is_applicable {
private:
template<typename eFn, typename eT, typename ans_type = decltype(std::declval<eFn>()(std::declval<eT>()))>
static auto check(eFn&&, eT&&)->std::true_type;
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<Fn>(), std::declval<T>()));
static constexpr const bool value = type::value;
};
}
#
#endif
<commit_msg>Add generalized container detector, is_range.<commit_after>#ifndef HMLIB_TYPETRAITS_INC
#define HMLIB_TYPETRAITS_INC 100
#
#include<type_traits>
#include<iterator>
namespace hmLib{
template<typename type1, typename type2>
struct select_derived{
template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value>
struct check{
using ans_type = void;
};
template<typename type>
struct check<type, true, false>{
using ans_type = type2;
};
template<typename type>
struct check<type, false, true>{
using ans_type = type1;
};
using type = typename check<void>::ans_type;
};
template<typename terget, typename... others>
struct near_base_of{
template<typename terget_, typename candidate_>
struct check{
using ans_type = candidate_;
};
using type = typename check<terget, void>::ans_type;
};
template<typename terget, typename try_type, typename... others>
struct near_base_of<terget, try_type, others...>{
template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value>
struct check{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type;
};
template<typename terget_, typename candidate_>
struct check<terget_, candidate_, true>{
using new_candidate = typename select_derived<candidate_, try_type>::type;
using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type;
};
template<typename terget_>
struct check<terget_, void, true>{
using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type;
};
using type = typename check<terget, void>::ans_type;
};
template <typename T>
struct has_begin_and_end {
private:
template <class U>
static auto check(U&& x)->decltype(x.begin(), x.end(), std::true_type{});
static auto check(...)->std::false_type;
public:
[[deprecated("please use is_range<T> for detecting the range-like classes.")]] typedef decltype(check(std::declval<typename std::decay<T>::type>())) type;
[[deprecated("please use is_range<T> for detecting the range-like classes.")]] constexpr static bool value = type::value;
};
template <typename T>
struct is_range {
private:
template <class U>
static auto check(U&& x)->decltype(std::begin(x), std::end(x), std::true_type{});
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<typename std::decay<T>::type>()));
constexpr static bool value = type::value;
};
template<typename T>
struct is_iterator{
private:
template<typename U>
static auto check(U&&)->decltype(typename std::iterator_traits<U>::iterator_category{}, std::true_type{});
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<typename std::decay<T>::type>()));
constexpr static bool value = type::value;
};
template<typename T, bool is_iterator_ = is_iterator<T>::value>
struct is_const_iterator: public std::false_type {};
template<typename T>
struct is_const_iterator<T, true> {
public:
using type = std::integral_constant<bool, std::is_assignable<decltype(*std::declval<T>()), typename std::iterator_traits<T>::value_type>::value>;
constexpr static bool value = type::value;
};
namespace detail {
struct result_of_impl {
template < class Result, class ... Args >
static Result Func(Result(*)(Args ...));
template < class T, class Result, class ... Args >
static Result Func(Result(T::*)(Args ...));
template < class T, class Result, class ... Args >
static Result Func(Result(T::*)(Args ...) const);
template < class T, class FuncType = decltype(&T::operator()) >
static decltype(Func(std::declval<FuncType>())) Func(T*);
};
}
template < typename Fn >
struct result_of {
using type = decltype(detail::result_of_impl::Func(std::declval<std::remove_pointer_t<Fn>*>()));
};
template<typename Fn, typename T>
struct is_applicable {
private:
template<typename eFn, typename eT, typename ans_type = decltype(std::declval<eFn>()(std::declval<eT>()))>
static auto check(eFn&&, eT&&)->std::true_type;
static auto check(...)->std::false_type;
public:
using type = decltype(check(std::declval<Fn>(), std::declval<T>()));
static constexpr const bool value = type::value;
};
}
#
#endif
<|endoftext|>
|
<commit_before>#pragma once
namespace cdp
{
template <typename T>
constexpr auto is_complete_impl(int = 0) -> decltype(!sizeof(T))
{
return true;
}
template <typename T>
constexpr bool is_complete_impl(...)
{
return false;
}
template <typename T>
constexpr bool is_complete()
{
return is_complete_impl<T>(0);
}
}
<commit_msg>Rename helpers to stop code completion from suggesting them<commit_after>#pragma once
namespace cdp
{
template <typename T>
constexpr auto _is_complete(int = 0) -> decltype(!sizeof(T))
{
return true;
}
template <typename T>
constexpr bool _is_complete(...)
{
return false;
}
template <typename T>
constexpr bool is_complete()
{
return _is_complete<T>(0);
}
}
<|endoftext|>
|
<commit_before>#include "Morton_shuffler.hpp"
#include <iostream>
extern int myrank, nprocs;
Morton_shuffler::Morton_shuffler(
int N0, int N1, int N2,
int d,
int nfiles)
{
this->d = d;
if (nprocs % nfiles != 0)
{
std::cerr <<
"Number of output files incompatible with number of processes.\n"
"Aborting.\n" << std::endl;
exit(EXIT_FAILURE);
}
int n[4];
// various descriptions for the real data
n[0] = N0;
n[1] = N1;
n[2] = N2;
n[3] = d;
this->dinput = new field_descriptor(4, n, MPI_REAL4, MPI_COMM_WORLD);
n[0] = N0/8;
n[1] = N1/8;
n[2] = N2/8;
n[3] = 8*8*8*this->d;
this->drcubbie = new field_descriptor(4, n, MPI_REAL4, MPI_COMM_WORLD);
n[0] = (N0/8) * (N1/8) * (N2/8);
n[1] = 8*8*8*this->d;
this->dzcubbie = new field_descriptor(2, n, MPI_REAL4, MPI_COMM_WORLD);
//set up output file descriptor
int out_rank, out_nprocs;
out_nprocs = nprocs/nfiles;
this->out_group = myrank / out_nprocs;
out_rank = myrank % out_nprocs;
n[0] = ((N0/8) * (N1/8) * (N2/8)) / nfiles;
n[1] = 8*8*8*this->d;
MPI_Comm_split(MPI_COMM_WORLD, this->out_group, out_rank, &this->out_communicator);
this->doutput = new field_descriptor(2, n, MPI_REAL4, this->out_communicator);
}
Morton_shuffler::~Morton_shuffler()
{
delete this->dinput;
delete this->drcubbie;
delete this->dzcubbie;
delete this->doutput;
MPI_Comm_free(&this->out_communicator);
}
int Morton_shuffler::shuffle(
float *a,
const char *base_fname)
{
// array where shuffled data will be placed
float *rtmp = fftwf_alloc_real(this->drcubbie->local_size);
// shuffle into z order
ptrdiff_t z, zz;
int rid, zid;
int kk;
ptrdiff_t cubbie_size = 8*8*8*this->d;
ptrdiff_t cc;
float *rz = fftwf_alloc_real(cubbie_size);
for (int k = 0; k < this->drcubbie->sizes[0]; k++)
{
rid = this->drcubbie->rank(k);
kk = k - this->drcubbie->starts[0];
for (int j = 0; j < this->drcubbie->sizes[1]; j++)
for (int i = 0; i < this->drcubbie->sizes[2]; i++)
{
z = regular_to_zindex(k, j, i);
zid = this->dzcubbie->rank(z);
zz = z - this->dzcubbie->starts[0];
if (myrank == rid || myrank == zid)
{
// first, copy data into cubbie
if (myrank == rid)
for (int tk = 0; tk < 8; tk++)
for (int tj = 0; tj < 8; tj++)
{
cc = (((kk*8+tk)*this->dinput->sizes[1] + (j*8+tj)) *
this->dinput->sizes[2] + i*8)*this->d;
std::copy(
a + cc,
a + cc + 8*this->d,
rz + (tk*8 + tj)*8*this->d);
}
// now copy or send/receive to zindexed array
if (rid == zid) std::copy(
rz,
rz + cubbie_size,
rtmp + zz*cubbie_size);
else
{
if (myrank == rid) MPI_Send(
rz,
cubbie_size,
MPI_REAL4,
zid,
z,
MPI_COMM_WORLD);
else MPI_Recv(
rtmp + zz*cubbie_size,
cubbie_size,
MPI_REAL4,
rid,
z,
MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
}
}
}
}
fftwf_free(rz);
char temp_char[200];
sprintf(temp_char,
"%s_z%.7x",
base_fname,
this->out_group*this->doutput->sizes[0]);
this->doutput->write(temp_char, rtmp);
fftwf_free(rtmp);
return EXIT_SUCCESS;
}
<commit_msg>fix (?) file write<commit_after>#include "Morton_shuffler.hpp"
#include <iostream>
extern int myrank, nprocs;
Morton_shuffler::Morton_shuffler(
int N0, int N1, int N2,
int d,
int nfiles)
{
this->d = d;
if (nprocs % nfiles != 0)
{
std::cerr <<
"Number of output files incompatible with number of processes.\n"
"Aborting.\n" << std::endl;
exit(EXIT_FAILURE);
}
int n[4];
// various descriptions for the real data
n[0] = N0;
n[1] = N1;
n[2] = N2;
n[3] = this->d;
this->dinput = new field_descriptor(4, n, MPI_REAL4, MPI_COMM_WORLD);
n[0] = N0/8;
n[1] = N1/8;
n[2] = N2/8;
n[3] = 8*8*8*this->d;
this->drcubbie = new field_descriptor(4, n, MPI_REAL4, MPI_COMM_WORLD);
n[0] = (N0/8) * (N1/8) * (N2/8);
n[1] = 8*8*8*this->d;
this->dzcubbie = new field_descriptor(2, n, MPI_REAL4, MPI_COMM_WORLD);
//set up output file descriptor
int out_rank, out_nprocs;
out_nprocs = nprocs/nfiles;
this->out_group = myrank / out_nprocs;
out_rank = myrank % out_nprocs;
n[0] = ((N0/8) * (N1/8) * (N2/8)) / nfiles;
n[1] = 8*8*8*this->d;
MPI_Comm_split(MPI_COMM_WORLD, this->out_group, out_rank, &this->out_communicator);
this->doutput = new field_descriptor(2, n, MPI_REAL4, this->out_communicator);
}
Morton_shuffler::~Morton_shuffler()
{
delete this->dinput;
delete this->drcubbie;
delete this->dzcubbie;
delete this->doutput;
MPI_Comm_free(&this->out_communicator);
}
int Morton_shuffler::shuffle(
float *a,
const char *base_fname)
{
// array where shuffled data will be placed
float *rtmp = fftwf_alloc_real(this->drcubbie->local_size);
// shuffle into z order
ptrdiff_t z, zz;
int rid, zid;
int kk;
ptrdiff_t cubbie_size = 8*8*8*this->d;
ptrdiff_t cc;
float *rz = fftwf_alloc_real(cubbie_size);
for (int k = 0; k < this->drcubbie->sizes[0]; k++)
{
rid = this->drcubbie->rank(k);
kk = k - this->drcubbie->starts[0];
for (int j = 0; j < this->drcubbie->sizes[1]; j++)
for (int i = 0; i < this->drcubbie->sizes[2]; i++)
{
z = regular_to_zindex(k, j, i);
zid = this->dzcubbie->rank(z);
zz = z - this->dzcubbie->starts[0];
if (myrank == rid || myrank == zid)
{
// first, copy data into cubbie
if (myrank == rid)
for (int tk = 0; tk < 8; tk++)
for (int tj = 0; tj < 8; tj++)
{
cc = (((kk*8+tk)*this->dinput->sizes[1] + (j*8+tj)) *
this->dinput->sizes[2] + i*8)*this->d;
std::copy(
a + cc,
a + cc + 8*this->d,
rz + (tk*8 + tj)*8*this->d);
}
// now copy or send/receive to zindexed array
if (rid == zid) std::copy(
rz,
rz + cubbie_size,
rtmp + zz*cubbie_size);
else
{
if (myrank == rid) MPI_Send(
rz,
cubbie_size,
MPI_REAL4,
zid,
z,
MPI_COMM_WORLD);
else MPI_Recv(
rtmp + zz*cubbie_size,
cubbie_size,
MPI_REAL4,
rid,
z,
MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
}
}
}
}
fftwf_free(rz);
char temp_char[200];
sprintf(temp_char,
"%s_z%.7x",
base_fname,
this->out_group*this->doutput->sizes[0]);
this->doutput->write(temp_char, rtmp);
//this->doutput->write(temp_char, rtmp + this->out_group*this->doutput->sizes[0]);
fftwf_free(rtmp);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>class Solution {
bool *rows;
bool *cols;
bool *add;
bool *diff;
int n;
bool valid(int i, int j)
{
if(!rows[i] && !cols[j] && !add[i+j] && !diff[i-j+n])
return true;
return false;
}
void help(vector<vector<string>> &result, vector<pair<int, int>> &tmp, int i)
{
if(i == n)
{
if(n == tmp.size())
{
string s(n, '.');
vector<string>t{n,s};
for(int k = 0;k < tmp.size();k++)
t[tmp[k].first][tmp[k].second] = 'Q';
result.push_back(t);
}
} else {
for(int j = 0;j < n;j++)
{
if(valid(i, j))
{
rows[i] = cols[j] = add[i+j] = diff[i-j+n] = true;
tmp.push_back(make_pair(i, j));
help(result, tmp, i+1);
tmp.pop_back();
rows[i] = cols[j] = add[i+j] = diff[i-j+n] = false;
}
}
}
}
public:
vector<vector<string> > solveNQueens(int n) {
rows = new bool[n];
cols = new bool[n];
add = new bool[2*n];
diff = new bool[2*n];
this->n = n;
vector<vector<string>> result;
vector<pair<int, int>> tmp;
help(result, tmp, 0);
return result;
}
};<commit_msg>N-Queens<commit_after>class Solution {
bool *rows;
bool *cols;
bool *add;
bool *diff;
int n;
bool valid(int i, int j)
{
if(!rows[i] && !cols[j] && !add[i+j] && !diff[i-j+n])
return true;
return false;
}
void help(vector<vector<string>> &result, vector<pair<int, int>> &tmp, int i)
{
if(i == n)
{
string s(n, '.');
vector<string>t{n,s};
for(int k = 0;k < tmp.size();k++)
t[tmp[k].first][tmp[k].second] = 'Q';
result.push_back(t);
return;
}
for(int j = 0;j < n;j++)
{
if(valid(i, j))
{
rows[i] = cols[j] = add[i+j] = diff[i-j+n] = true;
tmp.push_back(make_pair(i, j));
help(result, tmp, i+1);
tmp.pop_back();
rows[i] = cols[j] = add[i+j] = diff[i-j+n] = false;
}
}
}
public:
vector<vector<string> > solveNQueens(int n) {
rows = new bool[n];
cols = new bool[n];
add = new bool[2*n];
diff = new bool[2*n];
this->n = n;
vector<vector<string>> result;
vector<pair<int, int>> tmp;
help(result, tmp, 0);
return result;
}
};<|endoftext|>
|
<commit_before>#pragma once
#include <type_traits>
#include <utility>
namespace yks {
template <typename T>
class Optional {
public:
Optional()
: present(false)
{
update_debug_ptr();
}
Optional(const Optional& o) {
if (o.present) {
new (&storage) T(*o.get_pointer());
}
present = o.present;
update_debug_ptr();
}
Optional(Optional&& o) {
if (o.present) {
new (&storage) T(std::move(*o.get_pointer()));
}
present = o.present;
update_debug_ptr();
}
~Optional() {
if (present) {
get_pointer()->~T();
}
}
Optional& operator=(const Optional& o) {
if (present) {
if (o.present) {
*get_pointer() = *o.get_pointer();
} else {
get_pointer()->~T();
}
} else {
if (o.present) {
new (get_pointer()) T(o);
}
}
present = o.present;
update_debug_ptr();
}
template <typename... Args>
void emplace(Args&&... args)
{
if (present) {
get_pointer()->~T();
}
new (&storage) T(std::forward<Args>(args)...);
present = true;
update_debug_ptr();
}
explicit operator bool() const { return present; }
const T& operator* () const { return *get_pointer(); }
T& operator* () { return *get_pointer(); }
const T* operator->() const { return get_pointer(); }
T* operator->() { return get_pointer(); }
template <typename U>
T value_or(U&& value) const {
return present ? *get_pointer() : std::move(value);
}
private:
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type storage;
bool present;
#if _DEBUG
const T* debug_ptr;
#endif
void update_debug_ptr() {
#if _DEBUG
debug_ptr = present ? static_cast<const T*>(static_cast<const void*>(&storage)) : nullptr;
#endif
}
const T* get_pointer() const {
assert(present);
return static_cast<const T*>(static_cast<const void*>(&storage));
}
T* get_pointer() {
assert(present);
return static_cast<T*>(static_cast<void*>(&storage));
}
};
template <typename T, typename... Args>
Optional<T> make_optional(Args&&... args) {
Optional<T> optional;
optional.emplace(std::forward<Args>(args)...);
return optional;
}
}
<commit_msg>Fixed broken operator= in Optional<commit_after>#pragma once
#include <type_traits>
#include <utility>
namespace yks {
template <typename T>
class Optional {
public:
Optional()
: present(false)
{
update_debug_ptr();
}
Optional(const Optional& o) {
if (o.present) {
new (&storage) T(*o.get_pointer());
}
present = o.present;
update_debug_ptr();
}
Optional(Optional&& o) {
if (o.present) {
new (&storage) T(std::move(*o.get_pointer()));
}
present = o.present;
update_debug_ptr();
}
~Optional() {
if (present) {
get_pointer()->~T();
}
}
Optional& operator=(const Optional& o) {
if (present) {
if (o.present) {
*get_pointer() = *o.get_pointer();
} else {
get_pointer()->~T();
}
} else {
if (o.present) {
new (&storage) T(*o.get_pointer());
}
}
present = o.present;
update_debug_ptr();
return *this;
}
template <typename... Args>
void emplace(Args&&... args)
{
if (present) {
get_pointer()->~T();
}
new (&storage) T(std::forward<Args>(args)...);
present = true;
update_debug_ptr();
}
explicit operator bool() const { return present; }
const T& operator* () const { return *get_pointer(); }
T& operator* () { return *get_pointer(); }
const T* operator->() const { return get_pointer(); }
T* operator->() { return get_pointer(); }
template <typename U>
T value_or(U&& value) const {
return present ? *get_pointer() : std::move(value);
}
private:
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type storage;
bool present;
#if _DEBUG
const T* debug_ptr;
#endif
void update_debug_ptr() {
#if _DEBUG
debug_ptr = present ? static_cast<const T*>(static_cast<const void*>(&storage)) : nullptr;
#endif
}
const T* get_pointer() const {
assert(present);
return static_cast<const T*>(static_cast<const void*>(&storage));
}
T* get_pointer() {
assert(present);
return static_cast<T*>(static_cast<void*>(&storage));
}
};
template <typename T, typename... Args>
Optional<T> make_optional(Args&&... args) {
Optional<T> optional;
optional.emplace(std::forward<Args>(args)...);
return optional;
}
}
<|endoftext|>
|
<commit_before>#include "PanelComponents.h"
//#include "timeKeeper.h"
#include "Arduino.h"
//---Switch------------------------------------------------------
PanelSwitch::PanelSwitch( void )
{
}
void PanelSwitch::init( uint8_t pinNum )
{
pinNumber = pinNum;
pinMode( pinNumber, INPUT_PULLUP );
update();
//force newData high in case knob starts on last value
newData = 1;
}
void PanelSwitch::update( void )
{
uint8_t tempState = digitalRead( pinNumber ) ^ 0x01;
if( state != tempState )
{
state = tempState;
newData = 1;
}
}
uint8_t PanelSwitch::getState( void )
{
newData = 0;
return state;
}
//---Button------------------------------------------------------
PanelButton::PanelButton( void )
{
beingHeld = 0;
bank = 0;
}
void PanelButton::init( uint8_t pinInput )
{
init( pinInput, 0 );
}
void PanelButton::init( uint8_t pinInput, uint8_t bankInput )
{
bank = bankInput;
pinNumber = pinInput;
if( bank == 0 )
{
pinMode( pinNumber, INPUT_PULLUP );
update();
//force newData high in case knob starts on last value
newData = 1;
}
else
{
//Do bank related initialization here
}
}
//This is the intended operation:
// Button is pressed. If it has been long enough since last movement:
// update newData
// clear timer
// If This has already been done, check for button held. If so,
// update newData
// clear timer
void PanelButton::update( void )
{
uint8_t tempState;
if( bank == 0 )
{
tempState = digitalRead( pinNumber ) ^ 0x01;
}
else
{
tempState = cache ^ 0x01; //Take externally provided data
}
switch( state )
{
case 0: //Last state was 0
case 1: //Last state was 1
if(( state != tempState ) && (buttonDebounceTimeKeeper.mGet() > 50))
{
// Serial.println(buttonDebounceTimeKeeper.mGet());
state = tempState;
newData = 1;
//Start the timer
buttonDebounceTimeKeeper.mClear();
if( tempState == 1 )
{
//Ok, we are being held down
beingHeld = 1;
}
}
if(( tempState == 1 )&&( beingHeld == 1 ))
{
//We're being held
if(buttonDebounceTimeKeeper.mGet() > 1000)
{
newData = 1;
state = 2;//BUTTONHOLD;
//Serial.println("Got it.");
}
else
{
//Serial.println("WAITING!!!");
}
}
break;
case 2: //In the process of holding
if(( tempState == 0) && ( state != tempState ) && (buttonDebounceTimeKeeper.mGet() > 50))
{
// Serial.println(buttonDebounceTimeKeeper.mGet());
state = tempState;
newData = 1;
//Start the timer
buttonDebounceTimeKeeper.mClear();
beingHeld = 0;
}
break;
default:
break;
}
}
uint8_t PanelButton::getState( void )
{
newData = 0;
return state;
}
void PanelButton::setBank( uint8_t newBank )
{
bank = newBank;
}
//---Led---------------------------------------------------------
PanelLed::PanelLed( void )
{
state = LEDOFF;
bank = 0;
}
void PanelLed::init( uint8_t pinInput )
{
init( pinInput, 0 );
}
void PanelLed::init( uint8_t pinInput, uint8_t bankInput )
{
bank = bankInput;
pinNumber = pinInput;
if( bank == 0 )
{
pinMode( pinNumber, OUTPUT );
update();
}
else
{
//Do bank related initialization here
}
}
void PanelLed::init( uint8_t pinInput, uint8_t bankInput, volatile uint8_t * volatile flasherAddress, volatile uint8_t * volatile fastFlasherAddress )
{
init( pinInput, bankInput ); //Do regular init, plus:
flasherState = flasherAddress;
fastFlasherState = fastFlasherAddress;
}
void PanelLed::update( void )
{
uint8_t outputValue = 0;
switch(state)
{
case LEDON:
outputValue = 0;
break;
case LEDFLASHING:
outputValue = *flasherState;
break;
case LEDFLASHINGFAST:
outputValue = *fastFlasherState;
break;
default:
case LEDOFF:
outputValue = 1;
break;
}
Serial.print("A:");
Serial.print(*flasherState);
if( bank == 0 )
{
digitalWrite( pinNumber, outputValue );
Serial.print("B:");
Serial.print(*flasherState);
}
if( bank != 0 )
{
Serial.print("C:");
Serial.print(*flasherState);
cache = outputValue & 0x0001;
}
}
ledState_t PanelLed::getState( void )
{
return state;
}
void PanelLed::setState( ledState_t inputValue )
{
state = inputValue;
}
void PanelLed::setBank( uint8_t inputBank )
{
bank = inputBank;
}
//---Selector----------------------------------------------------
PanelSelector::PanelSelector( void )
{
}
// 8 bit resolution on the ADC should be fine. Right shift on analogRead
void PanelSelector::init( uint8_t pinNum, uint8_t maxInput, uint8_t minInput )
{
pinNumber = pinNum;
pinMode( pinNumber, INPUT );
//Set up the ranges
uint8_t stepHeight = ( maxInput - minInput ) / 9;
thresholds[0] = minInput + ( stepHeight / 2 );
int i;
for( i = 1; i < 9; i++ )
{
thresholds[i] = thresholds[i - 1] + stepHeight;
}
update();
//force newData high in case knob starts on last value
newData = 1;
}
void PanelSelector::update( void )
{
uint8_t analogReadRaw = (analogRead( pinNumber )) >> 2; //Now 8 bits
uint8_t tempState = 0;
//Seek the position
int i;
for( i = 0; i < 9; i++ )
{
if( analogReadRaw > thresholds[i] )
{
tempState = i + 1; //It's this or higher
}
}
//Check if new
if( state != tempState )
{
state = tempState;
newData = 1;
}
}
uint8_t PanelSelector::getState( void )
{
newData = 0;
return state;
}<commit_msg>removed print statements<commit_after>#include "PanelComponents.h"
//#include "timeKeeper.h"
#include "Arduino.h"
//---Switch------------------------------------------------------
PanelSwitch::PanelSwitch( void )
{
}
void PanelSwitch::init( uint8_t pinNum )
{
pinNumber = pinNum;
pinMode( pinNumber, INPUT_PULLUP );
update();
//force newData high in case knob starts on last value
newData = 1;
}
void PanelSwitch::update( void )
{
uint8_t tempState = digitalRead( pinNumber ) ^ 0x01;
if( state != tempState )
{
state = tempState;
newData = 1;
}
}
uint8_t PanelSwitch::getState( void )
{
newData = 0;
return state;
}
//---Button------------------------------------------------------
PanelButton::PanelButton( void )
{
beingHeld = 0;
bank = 0;
}
void PanelButton::init( uint8_t pinInput )
{
init( pinInput, 0 );
}
void PanelButton::init( uint8_t pinInput, uint8_t bankInput )
{
bank = bankInput;
pinNumber = pinInput;
if( bank == 0 )
{
pinMode( pinNumber, INPUT_PULLUP );
update();
//force newData high in case knob starts on last value
newData = 1;
}
else
{
//Do bank related initialization here
}
}
//This is the intended operation:
// Button is pressed. If it has been long enough since last movement:
// update newData
// clear timer
// If This has already been done, check for button held. If so,
// update newData
// clear timer
void PanelButton::update( void )
{
uint8_t tempState;
if( bank == 0 )
{
tempState = digitalRead( pinNumber ) ^ 0x01;
}
else
{
tempState = cache ^ 0x01; //Take externally provided data
}
switch( state )
{
case 0: //Last state was 0
case 1: //Last state was 1
if(( state != tempState ) && (buttonDebounceTimeKeeper.mGet() > 50))
{
// Serial.println(buttonDebounceTimeKeeper.mGet());
state = tempState;
newData = 1;
//Start the timer
buttonDebounceTimeKeeper.mClear();
if( tempState == 1 )
{
//Ok, we are being held down
beingHeld = 1;
}
}
if(( tempState == 1 )&&( beingHeld == 1 ))
{
//We're being held
if(buttonDebounceTimeKeeper.mGet() > 1000)
{
newData = 1;
state = 2;//BUTTONHOLD;
//Serial.println("Got it.");
}
else
{
//Serial.println("WAITING!!!");
}
}
break;
case 2: //In the process of holding
if(( tempState == 0) && ( state != tempState ) && (buttonDebounceTimeKeeper.mGet() > 50))
{
// Serial.println(buttonDebounceTimeKeeper.mGet());
state = tempState;
newData = 1;
//Start the timer
buttonDebounceTimeKeeper.mClear();
beingHeld = 0;
}
break;
default:
break;
}
}
uint8_t PanelButton::getState( void )
{
newData = 0;
return state;
}
void PanelButton::setBank( uint8_t newBank )
{
bank = newBank;
}
//---Led---------------------------------------------------------
PanelLed::PanelLed( void )
{
state = LEDOFF;
bank = 0;
}
void PanelLed::init( uint8_t pinInput )
{
init( pinInput, 0 );
}
void PanelLed::init( uint8_t pinInput, uint8_t bankInput )
{
bank = bankInput;
pinNumber = pinInput;
if( bank == 0 )
{
pinMode( pinNumber, OUTPUT );
update();
}
else
{
//Do bank related initialization here
}
}
void PanelLed::init( uint8_t pinInput, uint8_t bankInput, volatile uint8_t * volatile flasherAddress, volatile uint8_t * volatile fastFlasherAddress )
{
init( pinInput, bankInput ); //Do regular init, plus:
flasherState = flasherAddress;
fastFlasherState = fastFlasherAddress;
}
void PanelLed::update( void )
{
uint8_t outputValue = 0;
switch(state)
{
case LEDON:
outputValue = 0;
break;
case LEDFLASHING:
outputValue = *flasherState;
break;
case LEDFLASHINGFAST:
outputValue = *fastFlasherState;
break;
default:
case LEDOFF:
outputValue = 1;
break;
}
//Serial.print("A:");
//Serial.print(*flasherState);
if( bank == 0 )
{
digitalWrite( pinNumber, outputValue );
//Serial.print("B:");
//Serial.print(*flasherState);
}
if( bank != 0 )
{
//Serial.print("C:");
//Serial.print(*flasherState);
cache = outputValue & 0x0001;
}
}
ledState_t PanelLed::getState( void )
{
return state;
}
void PanelLed::setState( ledState_t inputValue )
{
state = inputValue;
}
void PanelLed::setBank( uint8_t inputBank )
{
bank = inputBank;
}
//---Selector----------------------------------------------------
PanelSelector::PanelSelector( void )
{
}
// 8 bit resolution on the ADC should be fine. Right shift on analogRead
void PanelSelector::init( uint8_t pinNum, uint8_t maxInput, uint8_t minInput )
{
pinNumber = pinNum;
pinMode( pinNumber, INPUT );
//Set up the ranges
uint8_t stepHeight = ( maxInput - minInput ) / 9;
thresholds[0] = minInput + ( stepHeight / 2 );
int i;
for( i = 1; i < 9; i++ )
{
thresholds[i] = thresholds[i - 1] + stepHeight;
}
update();
//force newData high in case knob starts on last value
newData = 1;
}
void PanelSelector::update( void )
{
uint8_t analogReadRaw = (analogRead( pinNumber )) >> 2; //Now 8 bits
uint8_t tempState = 0;
//Seek the position
int i;
for( i = 0; i < 9; i++ )
{
if( analogReadRaw > thresholds[i] )
{
tempState = i + 1; //It's this or higher
}
}
//Check if new
if( state != tempState )
{
state = tempState;
newData = 1;
}
}
uint8_t PanelSelector::getState( void )
{
newData = 0;
return state;
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <opencv2/core/core.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Lepton_Frame.h"
#include "Lepton_Driver.h"
#include "OpenCV_Adapter.h"
#include "Person_Finder.h"
int socket_fd;
struct sockaddr_in servaddr;
static void setupConnection(char *hostname)
{
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(11539);
servaddr.sin_addr.s_addr = inet_addr(hostname);
connect(socket_fd, (const sockaddr*)&servaddr, sizeof(servaddr));
}
int main(int argc, char **argv)
{
if (argc < 2) {
return -1;
}
setupConnection(argv[1]);
setupSPI();
for (;;) {
uint8_t *frame = nextFrame();
if (!checkFrame()) {
continue;
}
cv::Mat img = convertData(frame);
// cv::Mat processed = img.clone();
cv::Mat processed = findPerson(img);
// cv::Mat processed(SCAN_LINES, SCAN_COLUMNS, CV_8UC3, cv::Scalar(255,0,0));
// fprintf(stderr, "isContinuous = %d\n", processed.isContinuous());
write(socket_fd, processed.data, SCAN_LINES * SCAN_COLUMNS * 3);
}
}
<commit_msg>Update for new Lepton_Data_Sender API.<commit_after>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <opencv2/core/core.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Lepton_Frame.h"
#include "Lepton_Driver.h"
#include "OpenCV_Adapter.h"
#include "Person_Finder.h"
int socket_fd;
struct sockaddr_in servaddr;
static void setupConnection(char *hostname)
{
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(11539);
servaddr.sin_addr.s_addr = inet_addr(hostname);
connect(socket_fd, (const sockaddr*)&servaddr, sizeof(servaddr));
}
int main(int argc, char **argv)
{
if (argc < 2) {
return -1;
}
setupConnection(argv[1]);
setupLepton();
for (;;) {
uint8_t *frame = nextFrame();
if (!checkFrame()) {
continue;
}
cv::Mat img = convertData(frame);
// cv::Mat processed = img.clone();
cv::Mat processed = findPerson(img);
// cv::Mat processed(SCAN_LINES, SCAN_COLUMNS, CV_8UC3, cv::Scalar(255,0,0));
// fprintf(stderr, "isContinuous = %d\n", processed.isContinuous());
write(socket_fd, processed.data, SCAN_LINES * SCAN_COLUMNS * 3);
}
}
<|endoftext|>
|
<commit_before>#include <FWPlatform.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <Logger.h>
#include <ContextCairo.h>
#include <SDLSoundCanvas.h>
#include <Message.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <DrawEvent.h>
#include <SysEvent.h>
#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
using namespace std;
class PlatformSDL : public FWPlatform {
public:
PlatformSDL() : FWPlatform(1.0f,
// "#version 300 es",
"#version 100",
true) { }
double getTime() const override {
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
double t = 0;
if (r == 0) {
t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
}
return t;
}
string getLocalFilename(const char * fn, FileType type) {
string s = "assets/";
return s + fn;
}
std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
return std::make_shared<CurlClientFactory>();
}
int showActionSheet(const FWRect&, const FWActionSheet&) {
return 0;
}
std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
}
void sendMessage(const Message & message) override {
cerr << "sendMessage(" << int(message.getType()) << ")\n";
FWPlatform::sendMessage(message);
switch (message.getType()) {
case Message::SET_CAPTION:
SDL_WM_SetCaption(message.getTextValue().c_str(),
message.getTextValue().c_str());
break;
case Message::SHOW_MESSAGE_DIALOG:
#if 0
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_INFORMATION,
title.c_str(),
message.c_str(),
NULL);
#endif
break;
default:
break;
}
}
std::shared_ptr<SoundCanvas> createSoundCanvas() const override {
return std::make_shared<SDLSoundCanvas>();
}
std::shared_ptr<Logger> createLogger() const override {
return std::make_shared<BasicLogger>();
}
// std::shared_ptr<EventLoop> createEventLoop() override;
std::string showTextEntryDialog(const std::string & message) {
return "";
}
std::string getBundleFilename(const char * filename) {
string s = "assets/";
return s + filename;
}
void storeValue(const std::string & key, const std::string & value) {
}
std::string loadValue(const std::string & key) {
return "";
}
void swapBuffers() {
SDL_GL_SwapBuffers( );
}
void run() {
SDL_Event event;
cerr << "starting runloop\n";
while ( true ) {
/* Grab all the events off the queue. */
while( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_KEYDOWN:
/* Handle key presses. */
// handle_key_down( &event.key.keysym );
break;
case SDL_MOUSEBUTTONDOWN:
{
TouchEvent ev(TouchEvent::ACTION_DOWN, mouse_x, mouse_y, getTime(), 0);
postEvent(getActiveViewId(), ev);
button_pressed = true;
}
break;
case SDL_MOUSEBUTTONUP:
{
TouchEvent ev(TouchEvent::ACTION_UP, mouse_x, mouse_y, getTime(), 0);
postEvent(getActiveViewId(), ev);
button_pressed = false;
}
break;
case SDL_MOUSEMOTION:
if (button_pressed) {
TouchEvent ev(TouchEvent::ACTION_MOVE, event.motion.x, event.motion.y, getTime(), 0);
postEvent(getActiveViewId(), ev);
}
mouse_x = event.motion.x;
mouse_y = event.motion.y;
break;
case SDL_VIDEORESIZE:
{
int w = event.resize.w, h = event.resize.h;
cerr << "resized (" << w << " " << h << ")\n";
setDisplayWidth(w);
setDisplayHeight(h);
getApplication().getFirstChild()->onResize(w, h, w, h);
}
break;
case SDL_QUIT:
return;
}
}
getApplication().loadEvents();
if (getApplication().getFirstChild()->onUpdate(getTime())) {
DrawEvent ev;
postEvent(getActiveViewId(), ev);
swapBuffers();
}
}
}
private:
bool button_pressed = false;
int mouse_x = 0, mouse_y = 0;
};
#if 0
static void handle_key_down(SDL_keysym* keysym) {
/*
* We're only interested if 'Esc' has
* been presssed.
*
* EXERCISE:
* Handle the arrow keys and have that change the
* viewing position/angle.
*/
switch( keysym->sym ) {
case SDLK_ESCAPE:
quit_tutorial( 0 );
break;
case SDLK_SPACE:
should_rotate = !should_rotate;
break;
default:
break;
}
}
#endif
extern FWApplication * applicationMain();
int main(int argc, char *argv[]) {
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 ) {
/* Failed, exit. */
fprintf( stderr, "Video initialization failed: %s\n",
SDL_GetError( ) );
SDL_Quit( );
exit(1);
}
const SDL_VideoInfo * info = SDL_GetVideoInfo( );
if (!info) {
/* This should probably never happen. */
fprintf( stderr, "Video query failed: %s\n", SDL_GetError() );
SDL_Quit();
exit(1);
}
int width = 800, height = 600;
int bpp = info->vfmt->BitsPerPixel;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
int flags = SDL_OPENGL; // | SDL_FULLSCREEN;
if (SDL_SetVideoMode( width, height, bpp, flags ) == 0) {
fprintf( stderr, "Video mode set failed: %s\n",
SDL_GetError( ) );
SDL_Quit();
exit(1);
}
FWApplication * application = applicationMain();
cerr << "starting, app = " << application << "\n";
PlatformSDL platform;
platform.setApplication(application);
platform.getApplication().initialize(&platform);
platform.getApplication().onCmdLine(argc, argv);
platform.setDisplayWidth(width);
platform.setDisplayHeight(height);
platform.getApplication().initializeContent();
platform.run();
#if 0
auto eventloop = platform.createEventLoop();
eventloop->run();
#endif
SysEvent ev(SysEvent::SHUTDOWN);
ev.dispatch(platform.getApplication());
SDL_Quit();
return 0;
}
<commit_msg>add UpdateEvent, add timestamp to SysEvent and DrawEvent<commit_after>#include <FWPlatform.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <Logger.h>
#include <ContextCairo.h>
#include <SDLSoundCanvas.h>
#include <Message.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <DrawEvent.h>
#include <SysEvent.h>
#include <UpdateEvent.h>
#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
using namespace std;
class PlatformSDL : public FWPlatform {
public:
PlatformSDL() : FWPlatform(1.0f,
// "#version 300 es",
"#version 100",
true) { }
double getTime() const override {
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
double t = 0;
if (r == 0) {
t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
}
return t;
}
string getLocalFilename(const char * fn, FileType type) {
string s = "assets/";
return s + fn;
}
std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
return std::make_shared<CurlClientFactory>();
}
int showActionSheet(const FWRect&, const FWActionSheet&) {
return 0;
}
std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
}
void sendMessage(const Message & message) override {
cerr << "sendMessage(" << int(message.getType()) << ")\n";
FWPlatform::sendMessage(message);
switch (message.getType()) {
case Message::SET_CAPTION:
SDL_WM_SetCaption(message.getTextValue().c_str(),
message.getTextValue().c_str());
break;
case Message::SHOW_MESSAGE_DIALOG:
#if 0
SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_INFORMATION,
title.c_str(),
message.c_str(),
NULL);
#endif
break;
default:
break;
}
}
std::shared_ptr<SoundCanvas> createSoundCanvas() const override {
return std::make_shared<SDLSoundCanvas>();
}
std::shared_ptr<Logger> createLogger() const override {
return std::make_shared<BasicLogger>();
}
// std::shared_ptr<EventLoop> createEventLoop() override;
std::string showTextEntryDialog(const std::string & message) {
return "";
}
std::string getBundleFilename(const char * filename) {
string s = "assets/";
return s + filename;
}
void storeValue(const std::string & key, const std::string & value) {
}
std::string loadValue(const std::string & key) {
return "";
}
void swapBuffers() {
SDL_GL_SwapBuffers( );
}
void run() {
SDL_Event event;
cerr << "starting runloop\n";
while ( true ) {
/* Grab all the events off the queue. */
while( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_KEYDOWN:
/* Handle key presses. */
// handle_key_down( &event.key.keysym );
break;
case SDL_MOUSEBUTTONDOWN:
{
TouchEvent ev(TouchEvent::ACTION_DOWN, mouse_x, mouse_y, getTime(), 0);
postEvent(getActiveViewId(), ev);
button_pressed = true;
}
break;
case SDL_MOUSEBUTTONUP:
{
TouchEvent ev(TouchEvent::ACTION_UP, mouse_x, mouse_y, getTime(), 0);
postEvent(getActiveViewId(), ev);
button_pressed = false;
}
break;
case SDL_MOUSEMOTION:
if (button_pressed) {
TouchEvent ev(TouchEvent::ACTION_MOVE, event.motion.x, event.motion.y, getTime(), 0);
postEvent(getActiveViewId(), ev);
}
mouse_x = event.motion.x;
mouse_y = event.motion.y;
break;
case SDL_VIDEORESIZE:
{
int w = event.resize.w, h = event.resize.h;
cerr << "resized (" << w << " " << h << ")\n";
setDisplayWidth(w);
setDisplayHeight(h);
getApplication().getFirstChild()->onResize(w, h, w, h);
}
break;
case SDL_QUIT:
return;
}
}
getApplication().loadEvents();
UpdateEvent ev0(getTime());
postEvent(getActiveViewId(), ev0);
if (true) {
DrawEvent ev(getTime());
postEvent(getActiveViewId(), ev);
swapBuffers();
}
}
}
private:
bool button_pressed = false;
int mouse_x = 0, mouse_y = 0;
};
#if 0
static void handle_key_down(SDL_keysym* keysym) {
/*
* We're only interested if 'Esc' has
* been presssed.
*
* EXERCISE:
* Handle the arrow keys and have that change the
* viewing position/angle.
*/
switch( keysym->sym ) {
case SDLK_ESCAPE:
quit_tutorial( 0 );
break;
case SDLK_SPACE:
should_rotate = !should_rotate;
break;
default:
break;
}
}
#endif
extern FWApplication * applicationMain();
int main(int argc, char *argv[]) {
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 ) {
/* Failed, exit. */
fprintf( stderr, "Video initialization failed: %s\n",
SDL_GetError( ) );
SDL_Quit( );
exit(1);
}
const SDL_VideoInfo * info = SDL_GetVideoInfo( );
if (!info) {
/* This should probably never happen. */
fprintf( stderr, "Video query failed: %s\n", SDL_GetError() );
SDL_Quit();
exit(1);
}
int width = 800, height = 600;
int bpp = info->vfmt->BitsPerPixel;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
int flags = SDL_OPENGL; // | SDL_FULLSCREEN;
if (SDL_SetVideoMode( width, height, bpp, flags ) == 0) {
fprintf( stderr, "Video mode set failed: %s\n",
SDL_GetError( ) );
SDL_Quit();
exit(1);
}
FWApplication * application = applicationMain();
cerr << "starting, app = " << application << "\n";
PlatformSDL platform;
platform.setApplication(application);
platform.getApplication().initialize(&platform);
platform.getApplication().onCmdLine(argc, argv);
platform.setDisplayWidth(width);
platform.setDisplayHeight(height);
platform.getApplication().initializeContent();
platform.run();
#if 0
auto eventloop = platform.createEventLoop();
eventloop->run();
#endif
SysEvent ev(platform.getTime(), SysEvent::SHUTDOWN);
ev.dispatch(platform.getApplication());
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* BDSup2Sub++ (C) 2012 Adam T.
* Based on code from BDSup2Sub by Copyright 2009 Volker Oth (0xdeadbeef)
* and Copyright 2012 Miklos Juhasz (mjuhasz)
*
*
* 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 "suphd.h"
#include "subtitleprocessor.h"
#include "subpicturehd.h"
#include "Tools/filebuffer.h"
#include "Tools/bitstream.h"
#include "Tools/timeutil.h"
#include "bitmap.h"
#include "palette.h"
#include <QImage>
SupHD::SupHD(QString fileName, SubtitleProcessor *subtitleProcessor) :
supFileName(fileName)
{
this->subtitleProcessor = subtitleProcessor;
}
SupHD::~SupHD()
{
if (!fileBuffer.isNull())
{
fileBuffer.reset();
}
}
QImage SupHD::image()
{
return _bitmap.image(_palette);
}
QImage SupHD::image(Bitmap &bitmap)
{
return bitmap.image(_palette);
}
void SupHD::decode(int index)
{
if (index < subPictures.size())
{
decode(subPictures[index]);
}
else
{
throw QString("Index: %1 out of bounds.\n").arg(QString::number(index));
}
}
int SupHD::numFrames()
{
return subPictures.size();
}
qint64 SupHD::endTime(int index)
{
return subPictures[index].endTime();
}
qint64 SupHD::startTime(int index)
{
return subPictures[index].startTime();
}
qint64 SupHD::startOffset(int index)
{
return subPictures[index].imageBufferOffsetEven();
}
SubPicture *SupHD::subPicture(int index)
{
return &subPictures[index];
}
void SupHD::readAllSupFrames()
{
fileBuffer.reset(new FileBuffer(supFileName));
int index = 0;
int bufsize = (int)fileBuffer->getSize();
SubPictureHD pic;
subPictures.clear();
try
{
while (index < bufsize)
{
if (subtitleProcessor->isCancelled())
{
throw QString("Cancelled by user!");
}
emit currentProgressChanged(index);
if (fileBuffer->getWord(index) != 0x5350)
{
throw QString("ID 'SP' missing at index ").arg(QString::number(index, 16), 8, QChar('0'));
}
int masterIndex = index + 10; //end of header
pic = SubPictureHD();
// hard code size since it's not part of the format???
pic.setScreenWidth(1920);
pic.setScreenHeight(1080);
subtitleProcessor->printX(QString("#%1\n").arg(QString::number(subPictures.size() + 1)));;
pic.setStartTime(fileBuffer->getDWordLE(index += 2)); // read PTS
int packetSize = fileBuffer->getDWord(index += 10);
// offset to command buffer
int ofsCmd = fileBuffer->getDWord(index += 4) + masterIndex;
pic.setImageBufferSize(ofsCmd - (index + 4));
index = ofsCmd;
int dcsq = fileBuffer->getWord(index);
pic.setStartTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime())));
index+=2; // 2 bytes: dcsq
int nextIndex = fileBuffer->getDWord(index) + masterIndex; // offset to next dcsq
index += 5; // 4 bytes: offset, 1 byte: start
int cmd = 0;
bool stopDisplay = false;
bool stopCommand = false;
int alphaSum = 0;
int minAlphaSum = 256 * 256; // 256 fully transparent entries
while (!stopDisplay)
{
cmd = fileBuffer->getByte(index++);
switch (cmd)
{
case 0x01:
{
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime() + (dcsq * 1024))));
subtitleProcessor->printWarning("DCSQ start ignored due to missing DCSQ stop\n");
} break;
case 0x02:
{
stopDisplay = true;
pic.setEndTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ stop ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.endTime())));
} break;
case 0x83: // palette
{
subtitleProcessor->print(QString("Palette info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0')));
pic.setPaletteOffset(index);
index += 0x300;
} break;
case 0x84: // alpha
{
subtitleProcessor->print(QString("Alpha info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0'))); alphaSum = 0;
for (int i = index; i < index + 0x100; ++i)
{
alphaSum += fileBuffer->getByte(i);
}
if (alphaSum < minAlphaSum)
{
pic.setAlphaOffset(index);
minAlphaSum = alphaSum;
}
else
{
subtitleProcessor->printWarning(QString("Found faded alpha buffer -> alpha buffer skipped\n"));
}
index += 0x100;
} break;
case 0x85: // area
{
pic.setX((fileBuffer->getByte(index) << 4) | (fileBuffer->getByte(index + 1) >> 4));
int imageWidth = (((fileBuffer->getByte(index + 1) &0xf) << 8) | (fileBuffer->getByte(index + 2)));
pic.setImageWidth((imageWidth - pic.x()) + 1);
pic.setY((fileBuffer->getByte(index + 3) <<4 ) | (fileBuffer->getByte(index + 4) >> 4));
int imageHeight = (((fileBuffer->getByte(index + 4) &0xf) << 8) | (fileBuffer->getByte(index + 5)));
pic.setImageHeight((imageHeight - pic.y()) + 1);
subtitleProcessor->print(QString("Area info ofs: %1 (%2, %3) - (%4, %5)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.x()))
.arg(QString::number(pic.y()))
.arg(QString::number(pic.x() + pic.imageWidth()))
.arg(QString::number(pic.y() + pic.imageHeight())));
index += 6;
} break;
case 0x86: // even/odd offsets
{
pic.setImageBufferOffsetEven(fileBuffer->getDWord(index) + masterIndex);
pic.setImageBufferOffsetOdd(fileBuffer->getDWord(index + 4) + masterIndex);
subtitleProcessor->print(QString("RLE buffers ofs: %1 (even: %2, odd: %3)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetEven(), 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetOdd(), 16), 8, QChar('0')));
index += 8;
} break;
case 0xff:
{
if (stopCommand)
{
subtitleProcessor->printWarning(QString("DCSQ stop missing.\n"));
for (++index; index < bufsize; ++index)
{
if (fileBuffer->getByte(index++) != 0xff)
{
index--;
break;
}
}
stopDisplay = true;
} else {
index = nextIndex;
// add to display time
int d = fileBuffer->getWord(index);
dcsq = d;
nextIndex = fileBuffer->getDWord(index + 2) + masterIndex;
stopCommand = (index == nextIndex);
subtitleProcessor->print(QString("DCSQ ofs: %1 (%2ms), next DCSQ at ofs: %3\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number((d * 1024) / 90))
.arg(QString::number(nextIndex, 16), 8, QChar('0')));
index += 6;
}
} break;
default:
{
throw QString("Unexpected command %1 at index %2").arg(cmd).arg(QString::number(index, 16), 8, QChar('0'));
}
}
}
index = masterIndex + packetSize;
subPictures.push_back(pic);
}
}
catch (QString e)
{
if (subPictures.size() == 0)
{
throw e;
}
subtitleProcessor->printError(QString(e + "\n"));
subtitleProcessor->print(QString("Probably not all caption imported due to error.\n"));
}
emit currentProgressChanged(bufsize);
}
void SupHD::decode(SubPictureHD &subPicture)
{
_palette = decodePalette(subPicture);
_bitmap = decodeImage(subPicture, _palette.transparentIndex());
_primaryColorIndex = _bitmap.primaryColorIndex(_palette, subtitleProcessor->getAlphaThreshold());
}
void SupHD::decodeLine(QImage &trg, int trgOfs, int width, int maxPixels, BitStream* src)
{
int x = 0;
int pixelsLeft = 0;
int sumPixels = 0;
bool lf = false;
while (src->bitsLeft() > 0 && sumPixels < maxPixels)
{
int rleType = src->readBits(1);
int colorType = src->readBits(1);
int color;
int numPixels;
if (colorType == 1)
{
color = src->readBits(8);
}
else
{
color = src->readBits(2); // Colors between 0 and 3 are stored in two bits
}
if (rleType == 1)
{
int rleSize = src->readBits(1);
if (rleSize == 1)
{
numPixels = src->readBits(7) + 9;
if (numPixels == 9)
{
numPixels = width - x;
}
}
else
{
numPixels = src->readBits(3) + 2;
}
}
else
{
numPixels = 1;
}
if ((x + numPixels) == width)
{
src->syncToByte();
lf = true;
}
sumPixels += numPixels;
// write pixels to target
if ((x + numPixels) > width)
{
pixelsLeft = (x + numPixels) - width;
numPixels = width - x;
lf = true;
}
else
{
pixelsLeft = 0;
}
uchar* pixels = trg.bits();
for (int i = 0; i < numPixels; ++i)
{
pixels[trgOfs + x + i] = (uchar)color;
}
if (lf == true)
{
trgOfs += ((x + numPixels + (trg.bytesPerLine() - (x + numPixels)))
+ (width + (trg.bytesPerLine() - width))); // skip odd/even line
x = pixelsLeft;
lf = false;
}
else
{
x += numPixels;
}
// copy remaining pixels to new line
for (int i = 0; i < pixelsLeft; ++i)
{
pixels[trgOfs + i] = (uchar)color;
}
}
}
Palette SupHD::decodePalette(SubPictureHD &subPicture)
{
int ofs = subPicture.paletteOffset();
int alphaOfs = subPicture.alphaOffset();
Palette palette(256);
for (int i = 0; i < palette.size(); ++i)
{
// each palette entry consists of 3 bytes
int y = fileBuffer->getByte(ofs++);
int cr, cb;
if (subtitleProcessor->getSwapCrCb())
{
cb = fileBuffer->getByte(ofs++);
cr = fileBuffer->getByte(ofs++);
}
else
{
cr = fileBuffer->getByte(ofs++);
cb = fileBuffer->getByte(ofs++);
}
// each alpha entry consists of 1 byte
int alpha = 0xff - fileBuffer->getByte(alphaOfs++);
if (alpha < subtitleProcessor->getAlphaCrop()) // to not mess with scaling algorithms, make transparent color black
{
palette.setRGB(i, qRgb(0, 0, 0));
}
else
{
palette.setYCbCr(i, y, cb, cr);
}
palette.setAlpha(i, alpha);
}
return palette;
}
Bitmap SupHD::decodeImage(SubPictureHD &subPicture, int transparentIndex)
{
int w = subPicture.imageWidth();
int h = subPicture.imageHeight();
int warnings = 0;
if (w > subPicture.screenWidth() || h > subPicture.screenHeight())
{
throw QString("Subpicture too large: %1x%2 at offset %3")
.arg(QString::number(w))
.arg(QString::number(h))
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0'));
}
Bitmap bm(w, h, transparentIndex);
int sizeEven = subPicture.imageBufferOffsetOdd() - subPicture.imageBufferOffsetEven();
int sizeOdd = (subPicture.imageBufferSize() + subPicture.imageBufferOffsetEven()) - subPicture.imageBufferOffsetOdd();
if (sizeEven <= 0 || sizeOdd <= 0)
{
throw QString("Corrupt buffer offset information");
}
QVector<uchar> evenBuf = QVector<uchar>(sizeEven);
QVector<uchar> oddBuf = QVector<uchar>(sizeOdd);
for (int i = 0; i < evenBuf.size(); i++)
{
evenBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetEven() + i));
}
for (int i = 0; i < oddBuf.size(); ++i)
{
oddBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetOdd() + i));
}
// decode even lines
BitStream even = BitStream(evenBuf);
decodeLine(bm.image(), 0, w, w * ((h / 2) + (h & 1)), &even);
// decode odd lines
BitStream odd = BitStream(oddBuf);
decodeLine(bm.image(), w + (bm.image().bytesPerLine() - w), w, (h / 2) * w, &odd);
if (warnings > 0)
{
subtitleProcessor->printWarning(QString("problems during RLE decoding of picture at offset %1\n")
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0')));
}
return bm;
}
<commit_msg>Change to set window sizes instead of using setX, setY, setImageWidth, setImageHeight.<commit_after>/*
* BDSup2Sub++ (C) 2012 Adam T.
* Based on code from BDSup2Sub by Copyright 2009 Volker Oth (0xdeadbeef)
* and Copyright 2012 Miklos Juhasz (mjuhasz)
*
*
* 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 "suphd.h"
#include "subtitleprocessor.h"
#include "subpicturehd.h"
#include "Tools/filebuffer.h"
#include "Tools/bitstream.h"
#include "Tools/timeutil.h"
#include "bitmap.h"
#include "palette.h"
#include <QImage>
SupHD::SupHD(QString fileName, SubtitleProcessor *subtitleProcessor) :
supFileName(fileName)
{
this->subtitleProcessor = subtitleProcessor;
}
SupHD::~SupHD()
{
if (!fileBuffer.isNull())
{
fileBuffer.reset();
}
}
QImage SupHD::image()
{
return _bitmap.image(_palette);
}
QImage SupHD::image(Bitmap &bitmap)
{
return bitmap.image(_palette);
}
void SupHD::decode(int index)
{
if (index < subPictures.size())
{
decode(subPictures[index]);
}
else
{
throw QString("Index: %1 out of bounds.\n").arg(QString::number(index));
}
}
int SupHD::numFrames()
{
return subPictures.size();
}
qint64 SupHD::endTime(int index)
{
return subPictures[index].endTime();
}
qint64 SupHD::startTime(int index)
{
return subPictures[index].startTime();
}
qint64 SupHD::startOffset(int index)
{
return subPictures[index].imageBufferOffsetEven();
}
SubPicture *SupHD::subPicture(int index)
{
return &subPictures[index];
}
void SupHD::readAllSupFrames()
{
fileBuffer.reset(new FileBuffer(supFileName));
int index = 0;
int bufsize = (int)fileBuffer->getSize();
SubPictureHD pic;
subPictures.clear();
try
{
while (index < bufsize)
{
if (subtitleProcessor->isCancelled())
{
throw QString("Cancelled by user!");
}
emit currentProgressChanged(index);
if (fileBuffer->getWord(index) != 0x5350)
{
throw QString("ID 'SP' missing at index ").arg(QString::number(index, 16), 8, QChar('0'));
}
int masterIndex = index + 10; //end of header
pic = SubPictureHD();
// hard code size since it's not part of the format???
pic.setScreenWidth(1920);
pic.setScreenHeight(1080);
subtitleProcessor->printX(QString("#%1\n").arg(QString::number(subPictures.size() + 1)));;
pic.setStartTime(fileBuffer->getDWordLE(index += 2)); // read PTS
int packetSize = fileBuffer->getDWord(index += 10);
// offset to command buffer
int ofsCmd = fileBuffer->getDWord(index += 4) + masterIndex;
pic.setImageBufferSize(ofsCmd - (index + 4));
index = ofsCmd;
int dcsq = fileBuffer->getWord(index);
pic.setStartTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime())));
index+=2; // 2 bytes: dcsq
int nextIndex = fileBuffer->getDWord(index) + masterIndex; // offset to next dcsq
index += 5; // 4 bytes: offset, 1 byte: start
int cmd = 0;
bool stopDisplay = false;
bool stopCommand = false;
int alphaSum = 0;
int minAlphaSum = 256 * 256; // 256 fully transparent entries
while (!stopDisplay)
{
cmd = fileBuffer->getByte(index++);
switch (cmd)
{
case 0x01:
{
subtitleProcessor->printX(QString("DCSQ start ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.startTime() + (dcsq * 1024))));
subtitleProcessor->printWarning("DCSQ start ignored due to missing DCSQ stop\n");
} break;
case 0x02:
{
stopDisplay = true;
pic.setEndTime(pic.startTime() + (dcsq * 1024));
subtitleProcessor->printX(QString("DCSQ stop ofs: %1 (%2)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(TimeUtil::ptsToTimeStr(pic.endTime())));
} break;
case 0x83: // palette
{
subtitleProcessor->print(QString("Palette info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0')));
pic.setPaletteOffset(index);
index += 0x300;
} break;
case 0x84: // alpha
{
subtitleProcessor->print(QString("Alpha info ofs: %1\n").arg(QString::number(index, 16), 8, QChar('0'))); alphaSum = 0;
for (int i = index; i < index + 0x100; ++i)
{
alphaSum += fileBuffer->getByte(i);
}
if (alphaSum < minAlphaSum)
{
pic.setAlphaOffset(index);
minAlphaSum = alphaSum;
}
else
{
subtitleProcessor->printWarning(QString("Found faded alpha buffer -> alpha buffer skipped\n"));
}
index += 0x100;
} break;
case 0x85: // area
{
int x = (fileBuffer->getByte(index) << 4) | (fileBuffer->getByte(index + 1) >> 4);
int imageWidth = (((fileBuffer->getByte(index + 1) &0xf) << 8) | (fileBuffer->getByte(index + 2)));
int y = (fileBuffer->getByte(index + 3) <<4 ) | (fileBuffer->getByte(index + 4) >> 4);
int imageHeight = (((fileBuffer->getByte(index + 4) &0xf) << 8) | (fileBuffer->getByte(index + 5)));
QVector<QRect> imageRects = { QRect(x,
y,
(imageWidth - pic.x()) + 1,
(imageHeight - pic.y()) + 1),
};
pic.setWindowSizes(imageRects);
subtitleProcessor->print(QString("Area info ofs: %1 (%2, %3) - (%4, %5)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.x()))
.arg(QString::number(pic.y()))
.arg(QString::number(pic.x() + pic.imageWidth()))
.arg(QString::number(pic.y() + pic.imageHeight())));
index += 6;
} break;
case 0x86: // even/odd offsets
{
pic.setImageBufferOffsetEven(fileBuffer->getDWord(index) + masterIndex);
pic.setImageBufferOffsetOdd(fileBuffer->getDWord(index + 4) + masterIndex);
subtitleProcessor->print(QString("RLE buffers ofs: %1 (even: %2, odd: %3)\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetEven(), 16), 8, QChar('0'))
.arg(QString::number(pic.imageBufferOffsetOdd(), 16), 8, QChar('0')));
index += 8;
} break;
case 0xff:
{
if (stopCommand)
{
subtitleProcessor->printWarning(QString("DCSQ stop missing.\n"));
for (++index; index < bufsize; ++index)
{
if (fileBuffer->getByte(index++) != 0xff)
{
index--;
break;
}
}
stopDisplay = true;
} else {
index = nextIndex;
// add to display time
int d = fileBuffer->getWord(index);
dcsq = d;
nextIndex = fileBuffer->getDWord(index + 2) + masterIndex;
stopCommand = (index == nextIndex);
subtitleProcessor->print(QString("DCSQ ofs: %1 (%2ms), next DCSQ at ofs: %3\n")
.arg(QString::number(index, 16), 8, QChar('0'))
.arg(QString::number((d * 1024) / 90))
.arg(QString::number(nextIndex, 16), 8, QChar('0')));
index += 6;
}
} break;
default:
{
throw QString("Unexpected command %1 at index %2").arg(cmd).arg(QString::number(index, 16), 8, QChar('0'));
}
}
}
index = masterIndex + packetSize;
subPictures.push_back(pic);
}
}
catch (QString e)
{
if (subPictures.size() == 0)
{
throw e;
}
subtitleProcessor->printError(QString(e + "\n"));
subtitleProcessor->print(QString("Probably not all caption imported due to error.\n"));
}
emit currentProgressChanged(bufsize);
}
void SupHD::decode(SubPictureHD &subPicture)
{
_palette = decodePalette(subPicture);
_bitmap = decodeImage(subPicture, _palette.transparentIndex());
_primaryColorIndex = _bitmap.primaryColorIndex(_palette, subtitleProcessor->getAlphaThreshold());
}
void SupHD::decodeLine(QImage &trg, int trgOfs, int width, int maxPixels, BitStream* src)
{
int x = 0;
int pixelsLeft = 0;
int sumPixels = 0;
bool lf = false;
while (src->bitsLeft() > 0 && sumPixels < maxPixels)
{
int rleType = src->readBits(1);
int colorType = src->readBits(1);
int color;
int numPixels;
if (colorType == 1)
{
color = src->readBits(8);
}
else
{
color = src->readBits(2); // Colors between 0 and 3 are stored in two bits
}
if (rleType == 1)
{
int rleSize = src->readBits(1);
if (rleSize == 1)
{
numPixels = src->readBits(7) + 9;
if (numPixels == 9)
{
numPixels = width - x;
}
}
else
{
numPixels = src->readBits(3) + 2;
}
}
else
{
numPixels = 1;
}
if ((x + numPixels) == width)
{
src->syncToByte();
lf = true;
}
sumPixels += numPixels;
// write pixels to target
if ((x + numPixels) > width)
{
pixelsLeft = (x + numPixels) - width;
numPixels = width - x;
lf = true;
}
else
{
pixelsLeft = 0;
}
uchar* pixels = trg.bits();
for (int i = 0; i < numPixels; ++i)
{
pixels[trgOfs + x + i] = (uchar)color;
}
if (lf == true)
{
trgOfs += ((x + numPixels + (trg.bytesPerLine() - (x + numPixels)))
+ (width + (trg.bytesPerLine() - width))); // skip odd/even line
x = pixelsLeft;
lf = false;
}
else
{
x += numPixels;
}
// copy remaining pixels to new line
for (int i = 0; i < pixelsLeft; ++i)
{
pixels[trgOfs + i] = (uchar)color;
}
}
}
Palette SupHD::decodePalette(SubPictureHD &subPicture)
{
int ofs = subPicture.paletteOffset();
int alphaOfs = subPicture.alphaOffset();
Palette palette(256);
for (int i = 0; i < palette.size(); ++i)
{
// each palette entry consists of 3 bytes
int y = fileBuffer->getByte(ofs++);
int cr, cb;
if (subtitleProcessor->getSwapCrCb())
{
cb = fileBuffer->getByte(ofs++);
cr = fileBuffer->getByte(ofs++);
}
else
{
cr = fileBuffer->getByte(ofs++);
cb = fileBuffer->getByte(ofs++);
}
// each alpha entry consists of 1 byte
int alpha = 0xff - fileBuffer->getByte(alphaOfs++);
if (alpha < subtitleProcessor->getAlphaCrop()) // to not mess with scaling algorithms, make transparent color black
{
palette.setRGB(i, qRgb(0, 0, 0));
}
else
{
palette.setYCbCr(i, y, cb, cr);
}
palette.setAlpha(i, alpha);
}
return palette;
}
Bitmap SupHD::decodeImage(SubPictureHD &subPicture, int transparentIndex)
{
int w = subPicture.imageWidth();
int h = subPicture.imageHeight();
int warnings = 0;
if (w > subPicture.screenWidth() || h > subPicture.screenHeight())
{
throw QString("Subpicture too large: %1x%2 at offset %3")
.arg(QString::number(w))
.arg(QString::number(h))
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0'));
}
Bitmap bm(w, h, transparentIndex);
int sizeEven = subPicture.imageBufferOffsetOdd() - subPicture.imageBufferOffsetEven();
int sizeOdd = (subPicture.imageBufferSize() + subPicture.imageBufferOffsetEven()) - subPicture.imageBufferOffsetOdd();
if (sizeEven <= 0 || sizeOdd <= 0)
{
throw QString("Corrupt buffer offset information");
}
QVector<uchar> evenBuf = QVector<uchar>(sizeEven);
QVector<uchar> oddBuf = QVector<uchar>(sizeOdd);
for (int i = 0; i < evenBuf.size(); i++)
{
evenBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetEven() + i));
}
for (int i = 0; i < oddBuf.size(); ++i)
{
oddBuf.replace(i, (uchar)fileBuffer->getByte(subPicture.imageBufferOffsetOdd() + i));
}
// decode even lines
BitStream even = BitStream(evenBuf);
decodeLine(bm.image(), 0, w, w * ((h / 2) + (h & 1)), &even);
// decode odd lines
BitStream odd = BitStream(oddBuf);
decodeLine(bm.image(), w + (bm.image().bytesPerLine() - w), w, (h / 2) * w, &odd);
if (warnings > 0)
{
subtitleProcessor->printWarning(QString("problems during RLE decoding of picture at offset %1\n")
.arg(QString::number(subPicture.imageBufferOffsetEven(), 16), 8, QChar('0')));
}
return bm;
}
<|endoftext|>
|
<commit_before>#ifndef TPNOWAYLEXREADER_HH
#define TPNOWAYLEXREADER_HH
#include <stdio.h>
#include <map>
#include <string>
#include "TPLexPrefixTree.hh"
#include "Vocabulary.hh"
// A class that reads the lexicon from a file and calls the lexical prefix
// tree class to create the lexical tree.
//
// FILE FORMAT:
//
// ^word(prob) phone1 phone2 ...
// ^word phone1 phone2 ...
//
class TPNowayLexReader {
public:
TPNowayLexReader(std::map<std::string,int> &hmm_map,
std::vector<Hmm> &hmms,
TPLexPrefixTree &lex_tree,
Vocabulary &vocab);
/// \brief Reads the lexicon from a file.
///
/// Adds all the words to the vocabulary, and the word along with the HMMs of
/// their phones to the lexicon.
///
/// \exception UnknownHmm If a phone is not found from \ref m_hmm_map.
///
void read(FILE *file, const std::string &word_boundary);
void skip_while(FILE *file, const char *chars);
void get_until(FILE *file, std::string &str, const char *delims);
void set_silence_is_word(bool b) { m_silence_is_word = b; }
// Current state for error diagnosis
inline const std::string &word() const { return m_word; }
inline const std::string &phone() const { return m_phone; }
struct ReadError : public std::exception {
virtual const char *what() const throw()
{ return "TPNowayLexReader: read error"; }
};
struct InvalidProbability : public std::exception {
virtual const char *what() const throw()
{ return "TPNowayLexReader: invalid probability"; }
};
struct UnknownHmm : public std::exception {
UnknownHmm(const std::string & phone, const std::string & word) : m_phone(phone), m_word(word) {}
virtual ~UnknownHmm() throw () {}
virtual const char *what() const throw()
{ return "TPNowayLexReader: unknown hmm"; }
const std::string & phone() const
{ return m_phone; }
const std::string & word() const
{ return m_word; }
private:
std::string m_phone;
std::string m_word;
};
protected:
std::map<std::string,int> &m_hmm_map;
std::vector<Hmm> &m_hmms;
TPLexPrefixTree &m_lexicon;
Vocabulary &m_vocabulary;
int m_line_no;
std::string m_word;
// Temporary variables
std::string m_phone;
bool m_silence_is_word;
};
#endif /* TPNOWAYLEXREADER_HH */
<commit_msg>Documentation.<commit_after>#ifndef TPNOWAYLEXREADER_HH
#define TPNOWAYLEXREADER_HH
#include <stdio.h>
#include <map>
#include <string>
#include "TPLexPrefixTree.hh"
#include "Vocabulary.hh"
// A class that reads the lexicon from a file and calls the lexical prefix
// tree class to create the lexical tree.
//
// FILE FORMAT:
//
// ^word(prob) phone1 phone2 ...
// ^word phone1 phone2 ...
//
class TPNowayLexReader {
public:
TPNowayLexReader(std::map<std::string,int> &hmm_map,
std::vector<Hmm> &hmms,
TPLexPrefixTree &lex_tree,
Vocabulary &vocab);
/// \brief Reads the lexicon from a file.
///
/// Adds all the words to the vocabulary, and the word along with the HMMs of
/// their phones to the lexicon.
///
/// \exception UnknownHmm If a phone is not found from \ref m_hmm_map.
///
void read(FILE *file, const std::string &word_boundary);
void skip_while(FILE *file, const char *chars);
void get_until(FILE *file, std::string &str, const char *delims);
void set_silence_is_word(bool b) { m_silence_is_word = b; }
// Current state for error diagnosis
inline const std::string &word() const { return m_word; }
inline const std::string &phone() const { return m_phone; }
struct ReadError : public std::exception {
virtual const char *what() const throw()
{ return "TPNowayLexReader: read error"; }
};
struct InvalidProbability : public std::exception {
virtual const char *what() const throw()
{ return "TPNowayLexReader: invalid probability"; }
};
struct UnknownHmm : public std::exception {
UnknownHmm(const std::string & phone, const std::string & word) : m_phone(phone), m_word(word) {}
virtual ~UnknownHmm() throw () {}
virtual const char *what() const throw()
{ return "TPNowayLexReader: unknown hmm"; }
const std::string & phone() const
{ return m_phone; }
const std::string & word() const
{ return m_word; }
private:
std::string m_phone;
std::string m_word;
};
protected:
/// Mapping from phones (triphones) to HMM indices.
std::map<std::string,int> &m_hmm_map;
/// The HMMs.
std::vector<Hmm> &m_hmms;
TPLexPrefixTree &m_lexicon;
Vocabulary &m_vocabulary;
int m_line_no;
std::string m_word;
// Temporary variables
std::string m_phone;
bool m_silence_is_word;
};
#endif /* TPNOWAYLEXREADER_HH */
<|endoftext|>
|
<commit_before><commit_msg>add invalid framebuffer operation to OpenGL error messages<commit_after><|endoftext|>
|
<commit_before><commit_msg>debug helpers<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gcach_xpeer.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:48:54 $
*
* 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 _SV_GCACH_XPEER_HXX
#define _SV_GCACH_XPEER_HXX
#include <vcl/glyphcache.hxx>
#include <prex.h>
#include <X11/extensions/Xrender.h>
#include <postx.h>
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
class SalDisplay;
struct MultiScreenGlyph;
class X11GlyphPeer
: public GlyphCachePeer
{
public:
X11GlyphPeer();
virtual ~X11GlyphPeer();
Pixmap GetPixmap( ServerFont&, int nGlyphIndex, int nScreen );
const RawBitmap* GetRawBitmap( ServerFont&, int nGlyphIndex );
bool ForcedAntialiasing( const ServerFont&, int nScreen ) const;
GlyphSet GetGlyphSet( ServerFont&, int nScreen );
Glyph GetGlyphId( ServerFont&, int nGlyphIndex );
protected:
void InitAntialiasing();
virtual void RemovingFont( ServerFont& );
virtual void RemovingGlyph( ServerFont&, GlyphData&, int nGlyphIndex );
MultiScreenGlyph* PrepareForMultiscreen( ExtGlyphData& ) const;
void SetRenderGlyph( GlyphData&, Glyph ) const;
void SetRawBitmap( GlyphData&, const RawBitmap* ) const;
void SetPixmap( GlyphData&, Pixmap, int nScreen ) const;
Glyph GetRenderGlyph( const GlyphData& ) const;
const RawBitmap* GetRawBitmap( const GlyphData& ) const;
Pixmap GetPixmap( const GlyphData&, int nScreen ) const;
private:
Display* mpDisplay;
// thirty-two screens should be enough for everyone...
static const int MAX_GCACH_SCREENS = 32;
int mnMaxScreens;
int mnDefaultScreen;
int mnExtByteCount;
RawBitmap maRawBitmap;
sal_uInt32 mnForcedAA;
sal_uInt32 mnUsingXRender;
};
class X11GlyphCache : public GlyphCache
{
public:
X11GlyphPeer& GetPeer() { return reinterpret_cast<X11GlyphPeer&>( mrPeer ); }
static X11GlyphCache& GetInstance();
static void KillInstance();
private:
X11GlyphCache( X11GlyphPeer& );
};
#endif // _SV_GCACH_XPEER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.13.248); FILE MERGED 2008/04/01 13:02:00 thb 1.13.248.2: #i85898# Stripping all external header guards 2008/03/28 15:45:26 rt 1.13.248.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: gcach_xpeer.hxx,v $
* $Revision: 1.14 $
*
* 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 _SV_GCACH_XPEER_HXX
#define _SV_GCACH_XPEER_HXX
#include <vcl/glyphcache.hxx>
#include <prex.h>
#include <X11/extensions/Xrender.h>
#include <postx.h>
#include <vcl/dllapi.h>
class SalDisplay;
struct MultiScreenGlyph;
class X11GlyphPeer
: public GlyphCachePeer
{
public:
X11GlyphPeer();
virtual ~X11GlyphPeer();
Pixmap GetPixmap( ServerFont&, int nGlyphIndex, int nScreen );
const RawBitmap* GetRawBitmap( ServerFont&, int nGlyphIndex );
bool ForcedAntialiasing( const ServerFont&, int nScreen ) const;
GlyphSet GetGlyphSet( ServerFont&, int nScreen );
Glyph GetGlyphId( ServerFont&, int nGlyphIndex );
protected:
void InitAntialiasing();
virtual void RemovingFont( ServerFont& );
virtual void RemovingGlyph( ServerFont&, GlyphData&, int nGlyphIndex );
MultiScreenGlyph* PrepareForMultiscreen( ExtGlyphData& ) const;
void SetRenderGlyph( GlyphData&, Glyph ) const;
void SetRawBitmap( GlyphData&, const RawBitmap* ) const;
void SetPixmap( GlyphData&, Pixmap, int nScreen ) const;
Glyph GetRenderGlyph( const GlyphData& ) const;
const RawBitmap* GetRawBitmap( const GlyphData& ) const;
Pixmap GetPixmap( const GlyphData&, int nScreen ) const;
private:
Display* mpDisplay;
// thirty-two screens should be enough for everyone...
static const int MAX_GCACH_SCREENS = 32;
int mnMaxScreens;
int mnDefaultScreen;
int mnExtByteCount;
RawBitmap maRawBitmap;
sal_uInt32 mnForcedAA;
sal_uInt32 mnUsingXRender;
};
class X11GlyphCache : public GlyphCache
{
public:
X11GlyphPeer& GetPeer() { return reinterpret_cast<X11GlyphPeer&>( mrPeer ); }
static X11GlyphCache& GetInstance();
static void KillInstance();
private:
X11GlyphCache( X11GlyphPeer& );
};
#endif // _SV_GCACH_XPEER_HXX
<|endoftext|>
|
<commit_before>#include "Chimera_Win.h"
#include <boost/algorithm/string/replace.hpp>
#include <QtCore/qglobal.h>
#include <QtPlugin>
#include <QQmlContext.h>
#include <QtQml/QQml.h>
#include <QtEndian>
#include "QmlVlc/QmlVlcSurfacePlayerProxy.h"
#ifdef QT_STATIC
Q_IMPORT_PLUGIN( QWindowsIntegrationPlugin );
Q_IMPORT_PLUGIN( QtQuick2Plugin );
Q_IMPORT_PLUGIN( QtQuickLayoutsPlugin );
#endif
static std::string qtConf_resource_data;
static const unsigned char qtConf_resource_name[] = {
// qt
0x0,0x2,
0x0,0x0,0x7,0x84,
0x0,0x71,
0x0,0x74,
// etc
0x0,0x3,
0x0,0x0,0x6c,0xa3,
0x0,0x65,
0x0,0x74,0x0,0x63,
// qt.conf
0x0,0x7,
0x8,0x74,0xa6,0xa6,
0x0,0x71,
0x0,0x74,0x0,0x2e,0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x66,
};
static const unsigned char qtConf_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/qt
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/qt/etc
0x0,0x0,0x0,0xa,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
// :/qt/etc/qt.conf
0x0,0x0,0x0,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT
bool qRegisterResourceData( int, const unsigned char*,
const unsigned char* ,
const unsigned char* );
extern Q_CORE_EXPORT
bool qUnregisterResourceData( int, const unsigned char*,
const unsigned char*,
const unsigned char* );
QT_END_NAMESPACE
extern std::string g_dllPath;
////////////////////////////////////////////////////////////////////////////////
//Chimera_Win class
////////////////////////////////////////////////////////////////////////////////
void Chimera_Win::StaticInitialize()
{
#ifndef _DEBUG
if( !qApp ) {
std::string qtPrefix = g_dllPath + "/../";
boost::algorithm::replace_all( qtPrefix, "\\", "/" );
qtConf_resource_data = "4321[Paths]\n";
qtConf_resource_data += "Prefix = " + qtPrefix + "\n";
uint32_t qtConfSize = qtConf_resource_data.size() - sizeof( qtConfSize );
uint32_t qtConfSwappedSize = qToBigEndian( qtConfSize );
memcpy( &qtConf_resource_data[0], &qtConfSwappedSize, sizeof( qtConfSwappedSize ) );
qRegisterResourceData( 0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
}
#endif
QmlChimera::StaticInitialize();
}
void Chimera_Win::StaticDeinitialize()
{
#ifndef _DEBUG
qUnregisterResourceData(0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
#endif
}
Chimera_Win::Chimera_Win()
{
#ifdef QT_STATIC
qmlProtectModule( "QtQuick", 2 );
qmlProtectModule( "QtQuick.Layouts", 1 );
#endif
}
Chimera_Win::~Chimera_Win()
{
}
bool Chimera_Win::onWindowAttached( FB::AttachedEvent *evt, FB::PluginWindowWin* w )
{
vlc_open();
m_quickViewPtr.reset( new QQuickView );
m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView );
m_quickViewPtr->setProperty( "_q_embedded_native_parent_handle", WId( w->getHWND() ) );
m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint );
QQmlContext* context = m_quickViewPtr->rootContext();
m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() );
m_qmlVlcPlayer->classBegin();
//have to call apply_player_options()
//after QmlVlcSurfacePlayerProxy::classBegin
//to allow attach Proxy's vmem to plugin before play
apply_player_options();
setQml();
//simulate resize
onWindowResized( 0, w );
return false;
}
bool Chimera_Win::onWindowResized( FB::ResizedEvent*, FB::PluginWindowWin* w )
{
const int newWidth = w->getWindowWidth();
const int newHeight = w->getWindowHeight();
if( m_quickViewPtr && !is_fullscreen() ) {
if( newWidth > 0 && newHeight > 0 ) {
if( !m_quickViewPtr->isVisible() )
m_quickViewPtr->show();
MoveWindow( (HWND)m_quickViewPtr->winId(), 0, 0, newWidth, newHeight, TRUE );
} else
m_quickViewPtr->hide();
}
return false;
}
bool Chimera_Win::onWindowsEvent( FB::WindowsEvent* event, FB::PluginWindowWin* w )
{
if( WM_SETCURSOR == event->uMsg )
return true;
return false;
}
bool Chimera_Win::is_fullscreen()
{
if( m_quickViewPtr )
return 0 != ( m_quickViewPtr->visibility() & QWindow::FullScreen );
return false;
}
void Chimera_Win::set_fullscreen( bool fs )
{
if( m_quickViewPtr ) {
if( fs && !is_fullscreen() ) {
::SetParent( (HWND) m_quickViewPtr->winId(), NULL );
m_quickViewPtr->showFullScreen();
Q_EMIT fullscreenChanged( true );
} else if( !fs && is_fullscreen() ) {
FB::PluginWindowWin* w = static_cast<FB::PluginWindowWin*>( GetWindow() );
::SetParent( (HWND) m_quickViewPtr->winId(), w->getHWND() );
m_quickViewPtr->showNormal();
Q_EMIT fullscreenChanged( false );
}
}
}
<commit_msg>emulate window resize after fullscreen<commit_after>#include "Chimera_Win.h"
#include <boost/algorithm/string/replace.hpp>
#include <QtCore/qglobal.h>
#include <QtPlugin>
#include <QQmlContext.h>
#include <QtQml/QQml.h>
#include <QtEndian>
#include "QmlVlc/QmlVlcSurfacePlayerProxy.h"
#ifdef QT_STATIC
Q_IMPORT_PLUGIN( QWindowsIntegrationPlugin );
Q_IMPORT_PLUGIN( QtQuick2Plugin );
Q_IMPORT_PLUGIN( QtQuickLayoutsPlugin );
#endif
static std::string qtConf_resource_data;
static const unsigned char qtConf_resource_name[] = {
// qt
0x0,0x2,
0x0,0x0,0x7,0x84,
0x0,0x71,
0x0,0x74,
// etc
0x0,0x3,
0x0,0x0,0x6c,0xa3,
0x0,0x65,
0x0,0x74,0x0,0x63,
// qt.conf
0x0,0x7,
0x8,0x74,0xa6,0xa6,
0x0,0x71,
0x0,0x74,0x0,0x2e,0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x66,
};
static const unsigned char qtConf_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/qt
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/qt/etc
0x0,0x0,0x0,0xa,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
// :/qt/etc/qt.conf
0x0,0x0,0x0,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT
bool qRegisterResourceData( int, const unsigned char*,
const unsigned char* ,
const unsigned char* );
extern Q_CORE_EXPORT
bool qUnregisterResourceData( int, const unsigned char*,
const unsigned char*,
const unsigned char* );
QT_END_NAMESPACE
extern std::string g_dllPath;
////////////////////////////////////////////////////////////////////////////////
//Chimera_Win class
////////////////////////////////////////////////////////////////////////////////
void Chimera_Win::StaticInitialize()
{
#ifndef _DEBUG
if( !qApp ) {
std::string qtPrefix = g_dllPath + "/../";
boost::algorithm::replace_all( qtPrefix, "\\", "/" );
qtConf_resource_data = "4321[Paths]\n";
qtConf_resource_data += "Prefix = " + qtPrefix + "\n";
uint32_t qtConfSize = qtConf_resource_data.size() - sizeof( qtConfSize );
uint32_t qtConfSwappedSize = qToBigEndian( qtConfSize );
memcpy( &qtConf_resource_data[0], &qtConfSwappedSize, sizeof( qtConfSwappedSize ) );
qRegisterResourceData( 0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
}
#endif
QmlChimera::StaticInitialize();
}
void Chimera_Win::StaticDeinitialize()
{
#ifndef _DEBUG
qUnregisterResourceData(0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
#endif
}
Chimera_Win::Chimera_Win()
{
#ifdef QT_STATIC
qmlProtectModule( "QtQuick", 2 );
qmlProtectModule( "QtQuick.Layouts", 1 );
#endif
}
Chimera_Win::~Chimera_Win()
{
}
bool Chimera_Win::onWindowAttached( FB::AttachedEvent *evt, FB::PluginWindowWin* w )
{
vlc_open();
m_quickViewPtr.reset( new QQuickView );
m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView );
m_quickViewPtr->setProperty( "_q_embedded_native_parent_handle", WId( w->getHWND() ) );
m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint );
QQmlContext* context = m_quickViewPtr->rootContext();
m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() );
m_qmlVlcPlayer->classBegin();
//have to call apply_player_options()
//after QmlVlcSurfacePlayerProxy::classBegin
//to allow attach Proxy's vmem to plugin before play
apply_player_options();
setQml();
//simulate resize
onWindowResized( 0, w );
return false;
}
bool Chimera_Win::onWindowResized( FB::ResizedEvent*, FB::PluginWindowWin* w )
{
const int newWidth = w->getWindowWidth();
const int newHeight = w->getWindowHeight();
if( m_quickViewPtr && !is_fullscreen() ) {
if( newWidth > 0 && newHeight > 0 ) {
if( !m_quickViewPtr->isVisible() )
m_quickViewPtr->show();
MoveWindow( (HWND)m_quickViewPtr->winId(), 0, 0, newWidth, newHeight, TRUE );
} else
m_quickViewPtr->hide();
}
return false;
}
bool Chimera_Win::onWindowsEvent( FB::WindowsEvent* event, FB::PluginWindowWin* w )
{
if( WM_SETCURSOR == event->uMsg )
return true;
return false;
}
bool Chimera_Win::is_fullscreen()
{
if( m_quickViewPtr )
return 0 != ( m_quickViewPtr->visibility() & QWindow::FullScreen );
return false;
}
void Chimera_Win::set_fullscreen( bool fs )
{
if( m_quickViewPtr ) {
if( fs && !is_fullscreen() ) {
::SetParent( (HWND) m_quickViewPtr->winId(), NULL );
m_quickViewPtr->showFullScreen();
Q_EMIT fullscreenChanged( true );
} else if( !fs && is_fullscreen() ) {
FB::PluginWindowWin* w = static_cast<FB::PluginWindowWin*>( GetWindow() );
::SetParent( (HWND) m_quickViewPtr->winId(), w->getHWND() );
m_quickViewPtr->showNormal();
onWindowResized( 0, w );
Q_EMIT fullscreenChanged( false );
}
}
}
<|endoftext|>
|
<commit_before>/*! \file uvar.cc
*******************************************************************************
File: uvar.cc\n
Implementation of the UVar class.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2006.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.com
**************************************************************************** */
#include "uvariable.h"
#include "userver.h"
#include "uobject.h"
using namespace urbi;
namespace urbi {
class UVardata {
public:
UVardata(UVariable *v) { variable = v; };
~UVardata() {};
UVariable *variable;
};
};
// **************************************************************************
//! UVar constructor: implicit object ref (using 'lastUOjbect') + varname
UVar::UVar(const string &varname)
{
name = varname;
__init();
}
//! UVar constructor: object reference + var name
UVar::UVar(UObject& obj, const string &varname)
{
name = obj.__name + "." + varname;
__init();
}
//! UVar constructor: object name + var name
UVar::UVar(const string &objname, const string &varname)
{
name = objname + "." + varname;
__init();
}
//! UVar initialization
void
UVar::init(const string &objname, const string &varname)
{
name = objname + "." + varname;
__init();
}
//! UVar initializationvoid
void
UVar::__init()
{
this->owned = false;
varmap[name].push_back(this);
HMvariabletab::iterator it = ::urbiserver->variabletab.find(name.c_str());
if (it == ::urbiserver->variabletab.end())
vardata = new UVardata(new UVariable(name.c_str(),new
::UValue(),false,false,true)); // autoupdate unless otherwise specified
else {
vardata = new UVardata(it->second);
owned = !vardata->variable->autoUpdate;
}
}
//! set own mode
void
UVar::setOwned()
{
owned = true;
if (vardata)
vardata->variable->autoUpdate = false;
}
//! UVar destructor.
UVar::~UVar()
{
UVarTable::iterator varmapfind = varmap.find(name);
if (varmapfind != varmap.end()) {
for (list<UVar*>::iterator it = varmapfind->second.begin();
it != varmapfind->second.end();)
if ((*it) == this)
varmapfind->second.erase(it);
else
it++;
if (varmapfind->second.empty())
varmap.erase(varmapfind);
}
}
//! UVar float assignment
void
UVar::operator = (ufloat n)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
// type mismatch is not integrated at this stage
vardata->variable->value->dataType = ::DATA_NUM;
if (owned)
in() = n;
else
vardata->variable->setFloat(n);
}
//! UVar string assignment
void
UVar::operator = (string s)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
if (vardata->variable->value->dataType == ::DATA_VOID)
vardata->variable->value->str = new UString("");
// type mismatch is not integrated at this stage
vardata->variable->value->dataType = ::DATA_STRING;
::UValue tmpv(s.c_str());
vardata->variable->set(&tmpv);
}
//! UVar binary assignment
void
UVar::operator = (const UBinary &b)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
*vardata->variable->value=b;
vardata->variable->updated();
}
// UVar Casting
UVar::operator int () {
//check of dataType is done inside in and out
if (owned)
return (int)out();
else
return (int)in();
}
UVar::operator ufloat () {
//check of dataType is done inside in and out
if (owned)
return out();
else
return in();
}
UVar::operator string () {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_STRING))
return (string(vardata->variable->value->str->str()));
else
return string("");
}
UVar::operator UList() {
return (UList)*vardata->variable->value;
}
UVar::operator urbi::UBinary() {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_BINARY)) {
//simplest way is to echo our bin headers and parse again
UBinary b;
std::ostringstream msg;
msg << vardata->variable->value->refBinary->ref()->bufferSize;
UNamedParameters *param = vardata->variable->value->refBinary->ref()->parameters;
while (param) {
if (param->expression) {
if (param->expression->dataType == ::DATA_NUM)
msg<< " "<<(int)param->expression->val;
else if (param->expression->dataType == ::DATA_STRING)
msg << " "<<param->expression->str->str();
}
param = param->next;
}
std::list<urbi::BinaryData> lBin;
lBin.push_back(urbi::BinaryData( vardata->variable->value->refBinary->ref()->buffer, vardata->variable->value->refBinary->ref()->bufferSize));
std::list<urbi::BinaryData>::iterator lIter = lBin.begin();
b.parse(msg.str().c_str(), 0, lBin, lIter);
return b;
}
else return UBinary();
}
UVar::operator urbi::UBinary*() {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_BINARY)) {
//simplest way is to echo our bin headers and parse again
UBinary* b = new UBinary();
std::ostringstream msg;
msg << vardata->variable->value->refBinary->ref()->bufferSize;
UNamedParameters *param = vardata->variable->value->refBinary->ref()->parameters;
while (param) {
if (param->expression) {
if (param->expression->dataType == ::DATA_NUM)
msg<< " "<<(int)param->expression->val;
else if (param->expression->dataType == ::DATA_STRING)
msg << " "<<param->expression->str->str();
}
param = param->next;
}
std::list<urbi::BinaryData> lBin;
lBin.push_back(urbi::BinaryData( vardata->variable->value->refBinary->ref()->buffer, vardata->variable->value->refBinary->ref()->bufferSize));
std::list<urbi::BinaryData>::iterator lIter = lBin.begin();
b->parse(msg.str().c_str(), 0, lBin, lIter);
return b;
}
else return new UBinary();
}
UVar::operator UImage() {
return (UImage)*vardata->variable->value;
}
UVar::operator USound() {
return (USound)*vardata->variable->value;
}
//! UVar out value (read mode)
ufloat&
UVar::out()
{
static ufloat er=0;
if ((vardata) && (vardata->variable->value->dataType == ::DATA_NUM))
return (vardata->variable->target);
else return er;
}
//! UVar in value (write mode)
ufloat&
UVar::in()
{
static ufloat er=0;
if ((vardata) && (vardata->variable->value->dataType == ::DATA_NUM))
return (vardata->variable->value->val);
else return er;
}
UBlendType
UVar::blend()
{
if (vardata)
return ((UBlendType)vardata->variable->blendType);
else {
urbi::echo("Internal error on variable 'vardata', should not be zero\n");
return (UNORMAL);
}
}
//! UVar update
void
UVar::__update(UValue& v)
{
value = v;
}
<commit_msg>fixed (?) a bug that prevented a plugin from using a sensor variable from an other plugin correctly<commit_after>/*! \file uvar.cc
*******************************************************************************
File: uvar.cc\n
Implementation of the UVar class.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2006.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.com
**************************************************************************** */
#include "uvariable.h"
#include "userver.h"
#include "uobject.h"
using namespace urbi;
namespace urbi {
class UVardata {
public:
UVardata(UVariable *v) { variable = v; };
~UVardata() {};
UVariable *variable;
};
};
// **************************************************************************
//! UVar constructor: implicit object ref (using 'lastUOjbect') + varname
UVar::UVar(const string &varname)
{
name = varname;
__init();
}
//! UVar constructor: object reference + var name
UVar::UVar(UObject& obj, const string &varname)
{
name = obj.__name + "." + varname;
__init();
}
//! UVar constructor: object name + var name
UVar::UVar(const string &objname, const string &varname)
{
name = objname + "." + varname;
__init();
}
//! UVar initialization
void
UVar::init(const string &objname, const string &varname)
{
name = objname + "." + varname;
__init();
}
//! UVar initializationvoid
void
UVar::__init()
{
this->owned = false;
varmap[name].push_back(this);
HMvariabletab::iterator it = ::urbiserver->variabletab.find(name.c_str());
if (it == ::urbiserver->variabletab.end())
vardata = new UVardata(new UVariable(name.c_str(),new
::UValue(),false,false,true)); // autoupdate unless otherwise specified
else {
vardata = new UVardata(it->second);
//XXX why?? owned = !vardata->variable->autoUpdate;
}
}
//! set own mode
void
UVar::setOwned()
{
owned = true;
if (vardata)
vardata->variable->autoUpdate = false;
}
//! UVar destructor.
UVar::~UVar()
{
UVarTable::iterator varmapfind = varmap.find(name);
if (varmapfind != varmap.end()) {
for (list<UVar*>::iterator it = varmapfind->second.begin();
it != varmapfind->second.end();)
if ((*it) == this)
varmapfind->second.erase(it);
else
it++;
if (varmapfind->second.empty())
varmap.erase(varmapfind);
}
}
//! UVar float assignment
void
UVar::operator = (ufloat n)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
// type mismatch is not integrated at this stage
vardata->variable->value->dataType = ::DATA_NUM;
if (owned)
in() = n;
else
vardata->variable->setFloat(n);
}
//! UVar string assignment
void
UVar::operator = (string s)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
if (vardata->variable->value->dataType == ::DATA_VOID)
vardata->variable->value->str = new UString("");
// type mismatch is not integrated at this stage
vardata->variable->value->dataType = ::DATA_STRING;
::UValue tmpv(s.c_str());
vardata->variable->set(&tmpv);
}
//! UVar binary assignment
void
UVar::operator = (const UBinary &b)
{
if (!vardata) {
urbi::echo("Unable to locate variable %s in hashtable. Memory problem, report bug.\n",
name.c_str());
return;
}
*vardata->variable->value=b;
vardata->variable->updated();
}
// UVar Casting
UVar::operator int () {
//check of dataType is done inside in and out
if (owned)
return (int)out();
else
return (int)in();
}
UVar::operator ufloat () {
//check of dataType is done inside in and out
if (owned)
return out();
else
return in();
}
UVar::operator string () {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_STRING))
return (string(vardata->variable->value->str->str()));
else
return string("");
}
UVar::operator UList() {
return (UList)*vardata->variable->value;
}
UVar::operator urbi::UBinary() {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_BINARY)) {
//simplest way is to echo our bin headers and parse again
UBinary b;
std::ostringstream msg;
msg << vardata->variable->value->refBinary->ref()->bufferSize;
UNamedParameters *param = vardata->variable->value->refBinary->ref()->parameters;
while (param) {
if (param->expression) {
if (param->expression->dataType == ::DATA_NUM)
msg<< " "<<(int)param->expression->val;
else if (param->expression->dataType == ::DATA_STRING)
msg << " "<<param->expression->str->str();
}
param = param->next;
}
std::list<urbi::BinaryData> lBin;
lBin.push_back(urbi::BinaryData( vardata->variable->value->refBinary->ref()->buffer, vardata->variable->value->refBinary->ref()->bufferSize));
std::list<urbi::BinaryData>::iterator lIter = lBin.begin();
b.parse(msg.str().c_str(), 0, lBin, lIter);
return b;
}
else return UBinary();
}
UVar::operator urbi::UBinary*() {
if ((vardata) && (vardata->variable->value->dataType == ::DATA_BINARY)) {
//simplest way is to echo our bin headers and parse again
UBinary* b = new UBinary();
std::ostringstream msg;
msg << vardata->variable->value->refBinary->ref()->bufferSize;
UNamedParameters *param = vardata->variable->value->refBinary->ref()->parameters;
while (param) {
if (param->expression) {
if (param->expression->dataType == ::DATA_NUM)
msg<< " "<<(int)param->expression->val;
else if (param->expression->dataType == ::DATA_STRING)
msg << " "<<param->expression->str->str();
}
param = param->next;
}
std::list<urbi::BinaryData> lBin;
lBin.push_back(urbi::BinaryData( vardata->variable->value->refBinary->ref()->buffer, vardata->variable->value->refBinary->ref()->bufferSize));
std::list<urbi::BinaryData>::iterator lIter = lBin.begin();
b->parse(msg.str().c_str(), 0, lBin, lIter);
return b;
}
else return new UBinary();
}
UVar::operator UImage() {
return (UImage)*vardata->variable->value;
}
UVar::operator USound() {
return (USound)*vardata->variable->value;
}
//! UVar out value (read mode)
ufloat&
UVar::out()
{
static ufloat er=0;
if ((vardata) && (vardata->variable->value->dataType == ::DATA_NUM))
return (vardata->variable->target);
else return er;
}
//! UVar in value (write mode)
ufloat&
UVar::in()
{
static ufloat er=0;
if ((vardata) && (vardata->variable->value->dataType == ::DATA_NUM))
return (vardata->variable->value->val);
else return er;
}
UBlendType
UVar::blend()
{
if (vardata)
return ((UBlendType)vardata->variable->blendType);
else {
urbi::echo("Internal error on variable 'vardata', should not be zero\n");
return (UNORMAL);
}
}
//! UVar update
void
UVar::__update(UValue& v)
{
value = v;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2009-2010 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 the copyright holders 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.
*
* Authors: Ali Saidi
*/
#include "arch/arm/faults.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/tlb.hh"
#include "arch/arm/utility.hh"
#include "arch/arm/vtophys.hh"
#include "config/use_checker.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "sim/full_system.hh"
namespace ArmISA {
void
initCPU(ThreadContext *tc, int cpuId)
{
// Reset CP15?? What does that mean -- ali
// FPEXC.EN = 0
static Fault reset = new Reset;
reset->invoke(tc);
}
uint64_t
getArgument(ThreadContext *tc, int &number, uint16_t size, bool fp)
{
if (!FullSystem) {
panic("getArgument() only implemented for full system mode.\n");
M5_DUMMY_RETURN
}
if (size == (uint16_t)(-1))
size = ArmISA::MachineBytes;
if (fp)
panic("getArgument(): Floating point arguments not implemented\n");
if (number < NumArgumentRegs) {
// If the argument is 64 bits, it must be in an even regiser
// number. Increment the number here if it isn't even.
if (size == sizeof(uint64_t)) {
if ((number % 2) != 0)
number++;
// Read the two halves of the data. Number is inc here to
// get the second half of the 64 bit reg.
uint64_t tmp;
tmp = tc->readIntReg(number++);
tmp |= tc->readIntReg(number) << 32;
return tmp;
} else {
return tc->readIntReg(number);
}
} else {
Addr sp = tc->readIntReg(StackPointerReg);
FSTranslatingPortProxy &vp = tc->getVirtProxy();
uint64_t arg;
if (size == sizeof(uint64_t)) {
// If the argument is even it must be aligned
if ((number % 2) != 0)
number++;
arg = vp.read<uint64_t>(sp +
(number-NumArgumentRegs) * sizeof(uint32_t));
// since two 32 bit args == 1 64 bit arg, increment number
number++;
} else {
arg = vp.read<uint32_t>(sp +
(number-NumArgumentRegs) * sizeof(uint32_t));
}
return arg;
}
}
void
skipFunction(ThreadContext *tc)
{
TheISA::PCState newPC = tc->pcState();
newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
#if USE_CHECKER
tc->pcStateNoRecord(newPC);
#else
tc->pcState(newPC);
#endif
}
void
copyRegs(ThreadContext *src, ThreadContext *dest)
{
int i;
int saved_mode = ((CPSR)src->readMiscReg(MISCREG_CPSR)).mode;
// Make sure we're in user mode, so we can easily see all the registers
// in the copy loop
src->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
dest->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
for(i = 0; i < TheISA::NumIntRegs; i++)
dest->setIntReg(i, src->readIntReg(i));
// Restore us back to the old mode
src->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
dest->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
for(i = 0; i < TheISA::NumFloatRegs; i++)
dest->setFloatReg(i, src->readFloatReg(i));
for(i = 0; i < TheISA::NumMiscRegs; i++)
dest->setMiscRegNoEffect(i, src->readMiscRegNoEffect(i));
// setMiscReg "with effect" will set the misc register mapping correctly.
// e.g. updateRegMap(val)
dest->setMiscReg(MISCREG_CPSR, src->readMiscRegNoEffect(MISCREG_CPSR));
// Copy over the PC State
dest->pcState(src->pcState());
// Invalidate the tlb misc register cache
dest->getITBPtr()->invalidateMiscReg();
dest->getDTBPtr()->invalidateMiscReg();
}
Addr
truncPage(Addr addr)
{
return addr & ~(PageBytes - 1);
}
Addr
roundPage(Addr addr)
{
return (addr + PageBytes - 1) & ~(PageBytes - 1);
}
} // namespace ArmISA
<commit_msg>ARM: Don't reset CPUs that are going to be switched in.<commit_after>/*
* Copyright (c) 2009-2010 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 the copyright holders 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.
*
* Authors: Ali Saidi
*/
#include "arch/arm/faults.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/tlb.hh"
#include "arch/arm/utility.hh"
#include "arch/arm/vtophys.hh"
#include "config/use_checker.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "params/BaseCPU.hh"
#include "sim/full_system.hh"
namespace ArmISA {
void
initCPU(ThreadContext *tc, int cpuId)
{
// Reset CP15?? What does that mean -- ali
// FPEXC.EN = 0
if (tc->getCpuPtr()->params()->defer_registration)
return;
static Fault reset = new Reset;
reset->invoke(tc);
}
uint64_t
getArgument(ThreadContext *tc, int &number, uint16_t size, bool fp)
{
if (!FullSystem) {
panic("getArgument() only implemented for full system mode.\n");
M5_DUMMY_RETURN
}
if (size == (uint16_t)(-1))
size = ArmISA::MachineBytes;
if (fp)
panic("getArgument(): Floating point arguments not implemented\n");
if (number < NumArgumentRegs) {
// If the argument is 64 bits, it must be in an even regiser
// number. Increment the number here if it isn't even.
if (size == sizeof(uint64_t)) {
if ((number % 2) != 0)
number++;
// Read the two halves of the data. Number is inc here to
// get the second half of the 64 bit reg.
uint64_t tmp;
tmp = tc->readIntReg(number++);
tmp |= tc->readIntReg(number) << 32;
return tmp;
} else {
return tc->readIntReg(number);
}
} else {
Addr sp = tc->readIntReg(StackPointerReg);
FSTranslatingPortProxy &vp = tc->getVirtProxy();
uint64_t arg;
if (size == sizeof(uint64_t)) {
// If the argument is even it must be aligned
if ((number % 2) != 0)
number++;
arg = vp.read<uint64_t>(sp +
(number-NumArgumentRegs) * sizeof(uint32_t));
// since two 32 bit args == 1 64 bit arg, increment number
number++;
} else {
arg = vp.read<uint32_t>(sp +
(number-NumArgumentRegs) * sizeof(uint32_t));
}
return arg;
}
}
void
skipFunction(ThreadContext *tc)
{
TheISA::PCState newPC = tc->pcState();
newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
#if USE_CHECKER
tc->pcStateNoRecord(newPC);
#else
tc->pcState(newPC);
#endif
}
void
copyRegs(ThreadContext *src, ThreadContext *dest)
{
int i;
int saved_mode = ((CPSR)src->readMiscReg(MISCREG_CPSR)).mode;
// Make sure we're in user mode, so we can easily see all the registers
// in the copy loop
src->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
dest->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
for(i = 0; i < TheISA::NumIntRegs; i++)
dest->setIntReg(i, src->readIntReg(i));
// Restore us back to the old mode
src->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
dest->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
for(i = 0; i < TheISA::NumFloatRegs; i++)
dest->setFloatReg(i, src->readFloatReg(i));
for(i = 0; i < TheISA::NumMiscRegs; i++)
dest->setMiscRegNoEffect(i, src->readMiscRegNoEffect(i));
// setMiscReg "with effect" will set the misc register mapping correctly.
// e.g. updateRegMap(val)
dest->setMiscReg(MISCREG_CPSR, src->readMiscRegNoEffect(MISCREG_CPSR));
// Copy over the PC State
dest->pcState(src->pcState());
// Invalidate the tlb misc register cache
dest->getITBPtr()->invalidateMiscReg();
dest->getDTBPtr()->invalidateMiscReg();
}
Addr
truncPage(Addr addr)
{
return addr & ~(PageBytes - 1);
}
Addr
roundPage(Addr addr)
{
return (addr + PageBytes - 1) & ~(PageBytes - 1);
}
} // namespace ArmISA
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__
#error X86 is not yet supported!
namespace X86ISA
{
};
#endif // __ARCH_X86_UTILITY_HH__
<commit_msg>Added stub implementations or prototypes for all the functions in this file.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__
#include "arch/x86/types.hh"
#include "base/misc.hh"
class ThreadContext;
namespace X86ISA
{
static inline bool
inUserMode(ThreadContext *tc)
{
return false;
}
inline ExtMachInst
makeExtMI(MachInst inst, ThreadContext * xc) {
return inst;
}
inline bool isCallerSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCallerSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
// Instruction address compression hooks
inline Addr realPCToFetchPC(const Addr &addr)
{
return addr;
}
inline Addr fetchPCToRealPC(const Addr &addr)
{
return addr;
}
// the size of "fetched" instructions (not necessarily the size
// of real instructions for PISA)
inline size_t fetchInstSize()
{
return sizeof(MachInst);
}
/**
* Function to insure ISA semantics about 0 registers.
* @param tc The thread context.
*/
template <class TC>
void zeroRegisters(TC *tc);
inline void initCPU(ThreadContext *tc, int cpuId)
{
panic("initCPU not implemented!\n");
}
};
#endif // __ARCH_X86_UTILITY_HH__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_VTOPHYS_HH__
#define __ARCH_X86_VTOPHYS_HH__
#error X86 is not yet supported!
namespace X86ISA
{
};
#endif // __ARCH_X86_VTOPHYS_HH__
<commit_msg>Fill out a stub version of the vtophys header file.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_VTOPHYS_HH__
#define __ARCH_X86_VTOPHYS_HH__
#include "arch/x86/isa_traits.hh"
#include "arch/x86/pagetable.hh"
#include "sim/host.hh"
class ThreadContext;
class FunctionalPort;
namespace X86ISA
{
PageTableEntry
kernel_pte_lookup(FunctionalPort *mem, Addr ptbr, X86ISA::VAddr vaddr);
Addr vtophys(Addr vaddr);
Addr vtophys(ThreadContext *tc, Addr vaddr);
};
#endif // __ARCH_X86_VTOPHYS_HH__
<|endoftext|>
|
<commit_before>#include "bplustreeblocks.h"
using namespace bplustree;
const TRecordType BPlusTreeBlocks::commTypes[] =
{
COMM + LOG + SEND,
COMM + LOG + RECV,
COMM + PHY + SEND,
COMM + PHY + RECV,
RSEND + LOG,
RRECV + LOG,
RSEND + PHY,
RRECV + PHY
};
/****************************************
* Record blocks management methods
****************************************/
void BPlusTreeBlocks::newRecord()
{
if ( currentBlock == NULL )
{
blocks[0] = new TRecord[blockSize];
memset( blocks[0], 0, blockSize * sizeof( TRecord ) );
currentBlock = blocks[0];
currentRecord = 0;
}
else
{
currentRecord++;
if ( currentRecord == blockSize )
{
blocks.push_back( new TRecord[blockSize] );
memset( blocks[blocks.size() - 1], 0, blockSize * sizeof( TRecord ) );
currentBlock = blocks[blocks.size() - 1];
currentRecord = 0;
}
}
lastRecords.push_back( ¤tBlock[currentRecord] );
countInserted++;
}
void BPlusTreeBlocks::setType( TRecordType whichType )
{
currentBlock[currentRecord].type = whichType;
}
void BPlusTreeBlocks::setTime( TRecordTime whichTime )
{
currentBlock[currentRecord].time = whichTime;
}
void BPlusTreeBlocks::setThread( TThreadOrder whichThread )
{
currentBlock[currentRecord].thread = whichThread;
}
void BPlusTreeBlocks::setThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
currentBlock[currentRecord].thread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
}
void BPlusTreeBlocks::setCPU( TCPUOrder whichCPU )
{
currentBlock[currentRecord].CPU = whichCPU;
}
void BPlusTreeBlocks::setEventType( TEventType whichType )
{
currentBlock[currentRecord].URecordInfo.eventRecord.type = whichType;
}
void BPlusTreeBlocks::setEventValue( TEventValue whichValue )
{
currentBlock[currentRecord].URecordInfo.eventRecord.value = whichValue;
}
void BPlusTreeBlocks::setState( TState whichState )
{
currentBlock[currentRecord].URecordInfo.stateRecord.state = whichState;
}
void BPlusTreeBlocks::setStateEndTime( TRecordTime whichTime )
{
currentBlock[currentRecord].URecordInfo.stateRecord.endTime = whichTime;
}
void BPlusTreeBlocks::setCommIndex( TCommID whichID )
{
currentBlock[currentRecord].URecordInfo.commRecord.index = whichID;
}
/****************************************
* Communications management methods
****************************************/
void BPlusTreeBlocks::newComm( bool createRecords )
{
communications.push_back( new TCommInfo() );
currentComm = communications.size() - 1;
if ( !createRecords )
{
for ( UINT8 i = 0; i < commTypeSize; i++ )
commRecords[ i ] = NULL;
}
else
{
for ( UINT8 i = 0; i < commTypeSize; i++ )
{
newRecord();
commRecords[i] = ¤tBlock[currentRecord];
setType( commTypes[i] );
setCommIndex( currentComm );
}
}
}
void BPlusTreeBlocks::setSenderThread( TThreadOrder whichThread )
{
communications[currentComm]->senderThread = whichThread;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->thread = whichThread;
commRecords[physicalSend]->thread = whichThread;
commRecords[remoteLogicalReceive]->thread = whichThread;
commRecords[remotePhysicalReceive]->thread = whichThread;
}
}
void BPlusTreeBlocks::setSenderThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
TThreadOrder globalThread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
communications[currentComm]->senderThread = globalThread;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->thread = globalThread;
commRecords[physicalSend]->thread = globalThread;
commRecords[remoteLogicalReceive]->thread = globalThread;
commRecords[remotePhysicalReceive]->thread = globalThread;
}
}
void BPlusTreeBlocks::setSenderCPU( TCPUOrder whichCPU )
{
communications[currentComm]->senderCPU = whichCPU;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->CPU = whichCPU;
commRecords[physicalSend]->CPU = whichCPU;
commRecords[remoteLogicalReceive]->CPU = whichCPU;
commRecords[remotePhysicalReceive]->CPU = whichCPU;
}
}
void BPlusTreeBlocks::setReceiverThread( TThreadOrder whichThread )
{
communications[currentComm]->receiverThread = whichThread;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->thread = whichThread;
commRecords[physicalReceive]->thread = whichThread;
commRecords[remoteLogicalSend]->thread = whichThread;
commRecords[remotePhysicalSend]->thread = whichThread;
}
}
void BPlusTreeBlocks::setReceiverThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
TThreadOrder globalThread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
communications[currentComm]->receiverThread = globalThread;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->thread = globalThread;
commRecords[physicalReceive]->thread = globalThread;
commRecords[remoteLogicalSend]->thread = globalThread;
commRecords[remotePhysicalSend]->thread = globalThread;
}
}
void BPlusTreeBlocks::setReceiverCPU( TCPUOrder whichCPU )
{
communications[currentComm]->receiverCPU = whichCPU;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->CPU = whichCPU;
commRecords[physicalReceive]->CPU = whichCPU;
commRecords[remoteLogicalSend]->CPU = whichCPU;
commRecords[remotePhysicalSend]->CPU = whichCPU;
}
}
void BPlusTreeBlocks::setCommTag( TCommTag whichTag )
{
communications[currentComm]->tag = whichTag;
}
void BPlusTreeBlocks::setCommSize( TCommSize whichSize )
{
communications[currentComm]->size = whichSize;
}
void BPlusTreeBlocks::setLogicalSend( TRecordTime whichTime )
{
communications[currentComm]->logicalSendTime = whichTime;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->time = whichTime;
commRecords[remoteLogicalSend]->time = whichTime;
}
}
void BPlusTreeBlocks::setLogicalReceive( TRecordTime whichTime )
{
communications[currentComm]->logicalReceiveTime = whichTime;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->time = whichTime;
commRecords[remoteLogicalReceive]->time = whichTime;
}
}
void BPlusTreeBlocks::setPhysicalSend( TRecordTime whichTime )
{
communications[currentComm]->physicalSendTime = whichTime;
if ( commRecords[physicalSend] != NULL )
{
commRecords[physicalSend]->time = whichTime;
commRecords[remotePhysicalSend]->time = whichTime;
}
}
void BPlusTreeBlocks::setPhysicalReceive( TRecordTime whichTime )
{
communications[currentComm]->physicalReceiveTime = whichTime;
if ( commRecords[physicalReceive] != NULL )
{
commRecords[physicalReceive]->time = whichTime;
commRecords[remotePhysicalReceive]->time = whichTime;
}
}
TThreadOrder BPlusTreeBlocks::getSenderThread( TCommID whichComm ) const
{
return communications[whichComm]->senderThread;
}
TCPUOrder BPlusTreeBlocks::getSenderCPU( TCommID whichComm ) const
{
return communications[whichComm]->senderCPU;
}
TThreadOrder BPlusTreeBlocks::getReceiverThread( TCommID whichComm ) const
{
return communications[whichComm]->receiverThread;
}
TCPUOrder BPlusTreeBlocks::getReceiverCPU( TCommID whichComm ) const
{
return communications[whichComm]->receiverCPU;
}
TCommTag BPlusTreeBlocks::getCommTag( TCommID whichComm ) const
{
return communications[whichComm]->tag;
}
TCommSize BPlusTreeBlocks::getCommSize( TCommID whichComm ) const
{
return communications[whichComm]->size;
}
TRecordTime BPlusTreeBlocks::getLogicalSend( TCommID whichComm ) const
{
return communications[whichComm]->logicalSendTime;
}
TRecordTime BPlusTreeBlocks::getLogicalReceive( TCommID whichComm ) const
{
return communications[whichComm]->logicalReceiveTime;
}
TRecordTime BPlusTreeBlocks::getPhysicalSend( TCommID whichComm ) const
{
return communications[whichComm]->physicalSendTime;
}
TRecordTime BPlusTreeBlocks::getPhysicalReceive( TCommID whichComm ) const
{
return communications[whichComm]->physicalReceiveTime;
}
TRecordTime BPlusTreeBlocks::getLastRecordTime() const
{
return currentBlock[currentRecord].time;
}
<commit_msg>*** empty log message ***<commit_after>#include <string.h>
#include "bplustreeblocks.h"
using namespace bplustree;
const TRecordType BPlusTreeBlocks::commTypes[] =
{
COMM + LOG + SEND,
COMM + LOG + RECV,
COMM + PHY + SEND,
COMM + PHY + RECV,
RSEND + LOG,
RRECV + LOG,
RSEND + PHY,
RRECV + PHY
};
/****************************************
* Record blocks management methods
****************************************/
void BPlusTreeBlocks::newRecord()
{
if ( currentBlock == NULL )
{
blocks[0] = new TRecord[blockSize];
memset( blocks[0], 0, blockSize * sizeof( TRecord ) );
currentBlock = blocks[0];
currentRecord = 0;
}
else
{
currentRecord++;
if ( currentRecord == blockSize )
{
blocks.push_back( new TRecord[blockSize] );
memset( blocks[blocks.size() - 1], 0, blockSize * sizeof( TRecord ) );
currentBlock = blocks[blocks.size() - 1];
currentRecord = 0;
}
}
lastRecords.push_back( ¤tBlock[currentRecord] );
countInserted++;
}
void BPlusTreeBlocks::setType( TRecordType whichType )
{
currentBlock[currentRecord].type = whichType;
}
void BPlusTreeBlocks::setTime( TRecordTime whichTime )
{
currentBlock[currentRecord].time = whichTime;
}
void BPlusTreeBlocks::setThread( TThreadOrder whichThread )
{
currentBlock[currentRecord].thread = whichThread;
}
void BPlusTreeBlocks::setThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
currentBlock[currentRecord].thread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
}
void BPlusTreeBlocks::setCPU( TCPUOrder whichCPU )
{
currentBlock[currentRecord].CPU = whichCPU;
}
void BPlusTreeBlocks::setEventType( TEventType whichType )
{
currentBlock[currentRecord].URecordInfo.eventRecord.type = whichType;
}
void BPlusTreeBlocks::setEventValue( TEventValue whichValue )
{
currentBlock[currentRecord].URecordInfo.eventRecord.value = whichValue;
}
void BPlusTreeBlocks::setState( TState whichState )
{
currentBlock[currentRecord].URecordInfo.stateRecord.state = whichState;
}
void BPlusTreeBlocks::setStateEndTime( TRecordTime whichTime )
{
currentBlock[currentRecord].URecordInfo.stateRecord.endTime = whichTime;
}
void BPlusTreeBlocks::setCommIndex( TCommID whichID )
{
currentBlock[currentRecord].URecordInfo.commRecord.index = whichID;
}
/****************************************
* Communications management methods
****************************************/
void BPlusTreeBlocks::newComm( bool createRecords )
{
communications.push_back( new TCommInfo() );
currentComm = communications.size() - 1;
if ( !createRecords )
{
for ( UINT8 i = 0; i < commTypeSize; i++ )
commRecords[ i ] = NULL;
}
else
{
for ( UINT8 i = 0; i < commTypeSize; i++ )
{
newRecord();
commRecords[i] = ¤tBlock[currentRecord];
setType( commTypes[i] );
setCommIndex( currentComm );
}
}
}
void BPlusTreeBlocks::setSenderThread( TThreadOrder whichThread )
{
communications[currentComm]->senderThread = whichThread;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->thread = whichThread;
commRecords[physicalSend]->thread = whichThread;
commRecords[remoteLogicalReceive]->thread = whichThread;
commRecords[remotePhysicalReceive]->thread = whichThread;
}
}
void BPlusTreeBlocks::setSenderThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
TThreadOrder globalThread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
communications[currentComm]->senderThread = globalThread;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->thread = globalThread;
commRecords[physicalSend]->thread = globalThread;
commRecords[remoteLogicalReceive]->thread = globalThread;
commRecords[remotePhysicalReceive]->thread = globalThread;
}
}
void BPlusTreeBlocks::setSenderCPU( TCPUOrder whichCPU )
{
communications[currentComm]->senderCPU = whichCPU;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->CPU = whichCPU;
commRecords[physicalSend]->CPU = whichCPU;
commRecords[remoteLogicalReceive]->CPU = whichCPU;
commRecords[remotePhysicalReceive]->CPU = whichCPU;
}
}
void BPlusTreeBlocks::setReceiverThread( TThreadOrder whichThread )
{
communications[currentComm]->receiverThread = whichThread;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->thread = whichThread;
commRecords[physicalReceive]->thread = whichThread;
commRecords[remoteLogicalSend]->thread = whichThread;
commRecords[remotePhysicalSend]->thread = whichThread;
}
}
void BPlusTreeBlocks::setReceiverThread( TApplOrder whichAppl,
TTaskOrder whichTask,
TThreadOrder whichThread )
{
TThreadOrder globalThread = traceModel.getGlobalThread( whichAppl,
whichTask,
whichThread );
communications[currentComm]->receiverThread = globalThread;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->thread = globalThread;
commRecords[physicalReceive]->thread = globalThread;
commRecords[remoteLogicalSend]->thread = globalThread;
commRecords[remotePhysicalSend]->thread = globalThread;
}
}
void BPlusTreeBlocks::setReceiverCPU( TCPUOrder whichCPU )
{
communications[currentComm]->receiverCPU = whichCPU;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->CPU = whichCPU;
commRecords[physicalReceive]->CPU = whichCPU;
commRecords[remoteLogicalSend]->CPU = whichCPU;
commRecords[remotePhysicalSend]->CPU = whichCPU;
}
}
void BPlusTreeBlocks::setCommTag( TCommTag whichTag )
{
communications[currentComm]->tag = whichTag;
}
void BPlusTreeBlocks::setCommSize( TCommSize whichSize )
{
communications[currentComm]->size = whichSize;
}
void BPlusTreeBlocks::setLogicalSend( TRecordTime whichTime )
{
communications[currentComm]->logicalSendTime = whichTime;
if ( commRecords[logicalSend] != NULL )
{
commRecords[logicalSend]->time = whichTime;
commRecords[remoteLogicalSend]->time = whichTime;
}
}
void BPlusTreeBlocks::setLogicalReceive( TRecordTime whichTime )
{
communications[currentComm]->logicalReceiveTime = whichTime;
if ( commRecords[logicalReceive] != NULL )
{
commRecords[logicalReceive]->time = whichTime;
commRecords[remoteLogicalReceive]->time = whichTime;
}
}
void BPlusTreeBlocks::setPhysicalSend( TRecordTime whichTime )
{
communications[currentComm]->physicalSendTime = whichTime;
if ( commRecords[physicalSend] != NULL )
{
commRecords[physicalSend]->time = whichTime;
commRecords[remotePhysicalSend]->time = whichTime;
}
}
void BPlusTreeBlocks::setPhysicalReceive( TRecordTime whichTime )
{
communications[currentComm]->physicalReceiveTime = whichTime;
if ( commRecords[physicalReceive] != NULL )
{
commRecords[physicalReceive]->time = whichTime;
commRecords[remotePhysicalReceive]->time = whichTime;
}
}
TThreadOrder BPlusTreeBlocks::getSenderThread( TCommID whichComm ) const
{
return communications[whichComm]->senderThread;
}
TCPUOrder BPlusTreeBlocks::getSenderCPU( TCommID whichComm ) const
{
return communications[whichComm]->senderCPU;
}
TThreadOrder BPlusTreeBlocks::getReceiverThread( TCommID whichComm ) const
{
return communications[whichComm]->receiverThread;
}
TCPUOrder BPlusTreeBlocks::getReceiverCPU( TCommID whichComm ) const
{
return communications[whichComm]->receiverCPU;
}
TCommTag BPlusTreeBlocks::getCommTag( TCommID whichComm ) const
{
return communications[whichComm]->tag;
}
TCommSize BPlusTreeBlocks::getCommSize( TCommID whichComm ) const
{
return communications[whichComm]->size;
}
TRecordTime BPlusTreeBlocks::getLogicalSend( TCommID whichComm ) const
{
return communications[whichComm]->logicalSendTime;
}
TRecordTime BPlusTreeBlocks::getLogicalReceive( TCommID whichComm ) const
{
return communications[whichComm]->logicalReceiveTime;
}
TRecordTime BPlusTreeBlocks::getPhysicalSend( TCommID whichComm ) const
{
return communications[whichComm]->physicalSendTime;
}
TRecordTime BPlusTreeBlocks::getPhysicalReceive( TCommID whichComm ) const
{
return communications[whichComm]->physicalReceiveTime;
}
TRecordTime BPlusTreeBlocks::getLastRecordTime() const
{
return currentBlock[currentRecord].time;
}
<|endoftext|>
|
<commit_before>//userliteral header
//Copyright (c) 2014 mmYYmmdd
#if !defined MMYYMMDD_USER_LITERAL_INCLUDED
#define MMYYMMDD_USER_LITERAL_INCLUDED
#include <ratio>
// create std::integral_constant and std::ratio from user defined literal
// ユーザー定義リテラルから std::integral_constant と std::ratio を出力する
namespace mymd {
namespace detail_user_literal {
constexpr std::size_t buncho(char x)
{ return ('0' <= x && x <= '9')? x-'0': ('a' <= x && x <='f' )? x-'a'+10: ('A' <= x && x <='F' )? x-'A'+10: 0; }
template <std::size_t, std::size_t, std::size_t, char...> struct digit;
template <std::size_t L, std::size_t N, std::size_t D, char first, char... tail>
struct digit<L, N, D, first, tail...> {
static constexpr std::size_t num = digit<L, L * N + buncho(first), 10 * D, tail...>::num;
static constexpr std::size_t den = digit<L, L * N + buncho(first), 10 * D, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D, char... tail>
struct digit<L, N, D, 'x', tail...> {
static constexpr std::size_t num = digit<16, 0, D, tail...>::num;
static constexpr std::size_t den = digit<16, 0, D, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D, char... tail>
struct digit<L, N, D, 'X', tail...> {
static constexpr std::size_t num = digit<16, 0, D, tail...>::num;
static constexpr std::size_t den = digit<16, 0, D, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D, char... tail>
struct digit<L, N, D, 'b', tail...> {
static constexpr std::size_t num = digit<2, 0, D, tail...>::num;
static constexpr std::size_t den = digit<2, 0, D, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D, char... tail>
struct digit<L, N, D, 'B', tail...> {
static constexpr std::size_t num = digit<2, 0, D, tail...>::num;
static constexpr std::size_t den = digit<2, 0, D, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D, char... tail>
struct digit<L, N, D, '.', tail...> {
static constexpr std::size_t num = digit<L, N, 1, tail...>::num;
static constexpr std::size_t den = digit<L, N, 1, tail...>::den;
};
template <std::size_t L, std::size_t N, std::size_t D>
struct digit<L, N, D> {
constexpr static std::size_t num = N;
constexpr static std::size_t den = D;
};
template <char first, char... tail>
constexpr int num() { return digit<first=='0'? 8: 10, 0, 0, first, tail...>::num; }
template <char first, char... tail>
constexpr int den()
{
return digit<first=='0'? 8: 10, 0, 0, first, tail...>::den == 0? 1: digit<first=='0'? 8: 10, 0, 0, first, tail...>::den;
}
} //namespace detail_user_literal
namespace ul {
template <char... Char>
constexpr auto operator "" _ic()
->std::integral_constant<int, detail_user_literal::num<Char...>() / detail_user_literal::den<Char...>()>
{
return std::integral_constant<int, detail_user_literal::num<Char...>() / detail_user_literal::den<Char...>()>{};
}
template <char... Char>
constexpr auto operator "" _rc()
->std::ratio<detail_user_literal::num<Char...>(), detail_user_literal::den<Char...>()>
{
return std::ratio<detail_user_literal::num<Char...>(), detail_user_literal::den<Char...>()>{};
}
} // namespace ul
} // namespace mymd
#endif
<commit_msg>Delete userliteral.hpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "util.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
networkID = CBaseChainParams::MAIN;
nRPCPort = 9527;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseMainParams
{
public:
CBaseTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
nRPCPort = 19527;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
CBaseRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
/*
* Unit test
*/
class CBaseUnitTestParams : public CBaseMainParams
{
public:
CBaseUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strDataDir = "unittest";
}
};
static CBaseUnitTestParams unitTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
void SelectBaseParams(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = ®TestParams;
break;
case CBaseChainParams::UNITTEST:
pCurrentBaseParams = &unitTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
return CBaseChainParams::MAX_NETWORK_TYPES;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool SelectBaseParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectBaseParams(network);
return true;
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
<commit_msg>Delete chainparamsbase.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "tinyformat.h"
#include "util.h"
#include <assert.h>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::UNL = "nol";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::TESTNET4 = "test4";
const std::string CBaseChainParams::REGTEST = "regtest";
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams() { nRPCPort = 8332; }
};
static CBaseMainParams mainParams;
/**
* Unl network
*/
class CBaseUnlParams : public CBaseChainParams
{
public:
CBaseUnlParams()
{
nRPCPort = 9332;
strDataDir = "nol";
}
};
static CBaseUnlParams unlParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
nRPCPort = 18332;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
class CBaseTestNet4Params : public CBaseChainParams
{
public:
CBaseTestNet4Params()
{
nRPCPort = 28333;
strDataDir = "testnet4";
}
};
static CBaseTestNet4Params testNet4Params;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
nRPCPort = 18332;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
static CBaseChainParams *pCurrentBaseParams = 0;
const CBaseChainParams &BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
CBaseChainParams &BaseParams(const std::string &chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::UNL)
return unlParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::TESTNET4)
return testNet4Params;
else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string &chain) { pCurrentBaseParams = &BaseParams(chain); }
std::string ChainNameFromCommandLine()
{
uint64_t num_selected = 0;
bool fRegTest = GetBoolArg("-regtest", false);
num_selected += fRegTest;
bool fTestNet = GetBoolArg("-testnet", false);
num_selected += fTestNet;
bool fTestNet4 = GetBoolArg("-testnet4", false);
num_selected += fTestNet4;
bool fUnl = GetBoolArg("-chain_nol", false);
num_selected += fUnl;
if (num_selected > 1)
throw std::runtime_error("Invalid combination of -regtest, -testnet, and -testnet4.");
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
if (fTestNet4)
return CBaseChainParams::TESTNET4;
if (fUnl)
return CBaseChainParams::UNL;
return CBaseChainParams::MAIN;
}
bool AreBaseParamsConfigured() { return pCurrentBaseParams != nullptr; }
<commit_msg>Fix testnet4 RPC port<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "tinyformat.h"
#include "util.h"
#include <assert.h>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::UNL = "nol";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::TESTNET4 = "test4";
const std::string CBaseChainParams::REGTEST = "regtest";
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams() { nRPCPort = 8332; }
};
static CBaseMainParams mainParams;
/**
* Unl network
*/
class CBaseUnlParams : public CBaseChainParams
{
public:
CBaseUnlParams()
{
nRPCPort = 9332;
strDataDir = "nol";
}
};
static CBaseUnlParams unlParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
nRPCPort = 18332;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/**
* Testnet (v4)
*/
class CBaseTestNet4Params : public CBaseChainParams
{
public:
CBaseTestNet4Params()
{
nRPCPort = 28332;
strDataDir = "testnet4";
}
};
static CBaseTestNet4Params testNet4Params;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
nRPCPort = 18332;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
static CBaseChainParams *pCurrentBaseParams = 0;
const CBaseChainParams &BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
CBaseChainParams &BaseParams(const std::string &chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::UNL)
return unlParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::TESTNET4)
return testNet4Params;
else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string &chain) { pCurrentBaseParams = &BaseParams(chain); }
std::string ChainNameFromCommandLine()
{
uint64_t num_selected = 0;
bool fRegTest = GetBoolArg("-regtest", false);
num_selected += fRegTest;
bool fTestNet = GetBoolArg("-testnet", false);
num_selected += fTestNet;
bool fTestNet4 = GetBoolArg("-testnet4", false);
num_selected += fTestNet4;
bool fUnl = GetBoolArg("-chain_nol", false);
num_selected += fUnl;
if (num_selected > 1)
throw std::runtime_error("Invalid combination of -regtest, -testnet, and -testnet4.");
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
if (fTestNet4)
return CBaseChainParams::TESTNET4;
if (fUnl)
return CBaseChainParams::UNL;
return CBaseChainParams::MAIN;
}
bool AreBaseParamsConfigured() { return pCurrentBaseParams != nullptr; }
<|endoftext|>
|
<commit_before>#include "xchainer/cuda/cuda_backend.h"
#include <cuda_runtime.h>
#include <gtest/gtest.h>
#include "xchainer/context.h"
#include "xchainer/cuda/cuda_runtime.h"
#include "xchainer/device.h"
namespace xchainer {
namespace cuda {
namespace {
TEST(CudaBackendTest, GetDeviceCount) {
Context ctx;
int count = 0;
CheckError(cudaGetDeviceCount(&count));
EXPECT_EQ(count, CudaBackend(ctx).GetDeviceCount());
}
TEST(CudaBackendTest, GetDevice) {
Context ctx;
CudaBackend backend{ctx};
{
Device& device = backend.GetDevice(0);
EXPECT_EQ(&backend, &device.backend());
EXPECT_EQ(0, device.index());
}
{
Device& device3 = backend.GetDevice(3);
Device& device2 = backend.GetDevice(2);
EXPECT_EQ(&backend, &device3.backend());
EXPECT_EQ(3, device3.index());
EXPECT_EQ(&backend, &device2.backend());
EXPECT_EQ(2, device2.index());
}
{
EXPECT_THROW(backend.GetDevice(-1), std::out_of_range);
EXPECT_THROW(backend.GetDevice(backend.GetDeviceCount() + 1), std::out_of_range);
}
}
TEST(CudaBackendTest, GetName) {
Context ctx;
EXPECT_EQ("cuda", CudaBackend(ctx).GetName());
}
TEST(CudaBackendTest, SupportsTransfer) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(0);
Device& device1 = backend.GetDevice(1);
EXPECT_TRUE(backend.SupportsTransfer(device0, device0));
EXPECT_TRUE(backend.SupportsTransfer(device0, device1));
}
// Data transfer test
class CudaBackendTransferTest : public ::testing::TestWithParam<::testing::tuple<int, int>> {};
TEST_P(CudaBackendTransferTest, TransferTo) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(::testing::get<0>(GetParam()));
Device& device1 = backend.GetDevice(::testing::get<1>(GetParam()));
size_t bytesize = 5;
auto data = device1.Allocate(bytesize);
// Transfer
// TODO(niboshi): Offset is fixed to 0
std::tuple<std::shared_ptr<void>, size_t> tuple = device0.TransferDataTo(device1, data, 0, bytesize);
EXPECT_EQ(0, std::memcmp(data.get(), std::get<0>(tuple).get(), bytesize));
// TODO(niboshi): Test offset
cudaPointerAttributes attr = {};
CheckError(cudaPointerGetAttributes(&attr, std::get<0>(tuple).get()));
EXPECT_TRUE(attr.isManaged);
EXPECT_EQ(device1.index(), attr.device);
}
TEST_P(CudaBackendTransferTest, TransferFrom) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(::testing::get<0>(GetParam()));
Device& device1 = backend.GetDevice(::testing::get<1>(GetParam()));
size_t bytesize = 5;
auto data = device1.Allocate(bytesize);
// Transfer
// TODO(niboshi): Offset is fixed to 0
std::tuple<std::shared_ptr<void>, size_t> tuple = device1.TransferDataFrom(device0, data, 0, bytesize);
EXPECT_EQ(0, std::memcmp(data.get(), std::get<0>(tuple).get(), bytesize));
// TODO(niboshi): Test offset
cudaPointerAttributes attr = {};
CheckError(cudaPointerGetAttributes(&attr, std::get<0>(tuple).get()));
EXPECT_TRUE(attr.isManaged);
EXPECT_EQ(device1.index(), attr.device);
}
INSTANTIATE_TEST_CASE_P(Device, CudaBackendTransferTest,
::testing::Values(std::make_tuple(0, 0), // transfer between same devices
std::make_tuple(0, 1) // transfer between dfferent CUDA devices
));
} // namespace
} // namespace cuda
} // namespace xchainer
<commit_msg>clang-format<commit_after>#include "xchainer/cuda/cuda_backend.h"
#include <cuda_runtime.h>
#include <gtest/gtest.h>
#include "xchainer/context.h"
#include "xchainer/cuda/cuda_runtime.h"
#include "xchainer/device.h"
namespace xchainer {
namespace cuda {
namespace {
TEST(CudaBackendTest, GetDeviceCount) {
Context ctx;
int count = 0;
CheckError(cudaGetDeviceCount(&count));
EXPECT_EQ(count, CudaBackend(ctx).GetDeviceCount());
}
TEST(CudaBackendTest, GetDevice) {
Context ctx;
CudaBackend backend{ctx};
{
Device& device = backend.GetDevice(0);
EXPECT_EQ(&backend, &device.backend());
EXPECT_EQ(0, device.index());
}
{
Device& device3 = backend.GetDevice(3);
Device& device2 = backend.GetDevice(2);
EXPECT_EQ(&backend, &device3.backend());
EXPECT_EQ(3, device3.index());
EXPECT_EQ(&backend, &device2.backend());
EXPECT_EQ(2, device2.index());
}
{
EXPECT_THROW(backend.GetDevice(-1), std::out_of_range);
EXPECT_THROW(backend.GetDevice(backend.GetDeviceCount() + 1), std::out_of_range);
}
}
TEST(CudaBackendTest, GetName) {
Context ctx;
EXPECT_EQ("cuda", CudaBackend(ctx).GetName());
}
TEST(CudaBackendTest, SupportsTransfer) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(0);
Device& device1 = backend.GetDevice(1);
EXPECT_TRUE(backend.SupportsTransfer(device0, device0));
EXPECT_TRUE(backend.SupportsTransfer(device0, device1));
}
// Data transfer test
class CudaBackendTransferTest : public ::testing::TestWithParam<::testing::tuple<int, int>> {};
TEST_P(CudaBackendTransferTest, TransferTo) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(::testing::get<0>(GetParam()));
Device& device1 = backend.GetDevice(::testing::get<1>(GetParam()));
size_t bytesize = 5;
auto data = device1.Allocate(bytesize);
// Transfer
// TODO(niboshi): Offset is fixed to 0
std::tuple<std::shared_ptr<void>, size_t> tuple = device0.TransferDataTo(device1, data, 0, bytesize);
EXPECT_EQ(0, std::memcmp(data.get(), std::get<0>(tuple).get(), bytesize));
// TODO(niboshi): Test offset
cudaPointerAttributes attr = {};
CheckError(cudaPointerGetAttributes(&attr, std::get<0>(tuple).get()));
EXPECT_TRUE(attr.isManaged);
EXPECT_EQ(device1.index(), attr.device);
}
TEST_P(CudaBackendTransferTest, TransferFrom) {
Context ctx;
CudaBackend backend{ctx};
Device& device0 = backend.GetDevice(::testing::get<0>(GetParam()));
Device& device1 = backend.GetDevice(::testing::get<1>(GetParam()));
size_t bytesize = 5;
auto data = device1.Allocate(bytesize);
// Transfer
// TODO(niboshi): Offset is fixed to 0
std::tuple<std::shared_ptr<void>, size_t> tuple = device1.TransferDataFrom(device0, data, 0, bytesize);
EXPECT_EQ(0, std::memcmp(data.get(), std::get<0>(tuple).get(), bytesize));
// TODO(niboshi): Test offset
cudaPointerAttributes attr = {};
CheckError(cudaPointerGetAttributes(&attr, std::get<0>(tuple).get()));
EXPECT_TRUE(attr.isManaged);
EXPECT_EQ(device1.index(), attr.device);
}
INSTANTIATE_TEST_CASE_P(Device, CudaBackendTransferTest, ::testing::Values(std::make_tuple(0, 0), // transfer between same devices
std::make_tuple(0, 1) // transfer between dfferent CUDA devices
));
} // namespace
} // namespace cuda
} // namespace xchainer
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xformsapi.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:58:07 $
*
* 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
*
************************************************************************/
#include "xformsapi.hxx"
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/xforms/XFormsSupplier.hpp>
#include <com/sun/star/xforms/XDataTypeRepository.hpp>
#include <com/sun/star/xforms/XModel.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/xsd/DataTypeClass.hpp>
#include <unotools/processfactory.hxx>
#include <tools/debug.hxx>
#include <xmltoken.hxx>
#include <nmspmap.hxx>
#include <xmlnmspe.hxx>
#include <xmltkmap.hxx>
using rtl::OUString;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::UNO_QUERY_THROW;
using com::sun::star::beans::XPropertySet;
using com::sun::star::container::XNameAccess;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::xforms::XFormsSupplier;
using com::sun::star::xforms::XDataTypeRepository;
using com::sun::star::container::XNameContainer;
using utl::getProcessServiceFactory;
using com::sun::star::uno::makeAny;
using com::sun::star::uno::Any;
using com::sun::star::uno::Exception;
using namespace com::sun::star;
using namespace xmloff::token;
Reference<XPropertySet> lcl_createPropertySet( const OUString& rServiceName )
{
Reference<XMultiServiceFactory> xFactory = getProcessServiceFactory();
DBG_ASSERT( xFactory.is(), "can't get service factory" );
Reference<XPropertySet> xModel( xFactory->createInstance( rServiceName ),
UNO_QUERY_THROW );
DBG_ASSERT( xModel.is(), "can't create model" );
return xModel;
}
Reference<XPropertySet> lcl_createXFormsModel()
{
return lcl_createPropertySet( OUSTRING( "com.sun.star.xforms.Model" ) );
}
Reference<XPropertySet> lcl_createXFormsBinding()
{
return lcl_createPropertySet( OUSTRING( "com.sun.star.xforms.Binding" ) );
}
void lcl_addXFormsModel(
const Reference<frame::XModel>& xDocument,
const Reference<XPropertySet>& xModel )
{
bool bSuccess = false;
try
{
Reference<XFormsSupplier> xSupplier( xDocument, UNO_QUERY );
if( xSupplier.is() )
{
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
OUString sName;
xModel->getPropertyValue( OUSTRING("ID")) >>= sName;
xForms->insertByName( sName, makeAny( xModel ) );
bSuccess = true;
}
}
}
catch( const Exception& )
{
; // no success!
}
// TODO: implement proper error handling
DBG_ASSERT( bSuccess, "can't import model" );
}
Reference<XPropertySet> lcl_findXFormsBindingOrSubmission(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID,
bool bBinding )
{
// find binding by iterating over all models, and look for the
// given binding ID
Reference<XPropertySet> xRet;
try
{
// get supplier
Reference<XFormsSupplier> xSupplier( xDocument, UNO_QUERY );
if( xSupplier.is() )
{
// get XForms models
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
// iterate over all models
Sequence<OUString> aNames = xForms->getElementNames();
const OUString* pNames = aNames.getConstArray();
sal_Int32 nNames = aNames.getLength();
for( sal_Int32 n = 0; (n < nNames) && !xRet.is(); n++ )
{
Reference<xforms::XModel> xModel(
xForms->getByName( pNames[n] ), UNO_QUERY );
if( xModel.is() )
{
// ask model for bindings
Reference<XNameAccess> xBindings(
bBinding
? xModel->getBindings()
: xModel->getSubmissions(),
UNO_QUERY_THROW );
// finally, ask binding for name
if( xBindings->hasByName( rBindingID ) )
xRet.set( xBindings->getByName( rBindingID ),
UNO_QUERY );
}
}
}
}
}
catch( const Exception& )
{
; // no success!
}
if( ! xRet.is() )
; // TODO: rImport.SetError(...);
return xRet;
}
Reference<XPropertySet> lcl_findXFormsBinding(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID )
{
return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, true );
}
Reference<XPropertySet> lcl_findXFormsSubmission(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID )
{
return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, false );
}
void lcl_setValue( Reference<XPropertySet>& xPropertySet,
const OUString& rName,
const Any rAny )
{
xPropertySet->setPropertyValue( rName, rAny );
}
Reference<XPropertySet> lcl_getXFormsModel( const Reference<frame::XModel>& xDoc )
{
Reference<XPropertySet> xRet;
try
{
Reference<XFormsSupplier> xSupplier( xDoc, UNO_QUERY );
if( xSupplier.is() )
{
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
Sequence<OUString> aNames = xForms->getElementNames();
if( aNames.getLength() > 0 )
xRet.set( xForms->getByName( aNames[0] ), UNO_QUERY );
}
}
}
catch( const Exception& )
{
; // no success!
}
return xRet;
}
#define TOKEN_MAP_ENTRY(NAMESPACE,TOKEN) { XML_NAMESPACE_##NAMESPACE, xmloff::token::XML_##TOKEN, xmloff::token::XML_##TOKEN }
static SvXMLTokenMapEntry aTypes[] =
{
TOKEN_MAP_ENTRY( XSD, STRING ),
TOKEN_MAP_ENTRY( XSD, DECIMAL ),
TOKEN_MAP_ENTRY( XSD, DOUBLE ),
TOKEN_MAP_ENTRY( XSD, FLOAT ),
TOKEN_MAP_ENTRY( XSD, BOOLEAN ),
TOKEN_MAP_ENTRY( XSD, ANYURI ),
TOKEN_MAP_ENTRY( XSD, DATETIME_XSD ),
TOKEN_MAP_ENTRY( XSD, DATE ),
TOKEN_MAP_ENTRY( XSD, TIME ),
TOKEN_MAP_ENTRY( XSD, YEAR ),
TOKEN_MAP_ENTRY( XSD, MONTH ),
TOKEN_MAP_ENTRY( XSD, DAY ),
XML_TOKEN_MAP_END
};
sal_uInt16 lcl_getTypeClass(
const Reference<XDataTypeRepository>&
#ifdef DBG_UTIL
xRepository
#endif
,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
// translate name into token for local name
OUString sLocalName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);
SvXMLTokenMap aMap( aTypes );
sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );
sal_uInt16 nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;
if( mnToken != XML_TOK_UNKNOWN )
{
// we found an XSD name: then get the proper API name for it
DBG_ASSERT( xRepository.is(), "can't find type without repository");
switch( mnToken )
{
case XML_STRING:
nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;
break;
case XML_ANYURI:
nTypeClass = com::sun::star::xsd::DataTypeClass::anyURI;
break;
case XML_DECIMAL:
nTypeClass = com::sun::star::xsd::DataTypeClass::DECIMAL;
break;
case XML_DOUBLE:
nTypeClass = com::sun::star::xsd::DataTypeClass::DOUBLE;
break;
case XML_FLOAT:
nTypeClass = com::sun::star::xsd::DataTypeClass::FLOAT;
break;
case XML_BOOLEAN:
nTypeClass = com::sun::star::xsd::DataTypeClass::BOOLEAN;
break;
case XML_DATETIME_XSD:
nTypeClass = com::sun::star::xsd::DataTypeClass::DATETIME;
break;
case XML_DATE:
nTypeClass = com::sun::star::xsd::DataTypeClass::DATE;
break;
case XML_TIME:
nTypeClass = com::sun::star::xsd::DataTypeClass::TIME;
break;
case XML_YEAR:
nTypeClass = com::sun::star::xsd::DataTypeClass::gYear;
break;
case XML_DAY:
nTypeClass = com::sun::star::xsd::DataTypeClass::gDay;
break;
case XML_MONTH:
nTypeClass = com::sun::star::xsd::DataTypeClass::gMonth;
break;
/* data types not yet supported:
nTypeClass = com::sun::star::xsd::DataTypeClass::DURATION;
nTypeClass = com::sun::star::xsd::DataTypeClass::gYearMonth;
nTypeClass = com::sun::star::xsd::DataTypeClass::gMonthDay;
nTypeClass = com::sun::star::xsd::DataTypeClass::hexBinary;
nTypeClass = com::sun::star::xsd::DataTypeClass::base64Binary;
nTypeClass = com::sun::star::xsd::DataTypeClass::QName;
nTypeClass = com::sun::star::xsd::DataTypeClass::NOTATION;
*/
}
}
return nTypeClass;
}
rtl::OUString lcl_getTypeName(
const Reference<XDataTypeRepository>& xRepository,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
OUString sLocalName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);
SvXMLTokenMap aMap( aTypes );
sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );
return ( mnToken == XML_TOK_UNKNOWN )
? rXMLName
: lcl_getBasicTypeName( xRepository, rNamespaceMap, rXMLName );
}
rtl::OUString lcl_getBasicTypeName(
const Reference<XDataTypeRepository>& xRepository,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
OUString sTypeName = rXMLName;
try
{
sTypeName =
xRepository->getBasicDataType(
lcl_getTypeClass( xRepository, rNamespaceMap, rXMLName ) )
->getName();
}
catch( const Exception& )
{
DBG_ERROR( "exception during type creation" );
}
return sTypeName;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.34); FILE MERGED 2006/09/01 18:00:22 kaib 1.5.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xformsapi.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:31:54 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "xformsapi.hxx"
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/xforms/XFormsSupplier.hpp>
#include <com/sun/star/xforms/XDataTypeRepository.hpp>
#include <com/sun/star/xforms/XModel.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/xsd/DataTypeClass.hpp>
#include <unotools/processfactory.hxx>
#include <tools/debug.hxx>
#include <xmltoken.hxx>
#include <nmspmap.hxx>
#include <xmlnmspe.hxx>
#include <xmltkmap.hxx>
using rtl::OUString;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::UNO_QUERY_THROW;
using com::sun::star::beans::XPropertySet;
using com::sun::star::container::XNameAccess;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::xforms::XFormsSupplier;
using com::sun::star::xforms::XDataTypeRepository;
using com::sun::star::container::XNameContainer;
using utl::getProcessServiceFactory;
using com::sun::star::uno::makeAny;
using com::sun::star::uno::Any;
using com::sun::star::uno::Exception;
using namespace com::sun::star;
using namespace xmloff::token;
Reference<XPropertySet> lcl_createPropertySet( const OUString& rServiceName )
{
Reference<XMultiServiceFactory> xFactory = getProcessServiceFactory();
DBG_ASSERT( xFactory.is(), "can't get service factory" );
Reference<XPropertySet> xModel( xFactory->createInstance( rServiceName ),
UNO_QUERY_THROW );
DBG_ASSERT( xModel.is(), "can't create model" );
return xModel;
}
Reference<XPropertySet> lcl_createXFormsModel()
{
return lcl_createPropertySet( OUSTRING( "com.sun.star.xforms.Model" ) );
}
Reference<XPropertySet> lcl_createXFormsBinding()
{
return lcl_createPropertySet( OUSTRING( "com.sun.star.xforms.Binding" ) );
}
void lcl_addXFormsModel(
const Reference<frame::XModel>& xDocument,
const Reference<XPropertySet>& xModel )
{
bool bSuccess = false;
try
{
Reference<XFormsSupplier> xSupplier( xDocument, UNO_QUERY );
if( xSupplier.is() )
{
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
OUString sName;
xModel->getPropertyValue( OUSTRING("ID")) >>= sName;
xForms->insertByName( sName, makeAny( xModel ) );
bSuccess = true;
}
}
}
catch( const Exception& )
{
; // no success!
}
// TODO: implement proper error handling
DBG_ASSERT( bSuccess, "can't import model" );
}
Reference<XPropertySet> lcl_findXFormsBindingOrSubmission(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID,
bool bBinding )
{
// find binding by iterating over all models, and look for the
// given binding ID
Reference<XPropertySet> xRet;
try
{
// get supplier
Reference<XFormsSupplier> xSupplier( xDocument, UNO_QUERY );
if( xSupplier.is() )
{
// get XForms models
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
// iterate over all models
Sequence<OUString> aNames = xForms->getElementNames();
const OUString* pNames = aNames.getConstArray();
sal_Int32 nNames = aNames.getLength();
for( sal_Int32 n = 0; (n < nNames) && !xRet.is(); n++ )
{
Reference<xforms::XModel> xModel(
xForms->getByName( pNames[n] ), UNO_QUERY );
if( xModel.is() )
{
// ask model for bindings
Reference<XNameAccess> xBindings(
bBinding
? xModel->getBindings()
: xModel->getSubmissions(),
UNO_QUERY_THROW );
// finally, ask binding for name
if( xBindings->hasByName( rBindingID ) )
xRet.set( xBindings->getByName( rBindingID ),
UNO_QUERY );
}
}
}
}
}
catch( const Exception& )
{
; // no success!
}
if( ! xRet.is() )
; // TODO: rImport.SetError(...);
return xRet;
}
Reference<XPropertySet> lcl_findXFormsBinding(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID )
{
return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, true );
}
Reference<XPropertySet> lcl_findXFormsSubmission(
Reference<frame::XModel>& xDocument,
const rtl::OUString& rBindingID )
{
return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, false );
}
void lcl_setValue( Reference<XPropertySet>& xPropertySet,
const OUString& rName,
const Any rAny )
{
xPropertySet->setPropertyValue( rName, rAny );
}
Reference<XPropertySet> lcl_getXFormsModel( const Reference<frame::XModel>& xDoc )
{
Reference<XPropertySet> xRet;
try
{
Reference<XFormsSupplier> xSupplier( xDoc, UNO_QUERY );
if( xSupplier.is() )
{
Reference<XNameContainer> xForms = xSupplier->getXForms();
if( xForms.is() )
{
Sequence<OUString> aNames = xForms->getElementNames();
if( aNames.getLength() > 0 )
xRet.set( xForms->getByName( aNames[0] ), UNO_QUERY );
}
}
}
catch( const Exception& )
{
; // no success!
}
return xRet;
}
#define TOKEN_MAP_ENTRY(NAMESPACE,TOKEN) { XML_NAMESPACE_##NAMESPACE, xmloff::token::XML_##TOKEN, xmloff::token::XML_##TOKEN }
static SvXMLTokenMapEntry aTypes[] =
{
TOKEN_MAP_ENTRY( XSD, STRING ),
TOKEN_MAP_ENTRY( XSD, DECIMAL ),
TOKEN_MAP_ENTRY( XSD, DOUBLE ),
TOKEN_MAP_ENTRY( XSD, FLOAT ),
TOKEN_MAP_ENTRY( XSD, BOOLEAN ),
TOKEN_MAP_ENTRY( XSD, ANYURI ),
TOKEN_MAP_ENTRY( XSD, DATETIME_XSD ),
TOKEN_MAP_ENTRY( XSD, DATE ),
TOKEN_MAP_ENTRY( XSD, TIME ),
TOKEN_MAP_ENTRY( XSD, YEAR ),
TOKEN_MAP_ENTRY( XSD, MONTH ),
TOKEN_MAP_ENTRY( XSD, DAY ),
XML_TOKEN_MAP_END
};
sal_uInt16 lcl_getTypeClass(
const Reference<XDataTypeRepository>&
#ifdef DBG_UTIL
xRepository
#endif
,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
// translate name into token for local name
OUString sLocalName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);
SvXMLTokenMap aMap( aTypes );
sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );
sal_uInt16 nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;
if( mnToken != XML_TOK_UNKNOWN )
{
// we found an XSD name: then get the proper API name for it
DBG_ASSERT( xRepository.is(), "can't find type without repository");
switch( mnToken )
{
case XML_STRING:
nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;
break;
case XML_ANYURI:
nTypeClass = com::sun::star::xsd::DataTypeClass::anyURI;
break;
case XML_DECIMAL:
nTypeClass = com::sun::star::xsd::DataTypeClass::DECIMAL;
break;
case XML_DOUBLE:
nTypeClass = com::sun::star::xsd::DataTypeClass::DOUBLE;
break;
case XML_FLOAT:
nTypeClass = com::sun::star::xsd::DataTypeClass::FLOAT;
break;
case XML_BOOLEAN:
nTypeClass = com::sun::star::xsd::DataTypeClass::BOOLEAN;
break;
case XML_DATETIME_XSD:
nTypeClass = com::sun::star::xsd::DataTypeClass::DATETIME;
break;
case XML_DATE:
nTypeClass = com::sun::star::xsd::DataTypeClass::DATE;
break;
case XML_TIME:
nTypeClass = com::sun::star::xsd::DataTypeClass::TIME;
break;
case XML_YEAR:
nTypeClass = com::sun::star::xsd::DataTypeClass::gYear;
break;
case XML_DAY:
nTypeClass = com::sun::star::xsd::DataTypeClass::gDay;
break;
case XML_MONTH:
nTypeClass = com::sun::star::xsd::DataTypeClass::gMonth;
break;
/* data types not yet supported:
nTypeClass = com::sun::star::xsd::DataTypeClass::DURATION;
nTypeClass = com::sun::star::xsd::DataTypeClass::gYearMonth;
nTypeClass = com::sun::star::xsd::DataTypeClass::gMonthDay;
nTypeClass = com::sun::star::xsd::DataTypeClass::hexBinary;
nTypeClass = com::sun::star::xsd::DataTypeClass::base64Binary;
nTypeClass = com::sun::star::xsd::DataTypeClass::QName;
nTypeClass = com::sun::star::xsd::DataTypeClass::NOTATION;
*/
}
}
return nTypeClass;
}
rtl::OUString lcl_getTypeName(
const Reference<XDataTypeRepository>& xRepository,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
OUString sLocalName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);
SvXMLTokenMap aMap( aTypes );
sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );
return ( mnToken == XML_TOK_UNKNOWN )
? rXMLName
: lcl_getBasicTypeName( xRepository, rNamespaceMap, rXMLName );
}
rtl::OUString lcl_getBasicTypeName(
const Reference<XDataTypeRepository>& xRepository,
const SvXMLNamespaceMap& rNamespaceMap,
const OUString& rXMLName )
{
OUString sTypeName = rXMLName;
try
{
sTypeName =
xRepository->getBasicDataType(
lcl_getTypeClass( xRepository, rNamespaceMap, rXMLName ) )
->getName();
}
catch( const Exception& )
{
DBG_ERROR( "exception during type creation" );
}
return sTypeName;
}
<|endoftext|>
|
<commit_before>#include "BoundingBox.hpp"
#include "MotionPlanner.hpp"
#include <limits> // for numeric_limits
#include "boost/polygon/voronoi.hpp"
using boost::polygon::voronoi_builder;
using boost::polygon::voronoi_diagram;
namespace Slic3r {
MotionPlanner::MotionPlanner(const ExPolygons &islands)
: islands(islands), initialized(false)
{}
MotionPlanner::~MotionPlanner()
{
for (std::vector<MotionPlannerGraph*>::iterator graph = this->graphs.begin(); graph != this->graphs.end(); ++graph)
delete *graph;
}
size_t
MotionPlanner::islands_count() const
{
return this->islands.size();
}
void
MotionPlanner::initialize()
{
if (this->initialized) return;
if (this->islands.empty()) return; // prevent initialization of empty BoundingBox
ExPolygons expp;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
island->simplify(SCALED_EPSILON, expp);
}
this->islands = expp;
// loop through islands in order to create inner expolygons and collect their contours
this->inner.reserve(this->islands.size());
Polygons outer_holes;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
this->inner.push_back(ExPolygonCollection());
offset(*island, &this->inner.back().expolygons, -MP_INNER_MARGIN);
outer_holes.push_back(island->contour);
}
// grow island contours in order to prepare holes of the outer environment
// This is actually wrong because it might merge contours that are close,
// thus confusing the island check in shortest_path() below
//offset(outer_holes, &outer_holes, +MP_OUTER_MARGIN);
// generate outer contour as bounding box of everything
Points points;
for (Polygons::const_iterator contour = outer_holes.begin(); contour != outer_holes.end(); ++contour)
points.insert(points.end(), contour->points.begin(), contour->points.end());
BoundingBox bb(points);
// grow outer contour
Polygons contour;
offset(bb.polygon(), &contour, +MP_OUTER_MARGIN);
assert(contour.size() == 1);
// make expolygon for outer environment
ExPolygons outer;
diff(contour, outer_holes, &outer);
assert(outer.size() == 1);
this->outer = outer.front();
this->graphs.resize(this->islands.size() + 1, NULL);
this->initialized = true;
}
ExPolygonCollection
MotionPlanner::get_env(size_t island_idx) const
{
if (island_idx == -1) {
return ExPolygonCollection(this->outer);
} else {
return this->inner[island_idx];
}
}
void
MotionPlanner::shortest_path(const Point &from, const Point &to, Polyline* polyline)
{
// lazy generation of configuration space
if (!this->initialized) this->initialize();
// if we have an empty configuration space, return a straight move
if (this->islands.empty()) {
polyline->points.push_back(from);
polyline->points.push_back(to);
return;
}
// Are both points in the same island?
int island_idx = -1;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
if (island->contains(from) && island->contains(to)) {
// since both points are in the same island, is a direct move possible?
// if so, we avoid generating the visibility environment
if (island->contains(Line(from, to))) {
polyline->points.push_back(from);
polyline->points.push_back(to);
return;
}
island_idx = island - this->islands.begin();
break;
}
}
// Now check whether points are inside the environment.
Point inner_from = from;
Point inner_to = to;
bool from_is_inside, to_is_inside;
ExPolygonCollection env = this->get_env(island_idx);
if (!(from_is_inside = env.contains(from))) {
// Find the closest inner point to start from.
inner_from = this->nearest_env_point(env, from, to);
}
if (!(to_is_inside = env.contains(to))) {
// Find the closest inner point to start from.
inner_to = this->nearest_env_point(env, to, inner_from);
}
// perform actual path search
MotionPlannerGraph* graph = this->init_graph(island_idx);
graph->shortest_path(graph->find_node(inner_from), graph->find_node(inner_to), polyline);
polyline->points.insert(polyline->points.begin(), from);
polyline->points.push_back(to);
{
// grow our environment slightly in order for simplify_by_visibility()
// to work best by considering moves on boundaries valid as well
ExPolygonCollection grown_env;
offset(env, &grown_env.expolygons, +SCALED_EPSILON);
// remove unnecessary vertices
polyline->simplify_by_visibility(grown_env);
}
/*
SVG svg("shortest_path.svg");
svg.draw(this->outer);
svg.arrows = false;
for (MotionPlannerGraph::adjacency_list_t::const_iterator it = graph->adjacency_list.begin(); it != graph->adjacency_list.end(); ++it) {
Point a = graph->nodes[it - graph->adjacency_list.begin()];
for (std::vector<MotionPlannerGraph::neighbor>::const_iterator n = it->begin(); n != it->end(); ++n) {
Point b = graph->nodes[n->target];
svg.draw(Line(a, b));
}
}
svg.arrows = true;
svg.draw(from);
svg.draw(inner_from, "red");
svg.draw(to);
svg.draw(inner_to, "red");
svg.draw(*polyline, "red");
svg.Close();
*/
}
Point
MotionPlanner::nearest_env_point(const ExPolygonCollection &env, const Point &from, const Point &to) const
{
/* In order to ensure that the move between 'from' and the initial env point does
not violate any of the configuration space boundaries, we limit our search to
the points that satisfy this condition. */
/* Assume that this method is never called when 'env' contains 'from';
so 'from' is either inside a hole or outside all contours */
// get the points of the hole containing 'from', if any
Points pp;
for (ExPolygons::const_iterator ex = env.expolygons.begin(); ex != env.expolygons.end(); ++ex) {
for (Polygons::const_iterator h = ex->holes.begin(); h != ex->holes.end(); ++h) {
if (h->contains(from)) {
pp = *h;
}
}
if (!pp.empty()) break;
}
/* If 'from' is not inside a hole, it's outside of all contours, so take all
contours' points */
if (pp.empty()) {
for (ExPolygons::const_iterator ex = env.expolygons.begin(); ex != env.expolygons.end(); ++ex) {
Points contour_pp = ex->contour;
pp.insert(pp.end(), contour_pp.begin(), contour_pp.end());
}
}
/* Find the candidate result and check that it doesn't cross any boundary.
(We could skip all of the above polygon finding logic and directly test all points
in env, but this way we probably reduce complexity). */
Polygons env_pp = env;
while (pp.size() >= 2) {
// find the point in pp that is closest to both 'from' and 'to'
size_t result = from.nearest_waypoint_index(pp, to);
if (intersects((Lines)Line(from, pp[result]), env_pp)) {
// discard result
pp.erase(pp.begin() + result);
} else {
return pp[result];
}
}
// if we're here, return last point (better than nothing)
return pp.front();
}
MotionPlannerGraph*
MotionPlanner::init_graph(int island_idx)
{
if (this->graphs[island_idx + 1] == NULL) {
// if this graph doesn't exist, initialize it
MotionPlannerGraph* graph = this->graphs[island_idx + 1] = new MotionPlannerGraph();
/* We don't add polygon boundaries as graph edges, because we'd need to connect
them to the Voronoi-generated edges by recognizing coinciding nodes. */
typedef voronoi_diagram<double> VD;
VD vd;
// mapping between Voronoi vertices and graph nodes
typedef std::map<const VD::vertex_type*,size_t> t_vd_vertices;
t_vd_vertices vd_vertices;
// get boundaries as lines
ExPolygonCollection env = this->get_env(island_idx);
Lines lines = env.lines();
boost::polygon::construct_voronoi(lines.begin(), lines.end(), &vd);
// traverse the Voronoi diagram and generate graph nodes and edges
for (VD::const_edge_iterator edge = vd.edges().begin(); edge != vd.edges().end(); ++edge) {
if (edge->is_infinite()) continue;
const VD::vertex_type* v0 = edge->vertex0();
const VD::vertex_type* v1 = edge->vertex1();
Point p0 = Point(v0->x(), v0->y());
Point p1 = Point(v1->x(), v1->y());
// skip edge if any of its endpoints is outside our configuration space
if (!env.contains_b(p0) || !env.contains_b(p1)) continue;
t_vd_vertices::const_iterator i_v0 = vd_vertices.find(v0);
size_t v0_idx;
if (i_v0 == vd_vertices.end()) {
graph->nodes.push_back(p0);
vd_vertices[v0] = v0_idx = graph->nodes.size()-1;
} else {
v0_idx = i_v0->second;
}
t_vd_vertices::const_iterator i_v1 = vd_vertices.find(v1);
size_t v1_idx;
if (i_v1 == vd_vertices.end()) {
graph->nodes.push_back(p1);
vd_vertices[v1] = v1_idx = graph->nodes.size()-1;
} else {
v1_idx = i_v1->second;
}
// Euclidean distance is used as weight for the graph edge
double dist = graph->nodes[v0_idx].distance_to(graph->nodes[v1_idx]);
graph->add_edge(v0_idx, v1_idx, dist);
}
return graph;
}
return this->graphs[island_idx + 1];
}
void
MotionPlannerGraph::add_edge(size_t from, size_t to, double weight)
{
// extend adjacency list until this start node
if (this->adjacency_list.size() < from+1)
this->adjacency_list.resize(from+1);
this->adjacency_list[from].push_back(neighbor(to, weight));
}
size_t
MotionPlannerGraph::find_node(const Point &point) const
{
/*
for (Points::const_iterator p = this->nodes.begin(); p != this->nodes.end(); ++p) {
if (p->coincides_with(point)) return p - this->nodes.begin();
}
*/
return point.nearest_point_index(this->nodes);
}
void
MotionPlannerGraph::shortest_path(size_t from, size_t to, Polyline* polyline)
{
// this prevents a crash in case for some reason we got here with an empty adjacency list
if (this->adjacency_list.empty()) return;
const weight_t max_weight = std::numeric_limits<weight_t>::infinity();
std::vector<weight_t> dist;
std::vector<node_t> previous;
{
// number of nodes
size_t n = this->adjacency_list.size();
// initialize dist and previous
dist.clear();
dist.resize(n, max_weight);
dist[from] = 0; // distance from 'from' to itself
previous.clear();
previous.resize(n, -1);
// initialize the Q with all nodes
std::set<node_t> Q;
for (node_t i = 0; i < n; ++i) Q.insert(i);
while (!Q.empty())
{
// get node in Q having the minimum dist ('from' in the first loop)
node_t u;
{
double min_dist = -1;
for (std::set<node_t>::const_iterator n = Q.begin(); n != Q.end(); ++n) {
if (dist[*n] < min_dist || min_dist == -1) {
u = *n;
min_dist = dist[*n];
}
}
}
Q.erase(u);
// stop searching if we reached our destination
if (u == to) break;
// Visit each edge starting from node u
const std::vector<neighbor> &neighbors = this->adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
// neighbor node is v
node_t v = neighbor_iter->target;
// skip if we already visited this
if (Q.find(v) == Q.end()) continue;
// calculate total distance
weight_t alt = dist[u] + neighbor_iter->weight;
// if total distance through u is shorter than the previous
// distance (if any) between 'from' and 'v', replace it
if (alt < dist[v]) {
dist[v] = alt;
previous[v] = u;
}
}
}
}
for (node_t vertex = to; vertex != -1; vertex = previous[vertex])
polyline->points.push_back(this->nodes[vertex]);
polyline->points.push_back(this->nodes[from]);
polyline->reverse();
}
#ifdef SLIC3RXS
REGISTER_CLASS(MotionPlanner, "MotionPlanner");
#endif
}
<commit_msg>Fixed segfault in new MotionPlanner code when environments were empty (small islands). #2511<commit_after>#include "BoundingBox.hpp"
#include "MotionPlanner.hpp"
#include <limits> // for numeric_limits
#include "boost/polygon/voronoi.hpp"
using boost::polygon::voronoi_builder;
using boost::polygon::voronoi_diagram;
namespace Slic3r {
MotionPlanner::MotionPlanner(const ExPolygons &islands)
: islands(islands), initialized(false)
{}
MotionPlanner::~MotionPlanner()
{
for (std::vector<MotionPlannerGraph*>::iterator graph = this->graphs.begin(); graph != this->graphs.end(); ++graph)
delete *graph;
}
size_t
MotionPlanner::islands_count() const
{
return this->islands.size();
}
void
MotionPlanner::initialize()
{
if (this->initialized) return;
if (this->islands.empty()) return; // prevent initialization of empty BoundingBox
ExPolygons expp;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
island->simplify(SCALED_EPSILON, expp);
}
this->islands = expp;
// loop through islands in order to create inner expolygons and collect their contours
this->inner.reserve(this->islands.size());
Polygons outer_holes;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
this->inner.push_back(ExPolygonCollection());
offset(*island, &this->inner.back().expolygons, -MP_INNER_MARGIN);
outer_holes.push_back(island->contour);
}
// grow island contours in order to prepare holes of the outer environment
// This is actually wrong because it might merge contours that are close,
// thus confusing the island check in shortest_path() below
//offset(outer_holes, &outer_holes, +MP_OUTER_MARGIN);
// generate outer contour as bounding box of everything
Points points;
for (Polygons::const_iterator contour = outer_holes.begin(); contour != outer_holes.end(); ++contour)
points.insert(points.end(), contour->points.begin(), contour->points.end());
BoundingBox bb(points);
// grow outer contour
Polygons contour;
offset(bb.polygon(), &contour, +MP_OUTER_MARGIN);
assert(contour.size() == 1);
// make expolygon for outer environment
ExPolygons outer;
diff(contour, outer_holes, &outer);
assert(outer.size() == 1);
this->outer = outer.front();
this->graphs.resize(this->islands.size() + 1, NULL);
this->initialized = true;
}
ExPolygonCollection
MotionPlanner::get_env(size_t island_idx) const
{
if (island_idx == -1) {
return ExPolygonCollection(this->outer);
} else {
return this->inner[island_idx];
}
}
void
MotionPlanner::shortest_path(const Point &from, const Point &to, Polyline* polyline)
{
// lazy generation of configuration space
if (!this->initialized) this->initialize();
// if we have an empty configuration space, return a straight move
if (this->islands.empty()) {
polyline->points.push_back(from);
polyline->points.push_back(to);
return;
}
// Are both points in the same island?
int island_idx = -1;
for (ExPolygons::const_iterator island = this->islands.begin(); island != this->islands.end(); ++island) {
if (island->contains(from) && island->contains(to)) {
// since both points are in the same island, is a direct move possible?
// if so, we avoid generating the visibility environment
if (island->contains(Line(from, to))) {
polyline->points.push_back(from);
polyline->points.push_back(to);
return;
}
island_idx = island - this->islands.begin();
break;
}
}
// get environment
ExPolygonCollection env = this->get_env(island_idx);
if (env.expolygons.empty()) {
// if this environment is empty (probably because it's too small), perform straight move
// and avoid running the algorithms on empty dataset
polyline->points.push_back(from);
polyline->points.push_back(to);
return; // bye bye
}
// Now check whether points are inside the environment.
Point inner_from = from;
Point inner_to = to;
bool from_is_inside, to_is_inside;
if (!(from_is_inside = env.contains(from))) {
// Find the closest inner point to start from.
inner_from = this->nearest_env_point(env, from, to);
}
if (!(to_is_inside = env.contains(to))) {
// Find the closest inner point to start from.
inner_to = this->nearest_env_point(env, to, inner_from);
}
// perform actual path search
MotionPlannerGraph* graph = this->init_graph(island_idx);
graph->shortest_path(graph->find_node(inner_from), graph->find_node(inner_to), polyline);
polyline->points.insert(polyline->points.begin(), from);
polyline->points.push_back(to);
{
// grow our environment slightly in order for simplify_by_visibility()
// to work best by considering moves on boundaries valid as well
ExPolygonCollection grown_env;
offset(env, &grown_env.expolygons, +SCALED_EPSILON);
// remove unnecessary vertices
polyline->simplify_by_visibility(grown_env);
}
/*
SVG svg("shortest_path.svg");
svg.draw(this->outer);
svg.arrows = false;
for (MotionPlannerGraph::adjacency_list_t::const_iterator it = graph->adjacency_list.begin(); it != graph->adjacency_list.end(); ++it) {
Point a = graph->nodes[it - graph->adjacency_list.begin()];
for (std::vector<MotionPlannerGraph::neighbor>::const_iterator n = it->begin(); n != it->end(); ++n) {
Point b = graph->nodes[n->target];
svg.draw(Line(a, b));
}
}
svg.arrows = true;
svg.draw(from);
svg.draw(inner_from, "red");
svg.draw(to);
svg.draw(inner_to, "red");
svg.draw(*polyline, "red");
svg.Close();
*/
}
Point
MotionPlanner::nearest_env_point(const ExPolygonCollection &env, const Point &from, const Point &to) const
{
/* In order to ensure that the move between 'from' and the initial env point does
not violate any of the configuration space boundaries, we limit our search to
the points that satisfy this condition. */
/* Assume that this method is never called when 'env' contains 'from';
so 'from' is either inside a hole or outside all contours */
// get the points of the hole containing 'from', if any
Points pp;
for (ExPolygons::const_iterator ex = env.expolygons.begin(); ex != env.expolygons.end(); ++ex) {
for (Polygons::const_iterator h = ex->holes.begin(); h != ex->holes.end(); ++h) {
if (h->contains(from)) {
pp = *h;
}
}
if (!pp.empty()) break;
}
/* If 'from' is not inside a hole, it's outside of all contours, so take all
contours' points */
if (pp.empty()) {
for (ExPolygons::const_iterator ex = env.expolygons.begin(); ex != env.expolygons.end(); ++ex) {
Points contour_pp = ex->contour;
pp.insert(pp.end(), contour_pp.begin(), contour_pp.end());
}
}
/* Find the candidate result and check that it doesn't cross any boundary.
(We could skip all of the above polygon finding logic and directly test all points
in env, but this way we probably reduce complexity). */
Polygons env_pp = env;
while (pp.size() >= 2) {
// find the point in pp that is closest to both 'from' and 'to'
size_t result = from.nearest_waypoint_index(pp, to);
if (intersects((Lines)Line(from, pp[result]), env_pp)) {
// discard result
pp.erase(pp.begin() + result);
} else {
return pp[result];
}
}
// if we're here, return last point if any (better than nothing)
if (!pp.empty()) return pp.front();
// if we have no points at all, then we have an empty environment and we
// make this method behave as a no-op (we shouldn't get here by the way)
return from;
}
MotionPlannerGraph*
MotionPlanner::init_graph(int island_idx)
{
if (this->graphs[island_idx + 1] == NULL) {
// if this graph doesn't exist, initialize it
MotionPlannerGraph* graph = this->graphs[island_idx + 1] = new MotionPlannerGraph();
/* We don't add polygon boundaries as graph edges, because we'd need to connect
them to the Voronoi-generated edges by recognizing coinciding nodes. */
typedef voronoi_diagram<double> VD;
VD vd;
// mapping between Voronoi vertices and graph nodes
typedef std::map<const VD::vertex_type*,size_t> t_vd_vertices;
t_vd_vertices vd_vertices;
// get boundaries as lines
ExPolygonCollection env = this->get_env(island_idx);
Lines lines = env.lines();
boost::polygon::construct_voronoi(lines.begin(), lines.end(), &vd);
// traverse the Voronoi diagram and generate graph nodes and edges
for (VD::const_edge_iterator edge = vd.edges().begin(); edge != vd.edges().end(); ++edge) {
if (edge->is_infinite()) continue;
const VD::vertex_type* v0 = edge->vertex0();
const VD::vertex_type* v1 = edge->vertex1();
Point p0 = Point(v0->x(), v0->y());
Point p1 = Point(v1->x(), v1->y());
// skip edge if any of its endpoints is outside our configuration space
if (!env.contains_b(p0) || !env.contains_b(p1)) continue;
t_vd_vertices::const_iterator i_v0 = vd_vertices.find(v0);
size_t v0_idx;
if (i_v0 == vd_vertices.end()) {
graph->nodes.push_back(p0);
vd_vertices[v0] = v0_idx = graph->nodes.size()-1;
} else {
v0_idx = i_v0->second;
}
t_vd_vertices::const_iterator i_v1 = vd_vertices.find(v1);
size_t v1_idx;
if (i_v1 == vd_vertices.end()) {
graph->nodes.push_back(p1);
vd_vertices[v1] = v1_idx = graph->nodes.size()-1;
} else {
v1_idx = i_v1->second;
}
// Euclidean distance is used as weight for the graph edge
double dist = graph->nodes[v0_idx].distance_to(graph->nodes[v1_idx]);
graph->add_edge(v0_idx, v1_idx, dist);
}
return graph;
}
return this->graphs[island_idx + 1];
}
void
MotionPlannerGraph::add_edge(size_t from, size_t to, double weight)
{
// extend adjacency list until this start node
if (this->adjacency_list.size() < from+1)
this->adjacency_list.resize(from+1);
this->adjacency_list[from].push_back(neighbor(to, weight));
}
size_t
MotionPlannerGraph::find_node(const Point &point) const
{
/*
for (Points::const_iterator p = this->nodes.begin(); p != this->nodes.end(); ++p) {
if (p->coincides_with(point)) return p - this->nodes.begin();
}
*/
return point.nearest_point_index(this->nodes);
}
void
MotionPlannerGraph::shortest_path(size_t from, size_t to, Polyline* polyline)
{
// this prevents a crash in case for some reason we got here with an empty adjacency list
if (this->adjacency_list.empty()) return;
const weight_t max_weight = std::numeric_limits<weight_t>::infinity();
std::vector<weight_t> dist;
std::vector<node_t> previous;
{
// number of nodes
size_t n = this->adjacency_list.size();
// initialize dist and previous
dist.clear();
dist.resize(n, max_weight);
dist[from] = 0; // distance from 'from' to itself
previous.clear();
previous.resize(n, -1);
// initialize the Q with all nodes
std::set<node_t> Q;
for (node_t i = 0; i < n; ++i) Q.insert(i);
while (!Q.empty())
{
// get node in Q having the minimum dist ('from' in the first loop)
node_t u;
{
double min_dist = -1;
for (std::set<node_t>::const_iterator n = Q.begin(); n != Q.end(); ++n) {
if (dist[*n] < min_dist || min_dist == -1) {
u = *n;
min_dist = dist[*n];
}
}
}
Q.erase(u);
// stop searching if we reached our destination
if (u == to) break;
// Visit each edge starting from node u
const std::vector<neighbor> &neighbors = this->adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
// neighbor node is v
node_t v = neighbor_iter->target;
// skip if we already visited this
if (Q.find(v) == Q.end()) continue;
// calculate total distance
weight_t alt = dist[u] + neighbor_iter->weight;
// if total distance through u is shorter than the previous
// distance (if any) between 'from' and 'v', replace it
if (alt < dist[v]) {
dist[v] = alt;
previous[v] = u;
}
}
}
}
for (node_t vertex = to; vertex != -1; vertex = previous[vertex])
polyline->points.push_back(this->nodes[vertex]);
polyline->points.push_back(this->nodes[from]);
polyline->reverse();
}
#ifdef SLIC3RXS
REGISTER_CLASS(MotionPlanner, "MotionPlanner");
#endif
}
<|endoftext|>
|
<commit_before>#include <QDebug>
#include "appcontroller.h"
#include "appwindow.h"
#include "widgets/loginwidget.h"
#include "widgets/librarywidget.h"
//TODO: Minimizing to tray and restoring the window multiple times, after moving it for the first time and while not maximized, cause the window to move if taskbars are present. Cause not known.
AppController::AppController(QObject *parent) :
QObject(parent)
{
api = new ItchioApi(this);
setupSettings();
showTrayIcon();
showAppWindow();
}
void AppController::setupSettings()
{
settingsFile = "settings.scratch";
settings = new AppSettings(settingsFile, QSettings::IniFormat);
api->login("hue", "hue", settings->loadSettings(API_KEY));
}
void AppController::hide()
{
appWindow->showMinimized();
appWindow->setWindowFlags(appWindow->windowFlags() ^ Qt::Tool);
}
void AppController::show()
{
appWindow->setWindowFlags(appWindow->windowFlags() ^ Qt::Tool);
appWindow->show();
appWindow->setWindowState((appWindow->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
}
void AppController::quit()
{
QCoreApplication::exit();
}
void AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick
&& !appWindow->isVisible()) {
show();
}
}
void AppController::showTrayIcon()
{
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu();
actionQuit = new QAction("Quit", this);
connect (actionQuit, SIGNAL(triggered()), this, SLOT(quit()));
connect (trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));
trayIconMenu->addAction (actionQuit);
trayIcon->setIcon(QIcon(":/images/images/itchio-icon-16.png"));
trayIcon->setContextMenu (trayIconMenu);
trayIcon->show();
}
void AppController::showTrayIconNotification(TrayNotifications notification, int duration)
{
if(trayIcon->supportsMessages()) {
switch(notification)
{
case NOTIFICATION_TEST:
trayIcon->showMessage("Title", "Test", QSystemTrayIcon::Information, duration);
break;
}
}
}
void AppController::showAppWindow()
{
appWindow = new AppWindow(this);
appWindow->setWindowIcon(QIcon(":/images/images/itchio-icon-200.png"));
appWindow->show();
}
void AppController::onLogin()
{
settings->saveSettings(API_KEY, api->userKey);
settings->saveSettings(USERNAME, api->userName);
appWindow->loginWidget->hide();
appWindow->loginWidget->deleteLater();
appWindow->setupLibrary();
}
<commit_msg>Added conditional to api key login.<commit_after>#include <QDebug>
#include "appcontroller.h"
#include "appwindow.h"
#include "widgets/loginwidget.h"
#include "widgets/librarywidget.h"
//TODO: Minimizing to tray and restoring the window multiple times, after moving it for the first time and while not maximized, cause the window to move if taskbars are present. Cause not known.
AppController::AppController(QObject *parent) :
QObject(parent)
{
api = new ItchioApi(this);
setupSettings();
showTrayIcon();
showAppWindow();
}
void AppController::setupSettings()
{
settingsFile = "settings.scratch";
settings = new AppSettings(settingsFile, QSettings::IniFormat);
if(settings->loadSettings(API_KEY) != "") api->login("hue", "hue", settings->loadSettings(API_KEY));
}
void AppController::hide()
{
appWindow->showMinimized();
appWindow->setWindowFlags(appWindow->windowFlags() ^ Qt::Tool);
}
void AppController::show()
{
appWindow->setWindowFlags(appWindow->windowFlags() ^ Qt::Tool);
appWindow->show();
appWindow->setWindowState((appWindow->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
}
void AppController::quit()
{
QCoreApplication::exit();
}
void AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick
&& !appWindow->isVisible()) {
show();
}
}
void AppController::showTrayIcon()
{
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu();
actionQuit = new QAction("Quit", this);
connect (actionQuit, SIGNAL(triggered()), this, SLOT(quit()));
connect (trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));
trayIconMenu->addAction (actionQuit);
trayIcon->setIcon(QIcon(":/images/images/itchio-icon-16.png"));
trayIcon->setContextMenu (trayIconMenu);
trayIcon->show();
}
void AppController::showTrayIconNotification(TrayNotifications notification, int duration)
{
if(trayIcon->supportsMessages()) {
switch(notification)
{
case NOTIFICATION_TEST:
trayIcon->showMessage("Title", "Test", QSystemTrayIcon::Information, duration);
break;
}
}
}
void AppController::showAppWindow()
{
appWindow = new AppWindow(this);
appWindow->setWindowIcon(QIcon(":/images/images/itchio-icon-200.png"));
appWindow->show();
}
void AppController::onLogin()
{
settings->saveSettings(API_KEY, api->userKey);
settings->saveSettings(USERNAME, api->userName);
appWindow->loginWidget->hide();
appWindow->loginWidget->deleteLater();
appWindow->setupLibrary();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014-present Facebook, 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.
*/
#include <folly/String.h>
#include <boost/algorithm/string.hpp>
#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <random>
using namespace folly;
using namespace std;
BENCHMARK(libc_tolower, iters) {
static const size_t kSize = 256;
// This array is static to keep the compiler from optimizing the
// entire function down to a no-op if it has an inlined impl of
// tolower and thus is able to tell that there are no side-effects.
// No side-effects + no writes to anything other than local variables
// + no return value = no need to run any of the code in the function.
// gcc, for example, makes that optimization with -O2.
static char input[kSize];
for (size_t i = 0; i < kSize; i++) {
input[i] = (char)(i & 0xff);
}
for (auto i = iters; i > 0; i--) {
for (size_t offset = 0; offset < kSize; offset++) {
input[offset] = tolower(input[offset]);
}
}
}
BENCHMARK(folly_toLowerAscii, iters) {
static const size_t kSize = 256;
static char input[kSize];
for (size_t i = 0; i < kSize; i++) {
input[i] = (char)(i & 0xff);
}
for (auto i = iters; i > 0; i--) {
folly::toLowerAscii(input, kSize);
}
}
// A simple benchmark that tests various output sizes for a simple
// input; the goal is to measure the output buffer resize code cost.
void stringPrintfOutputSize(int iters, int param) {
string buffer;
BENCHMARK_SUSPEND {
buffer.resize(param, 'x');
}
for (int64_t i = 0; i < iters; ++i) {
string s = stringPrintf("msg: %d, %d, %s", 10, 20, buffer.c_str());
}
}
// The first few of these tend to fit in the inline buffer, while the
// subsequent ones cross that limit, trigger a second vsnprintf, and
// exercise a different codepath.
BENCHMARK_PARAM(stringPrintfOutputSize, 1)
BENCHMARK_PARAM(stringPrintfOutputSize, 4)
BENCHMARK_PARAM(stringPrintfOutputSize, 16)
BENCHMARK_PARAM(stringPrintfOutputSize, 64)
BENCHMARK_PARAM(stringPrintfOutputSize, 256)
BENCHMARK_PARAM(stringPrintfOutputSize, 1024)
// Benchmark simple stringAppendf behavior to show a pathology Lovro
// reported (t5735468).
BENCHMARK(stringPrintfAppendfBenchmark, iters) {
for (unsigned int i = 0; i < iters; ++i) {
string s;
BENCHMARK_SUSPEND {
s.reserve(300000);
}
for (int j = 0; j < 300000; ++j) {
stringAppendf(&s, "%d", 1);
}
}
}
namespace {
fbstring cbmString;
fbstring cbmEscapedString;
fbstring cEscapedString;
fbstring cUnescapedString;
const size_t kCBmStringLength = 64 << 10;
const uint32_t kCPrintablePercentage = 90;
fbstring uribmString;
fbstring uribmEscapedString;
fbstring uriEscapedString;
fbstring uriUnescapedString;
const size_t kURIBmStringLength = 256;
const uint32_t kURIPassThroughPercentage = 50;
fbstring hexlifyInput;
fbstring hexlifyOutput;
const size_t kHexlifyLength = 1024;
void initBenchmark() {
std::mt19937 rnd;
// C escape
std::uniform_int_distribution<uint32_t> printable(32, 126);
std::uniform_int_distribution<uint32_t> nonPrintable(0, 160);
std::uniform_int_distribution<uint32_t> percentage(0, 99);
cbmString.reserve(kCBmStringLength);
for (size_t i = 0; i < kCBmStringLength; ++i) {
unsigned char c;
if (percentage(rnd) < kCPrintablePercentage) {
c = printable(rnd);
} else {
c = nonPrintable(rnd);
// Generate characters in both non-printable ranges:
// 0..31 and 127..255
if (c >= 32) {
c += (126 - 32) + 1;
}
}
cbmString.push_back(c);
}
cbmEscapedString = cEscape<fbstring>(cbmString);
// URI escape
std::uniform_int_distribution<uint32_t> passthrough('a', 'z');
std::string encodeChars = " ?!\"',+[]";
std::uniform_int_distribution<uint32_t> encode(0, encodeChars.size() - 1);
uribmString.reserve(kURIBmStringLength);
for (size_t i = 0; i < kURIBmStringLength; ++i) {
unsigned char c;
if (percentage(rnd) < kURIPassThroughPercentage) {
c = passthrough(rnd);
} else {
c = encodeChars[encode(rnd)];
}
uribmString.push_back(c);
}
uribmEscapedString = uriEscape<fbstring>(uribmString);
// hexlify
hexlifyInput.resize(kHexlifyLength);
Random::secureRandom(&hexlifyInput[0], kHexlifyLength);
folly::hexlify(hexlifyInput, hexlifyOutput);
}
BENCHMARK(BM_cEscape, iters) {
while (iters--) {
cEscapedString = cEscape<fbstring>(cbmString);
doNotOptimizeAway(cEscapedString.size());
}
}
BENCHMARK(BM_cUnescape, iters) {
while (iters--) {
cUnescapedString = cUnescape<fbstring>(cbmEscapedString);
doNotOptimizeAway(cUnescapedString.size());
}
}
BENCHMARK(BM_uriEscape, iters) {
while (iters--) {
uriEscapedString = uriEscape<fbstring>(uribmString);
doNotOptimizeAway(uriEscapedString.size());
}
}
BENCHMARK(BM_uriUnescape, iters) {
while (iters--) {
uriUnescapedString = uriUnescape<fbstring>(uribmEscapedString);
doNotOptimizeAway(uriUnescapedString.size());
}
}
BENCHMARK(BM_unhexlify, iters) {
// iters/sec = bytes output per sec
std::string unhexed;
folly::StringPiece hex = hexlifyOutput;
for (; iters >= hex.size(); iters -= hex.size()) {
folly::unhexlify(hex, unhexed);
}
iters -= iters % 2; // round down to an even number of chars
hex = hex.subpiece(0, iters);
folly::unhexlify(hex, unhexed);
}
} // namespace
//////////////////////////////////////////////////////////////////////
BENCHMARK(splitOnSingleChar, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<StringPiece> pieces;
folly::split(':', line, pieces);
}
}
BENCHMARK(splitOnSingleCharFixed, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split(':', line, a, b, c, d);
}
}
BENCHMARK(splitOnSingleCharFixedAllowExtra, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split<false>(':', line, a, b, c, d);
}
}
BENCHMARK(splitStr, iters) {
static const std::string line = "one-*-two-*-three-*-four";
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<StringPiece> pieces;
folly::split("-*-", line, pieces);
}
}
BENCHMARK(splitStrFixed, iters) {
static const std::string line = "one-*-two-*-three-*-four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split("-*-", line, a, b, c, d);
}
}
BENCHMARK(boost_splitOnSingleChar, iters) {
static const std::string line = "one:two:three:four";
bool (*pred)(char) = [](char c) -> bool { return c == ':'; };
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<boost::iterator_range<std::string::const_iterator>> pieces;
boost::split(pieces, line, pred);
}
}
BENCHMARK(joinCharStr, iters) {
static const std::vector<std::string> input = {
"one", "two", "three", "four", "five", "six", "seven"};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(':', input, output);
}
}
BENCHMARK(joinStrStr, iters) {
static const std::vector<std::string> input = {
"one", "two", "three", "four", "five", "six", "seven"};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(":", input, output);
}
}
BENCHMARK(joinInt, iters) {
static const auto input = {123, 456, 78910, 1112, 1314, 151, 61718};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(":", input, output);
}
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
initBenchmark();
folly::runBenchmarks();
return 0;
}
/*
Results on x86_64:
============================================================================
folly/test/StringBenchmark.cpp relative time/iter iters/s
============================================================================
libc_tolower 773.30ns 1.29M
folly_toLowerAscii 65.04ns 15.38M
stringPrintfOutputSize(1) 224.67ns 4.45M
stringPrintfOutputSize(4) 231.53ns 4.32M
stringPrintfOutputSize(16) 286.54ns 3.49M
stringPrintfOutputSize(64) 305.47ns 3.27M
stringPrintfOutputSize(256) 1.48us 674.45K
stringPrintfOutputSize(1024) 5.89us 169.72K
stringPrintfAppendfBenchmark 34.43ms 29.04
BM_cEscape 461.51us 2.17K
BM_cUnescape 328.19us 3.05K
BM_uriEscape 4.36us 229.25K
BM_uriUnescape 2.22us 450.64K
splitOnSingleChar 1.46us 687.21K
splitOnSingleCharFixed 133.02ns 7.52M
splitOnSingleCharFixedAllowExtra 74.35ns 13.45M
splitStr 2.36us 424.00K
splitStrFixed 282.38ns 3.54M
boost_splitOnSingleChar 2.83us 353.12K
joinCharStr 2.65us 376.93K
joinStrStr 2.64us 378.09K
joinInt 3.89us 257.37K
============================================================================
*/
<commit_msg>Add benchmarks similar to `stringPrintf` for `folly::Format` and `fmt`<commit_after>/*
* Copyright 2014-present Facebook, 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.
*/
#include <fmt/format.h>
#include <folly/Format.h>
#include <folly/String.h>
#include <boost/algorithm/string.hpp>
#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <random>
using namespace folly;
using namespace std;
BENCHMARK(libc_tolower, iters) {
static const size_t kSize = 256;
// This array is static to keep the compiler from optimizing the
// entire function down to a no-op if it has an inlined impl of
// tolower and thus is able to tell that there are no side-effects.
// No side-effects + no writes to anything other than local variables
// + no return value = no need to run any of the code in the function.
// gcc, for example, makes that optimization with -O2.
static char input[kSize];
for (size_t i = 0; i < kSize; i++) {
input[i] = (char)(i & 0xff);
}
for (auto i = iters; i > 0; i--) {
for (size_t offset = 0; offset < kSize; offset++) {
input[offset] = tolower(input[offset]);
}
}
}
BENCHMARK(folly_toLowerAscii, iters) {
static const size_t kSize = 256;
static char input[kSize];
for (size_t i = 0; i < kSize; i++) {
input[i] = (char)(i & 0xff);
}
for (auto i = iters; i > 0; i--) {
folly::toLowerAscii(input, kSize);
}
}
// A simple benchmark that tests various output sizes for a simple
// input; the goal is to measure the output buffer resize code cost.
const size_t kAppendBufSize = 300000;
void stringPrintfOutputSize(int iters, int param) {
string buffer;
BENCHMARK_SUSPEND {
buffer.resize(param, 'x');
}
for (int64_t i = 0; i < iters; ++i) {
string s = stringPrintf("msg: %d, %d, %s", 10, 20, buffer.c_str());
}
}
// The first few of these tend to fit in the inline buffer, while the
// subsequent ones cross that limit, trigger a second vsnprintf, and
// exercise a different codepath.
BENCHMARK_PARAM(stringPrintfOutputSize, 1)
BENCHMARK_PARAM(stringPrintfOutputSize, 4)
BENCHMARK_PARAM(stringPrintfOutputSize, 16)
BENCHMARK_PARAM(stringPrintfOutputSize, 64)
BENCHMARK_PARAM(stringPrintfOutputSize, 256)
BENCHMARK_PARAM(stringPrintfOutputSize, 1024)
// Benchmark simple stringAppendf behavior to show a pathology Lovro
// reported (t5735468).
BENCHMARK(stringPrintfAppendfBenchmark, iters) {
for (size_t i = 0; i < iters; ++i) {
string s;
BENCHMARK_SUSPEND {
s.reserve(kAppendBufSize);
}
for (size_t j = 0; j < kAppendBufSize; ++j) {
stringAppendf(&s, "%d", 1);
}
DCHECK_EQ(s.size(), kAppendBufSize);
}
}
// A simple benchmark that tests various output sizes for a simple
// input; the goal is to measure the output buffer resize code cost.
// Intended for comparison with stringPrintf.
void fmtOutputSize(int iters, int param) {
string buffer;
BENCHMARK_SUSPEND {
buffer.resize(param, 'x');
}
for (int64_t i = 0; i < iters; ++i) {
string s = fmt::format("msg: {}, {}, {}", 10, 20, buffer);
}
}
// The first few of these tend to fit in the inline buffer, while the
// subsequent ones cross that limit, trigger a second vsnprintf, and
// exercise a different codepath.
BENCHMARK_PARAM(fmtOutputSize, 1)
BENCHMARK_PARAM(fmtOutputSize, 4)
BENCHMARK_PARAM(fmtOutputSize, 16)
BENCHMARK_PARAM(fmtOutputSize, 64)
BENCHMARK_PARAM(fmtOutputSize, 256)
BENCHMARK_PARAM(fmtOutputSize, 1024)
// Benchmark simple fmt append behavior; intended as a comparison
// against stringAppendf.
BENCHMARK(fmtAppendfBenchmark, iters) {
for (size_t i = 0; i < iters; ++i) {
fmt::memory_buffer buf;
for (size_t j = 0; j < kAppendBufSize; ++j) {
fmt::format_to(buf, "{}", 1);
}
string s = fmt::to_string(buf);
DCHECK_EQ(s.size(), kAppendBufSize);
}
}
// A simple benchmark that tests various output sizes for a simple
// input; the goal is to measure the output buffer resize code cost.
// Intended for comparison with stringPrintf and fmt.
void follyFmtOutputSize(int iters, int param) {
string buffer;
BENCHMARK_SUSPEND {
buffer.resize(param, 'x');
}
for (int64_t i = 0; i < iters; ++i) {
string s = format("msg: {}, {}, {}", 10, 20, buffer).str();
}
}
// The first few of these tend to fit in the inline buffer, while the
// subsequent ones cross that limit, trigger a second vsnprintf, and
// exercise a different codepath.
BENCHMARK_PARAM(follyFmtOutputSize, 1)
BENCHMARK_PARAM(follyFmtOutputSize, 4)
BENCHMARK_PARAM(follyFmtOutputSize, 16)
BENCHMARK_PARAM(follyFmtOutputSize, 64)
BENCHMARK_PARAM(follyFmtOutputSize, 256)
BENCHMARK_PARAM(follyFmtOutputSize, 1024)
// Benchmark simple fmt append behavior; intended as a comparison
// against stringAppendf.
BENCHMARK(follyFmtAppendfBenchmark, iters) {
for (size_t i = 0; i < iters; ++i) {
string s;
BENCHMARK_SUSPEND {
s.reserve(kAppendBufSize);
}
for (size_t j = 0; j < kAppendBufSize; ++j) {
format("{}", 1).appendTo(s);
}
DCHECK_EQ(s.size(), kAppendBufSize);
}
}
namespace {
fbstring cbmString;
fbstring cbmEscapedString;
fbstring cEscapedString;
fbstring cUnescapedString;
const size_t kCBmStringLength = 64 << 10;
const uint32_t kCPrintablePercentage = 90;
fbstring uribmString;
fbstring uribmEscapedString;
fbstring uriEscapedString;
fbstring uriUnescapedString;
const size_t kURIBmStringLength = 256;
const uint32_t kURIPassThroughPercentage = 50;
fbstring hexlifyInput;
fbstring hexlifyOutput;
const size_t kHexlifyLength = 1024;
void initBenchmark() {
std::mt19937 rnd;
// C escape
std::uniform_int_distribution<uint32_t> printable(32, 126);
std::uniform_int_distribution<uint32_t> nonPrintable(0, 160);
std::uniform_int_distribution<uint32_t> percentage(0, 99);
cbmString.reserve(kCBmStringLength);
for (size_t i = 0; i < kCBmStringLength; ++i) {
unsigned char c;
if (percentage(rnd) < kCPrintablePercentage) {
c = printable(rnd);
} else {
c = nonPrintable(rnd);
// Generate characters in both non-printable ranges:
// 0..31 and 127..255
if (c >= 32) {
c += (126 - 32) + 1;
}
}
cbmString.push_back(c);
}
cbmEscapedString = cEscape<fbstring>(cbmString);
// URI escape
std::uniform_int_distribution<uint32_t> passthrough('a', 'z');
std::string encodeChars = " ?!\"',+[]";
std::uniform_int_distribution<uint32_t> encode(0, encodeChars.size() - 1);
uribmString.reserve(kURIBmStringLength);
for (size_t i = 0; i < kURIBmStringLength; ++i) {
unsigned char c;
if (percentage(rnd) < kURIPassThroughPercentage) {
c = passthrough(rnd);
} else {
c = encodeChars[encode(rnd)];
}
uribmString.push_back(c);
}
uribmEscapedString = uriEscape<fbstring>(uribmString);
// hexlify
hexlifyInput.resize(kHexlifyLength);
Random::secureRandom(&hexlifyInput[0], kHexlifyLength);
folly::hexlify(hexlifyInput, hexlifyOutput);
}
BENCHMARK(BM_cEscape, iters) {
while (iters--) {
cEscapedString = cEscape<fbstring>(cbmString);
doNotOptimizeAway(cEscapedString.size());
}
}
BENCHMARK(BM_cUnescape, iters) {
while (iters--) {
cUnescapedString = cUnescape<fbstring>(cbmEscapedString);
doNotOptimizeAway(cUnescapedString.size());
}
}
BENCHMARK(BM_uriEscape, iters) {
while (iters--) {
uriEscapedString = uriEscape<fbstring>(uribmString);
doNotOptimizeAway(uriEscapedString.size());
}
}
BENCHMARK(BM_uriUnescape, iters) {
while (iters--) {
uriUnescapedString = uriUnescape<fbstring>(uribmEscapedString);
doNotOptimizeAway(uriUnescapedString.size());
}
}
BENCHMARK(BM_unhexlify, iters) {
// iters/sec = bytes output per sec
std::string unhexed;
folly::StringPiece hex = hexlifyOutput;
for (; iters >= hex.size(); iters -= hex.size()) {
folly::unhexlify(hex, unhexed);
}
iters -= iters % 2; // round down to an even number of chars
hex = hex.subpiece(0, iters);
folly::unhexlify(hex, unhexed);
}
} // namespace
//////////////////////////////////////////////////////////////////////
BENCHMARK(splitOnSingleChar, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<StringPiece> pieces;
folly::split(':', line, pieces);
}
}
BENCHMARK(splitOnSingleCharFixed, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split(':', line, a, b, c, d);
}
}
BENCHMARK(splitOnSingleCharFixedAllowExtra, iters) {
static const std::string line = "one:two:three:four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split<false>(':', line, a, b, c, d);
}
}
BENCHMARK(splitStr, iters) {
static const std::string line = "one-*-two-*-three-*-four";
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<StringPiece> pieces;
folly::split("-*-", line, pieces);
}
}
BENCHMARK(splitStrFixed, iters) {
static const std::string line = "one-*-two-*-three-*-four";
for (size_t i = 0; i < iters << 4; ++i) {
StringPiece a, b, c, d;
folly::split("-*-", line, a, b, c, d);
}
}
BENCHMARK(boost_splitOnSingleChar, iters) {
static const std::string line = "one:two:three:four";
bool (*pred)(char) = [](char c) -> bool { return c == ':'; };
for (size_t i = 0; i < iters << 4; ++i) {
std::vector<boost::iterator_range<std::string::const_iterator>> pieces;
boost::split(pieces, line, pred);
}
}
BENCHMARK(joinCharStr, iters) {
static const std::vector<std::string> input = {
"one", "two", "three", "four", "five", "six", "seven"};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(':', input, output);
}
}
BENCHMARK(joinStrStr, iters) {
static const std::vector<std::string> input = {
"one", "two", "three", "four", "five", "six", "seven"};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(":", input, output);
}
}
BENCHMARK(joinInt, iters) {
static const auto input = {123, 456, 78910, 1112, 1314, 151, 61718};
for (size_t i = 0; i < iters << 4; ++i) {
std::string output;
folly::join(":", input, output);
}
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
initBenchmark();
folly::runBenchmarks();
return 0;
}
/*
Results on x86_64:
============================================================================
folly/test/StringBenchmark.cpp relative time/iter iters/s
============================================================================
libc_tolower 773.30ns 1.29M
folly_toLowerAscii 65.04ns 15.38M
stringPrintfOutputSize(1) 224.67ns 4.45M
stringPrintfOutputSize(4) 231.53ns 4.32M
stringPrintfOutputSize(16) 286.54ns 3.49M
stringPrintfOutputSize(64) 305.47ns 3.27M
stringPrintfOutputSize(256) 1.48us 674.45K
stringPrintfOutputSize(1024) 5.89us 169.72K
stringPrintfAppendfBenchmark 34.43ms 29.04
BM_cEscape 461.51us 2.17K
BM_cUnescape 328.19us 3.05K
BM_uriEscape 4.36us 229.25K
BM_uriUnescape 2.22us 450.64K
splitOnSingleChar 1.46us 687.21K
splitOnSingleCharFixed 133.02ns 7.52M
splitOnSingleCharFixedAllowExtra 74.35ns 13.45M
splitStr 2.36us 424.00K
splitStrFixed 282.38ns 3.54M
boost_splitOnSingleChar 2.83us 353.12K
joinCharStr 2.65us 376.93K
joinStrStr 2.64us 378.09K
joinInt 3.89us 257.37K
============================================================================
*/
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Characters/String_Constant.h"
#include "../../../../Foundation/Containers/Sequence.h"
#include "../../../../Foundation/Debug/Trace.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/LinkMonitor.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/MemoryStream.h"
#include "../Advertisement.h"
#include "../Common.h"
#include "BasicServer.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************* BasicServer::Rep_ ******************************
********************************************************************************
*/
class BasicServer::Rep_ {
public:
Sequence<Advertisement> fAdvertisements;
FrequencyInfo fFrequencyInfo;
URI fLocation;
Rep_ (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fAdvertisements ()
, fFrequencyInfo (fi)
, fLocation (d.fLocation)
{
{
SSDP::Advertisement dan;
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fTarget = kTarget_UPNPRootDevice;
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), kTarget_UPNPRootDevice.c_str ());
fAdvertisements.Append (dan);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fTarget = dan.fUSN;
fAdvertisements.Append (dan);
}
if (not dd.fDeviceType.empty ()) {
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), dd.fDeviceType.c_str ());
dan.fTarget = dd.fDeviceType;
fAdvertisements.Append (dan);
}
}
StartNotifier_ ();
StartResponder_ ();
IO::Network::LinkMonitor lm;
lm.AddCallback ([this] (IO::Network::LinkMonitor::LinkChange lc, String netName, String ipNum) {
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Basic SSDP server - LinkMonitor callback", L"lc = %d, netName=%s, ipNum=%s", lc, netName.c_str (), ipNum.c_str ())};
if (lc == IO::Network::LinkMonitor::LinkChange::eAdded) {
this->Restart_ ();
}
});
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wpessimizing-move\"");
fLinkMonitor_ = move (optional<IO::Network::LinkMonitor> (move (lm)));
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wpessimizing-move\"");
}
Sequence<Advertisement> GetAdjustedAdvertisements_ () const
{
// @todo EXPLAIN THIS LOGIC? What its doing is - if NO LOCATION HOST SPECIFIED - picka good default (not so crazy) - but only
// in that case do we patch/replace the location for the advertisements? That makes little sense
if (fLocation.GetAuthority () and fLocation.GetAuthority ()->GetHost ()) {
return fAdvertisements;
}
else {
Sequence<Advertisement> revisedAdvertisements;
URI useURL = fLocation;
URI::Authority authority = useURL.GetAuthority ().value_or (URI::Authority{});
authority.SetHost (URI::Host{IO::Network::GetPrimaryInternetAddress ()});
useURL.SetAuthority (authority);
for (auto ai : fAdvertisements) {
ai.fLocation = useURL; // !@todo MAYBE this would make more sense replacing just the HOST part of each advertisement?
revisedAdvertisements.Append (ai);
}
return revisedAdvertisements;
}
}
void StartNotifier_ ()
{
fNotifierThread_ = Thread::New (
[this] () {
PeriodicNotifier l;
l.Run (GetAdjustedAdvertisements_ (), PeriodicNotifier::FrequencyInfo ());
},
Thread::eAutoStart, String{L"SSDP Notifier"});
}
void StartResponder_ ()
{
fSearchResponderThread_ = Thread::New (
[this] () {
SearchResponder sr;
sr.Run (GetAdjustedAdvertisements_ ());
},
Thread::eAutoStart, String{L"SSDP Search Responder"});
}
void Restart_ ()
{
Debug::TraceContextBumper ctx ("Restarting Basic SSDP server threads");
{
Thread::SuppressInterruptionInContext suppressInterruption; // critical to wait til done cuz captures this
if (fNotifierThread_ != nullptr) {
fNotifierThread_.AbortAndWaitForDone ();
}
if (fSearchResponderThread_ != nullptr) {
fSearchResponderThread_.AbortAndWaitForDone ();
}
}
StartNotifier_ ();
StartResponder_ ();
}
Execution::Thread::CleanupPtr fNotifierThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
Execution::Thread::CleanupPtr fSearchResponderThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
optional<IO::Network::LinkMonitor> fLinkMonitor_; // optional so we can delete it first on shutdown (so no restart while stopping stuff)
};
/*
********************************************************************************
********************************** BasicServer *********************************
********************************************************************************
*/
BasicServer::BasicServer (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fRep_ (make_shared<Rep_> (d, dd, fi))
{
}
<commit_msg>minor cleanup<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Characters/String_Constant.h"
#include "../../../../Foundation/Containers/Sequence.h"
#include "../../../../Foundation/Debug/Trace.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/LinkMonitor.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/MemoryStream.h"
#include "../Advertisement.h"
#include "../Common.h"
#include "BasicServer.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************* BasicServer::Rep_ ******************************
********************************************************************************
*/
class BasicServer::Rep_ {
public:
Sequence<Advertisement> fAdvertisements;
FrequencyInfo fFrequencyInfo;
URI fLocation;
Rep_ (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fAdvertisements ()
, fFrequencyInfo (fi)
, fLocation (d.fLocation)
{
{
SSDP::Advertisement dan;
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fTarget = kTarget_UPNPRootDevice;
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), kTarget_UPNPRootDevice.c_str ());
fAdvertisements.Append (dan);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fTarget = dan.fUSN;
fAdvertisements.Append (dan);
}
if (not dd.fDeviceType.empty ()) {
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), dd.fDeviceType.c_str ());
dan.fTarget = dd.fDeviceType;
fAdvertisements.Append (dan);
}
}
StartNotifier_ ();
StartResponder_ ();
IO::Network::LinkMonitor lm;
lm.AddCallback ([this] (IO::Network::LinkMonitor::LinkChange lc, String netName, String ipNum) {
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Basic SSDP server - LinkMonitor callback", L"lc = %d, netName=%s, ipNum=%s", lc, netName.c_str (), ipNum.c_str ())};
if (lc == IO::Network::LinkMonitor::LinkChange::eAdded) {
this->Restart_ ();
}
});
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wpessimizing-move\"");
fLinkMonitor_ = move (optional<IO::Network::LinkMonitor> (move (lm)));
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wpessimizing-move\"");
}
Sequence<Advertisement> GetAdjustedAdvertisements_ () const
{
// @todo EXPLAIN THIS LOGIC? What its doing is - if NO LOCATION HOST SPECIFIED - picka good default (not so crazy) - but only
// in that case do we patch/replace the location for the advertisements? That makes little sense
if (fLocation.GetAuthority () and fLocation.GetAuthority ()->GetHost ()) {
return fAdvertisements;
}
else {
Sequence<Advertisement> revisedAdvertisements;
URI useURL = fLocation;
URI::Authority authority = useURL.GetAuthority ().value_or (URI::Authority{});
authority.SetHost (IO::Network::GetPrimaryInternetAddress ());
useURL.SetAuthority (authority);
for (auto ai : fAdvertisements) {
ai.fLocation = useURL; // !@todo MAYBE this would make more sense replacing just the HOST part of each advertisement?
revisedAdvertisements.Append (ai);
}
return revisedAdvertisements;
}
}
void StartNotifier_ ()
{
fNotifierThread_ = Thread::New (
[this] () {
PeriodicNotifier l;
l.Run (GetAdjustedAdvertisements_ (), PeriodicNotifier::FrequencyInfo ());
},
Thread::eAutoStart, String{L"SSDP Notifier"});
}
void StartResponder_ ()
{
fSearchResponderThread_ = Thread::New (
[this] () {
SearchResponder sr;
sr.Run (GetAdjustedAdvertisements_ ());
},
Thread::eAutoStart, String{L"SSDP Search Responder"});
}
void Restart_ ()
{
Debug::TraceContextBumper ctx ("Restarting Basic SSDP server threads");
{
Thread::SuppressInterruptionInContext suppressInterruption; // critical to wait til done cuz captures this
if (fNotifierThread_ != nullptr) {
fNotifierThread_.AbortAndWaitForDone ();
}
if (fSearchResponderThread_ != nullptr) {
fSearchResponderThread_.AbortAndWaitForDone ();
}
}
StartNotifier_ ();
StartResponder_ ();
}
Execution::Thread::CleanupPtr fNotifierThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
Execution::Thread::CleanupPtr fSearchResponderThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
optional<IO::Network::LinkMonitor> fLinkMonitor_; // optional so we can delete it first on shutdown (so no restart while stopping stuff)
};
/*
********************************************************************************
********************************** BasicServer *********************************
********************************************************************************
*/
BasicServer::BasicServer (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fRep_ (make_shared<Rep_> (d, dd, fi))
{
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright © 2018 Luxon Jean-Pierre
* https://gumichan01.github.io/
*
* This library is under the MIT license
*
* Luxon Jean-Pierre (Gumichan01)
* luxon.jean.pierre@gmail.com
*
*/
#ifndef UTF8_ITERATOR_HPP_INCLUDED
#define UTF8_ITERATOR_HPP_INCLUDED
/**
* @file utf8_iterator.hpp
* @brief This is a UTF-8 string library header
*/
class UTF8string;
/**
* @class UTF8iterator
* @brief Iterator on UTF8 string
*
* This class defines the iterator of UTF-8 string
*/
class UTF8iterator
{
size_t index = 0;
UTF8string data;
char& operator ->();
public:
/**
* @fn explicit UTF8iterator(const UTF8string& u) noexcept
* Build an iterator object using a UTF8string object
* @param u utf-8 string
*/
explicit UTF8iterator(const UTF8string& u) noexcept;
/**
* @fn UTF8iterator(const UTF8iterator& it) noexcept
* @param it The iterator to copy
*/
UTF8iterator(const UTF8iterator& it) noexcept;
/**
* @fn UTF8iterator& operator ++() noexcept
* Prefix incrementation
* @return The same iterator, but it has moved forward
*/
UTF8iterator& operator ++() noexcept;
/**
* @fn UTF8iterator& operator ++(int) noexcept
*
* Postfix incrementation
*
* @return The same iterator before it has moved forward
*/
UTF8iterator operator ++(int) noexcept;
/**
* @fn UTF8iterator& operator --() noexcept
* Prefix derementation
* @return The same iterator, but it has moved backward
*/
UTF8iterator& operator --() noexcept;
/**
* @fn UTF8iterator operator --(int) noexcept
*
* Postfix decrementation
*
* @return The same iterator before it has moved backward
*/
UTF8iterator operator --(int) noexcept;
/**
* @fn UTF8iterator& operator =(const UTF8iterator& it) noexcept
* Asignement
* @param it The iterator that wille be assigned
* @return The same iterator as the argument
*/
UTF8iterator& operator =(const UTF8iterator& it) noexcept;
/**
* @fn bool operator ==(const UTF8iterator& it) const noexcept
*
* Check if the current iterator is pointing to the same position as
* the iterator given in argument equals.
*
* @param it The iterator to compare with
* @return TRUE if they are pointing to the same position, FALSE otherwise
*/
bool operator ==(const UTF8iterator& it) const noexcept;
/**
* @fn bool operator !=(const UTF8iterator& it) const noexcept
*
* Check if the current iterator is pointing to a different position
* from the iterator given in argument equals.
*
* @param it The iterator to compare with
* @return TRUE if they are not pointing to the same position,
* FALSE otherwise
*/
bool operator !=(const UTF8iterator& it) const noexcept;
/**
* @fn UTF8iterator operator +(const size_t n) const noexcept
*
* Returns an iterator which has been moved n positions forward
*
* @param n the number of step to move forward
* @return The same iterator that moved forward
*/
UTF8iterator operator +(const size_t n) const noexcept;
/**
* @fn UTF8iterator operator -(const size_t n) const noexcept
*
* Returns an iterator which has been moved n positions backward
*
* @param n the number of steps to move backward
* @return The same iterator that moved backward
*/
UTF8iterator operator -(const size_t n) const noexcept;
/**
* @fn const std::string operator *() const
*
* Dereferences the pointer returning the codepoint
* pointed by the iterator at its current potision
*
* @return The codepoint
* @note This function will throw an *std::out_of_range* exception
* if the iterator does not point to a codepoint
*/
const std::string operator *() const;
~UTF8iterator() = default;
};
#endif // UTF8_ITERATOR_HPP_INCLUDED
<commit_msg>utf8iterator: remove the defeult constructor<commit_after>/*
*
* Copyright © 2018 Luxon Jean-Pierre
* https://gumichan01.github.io/
*
* This library is under the MIT license
*
* Luxon Jean-Pierre (Gumichan01)
* luxon.jean.pierre@gmail.com
*
*/
#ifndef UTF8_ITERATOR_HPP_INCLUDED
#define UTF8_ITERATOR_HPP_INCLUDED
/**
* @file utf8_iterator.hpp
* @brief This is a UTF-8 string library header
*/
class UTF8string;
/**
* @class UTF8iterator
* @brief Iterator on UTF8 string
*
* This class defines the iterator of UTF-8 string
*/
class UTF8iterator
{
size_t index = 0;
UTF8string data;
char& operator ->();
public:
UTF8iterator() = delete;
/**
* @fn explicit UTF8iterator(const UTF8string& u) noexcept
* Build an iterator object using a UTF8string object
* @param u utf-8 string
*/
explicit UTF8iterator(const UTF8string& u) noexcept;
/**
* @fn UTF8iterator(const UTF8iterator& it) noexcept
* @param it The iterator to copy
*/
UTF8iterator(const UTF8iterator& it) noexcept;
/**
* @fn UTF8iterator& operator ++() noexcept
* Prefix incrementation
* @return The same iterator, but it has moved forward
*/
UTF8iterator& operator ++() noexcept;
/**
* @fn UTF8iterator& operator ++(int) noexcept
*
* Postfix incrementation
*
* @return The same iterator before it has moved forward
*/
UTF8iterator operator ++(int) noexcept;
/**
* @fn UTF8iterator& operator --() noexcept
* Prefix derementation
* @return The same iterator, but it has moved backward
*/
UTF8iterator& operator --() noexcept;
/**
* @fn UTF8iterator operator --(int) noexcept
*
* Postfix decrementation
*
* @return The same iterator before it has moved backward
*/
UTF8iterator operator --(int) noexcept;
/**
* @fn UTF8iterator& operator =(const UTF8iterator& it) noexcept
* Asignement
* @param it The iterator that wille be assigned
* @return The same iterator as the argument
*/
UTF8iterator& operator =(const UTF8iterator& it) noexcept;
/**
* @fn bool operator ==(const UTF8iterator& it) const noexcept
*
* Check if the current iterator is pointing to the same position as
* the iterator given in argument equals.
*
* @param it The iterator to compare with
* @return TRUE if they are pointing to the same position, FALSE otherwise
*/
bool operator ==(const UTF8iterator& it) const noexcept;
/**
* @fn bool operator !=(const UTF8iterator& it) const noexcept
*
* Check if the current iterator is pointing to a different position
* from the iterator given in argument equals.
*
* @param it The iterator to compare with
* @return TRUE if they are not pointing to the same position,
* FALSE otherwise
*/
bool operator !=(const UTF8iterator& it) const noexcept;
/**
* @fn UTF8iterator operator +(const size_t n) const noexcept
*
* Returns an iterator which has been moved n positions forward
*
* @param n the number of step to move forward
* @return The same iterator that moved forward
*/
UTF8iterator operator +(const size_t n) const noexcept;
/**
* @fn UTF8iterator operator -(const size_t n) const noexcept
*
* Returns an iterator which has been moved n positions backward
*
* @param n the number of steps to move backward
* @return The same iterator that moved backward
*/
UTF8iterator operator -(const size_t n) const noexcept;
/**
* @fn const std::string operator *() const
*
* Dereferences the pointer returning the codepoint
* pointed by the iterator at its current potision
*
* @return The codepoint
* @note This function will throw an *std::out_of_range* exception
* if the iterator does not point to a codepoint
*/
const std::string operator *() const;
~UTF8iterator() = default;
};
#endif // UTF8_ITERATOR_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
What is our "Hello world!" app?
An agent orbits around the origin emitting the audio line input. The camera
view can be switched between a freely navigable keyboard/mouse controlled mode
and a sphere follow mode.
Requirements:
2 channels of spatial sound
2 windows, one front view, one back view
stereographic rendering
*/
#include "allocore/al_Allocore.hpp"
#include "al_NavControl.hpp"
using namespace al;
struct Agent : public SoundSource, public gfx::Drawable{
Agent()
: oscPhase(0)
{}
virtual ~Agent(){}
virtual void onProcess(AudioIOData& io){
while(io()){
//float s = io.in(0);
//float s = rnd::uniform(); // make noise, just to hear something
float s = sin(oscPhase * M_2PI);
//float s = phase * 2 - 1;
oscPhase += 440./io.framesPerSecond();
if(oscPhase >= 1) oscPhase -= 1;
writeSample(s*0.2);
}
}
virtual void onUpdateNav(){
smooth(0.9);
//if((phase+=0.01) >= M_2PI) phase -= M_2PI;
//pos(cos(phase), sin(phase), 0);
//pos(0,0,0);
spin(0.3, 0.011, 0.417);
//moveF(0.01);
step();
}
virtual void onDraw(gfx::Graphics& g){
g.pushMatrix();
g.multMatrix(matrix());
g.begin(gfx::TRIANGLES);
float ds = 0.5;
g.vertex( 0, 0, ds*2);
g.vertex( ds/2, 0,-ds);
g.vertex(-ds/2, 0,-ds);
g.color(1,1,1);
g.color(1,1,0);
g.color(1,0,1);
g.end();
g.popMatrix();
}
double oscPhase;
};
#define AUDIO_BLOCK_SIZE 256
AudioScene scene(3, 1, AUDIO_BLOCK_SIZE);
Listener * listener;
Nav navMaster(Vec3d(0,0,-4), 0.95);
std::vector<Agent> agents(1);
gfx::Stereographic stereo;
void audioCB(AudioIOData& io){
int numFrames = io.framesPerBuffer();
for(unsigned i=0; i<agents.size(); ++i){
io.frame(0);
agents[i].onUpdateNav();
agents[i].onProcess(io);
}
navMaster.step(0.5);
scene.encode(numFrames, io.framesPerSecond());
scene.render(&io.out(0,0), numFrames);
//printf("%g\n", io.out(0,0));
}
struct MyWindow : public Window, public gfx::Drawable{
MyWindow(): gl(new gfx::GraphicsBackendOpenGL){}
bool onFrame(){
Pose pose(navMaster * transform);
listener->pos(pose.pos());
gfx::Viewport vp(dimensions().w, dimensions().h);
stereo.draw(gl, cam, pose, vp, *this);
return true;
}
virtual void onDraw(gfx::Graphics& g){
for(unsigned i=0; i<agents.size(); ++i){
agents[i].onDraw(g);
}
}
gfx::Graphics gl;
Pose transform;
Camera cam;
};
int main (int argc, char * argv[]){
listener = &scene.createListener(2);
listener->speakerPos(0,0,-90);
listener->speakerPos(1,1, 90);
// listener->speakerPos(0,0,-45);
// listener->speakerPos(1,1, 45);
for(unsigned i=0; i<agents.size(); ++i) scene.addSource(agents[i]);
MyWindow windows[2];
for(int i=0; i<2; ++i){
windows[i].add(new StandardWindowKeyControls);
windows[i].add(new NavInputControl(&navMaster));
windows[i].create(Window::Dim(600,480,i*650), "Hello Virtual World!");
windows[i].transform.quat(Quatd::fromAxisAngle(i*180, 0, 1, 0));
}
AudioIO audioIO(AUDIO_BLOCK_SIZE, 44100, audioCB, 0, 2, 1);
audioIO.start();
MainLoop::start();
return 0;
}
<commit_msg>updated virtualworld<commit_after>/*
What is our "Hello world!" app?
An agent orbits around the origin emitting the audio line input. The camera
view can be switched between a freely navigable keyboard/mouse controlled mode
and a sphere follow mode.
Requirements:
2 channels of spatial sound
2 windows, one front view, one back view
stereographic rendering
*/
#include "allocore/al_Allocore.hpp"
#include "al_NavControl.hpp"
using namespace al;
struct Agent : public SoundSource, public gfx::Drawable{
Agent()
: oscPhase(0)
{}
virtual ~Agent(){}
virtual void onProcess(AudioIOData& io){
while(io()){
//float s = io.in(0);
//float s = rnd::uniform(); // make noise, just to hear something
float s = sin(oscPhase * M_2PI);
//float s = phase * 2 - 1;
oscPhase += 440./io.framesPerSecond();
if(oscPhase >= 1) oscPhase -= 1;
writeSample(s*1);
}
}
virtual void onUpdateNav(){
smooth(0.9);
//if((phase+=0.01) >= M_2PI) phase -= M_2PI;
//pos(cos(phase), sin(phase), 0);
//pos(0,0,0);
spin(0.3, 0.011, 0.417);
//moveF(0.01);
step();
}
virtual void onDraw(gfx::Graphics& g){
g.pushMatrix();
g.multMatrix(matrix());
g.begin(gfx::TRIANGLES);
float ds = 0.5;
g.vertex( 0, 0, ds*2);
g.vertex( ds/2, 0,-ds);
g.vertex(-ds/2, 0,-ds);
g.color(1,1,1);
g.color(1,1,0);
g.color(1,0,1);
g.end();
g.popMatrix();
}
double oscPhase;
};
#define AUDIO_BLOCK_SIZE 256
AudioScene scene(3, 1, AUDIO_BLOCK_SIZE);
Listener * listener;
Nav navMaster(Vec3d(0,0,-4), 0.95);
std::vector<Agent> agents(1);
gfx::Stereographic stereo;
void audioCB(AudioIOData& io){
int numFrames = io.framesPerBuffer();
for(unsigned i=0; i<agents.size(); ++i){
io.frame(0);
agents[i].onUpdateNav();
agents[i].onProcess(io);
}
navMaster.step(0.5);
listener->pos(navMaster.pos());
scene.encode(numFrames, io.framesPerSecond());
scene.render(&io.out(0,0), numFrames);
//printf("%g\n", io.out(0,0));
}
struct MyWindow : public Window, public gfx::Drawable{
MyWindow(): gl(new gfx::GraphicsBackendOpenGL){}
bool onFrame(){
Pose pose(navMaster * transform);
//listener->pos(pose.pos());
gfx::Viewport vp(dimensions().w, dimensions().h);
stereo.draw(gl, cam, pose, vp, *this);
return true;
}
bool onKeyDown(const Keyboard& k) {
if (k.key() == Key::Tab) {
stereo.stereo(!stereo.stereo());
}
return true;
}
virtual void onDraw(gfx::Graphics& g){
for(unsigned i=0; i<agents.size(); ++i){
agents[i].onDraw(g);
}
}
gfx::Graphics gl;
Pose transform;
Camera cam;
};
int main (int argc, char * argv[]){
listener = &scene.createListener(2);
listener->speakerPos(0,0,-90);
listener->speakerPos(1,1, 90);
// listener->speakerPos(0,0,-45);
// listener->speakerPos(1,1, 45);
for(unsigned i=0; i<agents.size(); ++i) scene.addSource(agents[i]);
MyWindow windows[2];
for(int i=0; i<2; ++i){
windows[i].add(new StandardWindowKeyControls);
windows[i].add(new NavInputControl(&navMaster));
windows[i].create(Window::Dim(600,480,i*650), "Hello Virtual World!");
windows[i].transform.quat(Quatd::fromAxisAngle(i*180, 0, 1, 0));
}
AudioIO audioIO(AUDIO_BLOCK_SIZE, 44100, audioCB, 0, 2, 1);
audioIO.start();
MainLoop::start();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_GRAPHICS_OBJECT_HPP
#define OUZEL_GRAPHICS_OBJECT_HPP
#include <memory>
#include "Material.hpp"
namespace ouzel::graphics
{
class Object final
{
public:
Object() = default;
Object(const Object&) = delete;
Object& operator=(const Object&) = delete;
Object(Object&&) = delete;
Object& operator=(Object&&) = delete;
const Material* material = nullptr;
};
}
#endif // OUZEL_GRAPHICS_OBJECT_HPP
<commit_msg>Add buffers and transform to Object<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_GRAPHICS_OBJECT_HPP
#define OUZEL_GRAPHICS_OBJECT_HPP
#include <memory>
#include "Buffer.hpp"
#include "Material.hpp"
#include "../math/Matrix.hpp"
namespace ouzel::graphics
{
class Object final
{
public:
Object() = default;
Object(const Object&) = delete;
Object& operator=(const Object&) = delete;
Object(Object&&) = delete;
Object& operator=(Object&&) = delete;
const Buffer* indexBuffer = nullptr;
const Buffer* vertexBuffer = nullptr;
const Material* material = nullptr;
Matrix4F transform;
};
}
#endif // OUZEL_GRAPHICS_OBJECT_HPP
<|endoftext|>
|
<commit_before><commit_msg>Set TOFChi2 to -1 in Run3 converter<commit_after><|endoftext|>
|
<commit_before>#include "stft_client_storage.h"
#include <cinder/CinderMath.h>
namespace cieq {
namespace stft {
ClientStorage::ClientStorage(const Client::Format& fmt)
: mFftSize(fmt.getFftSize())
, mWindowType(fmt.getWindowType())
, mWindowSize(fmt.getWindowSize())
, mChannelSize(fmt.getChannelSize())
, mSmoothingFactor(0.5f)
{
if (mFftSize < mWindowSize)
mFftSize = mWindowSize;
if (!ci::isPowerOf2(mFftSize))
mFftSize = ci::nextPowerOf2(static_cast<uint32_t>(mFftSize));
mFft = std::make_unique<ci::audio::dsp::Fft>(mFftSize);
mFftBuffer = ci::audio::Buffer(mFftSize, mChannelSize);
mCopiedBuffer = ci::audio::Buffer(mFftSize, mChannelSize);
mBufferSpectral = ci::audio::BufferSpectral(mFftSize);
mMagSpectrum.resize(mFftSize / 2);
if (!mWindowSize)
mWindowSize = mFftSize;
else if (!ci::isPowerOf2(mWindowSize))
mWindowSize = ci::nextPowerOf2(static_cast<uint32_t>(mWindowSize));
mWindowingTable = ci::audio::makeAlignedArray<float>(mWindowSize);
generateWindow(mWindowType, mWindowingTable.get(), mWindowSize);
}
}} //!cieq::stft<commit_msg>Some housekeeping here<commit_after>#include "stft_client_storage.h"
#include <cinder/CinderMath.h>
namespace cieq {
namespace stft {
ClientStorage::ClientStorage(const Client::Format& fmt)
: mFftSize(fmt.getFftSize())
, mWindowType(fmt.getWindowType())
, mWindowSize(fmt.getWindowSize())
, mChannelSize(fmt.getChannelSize())
, mSmoothingFactor(0.5f)
{
// There's no point of having FFT size of less than a window size!
if (mFftSize < mWindowSize)
mFftSize = mWindowSize;
// This makes sure that we are zero padding
mFftSize = ci::nextPowerOf2(static_cast<uint32_t>(mFftSize));
// The actual FFT processor instance
mFft = std::make_unique<ci::audio::dsp::Fft>(mFftSize);
// The FFT buffer, the one that will be filled AFTER FFT is performed on data
mFftBuffer = ci::audio::Buffer(mFftSize, mChannelSize);
// Copied buffer. the one that will be filled by raw audio chunks BEFORE FFT
mCopiedBuffer = ci::audio::Buffer(mFftSize, mChannelSize);
// Intermediate buffer passed to FFT processor
mBufferSpectral = ci::audio::BufferSpectral(mFftSize);
// The floating point array that contains all the FFT data, will be passed to renderer
mMagSpectrum.resize(mFftSize / 2);
// Window table.
mWindowingTable = ci::audio::makeAlignedArray<float>(mWindowSize);
generateWindow(mWindowType, mWindowingTable.get(), mWindowSize);
}
}} //!cieq::stft<|endoftext|>
|
<commit_before><commit_msg>Zastosowanie pętli c++11<commit_after><|endoftext|>
|
<commit_before>#include "../adapter.hpp"
#include "../values.hpp"
namespace rev {
value_t::p Vector_Printable_str(value_t::p self) {
auto v = as<vector_t>(self);
std::string s = "[";
if (auto fst = imu::first(v)) {
s += str(*fst);
imu::for_each([&](const value_t::p& v) {
auto str = rev::str(v);
s += " " + str;
}, imu::rest(v));
}
s += "]";
return imu::nu<string_t>(s);
}
value_t::p Vector_Seqable_seq(value_t::p self) {
auto v = as<vector_t>(self);
if (imu::count(v) > 0) {
return imu::nu<seq_adapter_t<vector_t>>(v);
}
return nullptr;
}
value_t::p Vector_Collection_conj(value_t::p self, value_t::p o) {
return imu::conj(as<vector_t>(self), o);
}
value_t::p Vector_Associative_contains_key(value_t::p self, value_t::p k) {
return sym_t::false_;
}
value_t::p Vector_Associative_assoc(
value_t::p self, value_t::p k, value_t::p val) {
auto v = as<vector_t>(self);
auto n = as<int_t>(k);
return imu::assoc(v, n->value, val);
}
value_t::p Vector_IIndexed_nth2(value_t::p self, value_t::p n) {
return as<vector_t>(self)->nth(as<int_t>(n)->value);
}
value_t::p Vector_IIndexed_nth3(value_t::p self, value_t::p n, value_t::p d) {
auto i = as<int_t>(n)->value;
auto v = as<vector_t>(self);
if (i >= 0 && i < imu::count(v)) {
return v->nth(i);
}
return d;
}
value_t::p Vector_Lookup_lookup2(value_t::p s, value_t::p k) {
return Vector_IIndexed_nth2(s, k);
}
value_t::p Vector_Lookup_lookup3(value_t::p s, value_t::p k, value_t::p d) {
return Vector_IIndexed_nth3(s, k, d);
}
value_t::p VectorSeq_Seqable_seq(value_t::p self) {
return self;
}
value_t::p VectorSeq_Seq_first(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
return seq->first();
}
return nullptr;
}
value_t::p VectorSeq_Seq_rest(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
if (auto rest = seq->rest()) {
return imu::nu<seq_adapter_t<vector_t>>(rest);
}
}
return nullptr;
}
value_t::p VectorSeq_Next_next(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
if (auto rest = seq->rest()) {
return imu::nu<seq_adapter_t<vector_t>>(rest);
}
}
return nullptr;
}
value_t::p Vector_MapEntry_key(value_t::p self) {
return as<vector_t>(self)->nth(0);
}
value_t::p Vector_MapEntry_val(value_t::p self) {
return as<vector_t>(self)->nth(1);
}
value_t::p Vector_Equiv_equiv(value_t::p self, value_t::p other) {
equal_to eq;
return imu::seqs::equiv(imu::seq(as<vector_t>(self)), rt_seq_t::seq(other), eq) ? sym_t::true_ : sym_t::false_;
}
struct type_t::impl_t Vector_printable[] = {
{0, (intptr_t) Vector_Printable_str, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_seqable[] = {
{0, (intptr_t) Vector_Seqable_seq, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_coll[] = {
{0, 0, (intptr_t) Vector_Collection_conj, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_associative[] = {
{0, 0, (intptr_t) Vector_Associative_contains_key, 0, 0, 0, 0, 0},
{0, 0, 0, (intptr_t) Vector_Associative_assoc, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_iindexed[] = {
{0, 0,
(intptr_t) Vector_IIndexed_nth2,
(intptr_t) Vector_IIndexed_nth3,
0, 0, 0, 0}
};
struct type_t::impl_t Vector_lookup[] = {
{0, 0,
(intptr_t) Vector_Lookup_lookup2,
(intptr_t) Vector_Lookup_lookup3,
0, 0, 0, 0}
};
struct type_t::impl_t Vector_mapentry[] = {
{0, (intptr_t) Vector_MapEntry_key, 0, 0, 0, 0, 0, 0},
{0, (intptr_t) Vector_MapEntry_val, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_equiv[] = {
{0, 0, (intptr_t) Vector_Equiv_equiv, 0, 0, 0, 0, 0},
};
struct type_t::impl_t VectorSeq_seqable[] = {
{0, (intptr_t) VectorSeq_Seqable_seq, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t VectorSeq_seq[] = {
{0, (intptr_t) VectorSeq_Seq_first, 0, 0, 0, 0, 0, 0},
{0, (intptr_t) VectorSeq_Seq_rest, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t VectorSeq_next[] = {
{0, (intptr_t) VectorSeq_Next_next, 0, 0, 0, 0, 0, 0}
};
struct type_t::ext_t Vector_methods[] = {
{protocol_t::str, Vector_printable},
{protocol_t::seqable, Vector_seqable},
{protocol_t::ivector, nullptr},
{protocol_t::coll, Vector_coll},
{protocol_t::associative, Vector_associative},
{protocol_t::indexed, Vector_iindexed},
{protocol_t::equiv, Vector_equiv}
{protocol_t::lookup, Vector_lookup},
{protocol_t::mapentry, Vector_mapentry}
};
struct type_t::ext_t VectorSeq_methods[] = {
{protocol_t::seqable, VectorSeq_seqable},
{protocol_t::seq, VectorSeq_seq},
{protocol_t::next, VectorSeq_next}
};
static const uint64_t vec_size =
sizeof(Vector_methods) / sizeof(Vector_methods[0]);
static const uint64_t seq_size =
sizeof(VectorSeq_methods) / sizeof(VectorSeq_methods[0]);
template<>
type_t value_base_t<vector_tag_t>::prototype(
"PersistentVector.0", Vector_methods, vec_size);
template<>
type_t value_base_t<seq_adapter_t<vector_t>>::prototype(
"VectorSeq.0", VectorSeq_methods, seq_size);
}
<commit_msg>Add missing ,<commit_after>#include "../adapter.hpp"
#include "../values.hpp"
namespace rev {
value_t::p Vector_Printable_str(value_t::p self) {
auto v = as<vector_t>(self);
std::string s = "[";
if (auto fst = imu::first(v)) {
s += str(*fst);
imu::for_each([&](const value_t::p& v) {
auto str = rev::str(v);
s += " " + str;
}, imu::rest(v));
}
s += "]";
return imu::nu<string_t>(s);
}
value_t::p Vector_Seqable_seq(value_t::p self) {
auto v = as<vector_t>(self);
if (imu::count(v) > 0) {
return imu::nu<seq_adapter_t<vector_t>>(v);
}
return nullptr;
}
value_t::p Vector_Collection_conj(value_t::p self, value_t::p o) {
return imu::conj(as<vector_t>(self), o);
}
value_t::p Vector_Associative_contains_key(value_t::p self, value_t::p k) {
return sym_t::false_;
}
value_t::p Vector_Associative_assoc(
value_t::p self, value_t::p k, value_t::p val) {
auto v = as<vector_t>(self);
auto n = as<int_t>(k);
return imu::assoc(v, n->value, val);
}
value_t::p Vector_IIndexed_nth2(value_t::p self, value_t::p n) {
return as<vector_t>(self)->nth(as<int_t>(n)->value);
}
value_t::p Vector_IIndexed_nth3(value_t::p self, value_t::p n, value_t::p d) {
auto i = as<int_t>(n)->value;
auto v = as<vector_t>(self);
if (i >= 0 && i < imu::count(v)) {
return v->nth(i);
}
return d;
}
value_t::p Vector_Lookup_lookup2(value_t::p s, value_t::p k) {
return Vector_IIndexed_nth2(s, k);
}
value_t::p Vector_Lookup_lookup3(value_t::p s, value_t::p k, value_t::p d) {
return Vector_IIndexed_nth3(s, k, d);
}
value_t::p VectorSeq_Seqable_seq(value_t::p self) {
return self;
}
value_t::p VectorSeq_Seq_first(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
return seq->first();
}
return nullptr;
}
value_t::p VectorSeq_Seq_rest(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
if (auto rest = seq->rest()) {
return imu::nu<seq_adapter_t<vector_t>>(rest);
}
}
return nullptr;
}
value_t::p VectorSeq_Next_next(value_t::p self) {
auto seq = as<seq_adapter_t<vector_t>>(self)->seq();
if (!imu::is_empty(seq)) {
if (auto rest = seq->rest()) {
return imu::nu<seq_adapter_t<vector_t>>(rest);
}
}
return nullptr;
}
value_t::p Vector_MapEntry_key(value_t::p self) {
return as<vector_t>(self)->nth(0);
}
value_t::p Vector_MapEntry_val(value_t::p self) {
return as<vector_t>(self)->nth(1);
}
value_t::p Vector_Equiv_equiv(value_t::p self, value_t::p other) {
equal_to eq;
return imu::seqs::equiv(imu::seq(as<vector_t>(self)), rt_seq_t::seq(other), eq) ? sym_t::true_ : sym_t::false_;
}
struct type_t::impl_t Vector_printable[] = {
{0, (intptr_t) Vector_Printable_str, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_seqable[] = {
{0, (intptr_t) Vector_Seqable_seq, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_coll[] = {
{0, 0, (intptr_t) Vector_Collection_conj, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_associative[] = {
{0, 0, (intptr_t) Vector_Associative_contains_key, 0, 0, 0, 0, 0},
{0, 0, 0, (intptr_t) Vector_Associative_assoc, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_iindexed[] = {
{0, 0,
(intptr_t) Vector_IIndexed_nth2,
(intptr_t) Vector_IIndexed_nth3,
0, 0, 0, 0}
};
struct type_t::impl_t Vector_lookup[] = {
{0, 0,
(intptr_t) Vector_Lookup_lookup2,
(intptr_t) Vector_Lookup_lookup3,
0, 0, 0, 0}
};
struct type_t::impl_t Vector_mapentry[] = {
{0, (intptr_t) Vector_MapEntry_key, 0, 0, 0, 0, 0, 0},
{0, (intptr_t) Vector_MapEntry_val, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t Vector_equiv[] = {
{0, 0, (intptr_t) Vector_Equiv_equiv, 0, 0, 0, 0, 0},
};
struct type_t::impl_t VectorSeq_seqable[] = {
{0, (intptr_t) VectorSeq_Seqable_seq, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t VectorSeq_seq[] = {
{0, (intptr_t) VectorSeq_Seq_first, 0, 0, 0, 0, 0, 0},
{0, (intptr_t) VectorSeq_Seq_rest, 0, 0, 0, 0, 0, 0}
};
struct type_t::impl_t VectorSeq_next[] = {
{0, (intptr_t) VectorSeq_Next_next, 0, 0, 0, 0, 0, 0}
};
struct type_t::ext_t Vector_methods[] = {
{protocol_t::str, Vector_printable},
{protocol_t::seqable, Vector_seqable},
{protocol_t::ivector, nullptr},
{protocol_t::coll, Vector_coll},
{protocol_t::associative, Vector_associative},
{protocol_t::indexed, Vector_iindexed},
{protocol_t::equiv, Vector_equiv},
{protocol_t::lookup, Vector_lookup},
{protocol_t::mapentry, Vector_mapentry}
};
struct type_t::ext_t VectorSeq_methods[] = {
{protocol_t::seqable, VectorSeq_seqable},
{protocol_t::seq, VectorSeq_seq},
{protocol_t::next, VectorSeq_next}
};
static const uint64_t vec_size =
sizeof(Vector_methods) / sizeof(Vector_methods[0]);
static const uint64_t seq_size =
sizeof(VectorSeq_methods) / sizeof(VectorSeq_methods[0]);
template<>
type_t value_base_t<vector_tag_t>::prototype(
"PersistentVector.0", Vector_methods, vec_size);
template<>
type_t value_base_t<seq_adapter_t<vector_t>>::prototype(
"VectorSeq.0", VectorSeq_methods, seq_size);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
#include "sync/impl/sync_file.hpp"
#include "util/time.hpp"
#include <realm/util/file.hpp>
#include <realm/util/scope_exit.hpp>
#include <iomanip>
#include <sstream>
#include <system_error>
#include <fstream>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
inline static int mkstemp(char* _template) { return _open(_mktemp(_template), _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE); }
#else
#include <unistd.h>
#endif
using File = realm::util::File;
namespace realm {
namespace {
uint8_t value_of_hex_digit(char hex_digit)
{
if (hex_digit >= '0' && hex_digit <= '9') {
return hex_digit - '0';
} else if (hex_digit >= 'A' && hex_digit <= 'F') {
return 10 + hex_digit - 'A';
} else if (hex_digit >= 'a' && hex_digit <= 'f') {
return 10 + hex_digit - 'a';
} else {
throw std::invalid_argument("Cannot get the value of a character that isn't a hex digit.");
}
}
bool filename_is_reserved(const std::string& filename) {
return (filename == "." || filename == "..");
}
bool character_is_unreserved(char character)
{
bool is_capital_letter = (character >= 'A' && character <= 'Z');
bool is_lowercase_letter = (character >= 'a' && character <= 'z');
bool is_number = (character >= '0' && character <= '9');
bool is_allowed_symbol = (character == '-' || character == '_' || character == '.');
return is_capital_letter || is_lowercase_letter || is_number || is_allowed_symbol;
}
char decoded_char_for(const std::string& percent_encoding, size_t index)
{
if (index+2 >= percent_encoding.length()) {
throw std::invalid_argument("Malformed string: not enough characters after '%' before end of string.");
}
REALM_ASSERT(percent_encoding[index] == '%');
return (16*value_of_hex_digit(percent_encoding[index + 1])) + value_of_hex_digit(percent_encoding[index + 2]);
}
} // (anonymous namespace)
namespace util {
std::string make_percent_encoded_string(const std::string& raw_string)
{
std::string buffer;
buffer.reserve(raw_string.size());
for (size_t i=0; i<raw_string.size(); i++) {
unsigned char character = raw_string[i];
if (character_is_unreserved(character)) {
buffer.push_back(character);
} else {
buffer.resize(buffer.size() + 3);
// Format string must resolve to exactly 3 characters.
sprintf(&buffer.back() - 2, "%%%2X", character);
}
}
return buffer;
}
std::string make_raw_string(const std::string& percent_encoded_string)
{
std::string buffer;
size_t input_len = percent_encoded_string.length();
buffer.reserve(input_len);
size_t idx = 0;
while (idx < input_len) {
char current = percent_encoded_string[idx];
if (current == '%') {
// Decode. +3.
buffer.push_back(decoded_char_for(percent_encoded_string, idx));
idx += 3;
} else {
// No need to decode. +1.
if (!character_is_unreserved(current)) {
throw std::invalid_argument("Input string is invalid: contains reserved characters.");
}
buffer.push_back(current);
idx++;
}
}
return buffer;
}
std::string file_path_by_appending_component(const std::string& path, const std::string& component, FilePathType path_type)
{
// FIXME: Does this have to be changed to accomodate Windows platforms?
std::string buffer;
buffer.reserve(2 + path.length() + component.length());
buffer.append(path);
std::string terminal = "";
if (path_type == FilePathType::Directory && component[component.length() - 1] != '/') {
terminal = "/";
}
char path_last = path[path.length() - 1];
char component_first = component[0];
if (path_last == '/' && component_first == '/') {
buffer.append(component.substr(1));
buffer.append(terminal);
} else if (path_last == '/' || component_first == '/') {
buffer.append(component);
buffer.append(terminal);
} else {
buffer.append("/");
buffer.append(component);
buffer.append(terminal);
}
return buffer;
}
std::string file_path_by_appending_extension(const std::string& path, const std::string& extension)
{
std::string buffer;
buffer.reserve(1 + path.length() + extension.length());
buffer.append(path);
char path_last = path[path.length() - 1];
char extension_first = extension[0];
if (path_last == '.' && extension_first == '.') {
buffer.append(extension.substr(1));
} else if (path_last == '.' || extension_first == '.') {
buffer.append(extension);
} else {
buffer.append(".");
buffer.append(extension);
}
return buffer;
}
std::string create_timestamped_template(const std::string& prefix, int wildcard_count)
{
constexpr int WILDCARD_MAX = 20;
constexpr int WILDCARD_MIN = 6;
wildcard_count = std::min(WILDCARD_MAX, std::max(WILDCARD_MIN, wildcard_count));
std::time_t time = std::time(nullptr);
std::stringstream stream;
stream << prefix << "-" << util::put_time(time, "%Y%m%d-%H%M%S") << "-" << std::string(wildcard_count, 'X');
return stream.str();
}
std::string reserve_unique_file_name(const std::string& path, const std::string& template_string)
{
REALM_ASSERT_DEBUG(template_string.find("XXXXXX") != std::string::npos);
std::string path_buffer = file_path_by_appending_component(path, template_string, FilePathType::File);
int fd = mkstemp(&path_buffer[0]);
if (fd < 0) {
int err = errno;
throw std::system_error(err, std::system_category());
}
// Remove the file so we can use the name for our own file.
close(fd);
unlink(path_buffer.c_str());
return path_buffer;
}
} // util
constexpr const char SyncFileManager::c_sync_directory[];
constexpr const char SyncFileManager::c_utility_directory[];
constexpr const char SyncFileManager::c_recovery_directory[];
constexpr const char SyncFileManager::c_metadata_directory[];
constexpr const char SyncFileManager::c_metadata_realm[];
constexpr const char SyncFileManager::c_user_info_file[];
std::string SyncFileManager::get_special_directory(std::string directory_name) const
{
auto dir_path = file_path_by_appending_component(get_base_sync_directory(),
directory_name,
util::FilePathType::Directory);
util::try_make_dir(dir_path);
return dir_path;
}
std::string SyncFileManager::get_base_sync_directory() const
{
auto sync_path = file_path_by_appending_component(m_base_path,
c_sync_directory,
util::FilePathType::Directory);
util::try_make_dir(sync_path);
return sync_path;
}
std::string SyncFileManager::user_directory(const std::string& local_identity,
util::Optional<SyncUserIdentifier> user_info) const
{
REALM_ASSERT(local_identity.length() > 0);
std::string escaped = util::make_percent_encoded_string(local_identity);
if (filename_is_reserved(escaped))
throw std::invalid_argument("A user can't have an identifier reserved by the filesystem.");
auto user_path = file_path_by_appending_component(get_base_sync_directory(),
escaped,
util::FilePathType::Directory);
bool dir_created = util::try_make_dir(user_path);
if (dir_created && user_info) {
// Add a text file in the user directory containing the user identity, for backup purposes.
// Only do this the first time the directory is created.
auto info_path = util::file_path_by_appending_component(user_path, c_user_info_file);
std::ofstream info_file;
info_file.open(info_path.c_str());
if (info_file.is_open()) {
info_file << user_info->user_id << "\n" << user_info->auth_server_url << "\n";
info_file.close();
}
}
return user_path;
}
void SyncFileManager::remove_user_directory(const std::string& local_identity) const
{
REALM_ASSERT(local_identity.length() > 0);
const auto& escaped = util::make_percent_encoded_string(local_identity);
if (filename_is_reserved(escaped))
throw std::invalid_argument("A user can't have an identifier reserved by the filesystem.");
auto user_path = file_path_by_appending_component(get_base_sync_directory(),
escaped,
util::FilePathType::Directory);
util::try_remove_dir_recursive(user_path);
}
bool SyncFileManager::try_rename_user_directory(const std::string& old_name, const std::string& new_name) const
{
REALM_ASSERT_DEBUG(old_name.length() > 0 && new_name.length() > 0);
const auto& old_name_escaped = util::make_percent_encoded_string(old_name);
const auto& new_name_escaped = util::make_percent_encoded_string(new_name);
const std::string& base = get_base_sync_directory();
if (filename_is_reserved(old_name_escaped) || filename_is_reserved(new_name_escaped))
throw std::invalid_argument("A user directory can't be renamed using a reserved identifier.");
const auto& old_path = file_path_by_appending_component(base, old_name_escaped, util::FilePathType::Directory);
const auto& new_path = file_path_by_appending_component(base, new_name_escaped, util::FilePathType::Directory);
try {
File::move(old_path, new_path);
} catch (File::NotFound const&) {
return false;
}
return true;
}
bool SyncFileManager::remove_realm(const std::string& absolute_path) const
{
REALM_ASSERT(absolute_path.length() > 0);
bool success = true;
// Remove the Realm file (e.g. "example.realm").
success = File::try_remove(absolute_path);
// Remove the lock file (e.g. "example.realm.lock").
auto lock_path = util::file_path_by_appending_extension(absolute_path, "lock");
success = File::try_remove(lock_path);
// Remove the management directory (e.g. "example.realm.management").
auto management_path = util::file_path_by_appending_extension(absolute_path, "management");
try {
util::try_remove_dir_recursive(management_path);
}
catch (File::AccessError const&) {
success = false;
}
return success;
}
bool SyncFileManager::copy_realm_file(const std::string& old_path, const std::string& new_path) const
{
REALM_ASSERT(old_path.length() > 0);
try {
if (File::exists(new_path)) {
return false;
}
File::copy(old_path, new_path);
}
catch (File::NotFound const&) {
return false;
}
catch (File::AccessError const&) {
return false;
}
return true;
}
bool SyncFileManager::remove_realm(const std::string& local_identity, const std::string& raw_realm_path) const
{
REALM_ASSERT(local_identity.length() > 0);
REALM_ASSERT(raw_realm_path.length() > 0);
if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path))
throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem.");
auto escaped = util::make_percent_encoded_string(raw_realm_path);
auto realm_path = util::file_path_by_appending_component(user_directory(local_identity), escaped);
return remove_realm(realm_path);
}
std::string SyncFileManager::path(const std::string& local_identity, const std::string& raw_realm_path,
util::Optional<SyncUserIdentifier> user_info) const
{
REALM_ASSERT(local_identity.length() > 0);
REALM_ASSERT(raw_realm_path.length() > 0);
if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path))
throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem.");
auto escaped = util::make_percent_encoded_string(raw_realm_path);
auto realm_path = util::file_path_by_appending_component(user_directory(local_identity, user_info), escaped);
return realm_path;
}
std::string SyncFileManager::metadata_path() const
{
auto dir_path = file_path_by_appending_component(get_utility_directory(),
c_metadata_directory,
util::FilePathType::Directory);
util::try_make_dir(dir_path);
return util::file_path_by_appending_component(dir_path, c_metadata_realm);
}
bool SyncFileManager::remove_metadata_realm() const
{
auto dir_path = file_path_by_appending_component(get_utility_directory(),
c_metadata_directory,
util::FilePathType::Directory);
try {
util::try_remove_dir_recursive(dir_path);
return true;
}
catch (File::AccessError const&) {
return false;
}
}
} // realm
<commit_msg>Don't use POSIX on Windows (#619)<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
#include "sync/impl/sync_file.hpp"
#include "util/time.hpp"
#include <realm/util/file.hpp>
#include <realm/util/scope_exit.hpp>
#include <iomanip>
#include <sstream>
#include <system_error>
#include <fstream>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
inline static int mkstemp(char* _template) { return _open(_mktemp(_template), _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE); }
#else
#include <unistd.h>
#endif
using File = realm::util::File;
namespace realm {
namespace {
uint8_t value_of_hex_digit(char hex_digit)
{
if (hex_digit >= '0' && hex_digit <= '9') {
return hex_digit - '0';
} else if (hex_digit >= 'A' && hex_digit <= 'F') {
return 10 + hex_digit - 'A';
} else if (hex_digit >= 'a' && hex_digit <= 'f') {
return 10 + hex_digit - 'a';
} else {
throw std::invalid_argument("Cannot get the value of a character that isn't a hex digit.");
}
}
bool filename_is_reserved(const std::string& filename) {
return (filename == "." || filename == "..");
}
bool character_is_unreserved(char character)
{
bool is_capital_letter = (character >= 'A' && character <= 'Z');
bool is_lowercase_letter = (character >= 'a' && character <= 'z');
bool is_number = (character >= '0' && character <= '9');
bool is_allowed_symbol = (character == '-' || character == '_' || character == '.');
return is_capital_letter || is_lowercase_letter || is_number || is_allowed_symbol;
}
char decoded_char_for(const std::string& percent_encoding, size_t index)
{
if (index+2 >= percent_encoding.length()) {
throw std::invalid_argument("Malformed string: not enough characters after '%' before end of string.");
}
REALM_ASSERT(percent_encoding[index] == '%');
return (16*value_of_hex_digit(percent_encoding[index + 1])) + value_of_hex_digit(percent_encoding[index + 2]);
}
} // (anonymous namespace)
namespace util {
std::string make_percent_encoded_string(const std::string& raw_string)
{
std::string buffer;
buffer.reserve(raw_string.size());
for (size_t i=0; i<raw_string.size(); i++) {
unsigned char character = raw_string[i];
if (character_is_unreserved(character)) {
buffer.push_back(character);
} else {
buffer.resize(buffer.size() + 3);
// Format string must resolve to exactly 3 characters.
sprintf(&buffer.back() - 2, "%%%2X", character);
}
}
return buffer;
}
std::string make_raw_string(const std::string& percent_encoded_string)
{
std::string buffer;
size_t input_len = percent_encoded_string.length();
buffer.reserve(input_len);
size_t idx = 0;
while (idx < input_len) {
char current = percent_encoded_string[idx];
if (current == '%') {
// Decode. +3.
buffer.push_back(decoded_char_for(percent_encoded_string, idx));
idx += 3;
} else {
// No need to decode. +1.
if (!character_is_unreserved(current)) {
throw std::invalid_argument("Input string is invalid: contains reserved characters.");
}
buffer.push_back(current);
idx++;
}
}
return buffer;
}
std::string file_path_by_appending_component(const std::string& path, const std::string& component, FilePathType path_type)
{
// FIXME: Does this have to be changed to accomodate Windows platforms?
std::string buffer;
buffer.reserve(2 + path.length() + component.length());
buffer.append(path);
std::string terminal = "";
if (path_type == FilePathType::Directory && component[component.length() - 1] != '/') {
terminal = "/";
}
char path_last = path[path.length() - 1];
char component_first = component[0];
if (path_last == '/' && component_first == '/') {
buffer.append(component.substr(1));
buffer.append(terminal);
} else if (path_last == '/' || component_first == '/') {
buffer.append(component);
buffer.append(terminal);
} else {
buffer.append("/");
buffer.append(component);
buffer.append(terminal);
}
return buffer;
}
std::string file_path_by_appending_extension(const std::string& path, const std::string& extension)
{
std::string buffer;
buffer.reserve(1 + path.length() + extension.length());
buffer.append(path);
char path_last = path[path.length() - 1];
char extension_first = extension[0];
if (path_last == '.' && extension_first == '.') {
buffer.append(extension.substr(1));
} else if (path_last == '.' || extension_first == '.') {
buffer.append(extension);
} else {
buffer.append(".");
buffer.append(extension);
}
return buffer;
}
std::string create_timestamped_template(const std::string& prefix, int wildcard_count)
{
constexpr int WILDCARD_MAX = 20;
constexpr int WILDCARD_MIN = 6;
wildcard_count = std::min(WILDCARD_MAX, std::max(WILDCARD_MIN, wildcard_count));
std::time_t time = std::time(nullptr);
std::stringstream stream;
stream << prefix << "-" << util::put_time(time, "%Y%m%d-%H%M%S") << "-" << std::string(wildcard_count, 'X');
return stream.str();
}
std::string reserve_unique_file_name(const std::string& path, const std::string& template_string)
{
REALM_ASSERT_DEBUG(template_string.find("XXXXXX") != std::string::npos);
std::string path_buffer = file_path_by_appending_component(path, template_string, FilePathType::File);
int fd = mkstemp(&path_buffer[0]);
if (fd < 0) {
int err = errno;
throw std::system_error(err, std::system_category());
}
// Remove the file so we can use the name for our own file.
#ifdef _WIN32
_close(fd);
_unlink(path_buffer.c_str());
#else
close(fd);
unlink(path_buffer.c_str());
#endif
return path_buffer;
}
} // util
constexpr const char SyncFileManager::c_sync_directory[];
constexpr const char SyncFileManager::c_utility_directory[];
constexpr const char SyncFileManager::c_recovery_directory[];
constexpr const char SyncFileManager::c_metadata_directory[];
constexpr const char SyncFileManager::c_metadata_realm[];
constexpr const char SyncFileManager::c_user_info_file[];
std::string SyncFileManager::get_special_directory(std::string directory_name) const
{
auto dir_path = file_path_by_appending_component(get_base_sync_directory(),
directory_name,
util::FilePathType::Directory);
util::try_make_dir(dir_path);
return dir_path;
}
std::string SyncFileManager::get_base_sync_directory() const
{
auto sync_path = file_path_by_appending_component(m_base_path,
c_sync_directory,
util::FilePathType::Directory);
util::try_make_dir(sync_path);
return sync_path;
}
std::string SyncFileManager::user_directory(const std::string& local_identity,
util::Optional<SyncUserIdentifier> user_info) const
{
REALM_ASSERT(local_identity.length() > 0);
std::string escaped = util::make_percent_encoded_string(local_identity);
if (filename_is_reserved(escaped))
throw std::invalid_argument("A user can't have an identifier reserved by the filesystem.");
auto user_path = file_path_by_appending_component(get_base_sync_directory(),
escaped,
util::FilePathType::Directory);
bool dir_created = util::try_make_dir(user_path);
if (dir_created && user_info) {
// Add a text file in the user directory containing the user identity, for backup purposes.
// Only do this the first time the directory is created.
auto info_path = util::file_path_by_appending_component(user_path, c_user_info_file);
std::ofstream info_file;
info_file.open(info_path.c_str());
if (info_file.is_open()) {
info_file << user_info->user_id << "\n" << user_info->auth_server_url << "\n";
info_file.close();
}
}
return user_path;
}
void SyncFileManager::remove_user_directory(const std::string& local_identity) const
{
REALM_ASSERT(local_identity.length() > 0);
const auto& escaped = util::make_percent_encoded_string(local_identity);
if (filename_is_reserved(escaped))
throw std::invalid_argument("A user can't have an identifier reserved by the filesystem.");
auto user_path = file_path_by_appending_component(get_base_sync_directory(),
escaped,
util::FilePathType::Directory);
util::try_remove_dir_recursive(user_path);
}
bool SyncFileManager::try_rename_user_directory(const std::string& old_name, const std::string& new_name) const
{
REALM_ASSERT_DEBUG(old_name.length() > 0 && new_name.length() > 0);
const auto& old_name_escaped = util::make_percent_encoded_string(old_name);
const auto& new_name_escaped = util::make_percent_encoded_string(new_name);
const std::string& base = get_base_sync_directory();
if (filename_is_reserved(old_name_escaped) || filename_is_reserved(new_name_escaped))
throw std::invalid_argument("A user directory can't be renamed using a reserved identifier.");
const auto& old_path = file_path_by_appending_component(base, old_name_escaped, util::FilePathType::Directory);
const auto& new_path = file_path_by_appending_component(base, new_name_escaped, util::FilePathType::Directory);
try {
File::move(old_path, new_path);
} catch (File::NotFound const&) {
return false;
}
return true;
}
bool SyncFileManager::remove_realm(const std::string& absolute_path) const
{
REALM_ASSERT(absolute_path.length() > 0);
bool success = true;
// Remove the Realm file (e.g. "example.realm").
success = File::try_remove(absolute_path);
// Remove the lock file (e.g. "example.realm.lock").
auto lock_path = util::file_path_by_appending_extension(absolute_path, "lock");
success = File::try_remove(lock_path);
// Remove the management directory (e.g. "example.realm.management").
auto management_path = util::file_path_by_appending_extension(absolute_path, "management");
try {
util::try_remove_dir_recursive(management_path);
}
catch (File::AccessError const&) {
success = false;
}
return success;
}
bool SyncFileManager::copy_realm_file(const std::string& old_path, const std::string& new_path) const
{
REALM_ASSERT(old_path.length() > 0);
try {
if (File::exists(new_path)) {
return false;
}
File::copy(old_path, new_path);
}
catch (File::NotFound const&) {
return false;
}
catch (File::AccessError const&) {
return false;
}
return true;
}
bool SyncFileManager::remove_realm(const std::string& local_identity, const std::string& raw_realm_path) const
{
REALM_ASSERT(local_identity.length() > 0);
REALM_ASSERT(raw_realm_path.length() > 0);
if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path))
throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem.");
auto escaped = util::make_percent_encoded_string(raw_realm_path);
auto realm_path = util::file_path_by_appending_component(user_directory(local_identity), escaped);
return remove_realm(realm_path);
}
std::string SyncFileManager::path(const std::string& local_identity, const std::string& raw_realm_path,
util::Optional<SyncUserIdentifier> user_info) const
{
REALM_ASSERT(local_identity.length() > 0);
REALM_ASSERT(raw_realm_path.length() > 0);
if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path))
throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem.");
auto escaped = util::make_percent_encoded_string(raw_realm_path);
auto realm_path = util::file_path_by_appending_component(user_directory(local_identity, user_info), escaped);
return realm_path;
}
std::string SyncFileManager::metadata_path() const
{
auto dir_path = file_path_by_appending_component(get_utility_directory(),
c_metadata_directory,
util::FilePathType::Directory);
util::try_make_dir(dir_path);
return util::file_path_by_appending_component(dir_path, c_metadata_realm);
}
bool SyncFileManager::remove_metadata_realm() const
{
auto dir_path = file_path_by_appending_component(get_utility_directory(),
c_metadata_directory,
util::FilePathType::Directory);
try {
util::try_remove_dir_recursive(dir_path);
return true;
}
catch (File::AccessError const&) {
return false;
}
}
} // realm
<|endoftext|>
|
<commit_before>// @(#)root/thread:$Id$
// Authors: Enric Tejedor, Enrico Guiraud CERN 05/06/2018
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TTreeProcessorMT
#define ROOT_TTreeProcessorMT
#include "TKey.h"
#include "TTree.h"
#include "TFile.h"
#include "TChain.h"
#include "TEntryList.h"
#include "TTreeReader.h"
#include "TError.h"
#include "TEntryList.h"
#include "TFriendElement.h"
#include "ROOT/RMakeUnique.hxx"
#include "ROOT/TThreadedObject.hxx"
#include "ROOT/TThreadExecutor.hxx"
#include <functional>
#include <utility> // std::pair
#include <vector>
/** \class TTreeView
\brief A helper class that encapsulates a file and a tree.
A helper class that encapsulates a TFile and a TTree, along with their names.
It is used together with TTProcessor and ROOT::TThreadedObject, so that
in the TTProcessor::Process method each thread can work on its own
<TFile,TTree> pair.
This class can also be used with a collection of file names or a TChain, in case
the tree is stored in more than one file. A view will always contain only the
current (active) tree and file objects.
A copy constructor is defined for TTreeView to work with ROOT::TThreadedObject.
The latter makes a copy of a model object every time a new thread accesses
the threaded object.
*/
namespace ROOT {
namespace Internal {
/// Names, aliases, and file names of a TTree's or TChain's friends
using NameAlias = std::pair<std::string, std::string>;
struct FriendInfo {
/// Pairs of names and aliases of friend trees/chains
std::vector<Internal::NameAlias> fFriendNames;
/// Names of the files where each friend is stored. fFriendFileNames[i] is the list of files for friend with
/// name fFriendNames[i]
std::vector<std::vector<std::string>> fFriendFileNames;
};
class TTreeView {
private:
std::vector<std::unique_ptr<TChain>> fFriends; ///< Friends of the tree/chain, if present
std::unique_ptr<TEntryList> fEntryList; ///< TEntryList for fChain, if present
// NOTE: fFriends and fEntryList MUST come before fChain to be deleted after it, because neither friend trees nor
// entrylists are deregistered from the main tree at destruction (ROOT-9283 tracks the issue for friends).
std::unique_ptr<TChain> fChain; ///< Chain on which to operate
void MakeChain(const std::vector<std::string> &treeName, const std::vector<std::string> &fileNames,
const FriendInfo &friendInfo, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries);
public:
TTreeView() = default;
// no-op, we don't want to copy the local TChains
TTreeView(const TTreeView &) {}
std::unique_ptr<TTreeReader> GetTreeReader(Long64_t start, Long64_t end, const std::vector<std::string> &treeName,
const std::vector<std::string> &fileNames, const FriendInfo &friendInfo,
const TEntryList &entryList, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries);
};
} // End of namespace Internal
class TTreeProcessorMT {
private:
const std::vector<std::string> fFileNames; ///< Names of the files
const std::vector<std::string> fTreeNames; ///< TTree names (always same size and ordering as fFileNames)
/// User-defined selection of entry numbers to be processed, empty if none was provided
TEntryList fEntryList;
const Internal::FriendInfo fFriendInfo;
ROOT::TThreadExecutor fPool; ///<! Thread pool for processing.
/// Thread-local TreeViews
// Must be declared after fPool, for IMT to be initialized first!
ROOT::TThreadedObject<ROOT::Internal::TTreeView> fTreeView{TNumSlots{ROOT::GetThreadPoolSize()}};
Internal::FriendInfo GetFriendInfo(TTree &tree);
std::vector<std::string> FindTreeNames();
static unsigned int fgMaxTasksPerFilePerWorker;
static unsigned int fgTasksPerWorkerHint;
public:
TTreeProcessorMT(std::string_view filename, std::string_view treename = "", UInt_t nThreads = 0u);
TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename = "",
UInt_t nThreads = 0u);
TTreeProcessorMT(TTree &tree, const TEntryList &entries, UInt_t nThreads = 0u);
TTreeProcessorMT(TTree &tree, UInt_t nThreads = 0u);
void Process(std::function<void(TTreeReader &)> func);
static void SetMaxTasksPerFilePerWorker(unsigned int m);
static unsigned int GetMaxTasksPerFilePerWorker();
static void SetTasksPerWorkerHint(unsigned int m);
static unsigned int GetTasksPerWorkerHint();
};
} // End of namespace ROOT
#endif // defined TTreeProcessorMT
<commit_msg>[TreeProcMT] Deprecate {G,S}etMaxTasksPerFilePerWorker<commit_after>// @(#)root/thread:$Id$
// Authors: Enric Tejedor, Enrico Guiraud CERN 05/06/2018
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TTreeProcessorMT
#define ROOT_TTreeProcessorMT
#include "TKey.h"
#include "TTree.h"
#include "TFile.h"
#include "TChain.h"
#include "TEntryList.h"
#include "TTreeReader.h"
#include "TError.h"
#include "TEntryList.h"
#include "TFriendElement.h"
#include "ROOT/RMakeUnique.hxx"
#include "ROOT/TThreadedObject.hxx"
#include "ROOT/TThreadExecutor.hxx"
#include <functional>
#include <utility> // std::pair
#include <vector>
/** \class TTreeView
\brief A helper class that encapsulates a file and a tree.
A helper class that encapsulates a TFile and a TTree, along with their names.
It is used together with TTProcessor and ROOT::TThreadedObject, so that
in the TTProcessor::Process method each thread can work on its own
<TFile,TTree> pair.
This class can also be used with a collection of file names or a TChain, in case
the tree is stored in more than one file. A view will always contain only the
current (active) tree and file objects.
A copy constructor is defined for TTreeView to work with ROOT::TThreadedObject.
The latter makes a copy of a model object every time a new thread accesses
the threaded object.
*/
namespace ROOT {
namespace Internal {
/// Names, aliases, and file names of a TTree's or TChain's friends
using NameAlias = std::pair<std::string, std::string>;
struct FriendInfo {
/// Pairs of names and aliases of friend trees/chains
std::vector<Internal::NameAlias> fFriendNames;
/// Names of the files where each friend is stored. fFriendFileNames[i] is the list of files for friend with
/// name fFriendNames[i]
std::vector<std::vector<std::string>> fFriendFileNames;
};
class TTreeView {
private:
std::vector<std::unique_ptr<TChain>> fFriends; ///< Friends of the tree/chain, if present
std::unique_ptr<TEntryList> fEntryList; ///< TEntryList for fChain, if present
// NOTE: fFriends and fEntryList MUST come before fChain to be deleted after it, because neither friend trees nor
// entrylists are deregistered from the main tree at destruction (ROOT-9283 tracks the issue for friends).
std::unique_ptr<TChain> fChain; ///< Chain on which to operate
void MakeChain(const std::vector<std::string> &treeName, const std::vector<std::string> &fileNames,
const FriendInfo &friendInfo, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries);
public:
TTreeView() = default;
// no-op, we don't want to copy the local TChains
TTreeView(const TTreeView &) {}
std::unique_ptr<TTreeReader> GetTreeReader(Long64_t start, Long64_t end, const std::vector<std::string> &treeName,
const std::vector<std::string> &fileNames, const FriendInfo &friendInfo,
const TEntryList &entryList, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries);
};
} // End of namespace Internal
class TTreeProcessorMT {
private:
const std::vector<std::string> fFileNames; ///< Names of the files
const std::vector<std::string> fTreeNames; ///< TTree names (always same size and ordering as fFileNames)
/// User-defined selection of entry numbers to be processed, empty if none was provided
TEntryList fEntryList;
const Internal::FriendInfo fFriendInfo;
ROOT::TThreadExecutor fPool; ///<! Thread pool for processing.
/// Thread-local TreeViews
// Must be declared after fPool, for IMT to be initialized first!
ROOT::TThreadedObject<ROOT::Internal::TTreeView> fTreeView{TNumSlots{ROOT::GetThreadPoolSize()}};
Internal::FriendInfo GetFriendInfo(TTree &tree);
std::vector<std::string> FindTreeNames();
static unsigned int fgMaxTasksPerFilePerWorker;
static unsigned int fgTasksPerWorkerHint;
public:
TTreeProcessorMT(std::string_view filename, std::string_view treename = "", UInt_t nThreads = 0u);
TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename = "",
UInt_t nThreads = 0u);
TTreeProcessorMT(TTree &tree, const TEntryList &entries, UInt_t nThreads = 0u);
TTreeProcessorMT(TTree &tree, UInt_t nThreads = 0u);
void Process(std::function<void(TTreeReader &)> func);
R__DEPRECATED(6, 26, "Please use SetTasksPerWorkerHint instead. This setting will be ignored.")
static void SetMaxTasksPerFilePerWorker(unsigned int m);
R__DEPRECATED(6, 26, "Please use SetTasksPerWorkerHint and GetTasksPerWorkerHint instead. This setting is ignored.")
static unsigned int GetMaxTasksPerFilePerWorker();
static void SetTasksPerWorkerHint(unsigned int m);
static unsigned int GetTasksPerWorkerHint();
};
} // End of namespace ROOT
#endif // defined TTreeProcessorMT
<|endoftext|>
|
<commit_before>#include "Graphics/Engine.h"
#include "EngineInternal.h"
#include "vulkan/vulkan.hpp"
#include <exception>
#include <iostream>
#include <memory>
#include <vector>
using namespace CR::Graphics;
using namespace std;
using namespace std::string_literals;
namespace {
constexpr uint MajorVersion = 0; // 64K max
constexpr uint MinorVersion = 1; // 256 max
constexpr uint PatchVersion = 1; // 256 max
constexpr uint Version = (MajorVersion << 16) || (MajorVersion << 8) || (PatchVersion);
class Engine {
public:
Engine(const EngineSettings& a_settings);
~Engine();
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
// private: internal so private anyway
vk::Instance m_Instance;
vk::Device m_Device;
};
unique_ptr<Engine> g_Engine;
} // namespace
Engine::Engine(const EngineSettings& a_settings) {
vector<string> enabledLayers;
if(a_settings.EnableDebug) {
vector<vk::LayerProperties> layers = vk::enumerateInstanceLayerProperties();
for(const auto& layer : layers) {
if("VK_LAYER_LUNARG_standard_validation"s == layer.layerName) { enabledLayers.push_back(layer.layerName); }
}
}
vk::ApplicationInfo appInfo;
appInfo.pApplicationName = a_settings.ApplicationName.c_str();
appInfo.applicationVersion = a_settings.ApplicationVersion;
appInfo.pEngineName = "Conjure";
appInfo.engineVersion = Version;
appInfo.apiVersion = VK_API_VERSION_1_0;
vector<const char*> enabledLayersPtrs;
for(auto& layer : enabledLayers) { enabledLayersPtrs.push_back(layer.c_str()); }
vk::InstanceCreateInfo createInfo;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledLayerCount = (uint32_t)size(enabledLayersPtrs);
createInfo.ppEnabledLayerNames = data(enabledLayersPtrs);
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = nullptr;
m_Instance = vk::createInstance(createInfo);
vector<vk::PhysicalDevice> physicalDevices = m_Instance.enumeratePhysicalDevices();
vk::PhysicalDevice selectedDevice;
bool foundDevice = false;
int graphicsQueueIndex = -1;
int transferQueueIndex = -1;
for(auto& device : physicalDevices) {
auto props = device.getProperties();
cout << "Device Name: " << props.deviceName << endl;
auto memProps = device.getMemoryProperties();
for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i) {
if(memProps.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eDeviceLocal) {
cout << "Device Local Memory Amount: "
<< memProps.memoryHeaps[memProps.memoryTypes[i].heapIndex].size / (1024 * 1024) << "MB" << endl;
}
}
vector<vk::QueueFamilyProperties> queueProps = device.getQueueFamilyProperties();
bool supportsGraphics = false;
bool supportsTransfer = false;
for(uint32_t i = 0; i < queueProps.size(); ++i) {
// This one should only be false for tesla compute cards and similiar
if((queueProps[i].queueFlags & vk::QueueFlagBits::eGraphics) && queueProps[i].queueCount >= 1) {
supportsGraphics = true;
graphicsQueueIndex = i;
}
if((queueProps[i].queueFlags & vk::QueueFlagBits::eTransfer) && queueProps[i].queueCount >= 1) {
supportsTransfer = true;
transferQueueIndex = i;
}
}
auto features = device.getFeatures();
// TODO: We dont have a good heuristic for selecting a device, for now just take first one that supports
// graphics and hope for the best. My machine has only one, so cant test a better implementation.
if(supportsGraphics && supportsTransfer && features.textureCompressionBC && features.fullDrawIndexUint32) {
foundDevice = true;
selectedDevice = device;
break;
}
}
if(!foundDevice) { throw runtime_error("Could not find a valid vulkan device"); }
vk::PhysicalDeviceFeatures requiredFeatures;
requiredFeatures.textureCompressionBC = true;
requiredFeatures.fullDrawIndexUint32 = true;
float graphicsPriority = 1.0f;
float transferPriority = 0.0f;
vk::DeviceQueueCreateInfo queueInfos[2];
queueInfos[0].queueFamilyIndex = graphicsQueueIndex;
queueInfos[0].queueCount = 1;
queueInfos[0].pQueuePriorities = &graphicsPriority;
queueInfos[1] = queueInfos[0];
queueInfos[1].queueFamilyIndex = transferQueueIndex;
queueInfos[1].pQueuePriorities = &transferPriority;
vk::DeviceCreateInfo createLogDevInfo;
createLogDevInfo.queueCreateInfoCount = (int)size(queueInfos);
createLogDevInfo.pQueueCreateInfos = queueInfos;
createLogDevInfo.pEnabledFeatures = &requiredFeatures;
createLogDevInfo.enabledLayerCount = 0;
createLogDevInfo.ppEnabledLayerNames = nullptr;
createLogDevInfo.enabledExtensionCount = 0;
createLogDevInfo.ppEnabledExtensionNames = nullptr;
m_Device = selectedDevice.createDevice(createLogDevInfo);
}
Engine::~Engine() {
m_Device.destroy();
m_Instance.destroy();
}
void CR::Graphics::CreateEngine(const EngineSettings& a_settings) {
g_Engine = make_unique<Engine>(a_settings);
}
void CR::Graphics::ShutdownEngine() {
g_Engine.reset();
}
vk::Device& CR::Graphics::GetDevice() {
assert(g_Engine.get());
return g_Engine->m_Device;
}
<commit_msg>log texture maximum sizes<commit_after>#include "Graphics/Engine.h"
#include "EngineInternal.h"
#include "vulkan/vulkan.hpp"
#include <exception>
#include <iostream>
#include <memory>
#include <vector>
using namespace CR::Graphics;
using namespace std;
using namespace std::string_literals;
namespace {
constexpr uint MajorVersion = 0; // 64K max
constexpr uint MinorVersion = 1; // 256 max
constexpr uint PatchVersion = 1; // 256 max
constexpr uint Version = (MajorVersion << 16) || (MajorVersion << 8) || (PatchVersion);
class Engine {
public:
Engine(const EngineSettings& a_settings);
~Engine();
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
// private: internal so private anyway
vk::Instance m_Instance;
vk::Device m_Device;
};
unique_ptr<Engine> g_Engine;
} // namespace
Engine::Engine(const EngineSettings& a_settings) {
vector<string> enabledLayers;
if(a_settings.EnableDebug) {
vector<vk::LayerProperties> layers = vk::enumerateInstanceLayerProperties();
for(const auto& layer : layers) {
if("VK_LAYER_LUNARG_standard_validation"s == layer.layerName) { enabledLayers.push_back(layer.layerName); }
}
}
vk::ApplicationInfo appInfo;
appInfo.pApplicationName = a_settings.ApplicationName.c_str();
appInfo.applicationVersion = a_settings.ApplicationVersion;
appInfo.pEngineName = "Conjure";
appInfo.engineVersion = Version;
appInfo.apiVersion = VK_API_VERSION_1_0;
vector<const char*> enabledLayersPtrs;
for(auto& layer : enabledLayers) { enabledLayersPtrs.push_back(layer.c_str()); }
vk::InstanceCreateInfo createInfo;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledLayerCount = (uint32_t)size(enabledLayersPtrs);
createInfo.ppEnabledLayerNames = data(enabledLayersPtrs);
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = nullptr;
m_Instance = vk::createInstance(createInfo);
vector<vk::PhysicalDevice> physicalDevices = m_Instance.enumeratePhysicalDevices();
vk::PhysicalDevice selectedDevice;
bool foundDevice = false;
int graphicsQueueIndex = -1;
int transferQueueIndex = -1;
for(auto& device : physicalDevices) {
auto props = device.getProperties();
cout << "Device Name: " << props.deviceName << endl;
auto memProps = device.getMemoryProperties();
for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i) {
if(memProps.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eDeviceLocal) {
cout << "Device Local Memory Amount: "
<< memProps.memoryHeaps[memProps.memoryTypes[i].heapIndex].size / (1024 * 1024) << "MB" << endl;
}
}
vector<vk::QueueFamilyProperties> queueProps = device.getQueueFamilyProperties();
bool supportsGraphics = false;
bool supportsTransfer = false;
for(uint32_t i = 0; i < queueProps.size(); ++i) {
// This one should only be false for tesla compute cards and similiar
if((queueProps[i].queueFlags & vk::QueueFlagBits::eGraphics) && queueProps[i].queueCount >= 1) {
supportsGraphics = true;
graphicsQueueIndex = i;
}
if((queueProps[i].queueFlags & vk::QueueFlagBits::eTransfer) && queueProps[i].queueCount >= 1) {
supportsTransfer = true;
transferQueueIndex = i;
}
}
auto features = device.getFeatures();
// TODO: We dont have a good heuristic for selecting a device, for now just take first one that supports
// graphics and hope for the best. My machine has only one, so cant test a better implementation.
if(supportsGraphics && supportsTransfer && features.textureCompressionBC && features.fullDrawIndexUint32) {
foundDevice = true;
selectedDevice = device;
break;
}
}
if(!foundDevice) { throw runtime_error("Could not find a valid vulkan device"); }
vk::Format formatsToLog[] = {vk::Format::eBc1RgbSrgbBlock, vk::Format::eBc3SrgbBlock, vk::Format::eBc4UnormBlock,
vk::Format::eBc5SnormBlock, vk::Format::eA8B8G8R8SrgbPack32};
for(auto& format : formatsToLog) {
auto formatProps = selectedDevice.getImageFormatProperties(
format, vk::ImageType::e2D, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eSampled,
vk::ImageCreateFlagBits::e2DArrayCompatible);
cout << to_string(format) << " - Max width: " << formatProps.maxExtent.width
<< " Max height: " << formatProps.maxExtent.height << " Max array size: " << formatProps.maxArrayLayers
<< endl;
}
vk::PhysicalDeviceFeatures requiredFeatures;
requiredFeatures.textureCompressionBC = true;
requiredFeatures.fullDrawIndexUint32 = true;
float graphicsPriority = 1.0f;
float transferPriority = 0.0f;
vk::DeviceQueueCreateInfo queueInfos[2];
queueInfos[0].queueFamilyIndex = graphicsQueueIndex;
queueInfos[0].queueCount = 1;
queueInfos[0].pQueuePriorities = &graphicsPriority;
queueInfos[1] = queueInfos[0];
queueInfos[1].queueFamilyIndex = transferQueueIndex;
queueInfos[1].pQueuePriorities = &transferPriority;
vk::DeviceCreateInfo createLogDevInfo;
createLogDevInfo.queueCreateInfoCount = (int)size(queueInfos);
createLogDevInfo.pQueueCreateInfos = queueInfos;
createLogDevInfo.pEnabledFeatures = &requiredFeatures;
createLogDevInfo.enabledLayerCount = 0;
createLogDevInfo.ppEnabledLayerNames = nullptr;
createLogDevInfo.enabledExtensionCount = 0;
createLogDevInfo.ppEnabledExtensionNames = nullptr;
m_Device = selectedDevice.createDevice(createLogDevInfo);
}
Engine::~Engine() {
m_Device.destroy();
m_Instance.destroy();
}
void CR::Graphics::CreateEngine(const EngineSettings& a_settings) {
g_Engine = make_unique<Engine>(a_settings);
}
void CR::Graphics::ShutdownEngine() {
g_Engine.reset();
}
vk::Device& CR::Graphics::GetDevice() {
assert(g_Engine.get());
return g_Engine->m_Device;
}
<|endoftext|>
|
<commit_before>/*
* InputSystem.cpp
*
* Created on: 15/07/2014
* Author: vitor
*/
#include "InputSystem.h"
void InputSystem::process_entities(std::map<uint64_t, EntityPtr>& entities,
double dt) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
world_ptr->get_event_manager().broadcast<Quit>();
break;
case SDL_KEYDOWN:
if (!event.key.repeat) {
world_ptr->get_event_manager().broadcast<KeyboardDown>(
event.key.keysym.scancode);
}
break;
case SDL_KEYUP:
if (!event.key.repeat) {
world_ptr->get_event_manager().broadcast<KeyboardUp>(
event.key.keysym.scancode);
}
break;
default:
break;
}
}
}
void InputSystem::process_entity(Entity& entity, double dt) {
}
<commit_msg>Removed unnecessary repeat check for KEYUP.<commit_after>/*
* InputSystem.cpp
*
* Created on: 15/07/2014
* Author: vitor
*/
#include "InputSystem.h"
void InputSystem::process_entities(std::map<uint64_t, EntityPtr>& entities,
double dt) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
world_ptr->get_event_manager().broadcast<Quit>();
break;
case SDL_KEYDOWN:
if (!event.key.repeat) {
world_ptr->get_event_manager().broadcast<KeyboardDown>(
event.key.keysym.scancode);
}
break;
case SDL_KEYUP:
world_ptr->get_event_manager().broadcast<KeyboardUp>(
event.key.keysym.scancode);
break;
default:
break;
}
}
}
void InputSystem::process_entity(Entity& entity, double dt) {
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "seastarx.hh"
#include "db/timeout_clock.hh"
#include "schema_fwd.hh"
namespace seastar {
class file;
} // namespace seastar
struct reader_resources {
int count = 0;
ssize_t memory = 0;
static reader_resources with_memory(ssize_t memory) { return reader_resources(0, memory); }
reader_resources() = default;
reader_resources(int count, ssize_t memory)
: count(count)
, memory(memory) {
}
bool operator>=(const reader_resources& other) const {
return count >= other.count && memory >= other.memory;
}
reader_resources operator-(const reader_resources& other) const {
return reader_resources{count - other.count, memory - other.memory};
}
reader_resources& operator-=(const reader_resources& other) {
count -= other.count;
memory -= other.memory;
return *this;
}
reader_resources operator+(const reader_resources& other) const {
return reader_resources{count + other.count, memory + other.memory};
}
reader_resources& operator+=(const reader_resources& other) {
count += other.count;
memory += other.memory;
return *this;
}
explicit operator bool() const {
return count > 0 || memory > 0;
}
};
inline bool operator==(const reader_resources& a, const reader_resources& b) {
return a.count == b.count && a.memory == b.memory;
}
class reader_concurrency_semaphore;
/// A permit for a specific read.
///
/// Used to track the read's resource consumption and wait for admission to read
/// from the disk.
/// Use `consume_memory()` to register memory usage. Use `wait_admission()` to
/// wait for admission, before reading from the disk. Both methods return a
/// `resource_units` RAII object that should be held onto while the respective
/// resources are in use.
class reader_permit {
friend class reader_concurrency_semaphore;
public:
class resource_units;
enum class state {
waiting, // waiting for admission
active,
inactive,
evicted,
};
class impl;
private:
shared_ptr<impl> _impl;
private:
explicit reader_permit(reader_concurrency_semaphore& semaphore, const schema* const schema, std::string_view op_name);
explicit reader_permit(reader_concurrency_semaphore& semaphore, const schema* const schema, sstring&& op_name);
void on_waiting();
void on_admission();
public:
~reader_permit();
reader_permit(const reader_permit&) = default;
reader_permit(reader_permit&&) = default;
reader_permit& operator=(const reader_permit&) = default;
reader_permit& operator=(reader_permit&&) = default;
bool operator==(const reader_permit& o) const {
return _impl == o._impl;
}
reader_concurrency_semaphore& semaphore();
future<resource_units> wait_admission(size_t memory, db::timeout_clock::time_point timeout);
void consume(reader_resources res);
void signal(reader_resources res);
resource_units consume_memory(size_t memory = 0);
resource_units consume_resources(reader_resources res);
reader_resources consumed_resources() const;
sstring description() const;
};
class reader_permit::resource_units {
reader_permit _permit;
reader_resources _resources;
friend class reader_permit;
friend class reader_concurrency_semaphore;
private:
resource_units(reader_permit permit, reader_resources res) noexcept;
public:
resource_units(const resource_units&) = delete;
resource_units(resource_units&&) noexcept;
~resource_units();
resource_units& operator=(const resource_units&) = delete;
resource_units& operator=(resource_units&&) noexcept;
void add(resource_units&& o);
void reset(reader_resources res = {});
reader_permit permit() const { return _permit; }
reader_resources resources() const { return _resources; }
};
template <typename Char>
temporary_buffer<Char> make_tracked_temporary_buffer(temporary_buffer<Char> buf, reader_permit& permit) {
return temporary_buffer<Char>(buf.get_write(), buf.size(),
make_deleter(buf.release(), [units = permit.consume_memory(buf.size())] () mutable { units.reset(); }));
}
file make_tracked_file(file f, reader_permit p);
template <typename T>
class tracking_allocator {
public:
using value_type = T;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::false_type;
private:
reader_permit _permit;
std::allocator<T> _alloc;
public:
tracking_allocator(reader_permit permit) noexcept : _permit(std::move(permit)) { }
T* allocate(size_t n) {
auto p = _alloc.allocate(n);
_permit.consume(reader_resources::with_memory(n * sizeof(T)));
return p;
}
void deallocate(T* p, size_t n) {
_alloc.deallocate(p, n);
if (n) {
_permit.signal(reader_resources::with_memory(n * sizeof(T)));
}
}
template <typename U>
friend bool operator==(const tracking_allocator<U>& a, const tracking_allocator<U>& b);
};
template <typename T>
bool operator==(const tracking_allocator<T>& a, const tracking_allocator<T>& b) {
return a._semaphore == b._semaphore;
}
<commit_msg>reader_permit: add reader_permit_opt<commit_after>/*
* Copyright (C) 2019-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/util/optimized_optional.hh>
#include "seastarx.hh"
#include "db/timeout_clock.hh"
#include "schema_fwd.hh"
namespace seastar {
class file;
} // namespace seastar
struct reader_resources {
int count = 0;
ssize_t memory = 0;
static reader_resources with_memory(ssize_t memory) { return reader_resources(0, memory); }
reader_resources() = default;
reader_resources(int count, ssize_t memory)
: count(count)
, memory(memory) {
}
bool operator>=(const reader_resources& other) const {
return count >= other.count && memory >= other.memory;
}
reader_resources operator-(const reader_resources& other) const {
return reader_resources{count - other.count, memory - other.memory};
}
reader_resources& operator-=(const reader_resources& other) {
count -= other.count;
memory -= other.memory;
return *this;
}
reader_resources operator+(const reader_resources& other) const {
return reader_resources{count + other.count, memory + other.memory};
}
reader_resources& operator+=(const reader_resources& other) {
count += other.count;
memory += other.memory;
return *this;
}
explicit operator bool() const {
return count > 0 || memory > 0;
}
};
inline bool operator==(const reader_resources& a, const reader_resources& b) {
return a.count == b.count && a.memory == b.memory;
}
class reader_concurrency_semaphore;
/// A permit for a specific read.
///
/// Used to track the read's resource consumption and wait for admission to read
/// from the disk.
/// Use `consume_memory()` to register memory usage. Use `wait_admission()` to
/// wait for admission, before reading from the disk. Both methods return a
/// `resource_units` RAII object that should be held onto while the respective
/// resources are in use.
class reader_permit {
friend class reader_concurrency_semaphore;
public:
class resource_units;
enum class state {
waiting, // waiting for admission
active,
inactive,
evicted,
};
class impl;
private:
shared_ptr<impl> _impl;
private:
reader_permit() = default;
explicit reader_permit(reader_concurrency_semaphore& semaphore, const schema* const schema, std::string_view op_name);
explicit reader_permit(reader_concurrency_semaphore& semaphore, const schema* const schema, sstring&& op_name);
void on_waiting();
void on_admission();
operator bool() const { return bool(_impl); }
friend class optimized_optional<reader_permit>;
public:
~reader_permit();
reader_permit(const reader_permit&) = default;
reader_permit(reader_permit&&) = default;
reader_permit& operator=(const reader_permit&) = default;
reader_permit& operator=(reader_permit&&) = default;
bool operator==(const reader_permit& o) const {
return _impl == o._impl;
}
reader_concurrency_semaphore& semaphore();
future<resource_units> wait_admission(size_t memory, db::timeout_clock::time_point timeout);
void consume(reader_resources res);
void signal(reader_resources res);
resource_units consume_memory(size_t memory = 0);
resource_units consume_resources(reader_resources res);
reader_resources consumed_resources() const;
sstring description() const;
};
using reader_permit_opt = optimized_optional<reader_permit>;
class reader_permit::resource_units {
reader_permit _permit;
reader_resources _resources;
friend class reader_permit;
friend class reader_concurrency_semaphore;
private:
resource_units(reader_permit permit, reader_resources res) noexcept;
public:
resource_units(const resource_units&) = delete;
resource_units(resource_units&&) noexcept;
~resource_units();
resource_units& operator=(const resource_units&) = delete;
resource_units& operator=(resource_units&&) noexcept;
void add(resource_units&& o);
void reset(reader_resources res = {});
reader_permit permit() const { return _permit; }
reader_resources resources() const { return _resources; }
};
template <typename Char>
temporary_buffer<Char> make_tracked_temporary_buffer(temporary_buffer<Char> buf, reader_permit& permit) {
return temporary_buffer<Char>(buf.get_write(), buf.size(),
make_deleter(buf.release(), [units = permit.consume_memory(buf.size())] () mutable { units.reset(); }));
}
file make_tracked_file(file f, reader_permit p);
template <typename T>
class tracking_allocator {
public:
using value_type = T;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::false_type;
private:
reader_permit _permit;
std::allocator<T> _alloc;
public:
tracking_allocator(reader_permit permit) noexcept : _permit(std::move(permit)) { }
T* allocate(size_t n) {
auto p = _alloc.allocate(n);
_permit.consume(reader_resources::with_memory(n * sizeof(T)));
return p;
}
void deallocate(T* p, size_t n) {
_alloc.deallocate(p, n);
if (n) {
_permit.signal(reader_resources::with_memory(n * sizeof(T)));
}
}
template <typename U>
friend bool operator==(const tracking_allocator<U>& a, const tracking_allocator<U>& b);
};
template <typename T>
bool operator==(const tracking_allocator<T>& a, const tracking_allocator<T>& b) {
return a._semaphore == b._semaphore;
}
<|endoftext|>
|
<commit_before>// Created 18-Jul-2013 by Daniel Margala (University of California, Irvine) <dmargala@uci.edu>
// convert guiding offsets to tp correction
// g++ -lboost_program_options guidingtp.cxx -o guidingtp
#include "boost/program_options.hpp"
#include "boost/math/special_functions/gamma.hpp"
#include <iostream>
#include <fstream>
#include <cmath>
namespace po = boost::program_options;
const double PLATESCALE = 217.7358/3600; /* mm/arcsec */
// Calculates the fraction of light from an object with the specified Gaussian
// fwhm that enters a fiber of the specified diameter when the object's centroid
// is offset from the fiber center by the specified amount. All inputs should
// be specified in the same units. The default diameter is the BOSS fiber size
// in arcsecs, so requires that fwhm and offset also be specified in arcsecs.
// Accuracy gets worse with increasing diameter/fwhm, but should be at least 0.5%
// for fwhm > diameter/4 (or fwhm > 0.5 arcsec for BOSS fibers).
double fiberFraction(double fwhm, double offset, double diameter=2.0/*arcsec*/) {
if(fwhm <= 0) {
std::cerr << "fiberFraction: invalid fwhm <= 0." << std::endl;
}
if(offset < 0) {
std::cerr << "fiberFraction: invalid offset < 0." << std::endl;
}
if(diameter <= 0) {
std::cerr << "fiberFraction: invalid diameter <= 0." << std::endl;
}
if(diameter > 4*fwhm) {
std::cerr << "fiberFraction: diameter > 4*fwhm not implemented yet." << std::endl;
}
// Convert from FWHM to sigma.
double sigma(fwhm/2.3548200450309493820); // constant is 2*sqrt(2*log(2))
// Calculate dimensionless ratios
double t(offset/sigma), ss(diameter/(2*sigma));
double tSqby2(t*t/2),ssSqby2(ss*ss/2);
// Use a series expansion of the BesselI[0,x] appearing in the radial integral.
double lastSum,sum(1-std::exp(-ssSqby2)),prod(1);
int k(0);
while(++k < 1000) {
lastSum = sum;
prod *= tSqby2;
double term(prod*boost::math::gamma_p(k+1,ssSqby2)/boost::math::tgamma(k+1));
sum += term;
if(std::fabs(term) < 1e-2*sum) break;
}
return sum*std::exp(-tSqby2);
}
int main(int argc, char **argv) {
// Configure command-line option processing
po::options_description cli("Throughput correction");
double psfmin, psfstep;
int plate, psfnumsteps;
std::string inputName;
cli.add_options()
("help,h", "Prints this info and exits.")
("verbose", "Prints additional information.")
("psf-min", po::value<double>(&psfmin)->default_value(1),
"PSF fwhm minimum.")
("psf-num", po::value<int>(&psfnumsteps)->default_value(10),
"Number of PSF FHWM steps.")
("psf-step", po::value<double>(&psfstep)->default_value(0.1,"0.1"),
"PSF fwhm step size.")
("plate,p", po::value<int>(&plate)->default_value(0),
"Plate number to use.")
;
// do the command line parsing now
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, cli), vm);
po::notify(vm);
}
catch(std::exception const &e) {
std::cerr << "Unable to parse command line options: " << e.what() << std::endl;
return -1;
}
if(vm.count("help")) {
std::cout << cli << std::endl;
return 1;
}
bool verbose(vm.count("verbose"));
if (plate == 0) {
std::cerr << "Must specify plate number!" << std::endl;
return -2;
}
boost::format fmt("%f %f %f %f %f %f");
std::string outname("tpcorr-"+boost::lexical_cast<std::string>(plate)+".dat");
std::ofstream out(outname.c_str());
std::string inlabelname("guidederivs/plate-"+boost::lexical_cast<std::string>(plate)+"-label.dat");
std::string in4000name("guidederivs/plate-"+boost::lexical_cast<std::string>(plate)+"-4000.dat");
std::string in5400name("guidederivs/plate-"+boost::lexical_cast<std::string>(plate)+"-5400.dat");
std::cout << "reading " << inlabelname << std::endl;
std::ifstream inlabels(inlabelname.c_str());
std::ifstream in4000(in4000name.c_str());
std::ifstream in5400(in5400name.c_str());
double x,y,ha,lambda;
double dx,dy,dr4000,dr5400;
double tp;
int count(0);
double psffwhm;
while(inlabels.good() && !inlabels.eof()) {
inlabels >> x >> y >> ha >> lambda;
in4000 >> dx >> dy;
dr4000 = std::sqrt(dx*dx+dy*dy)/PLATESCALE;
in5400 >> dx >> dy;
dr5400 = std::sqrt(dx*dx+dy*dy)/PLATESCALE;
if(!inlabels.good() || inlabels.eof()) break;
for(int i = 0; i < psfnumsteps; ++i) {
psffwhm = psfmin + i*psfstep;
if(count==0) std::cout << psffwhm << std::endl;
tp = fiberFraction(psffwhm,dr4000)/fiberFraction(psffwhm,dr5400);
out << fmt % x % y % ha % lambda % psffwhm % tp << std::endl;
}
count++;
}
if(verbose) {
std::cout << "Read " << count << " lines." << std::endl;
}
inlabels.close();
in4000.close();
in5400.close();
out.close();
return 0;
}<commit_msg>remove hardcoded path in guidingtp<commit_after>// Created 18-Jul-2013 by Daniel Margala (University of California, Irvine) <dmargala@uci.edu>
// convert guiding offsets to tp correction
// g++ -lboost_program_options guidingtp.cxx -o guidingtp
#include "boost/program_options.hpp"
#include "boost/math/special_functions/gamma.hpp"
#include <iostream>
#include <fstream>
#include <cmath>
namespace po = boost::program_options;
const double PLATESCALE = 217.7358/3600; /* mm/arcsec */
// Calculates the fraction of light from an object with the specified Gaussian
// fwhm that enters a fiber of the specified diameter when the object's centroid
// is offset from the fiber center by the specified amount. All inputs should
// be specified in the same units. The default diameter is the BOSS fiber size
// in arcsecs, so requires that fwhm and offset also be specified in arcsecs.
// Accuracy gets worse with increasing diameter/fwhm, but should be at least 0.5%
// for fwhm > diameter/4 (or fwhm > 0.5 arcsec for BOSS fibers).
double fiberFraction(double fwhm, double offset, double diameter=2.0/*arcsec*/) {
if(fwhm <= 0) {
std::cerr << "fiberFraction: invalid fwhm <= 0." << std::endl;
}
if(offset < 0) {
std::cerr << "fiberFraction: invalid offset < 0." << std::endl;
}
if(diameter <= 0) {
std::cerr << "fiberFraction: invalid diameter <= 0." << std::endl;
}
if(diameter > 4*fwhm) {
std::cerr << "fiberFraction: diameter > 4*fwhm not implemented yet." << std::endl;
}
// Convert from FWHM to sigma.
double sigma(fwhm/2.3548200450309493820); // constant is 2*sqrt(2*log(2))
// Calculate dimensionless ratios
double t(offset/sigma), ss(diameter/(2*sigma));
double tSqby2(t*t/2),ssSqby2(ss*ss/2);
// Use a series expansion of the BesselI[0,x] appearing in the radial integral.
double lastSum,sum(1-std::exp(-ssSqby2)),prod(1);
int k(0);
while(++k < 1000) {
lastSum = sum;
prod *= tSqby2;
double term(prod*boost::math::gamma_p(k+1,ssSqby2)/boost::math::tgamma(k+1));
sum += term;
if(std::fabs(term) < 1e-2*sum) break;
}
return sum*std::exp(-tSqby2);
}
int main(int argc, char **argv) {
// Configure command-line option processing
po::options_description cli("Throughput correction");
double psfmin, psfstep;
int plate, psfnumsteps;
std::string inputName, prefix;
cli.add_options()
("help,h", "Prints this info and exits.")
("verbose", "Prints additional information.")
("psf-min", po::value<double>(&psfmin)->default_value(1),
"PSF fwhm minimum.")
("psf-num", po::value<int>(&psfnumsteps)->default_value(10),
"Number of PSF FHWM steps.")
("psf-step", po::value<double>(&psfstep)->default_value(0.1,"0.1"),
"PSF fwhm step size.")
("plate,p", po::value<int>(&plate)->default_value(0),
"Plate number to use.")
("prefix", po::value<std::string>(&prefix)->default_value(""),
"tpcorr file prefix.")
;
// do the command line parsing now
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, cli), vm);
po::notify(vm);
}
catch(std::exception const &e) {
std::cerr << "Unable to parse command line options: " << e.what() << std::endl;
return -1;
}
if(vm.count("help")) {
std::cout << cli << std::endl;
return 1;
}
bool verbose(vm.count("verbose"));
if (plate == 0) {
std::cerr << "Must specify plate number!" << std::endl;
return -2;
}
boost::format fmt("%f %f %f %f %f %f");
std::string outname("tpcorr-"+boost::lexical_cast<std::string>(plate)+".dat");
std::ofstream out(outname.c_str());
std::string inlabelname(prefix+boost::lexical_cast<std::string>(plate)+"-label.dat");
std::string in4000name(prefix+boost::lexical_cast<std::string>(plate)+"-4000.dat");
std::string in5400name(prefix+boost::lexical_cast<std::string>(plate)+"-5400.dat");
std::cout << "reading " << inlabelname << std::endl;
std::ifstream inlabels(inlabelname.c_str());
std::ifstream in4000(in4000name.c_str());
std::ifstream in5400(in5400name.c_str());
double x,y,ha,lambda;
double dx,dy,dr4000,dr5400;
double tp;
int count(0);
double psffwhm;
while(inlabels.good() && !inlabels.eof()) {
inlabels >> x >> y >> ha >> lambda;
in4000 >> dx >> dy;
dr4000 = std::sqrt(dx*dx+dy*dy)/PLATESCALE;
in5400 >> dx >> dy;
dr5400 = std::sqrt(dx*dx+dy*dy)/PLATESCALE;
if(!inlabels.good() || inlabels.eof()) break;
for(int i = 0; i < psfnumsteps; ++i) {
psffwhm = psfmin + i*psfstep;
if(count==0) std::cout << psffwhm << std::endl;
tp = fiberFraction(psffwhm,dr4000)/fiberFraction(psffwhm,dr5400);
out << fmt % x % y % ha % lambda % psffwhm % tp << std::endl;
}
count++;
}
if(verbose) {
std::cout << "Read " << count << " lines." << std::endl;
}
inlabels.close();
in4000.close();
in5400.close();
out.close();
return 0;
}<|endoftext|>
|
<commit_before>#ifndef __TEST__MODELS__UTILITY_HPP__
#define __TEST__MODELS__UTILITY_HPP__
#include <stdexcept>
#include <boost/algorithm/string.hpp>
/**
* Gets the path separator for the OS.
*
* @return '\' for Windows, '/' otherwise.
*/
char get_path_separator() {
static char path_separator = 0;
if (path_separator == 0) {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator = fgetc(in);
pclose(in);
}
return path_separator;
}
/**
* Returns the path as a string with the appropriate
* path separator.
*
* @param model_path vector of strings representing path to the model
*
* @return the string representation of the path with the appropriate
* path separator.
*/
std::string convert_model_path(const std::vector<std::string>& model_path) {
std::string path;
if (model_path.size() > 0) {
path.append(model_path[0]);
for (size_t i = 1; i < model_path.size(); i++) {
path.append(1, get_path_separator());
path.append(model_path[i]);
}
}
return path;
}
/**
* Runs the command provided and returns the system output
* as a string.
*
* @param command A command that can be run from the shell
* @return the system output of the command
*/
std::string run_command(const std::string& command) {
FILE *in;
if(!(in = popen(command.c_str(), "r"))) {
std::string err_msg;
err_msg = "Could not run: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
std::string output;
char buf[1024];
size_t count = fread(&buf, 1, 1024, in);
while (count > 0) {
output += std::string(&buf[0], &buf[count]);
count = fread(&buf, 1, 1024, in);
}
pclose(in);
return output;
}
/**
* Returns the help options from the string provided.
* Help options start with "--".
*
* @param help_output output from "model/command --help"
* @return a vector of strings of the help options
*/
std::vector<std::string> parse_help_options(const std::string& help_output) {
std::vector<std::string> help_options;
size_t option_start = help_output.find("--");
while (option_start != std::string::npos) {
// find the option name (skip two characters for "--")
option_start += 2;
size_t option_end = help_output.find_first_of("= ", option_start);
help_options.push_back(help_output.substr(option_start, option_end-option_start));
option_start = help_output.find("--", option_start+1);
}
return help_options;
}
/**
* Parses output from a Stan model run from the command line.
* Returns option, value pairs.
*
* @param command_output The output from a Stan model run from the command line.
*
* @return Option, value pairs as indicated by the Stan model.
*/
std::vector<std::pair<std::string, std::string> >
parse_command_output(const std::string& command_output) {
using std::vector;
using std::pair;
using std::string;
vector<pair<string, string> > output;
string option, value;
size_t start = 0, end = command_output.find("\n", start);
EXPECT_EQ("STAN SAMPLING COMMAND",
command_output.substr(start, end))
<< "command could not be run. output is: \n"
<< command_output;
if ("STAN SAMPLING COMMAND" != command_output.substr(start, end)) {
return output;
}
start = end+1;
end = command_output.find("\n", start);
size_t equal_pos = command_output.find("=", start);
while (equal_pos != string::npos) {
using boost::trim;
option = command_output.substr(start, equal_pos-start);
value = command_output.substr(equal_pos+1, end - equal_pos - 1);
trim(option);
trim(value);
output.push_back(pair<string, string>(option, value));
start = end+1;
end = command_output.find("\n", start);
equal_pos = command_output.find("=", start);
}
return output;
}
#endif
<commit_msg>test-models: updated run command<commit_after>#ifndef __TEST__MODELS__UTILITY_HPP__
#define __TEST__MODELS__UTILITY_HPP__
#include <stdexcept>
#include <boost/algorithm/string.hpp>
/**
* Gets the path separator for the OS.
*
* @return '\' for Windows, '/' otherwise.
*/
char get_path_separator() {
static char path_separator = 0;
if (path_separator == 0) {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator = fgetc(in);
pclose(in);
}
return path_separator;
}
/**
* Returns the path as a string with the appropriate
* path separator.
*
* @param model_path vector of strings representing path to the model
*
* @return the string representation of the path with the appropriate
* path separator.
*/
std::string convert_model_path(const std::vector<std::string>& model_path) {
std::string path;
if (model_path.size() > 0) {
path.append(model_path[0]);
for (size_t i = 1; i < model_path.size(); i++) {
path.append(1, get_path_separator());
path.append(model_path[i]);
}
}
return path;
}
/**
* Runs the command provided and returns the system output
* as a string.
*
* @param command A command that can be run from the shell
* @return the system output of the command
*/
std::string run_command(std::string command) {
FILE *in;
command += " 2>&1"; // capture stderr
if(!(in = popen(command.c_str(), "r"))) {
std::string err_msg;
err_msg = "Could not run: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
std::string output;
char buf[1024];
size_t count = fread(&buf, 1, 1024, in);
while (count > 0) {
output += std::string(&buf[0], &buf[count]);
count = fread(&buf, 1, 1024, in);
}
if (pclose(in) != 0) {
std::string err_msg;
err_msg = "Could not run: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
return output;
}
/**
* Returns the help options from the string provided.
* Help options start with "--".
*
* @param help_output output from "model/command --help"
* @return a vector of strings of the help options
*/
std::vector<std::string> parse_help_options(const std::string& help_output) {
std::vector<std::string> help_options;
size_t option_start = help_output.find("--");
while (option_start != std::string::npos) {
// find the option name (skip two characters for "--")
option_start += 2;
size_t option_end = help_output.find_first_of("= ", option_start);
help_options.push_back(help_output.substr(option_start, option_end-option_start));
option_start = help_output.find("--", option_start+1);
}
return help_options;
}
/**
* Parses output from a Stan model run from the command line.
* Returns option, value pairs.
*
* @param command_output The output from a Stan model run from the command line.
*
* @return Option, value pairs as indicated by the Stan model.
*/
std::vector<std::pair<std::string, std::string> >
parse_command_output(const std::string& command_output) {
using std::vector;
using std::pair;
using std::string;
vector<pair<string, string> > output;
string option, value;
size_t start = 0, end = command_output.find("\n", start);
EXPECT_EQ("STAN SAMPLING COMMAND",
command_output.substr(start, end))
<< "command could not be run. output is: \n"
<< command_output;
if ("STAN SAMPLING COMMAND" != command_output.substr(start, end)) {
return output;
}
start = end+1;
end = command_output.find("\n", start);
size_t equal_pos = command_output.find("=", start);
while (equal_pos != string::npos) {
using boost::trim;
option = command_output.substr(start, equal_pos-start);
value = command_output.substr(equal_pos+1, end - equal_pos - 1);
trim(option);
trim(value);
output.push_back(pair<string, string>(option, value));
start = end+1;
end = command_output.find("\n", start);
equal_pos = command_output.find("=", start);
}
return output;
}
#endif
<|endoftext|>
|
<commit_before>#include <boost/assert.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <openssl/ec.h>
#include <openssl/err.h>
#include "keystore.h"
#include "main.h"
#include "script.h"
#include "wallet.h"
using namespace std;
using namespace boost::assign;
typedef vector<unsigned char> valtype;
extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType);
BOOST_AUTO_TEST_SUITE(multisig_tests)
CScript
sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
BOOST_FOREACH(CKey key, keys)
{
vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
BOOST_AUTO_TEST_CASE(multisig_verify)
{
CKey key[4];
for(int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
CTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CTransaction txTo[3]; // Spending transaction
for(int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
vector<CKey> keys;
CScript s;
// Test a AND b:
keys.clear();
keys += key[0],key[1]; // magic operator+= from boost.assign
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, txTo[0], 0, true, 0));
for(int i = 0; i < 4; i++)
{
keys.clear();
keys += key[i];
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, true, 0), strprintf("a&b 1: %d", i));
keys.clear();
keys += key[1],key[i];
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, true, 0), strprintf("a&b 2: %d", i));
}
// Test a OR b:
for(int i = 0; i < 4; i++)
{
keys.clear();
keys += key[i];
s = sign_multisig(a_or_b, keys, txTo[1], 0);
if(i == 0 || i == 1)
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, txTo[1], 0, true, 0), strprintf("a|b: %d", i));
else
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0), strprintf("a|b: %d", i));
}
s.clear();
s << OP_0 << OP_0;
BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0));
s.clear();
s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, true, 0));
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
{
keys.clear();
keys += key[i],key[j];
s = sign_multisig(escrow, keys, txTo[2], 0);
if(i < j && i < 3 && j < 3)
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, txTo[2], 0, true, 0), strprintf("escrow 1: %d %d", i, j));
else
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, txTo[2], 0, true, 0), strprintf("escrow 2: %d %d", i, j));
}
}
BOOST_AUTO_TEST_CASE(multisig_IsStandard)
{
CKey key[4];
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
txnouttype whichType;
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_and_b, whichType));
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_or_b, whichType));
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(escrow, whichType));
CScript one_of_four;
one_of_four << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << key[3].GetPubKey() << OP_4 << OP_CHECKMULTISIG;
BOOST_CHECK(!::IsStandard(one_of_four, whichType));
CScript malformed[6];
malformed[0] << OP_3 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
malformed[1] << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
malformed[2] << OP_0 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
malformed[3] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_0 << OP_CHECKMULTISIG;
malformed[4] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_CHECKMULTISIG;
malformed[5] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey();
for (int i = 0; i < 6; i++)
BOOST_CHECK(!::IsStandard(malformed[i], whichType));
}
BOOST_AUTO_TEST_CASE(multisig_Solver1)
{
// Tests Solver() that returns lists of keys that are
// required to satisfy a ScriptPubKey
//
// Also tests IsMine() and ExtractAddress()
//
// Note: ExtractAddress for the multisignature transactions
// always returns false for this release, even if you have
// one key that would satisfy an (a|b) or 2-of-3 keys needed
// to spend an escrow transaction.
//
CBasicKeyStore keystore, emptykeystore, partialkeystore;
CKey key[3];
CTxDestination keyaddr[3];
for (int i = 0; i < 3; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
keyaddr[i] = key[i].GetPubKey().GetID();
}
partialkeystore.AddKey(key[0]);
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << key[0].GetPubKey() << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_DUP << OP_HASH160 << key[0].GetPubKey().GetID() << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4);
CTxDestination addr;
BOOST_CHECK(!ExtractDestination(s, addr));
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4);
vector<CTxDestination> addrs;
int nRequired;
BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired));
BOOST_CHECK(addrs[0] == keyaddr[0]);
BOOST_CHECK(addrs[1] == keyaddr[1]);
BOOST_CHECK(nRequired = 1);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 5);
}
}
BOOST_AUTO_TEST_CASE(multisig_Sign)
{
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for(int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
CTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CTransaction txTo[3]; // Spending transaction
for(int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
for(int i = 0; i < 3; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add required enum<commit_after>#include <boost/assert.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <openssl/ec.h>
#include <openssl/err.h>
#include "keystore.h"
#include "main.h"
#include "script.h"
#include "wallet.h"
using namespace std;
using namespace boost::assign;
typedef vector<unsigned char> valtype;
extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType);
/** Script verification flags */
enum
{
SCRIPT_VERIFY_NONE = 0,
SCRIPT_VERIFY_P2SH = (1U << 0),
SCRIPT_VERIFY_STRICTENC = (1U << 1),
SCRIPT_VERIFY_NOCACHE = (1U << 2),
};
BOOST_AUTO_TEST_SUITE(multisig_tests)
CScript
sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
BOOST_FOREACH(CKey key, keys)
{
vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
BOOST_AUTO_TEST_CASE(multisig_verify)
{
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
CKey key[4];
for(int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
CTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CTransaction txTo[3]; // Spending transaction
for(int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
vector<CKey> keys;
CScript s;
// Test a AND b:
keys.clear();
keys += key[0],key[1]; // magic operator+= from boost.assign
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, txTo[0], 0, flags, 0));
for(int i = 0; i < 4; i++)
{
keys.clear();
keys += key[i];
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, flags, 0), strprintf("a&b 1: %d", i));
keys.clear();
keys += key[1],key[i];
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, txTo[0], 0, flags, 0), strprintf("a&b 2: %d", i));
}
// Test a OR b:
for(int i = 0; i < 4; i++)
{
keys.clear();
keys += key[i];
s = sign_multisig(a_or_b, keys, txTo[1], 0);
if(i == 0 || i == 1)
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, txTo[1], 0, flags, 0), strprintf("a|b: %d", i));
else
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, txTo[1], 0, flags, 0), strprintf("a|b: %d", i));
}
s.clear();
s << OP_0 << OP_0;
BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, flags, 0));
s.clear();
s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, txTo[1], 0, flags, 0));
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
{
keys.clear();
keys += key[i],key[j];
s = sign_multisig(escrow, keys, txTo[2], 0);
if(i < j && i < 3 && j < 3)
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, txTo[2], 0, flags, 0), strprintf("escrow 1: %d %d", i, j));
else
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, txTo[2], 0, flags, 0), strprintf("escrow 2: %d %d", i, j));
}
}
BOOST_AUTO_TEST_CASE(multisig_IsStandard)
{
CKey key[4];
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
txnouttype whichType;
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_and_b, whichType));
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_or_b, whichType));
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(escrow, whichType));
CScript one_of_four;
one_of_four << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << key[3].GetPubKey() << OP_4 << OP_CHECKMULTISIG;
BOOST_CHECK(!::IsStandard(one_of_four, whichType));
CScript malformed[6];
malformed[0] << OP_3 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
malformed[1] << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
malformed[2] << OP_0 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
malformed[3] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_0 << OP_CHECKMULTISIG;
malformed[4] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_CHECKMULTISIG;
malformed[5] << OP_1 << key[0].GetPubKey() << key[1].GetPubKey();
for (int i = 0; i < 6; i++)
BOOST_CHECK(!::IsStandard(malformed[i], whichType));
}
BOOST_AUTO_TEST_CASE(multisig_Solver1)
{
// Tests Solver() that returns lists of keys that are
// required to satisfy a ScriptPubKey
//
// Also tests IsMine() and ExtractAddress()
//
// Note: ExtractAddress for the multisignature transactions
// always returns false for this release, even if you have
// one key that would satisfy an (a|b) or 2-of-3 keys needed
// to spend an escrow transaction.
//
CBasicKeyStore keystore, emptykeystore, partialkeystore;
CKey key[3];
CTxDestination keyaddr[3];
for (int i = 0; i < 3; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
keyaddr[i] = key[i].GetPubKey().GetID();
}
partialkeystore.AddKey(key[0]);
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << key[0].GetPubKey() << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_DUP << OP_HASH160 << key[0].GetPubKey().GetID() << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4U);
CTxDestination addr;
BOOST_CHECK(!ExtractDestination(s, addr));
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4U);
vector<CTxDestination> addrs;
int nRequired;
BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired));
BOOST_CHECK(addrs[0] == keyaddr[0]);
BOOST_CHECK(addrs[1] == keyaddr[1]);
BOOST_CHECK(nRequired == 1);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 5);
}
}
BOOST_AUTO_TEST_CASE(multisig_Sign)
{
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for(int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
CScript a_and_b;
a_and_b << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << key[0].GetPubKey() << key[1].GetPubKey() << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << key[0].GetPubKey() << key[1].GetPubKey() << key[2].GetPubKey() << OP_3 << OP_CHECKMULTISIG;
CTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CTransaction txTo[3]; // Spending transaction
for(int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
for(int i = 0; i < 3; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
#if defined(BOTAN_HAS_PASSHASH9)
#include <botan/passhash9.h>
#endif
namespace Botan_Tests {
namespace {
#if defined(BOTAN_HAS_BCRYPT)
class Bcrypt_Tests : public Text_Based_Test
{
public:
Bcrypt_Tests() : Text_Based_Test("bcrypt.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = get_req_bin(vars, "Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = get_req_str(vars, "Passhash");
Test::Result result("bcrypt");
result.test_eq("correct hash accepted", Botan::check_bcrypt(password, passhash), true);
const size_t max_level = (Test::run_long_tests() ? 14 : 7);
for(size_t level = 4; level <= max_level; ++level)
{
const std::string gen_hash = generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
return result;
}
};
BOTAN_REGISTER_TEST("bcrypt", Bcrypt_Tests);
#endif
#if defined(BOTAN_HAS_PASSHASH9)
class Passhash9_Tests : public Text_Based_Test
{
public:
Passhash9_Tests() : Text_Based_Test("passhash9.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = get_req_bin(vars, "Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = get_req_str(vars, "Passhash");
Test::Result result("passhash9");
result.test_eq("correct hash accepted", Botan::check_passhash9(password, passhash), true);
for(uint8_t alg_id = 0; alg_id <= 4; ++alg_id)
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), 2, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
const size_t max_level = (Test::run_long_tests() ? 14 : 8);
for(size_t level = 1; level <= max_level; ++level)
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), level);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
return result;
}
};
BOTAN_REGISTER_TEST("passhash9", Passhash9_Tests);
#endif
}
}
<commit_msg>Avoid long tests for each bcrypt password<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_BCRYPT)
#include <botan/bcrypt.h>
#endif
#if defined(BOTAN_HAS_PASSHASH9)
#include <botan/passhash9.h>
#endif
namespace Botan_Tests {
namespace {
#if defined(BOTAN_HAS_BCRYPT)
class Bcrypt_Tests : public Text_Based_Test
{
public:
Bcrypt_Tests() : Text_Based_Test("bcrypt.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = get_req_bin(vars, "Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = get_req_str(vars, "Passhash");
Test::Result result("bcrypt");
result.test_eq("correct hash accepted", Botan::check_bcrypt(password, passhash), true);
// self-test low levels for each test password
for(size_t level = 4; level <= 6; ++level)
{
const std::string gen_hash = generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
return result;
}
std::vector<Test::Result> run_final_tests()
{
Test::Result result("bcrypt");
uint64_t start = Test::timestamp();
const std::string password = "ag00d1_2BE5ur3";
const size_t max_level = (Test::run_long_tests() ? 15 : 10);
for(size_t level = 4; level <= max_level; ++level)
{
const std::string gen_hash = generate_bcrypt(password, Test::rng(), level);
result.test_eq("generated hash accepted", Botan::check_bcrypt(password, gen_hash), true);
}
result.set_ns_consumed(Test::timestamp() - start);
return {result};
}
};
BOTAN_REGISTER_TEST("bcrypt", Bcrypt_Tests);
#endif
#if defined(BOTAN_HAS_PASSHASH9)
class Passhash9_Tests : public Text_Based_Test
{
public:
Passhash9_Tests() : Text_Based_Test("passhash9.vec", "Password,Passhash") {}
Test::Result run_one_test(const std::string&, const VarMap& vars) override
{
// Encoded as binary so we can test binary inputs
const std::vector<uint8_t> password_vec = get_req_bin(vars, "Password");
const std::string password(reinterpret_cast<const char*>(password_vec.data()),
password_vec.size());
const std::string passhash = get_req_str(vars, "Passhash");
Test::Result result("passhash9");
result.test_eq("correct hash accepted", Botan::check_passhash9(password, passhash), true);
for(uint8_t alg_id = 0; alg_id <= 4; ++alg_id)
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), 2, alg_id);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
const size_t max_level = (Test::run_long_tests() ? 14 : 8);
for(size_t level = 1; level <= max_level; ++level)
{
const std::string gen_hash = Botan::generate_passhash9(password, Test::rng(), level);
if(!result.test_eq("generated hash accepted", Botan::check_passhash9(password, gen_hash), true))
{
result.test_note("hash was " + gen_hash);
}
}
return result;
}
};
BOTAN_REGISTER_TEST("passhash9", Passhash9_Tests);
#endif
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
MrEd interface to various garbage collectors, including the Boehm
collector, SenoraGC, and MzScheme's precise collector.
Copyright (c) 2004-2010 PLT Scheme Inc.
*************************************************************************/
/*************************************************************************
Based On:
Copyright (c) 1994 by Xerox Corporation. All rights reserved.
THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
Last modified on Sat Nov 19 19:31:14 PST 1994 by ellis
on Sat Jun 8 15:10:00 PST 1994 by boehm
Permission is hereby granted to copy this code for any purpose,
provided the above notices are retained on all copies.
Authors: John R. Ellis and Jesse Hull
**************************************************************************/
/* Boehm, December 20, 1994 7:26 pm PST */
#include <stddef.h>
#include "wxGC.h"
/* With extensions, or with x86 Mac OS X, MrEd's `new' gets used by
libraries that shouldn't use it. So we can't define `new' on that
platform. For PPC, we define `new' and `delete' to use malloc() and
free(); for some reason, linking fails in Mac OS X 10.3 if we just
omit `new' and `delete'. There should be no problem under Windows,
due to the way DLL linking works. */
#ifndef WIN32
# if defined(OS_X) && defined(__POWERPC__)
# define MALLOC_FOR_BUILTIN_NEW
# include <stdio.h>
# include <stdlib.h>
# else
# define DONT_DEFINE_BUILTIN_NEW
# endif
#endif
#ifdef COMPACT_BACKTRACE_GC
# include <stdio.h>
#endif
#ifdef MPW_CPLUS
extern "C" {
typedef void (*GC_F_PTR)(void *, void *);
}
# define CAST_GCP (GC_F_PTR)
# define CAST_GCPP (GC_F_PTR *)
#else
# define CAST_GCP /* empty */
# define CAST_GCPP /* empty */
#endif
#ifdef USE_SENORA_GC
struct GC_Set *cpp_objects;
typedef void (*GC_finalization_proc)(void *, void *);
#if SGC_STD_DEBUGGING
# define USE_WXOBJECT_TRACE_COUNTER
#endif
#endif
#ifndef DONT_DEFINE_BUILTIN_NEW
void *operator new(size_t size)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
return malloc(size);
#else
# ifdef USE_SENORA_GC
if (!cpp_objects)
cpp_objects = GC_new_set("C++", NULL, NULL, NULL, NULL, NULL, 0);
return GC_malloc_specific(size, cpp_objects);
# else
return GC_malloc(size);
#endif
#endif
}
void operator delete(void *obj)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
free(obj);
#endif
}
#endif
void gc_cleanup::install_cleanup(void)
{
GC_finalization_proc old_fn;
void *old_data;
# ifdef MZ_PRECISE_GC
# define ALLOW_NON_BASE 0
# define CHECK_BASE 0
# else
# ifdef wx_xt
# define ALLOW_NON_BASE 0
# define CHECK_BASE 0
# else
# ifdef WIN32
# define ALLOW_NON_BASE 0
# define CHECK_BASE 1
# define CRASH_ON_NONBASE 1
# else
# define ALLOW_NON_BASE 1
# define CHECK_BASE 0
# endif
# endif
# endif
# if CHECK_BASE || ALLOW_NON_BASE
if (GC_base(this) != (void *)this) {
# if ALLOW_NON_BASE
return;
# else
# ifdef CRASH_ON_NONBASE
*(long *)0x0 = 1;
# else
printf("Clean-up object is not the base object\n");
abort();
# endif
# endif
}
# endif
GC_register_finalizer_ignore_self(gcOBJ_TO_PTR(this),
CAST_GCP GC_cleanup, NULL,
CAST_GCPP &old_fn, &old_data);
# if CHECK_BASE
if (old_fn) {
# ifdef CRASH_ON_NONBASE
*(long *)0x0 = 1;
# else
printf("Object already has a clean-up\n");
abort();
# endif
}
# endif
}
#define SHOW_CLEANUP_TIMES 0
#if SHOW_CLEANUP_TIMES
extern "C" long scheme_get_process_milliseconds();
#endif
void GC_cleanup(void *obj, void *)
{
gc *clean = (gc *)gcPTR_TO_OBJ(obj);
#ifdef MZ_PRECISE_GC
# ifdef COMPACT_BACKTRACE_GC
# if SHOW_CLEANUP_TIMES
long start;
start = scheme_get_process_milliseconds();
char *s;
s = clean->gcGetName();
printf("Cleanup: %s\n", s ? s : "???");
# endif
# endif
GC_cpp_delete(clean);
# ifdef COMPACT_BACKTRACE_GC
# if SHOW_CLEANUP_TIMES
start = scheme_get_process_milliseconds() - start;
printf(" done %d\n", start);
# endif
# endif
#else
clean->~gc();
#endif
}
/**********************************************************************/
#ifdef OPERATOR_NEW_ARRAY
# ifndef DONT_DEFINE_BUILTIN_NEW
void* operator new[](size_t size)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
return malloc(size);
#else
# ifdef USE_SENORA_GC
if (!cpp_objects)
cpp_objects = GC_new_set("C++", NULL, NULL, NULL, NULL, NULL, 0);
return GC_malloc_specific(size, cpp_objects);
# else
return GC_malloc(size);
# endif
#endif
}
void operator delete[](void *obj)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
free(obj);
#endif
}
# endif
#endif
/**********************************************************************/
#ifdef USE_SENORA_GC
struct GC_Set *wx_objects;
# ifdef USE_WXOBJECT_TRACE_COUNTER
extern void wxTraceCount(void *, int);
extern void wxTracePath(void *, unsigned long, void *);
extern void wxTraceInit(void);
extern void wxTraceDone(void);
extern void wxObjectFinalize(void *);
# endif
void *GC_cpp_malloc(size_t size)
{
if (!wx_objects)
wx_objects = GC_new_set("wxObjects",
# ifdef USE_WXOBJECT_TRACE_COUNTER
wxTraceInit,
wxTraceDone,
wxTraceCount,
wxTracePath,
wxObjectFinalize,
# else
NULL, NULL, NULL, NULL, NULL,
# endif
0);
return GC_malloc_specific(size, wx_objects);
}
# ifdef SGC_STD_DEBUGGING
void GC_cpp_for_each(void (*f)(void *, int, void *), void *data)
{
if (wx_objects)
GC_for_each_element(wx_objects, f, data);
}
int GC_is_wx_object(void *v)
{
return wx_objects && (GC_set(v) == wx_objects);
}
# endif
#endif
/**********************************************************************/
#ifdef MZ_PRECISE_GC
# define ZERO_OUT_DISPATCH 1
# ifdef COMPACT_BACKTRACE_GC
static char *get_xtagged_name(void *p);
extern char *(*GC_get_xtagged_name)(void *p);
# endif
typedef struct {
short tag;
short filler_used_for_hashing;
void *val;
} GC_WB;
void *GC_weak_box_val(void *b)
{
return ((GC_WB *)b)->val;
}
#include "scheme.h"
static void mark_cpp_object(void *p)
{
gc *obj = (gc *)p;
#if ZERO_OUT_DISPATCH
if (*(long *)obj)
#endif
obj->gcMark();
}
static void fixup_cpp_object(void *p)
{
gc *obj = (gc *)p;
#if ZERO_OUT_DISPATCH
if (*(long *)obj)
#endif
obj->gcFixup();
}
static int is_initialized;
static void initize(void)
{
/* Initialize: */
GC_mark_xtagged = mark_cpp_object;
GC_fixup_xtagged = fixup_cpp_object;
# ifdef COMPACT_BACKTRACE_GC
GC_get_xtagged_name = get_xtagged_name;
# endif
is_initialized = 1;
}
void *GC_cpp_malloc(size_t size)
{
void *p;
if (!is_initialized)
initize();
p = GC_malloc_one_xtagged(size);
return p;
}
void GC_cpp_delete(gc *v)
{
v->~gc();
#if ZERO_OUT_DISPATCH
((long *)v)[0] = 0;
#endif
}
# ifdef COMPACT_BACKTRACE_GC
static char name_buffer[256];
static char *get_xtagged_name(void *p)
{
char *s;
s = ((gc *)gcPTR_TO_OBJ(p))->gcGetName();
sprintf(name_buffer, "<%s>", (s ? s : "XTAGGED"));
return name_buffer;
}
char *gc::gcGetName() {
return NULL;
}
# endif
#endif
/**********************************************************************/
/* The accounting shadow serves two purposes. First, it allocates
largely untouched atomic memory to reflect the allocation of
bitmaps outside the GC space, so that the nominal allocation total
is related to the total taking into accoun bitmaps. Second, because
bitmaps are released through finalizers, the accounting shadow
forces a GC more frequently than might otherwise happen as the
total size of bitmaps grows. */
#define INIT_ACCUM_SIZE 1024 * 1024 * 5
#define INIT_ACCUM_COUNT 1000
static long total, accum = INIT_ACCUM_SIZE;
static int total_count, accum_count = INIT_ACCUM_COUNT;
void *GC_malloc_accounting_shadow(long a)
{
long *p;
if (a < (long)sizeof(long))
a = sizeof(long);
total += a;
accum -= a;
total_count += 1;
accum_count -= 1;
if (accum <= 0) {
GC_gcollect();
accum = total >> 1;
if (accum < INIT_ACCUM_SIZE)
accum = INIT_ACCUM_SIZE;
}
#ifdef wx_msw
/* Under Windows, the number of bitmaps matters, even if
they're small. */
if (accum_count <= 0) {
GC_gcollect();
accum_count = total_count >> 1;
if (accum_count < INIT_ACCUM_COUNT)
accum_count = INIT_ACCUM_COUNT;
}
#endif
p = (long *)GC_malloc_atomic(a);
*p = a;
return (void *)p;
}
void GC_free_accounting_shadow(void *p)
{
if (p) {
total -= *(long *)p;
accum += *(long *)p;
total_count -= 1;
accum_count += 1;
}
}
<commit_msg>fix MrEd3m build when using SGC<commit_after>/*************************************************************************
MrEd interface to various garbage collectors, including the Boehm
collector, SenoraGC, and MzScheme's precise collector.
Copyright (c) 2004-2010 PLT Scheme Inc.
*************************************************************************/
/*************************************************************************
Based On:
Copyright (c) 1994 by Xerox Corporation. All rights reserved.
THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
Last modified on Sat Nov 19 19:31:14 PST 1994 by ellis
on Sat Jun 8 15:10:00 PST 1994 by boehm
Permission is hereby granted to copy this code for any purpose,
provided the above notices are retained on all copies.
Authors: John R. Ellis and Jesse Hull
**************************************************************************/
/* Boehm, December 20, 1994 7:26 pm PST */
#include <stddef.h>
#include "wxGC.h"
/* With extensions, or with x86 Mac OS X, MrEd's `new' gets used by
libraries that shouldn't use it. So we can't define `new' on that
platform. For PPC, we define `new' and `delete' to use malloc() and
free(); for some reason, linking fails in Mac OS X 10.3 if we just
omit `new' and `delete'. There should be no problem under Windows,
due to the way DLL linking works. */
#ifndef WIN32
# if defined(OS_X) && defined(__POWERPC__)
# define MALLOC_FOR_BUILTIN_NEW
# include <stdio.h>
# include <stdlib.h>
# else
# define DONT_DEFINE_BUILTIN_NEW
# endif
#endif
#ifdef COMPACT_BACKTRACE_GC
# include <stdio.h>
#endif
#ifdef MPW_CPLUS
extern "C" {
typedef void (*GC_F_PTR)(void *, void *);
}
# define CAST_GCP (GC_F_PTR)
# define CAST_GCPP (GC_F_PTR *)
#else
# define CAST_GCP /* empty */
# define CAST_GCPP /* empty */
#endif
#ifdef MZ_PRECISE_GC
# undef USE_SENORA_GC
#endif
#ifdef USE_SENORA_GC
struct GC_Set *cpp_objects;
typedef void (*GC_finalization_proc)(void *, void *);
#if SGC_STD_DEBUGGING
# define USE_WXOBJECT_TRACE_COUNTER
#endif
#endif
#ifndef DONT_DEFINE_BUILTIN_NEW
void *operator new(size_t size)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
return malloc(size);
#else
# ifdef USE_SENORA_GC
if (!cpp_objects)
cpp_objects = GC_new_set("C++", NULL, NULL, NULL, NULL, NULL, 0);
return GC_malloc_specific(size, cpp_objects);
# else
return GC_malloc(size);
#endif
#endif
}
void operator delete(void *obj)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
free(obj);
#endif
}
#endif
void gc_cleanup::install_cleanup(void)
{
GC_finalization_proc old_fn;
void *old_data;
# ifdef MZ_PRECISE_GC
# define ALLOW_NON_BASE 0
# define CHECK_BASE 0
# else
# ifdef wx_xt
# define ALLOW_NON_BASE 0
# define CHECK_BASE 0
# else
# ifdef WIN32
# define ALLOW_NON_BASE 0
# define CHECK_BASE 1
# define CRASH_ON_NONBASE 1
# else
# define ALLOW_NON_BASE 1
# define CHECK_BASE 0
# endif
# endif
# endif
# if CHECK_BASE || ALLOW_NON_BASE
if (GC_base(this) != (void *)this) {
# if ALLOW_NON_BASE
return;
# else
# ifdef CRASH_ON_NONBASE
*(long *)0x0 = 1;
# else
printf("Clean-up object is not the base object\n");
abort();
# endif
# endif
}
# endif
GC_register_finalizer_ignore_self(gcOBJ_TO_PTR(this),
CAST_GCP GC_cleanup, NULL,
CAST_GCPP &old_fn, &old_data);
# if CHECK_BASE
if (old_fn) {
# ifdef CRASH_ON_NONBASE
*(long *)0x0 = 1;
# else
printf("Object already has a clean-up\n");
abort();
# endif
}
# endif
}
#define SHOW_CLEANUP_TIMES 0
#if SHOW_CLEANUP_TIMES
extern "C" long scheme_get_process_milliseconds();
#endif
void GC_cleanup(void *obj, void *)
{
gc *clean = (gc *)gcPTR_TO_OBJ(obj);
#ifdef MZ_PRECISE_GC
# ifdef COMPACT_BACKTRACE_GC
# if SHOW_CLEANUP_TIMES
long start;
start = scheme_get_process_milliseconds();
char *s;
s = clean->gcGetName();
printf("Cleanup: %s\n", s ? s : "???");
# endif
# endif
GC_cpp_delete(clean);
# ifdef COMPACT_BACKTRACE_GC
# if SHOW_CLEANUP_TIMES
start = scheme_get_process_milliseconds() - start;
printf(" done %d\n", start);
# endif
# endif
#else
clean->~gc();
#endif
}
/**********************************************************************/
#ifdef OPERATOR_NEW_ARRAY
# ifndef DONT_DEFINE_BUILTIN_NEW
void* operator new[](size_t size)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
return malloc(size);
#else
# ifdef USE_SENORA_GC
if (!cpp_objects)
cpp_objects = GC_new_set("C++", NULL, NULL, NULL, NULL, NULL, 0);
return GC_malloc_specific(size, cpp_objects);
# else
return GC_malloc(size);
# endif
#endif
}
void operator delete[](void *obj)
{
#ifdef MALLOC_FOR_BUILTIN_NEW
free(obj);
#endif
}
# endif
#endif
/**********************************************************************/
#ifdef USE_SENORA_GC
struct GC_Set *wx_objects;
# ifdef USE_WXOBJECT_TRACE_COUNTER
extern void wxTraceCount(void *, int);
extern void wxTracePath(void *, unsigned long, void *);
extern void wxTraceInit(void);
extern void wxTraceDone(void);
extern void wxObjectFinalize(void *);
# endif
void *GC_cpp_malloc(size_t size)
{
if (!wx_objects)
wx_objects = GC_new_set("wxObjects",
# ifdef USE_WXOBJECT_TRACE_COUNTER
wxTraceInit,
wxTraceDone,
wxTraceCount,
wxTracePath,
wxObjectFinalize,
# else
NULL, NULL, NULL, NULL, NULL,
# endif
0);
return GC_malloc_specific(size, wx_objects);
}
# ifdef SGC_STD_DEBUGGING
void GC_cpp_for_each(void (*f)(void *, int, void *), void *data)
{
if (wx_objects)
GC_for_each_element(wx_objects, f, data);
}
int GC_is_wx_object(void *v)
{
return wx_objects && (GC_set(v) == wx_objects);
}
# endif
#endif
/**********************************************************************/
#ifdef MZ_PRECISE_GC
# define ZERO_OUT_DISPATCH 1
# ifdef COMPACT_BACKTRACE_GC
static char *get_xtagged_name(void *p);
extern char *(*GC_get_xtagged_name)(void *p);
# endif
typedef struct {
short tag;
short filler_used_for_hashing;
void *val;
} GC_WB;
void *GC_weak_box_val(void *b)
{
return ((GC_WB *)b)->val;
}
#include "scheme.h"
static void mark_cpp_object(void *p)
{
gc *obj = (gc *)p;
#if ZERO_OUT_DISPATCH
if (*(long *)obj)
#endif
obj->gcMark();
}
static void fixup_cpp_object(void *p)
{
gc *obj = (gc *)p;
#if ZERO_OUT_DISPATCH
if (*(long *)obj)
#endif
obj->gcFixup();
}
static int is_initialized;
static void initize(void)
{
/* Initialize: */
GC_mark_xtagged = mark_cpp_object;
GC_fixup_xtagged = fixup_cpp_object;
# ifdef COMPACT_BACKTRACE_GC
GC_get_xtagged_name = get_xtagged_name;
# endif
is_initialized = 1;
}
void *GC_cpp_malloc(size_t size)
{
void *p;
if (!is_initialized)
initize();
p = GC_malloc_one_xtagged(size);
return p;
}
void GC_cpp_delete(gc *v)
{
v->~gc();
#if ZERO_OUT_DISPATCH
((long *)v)[0] = 0;
#endif
}
# ifdef COMPACT_BACKTRACE_GC
static char name_buffer[256];
static char *get_xtagged_name(void *p)
{
char *s;
s = ((gc *)gcPTR_TO_OBJ(p))->gcGetName();
sprintf(name_buffer, "<%s>", (s ? s : "XTAGGED"));
return name_buffer;
}
char *gc::gcGetName() {
return NULL;
}
# endif
#endif
/**********************************************************************/
/* The accounting shadow serves two purposes. First, it allocates
largely untouched atomic memory to reflect the allocation of
bitmaps outside the GC space, so that the nominal allocation total
is related to the total taking into accoun bitmaps. Second, because
bitmaps are released through finalizers, the accounting shadow
forces a GC more frequently than might otherwise happen as the
total size of bitmaps grows. */
#define INIT_ACCUM_SIZE 1024 * 1024 * 5
#define INIT_ACCUM_COUNT 1000
static long total, accum = INIT_ACCUM_SIZE;
static int total_count, accum_count = INIT_ACCUM_COUNT;
void *GC_malloc_accounting_shadow(long a)
{
long *p;
if (a < (long)sizeof(long))
a = sizeof(long);
total += a;
accum -= a;
total_count += 1;
accum_count -= 1;
if (accum <= 0) {
GC_gcollect();
accum = total >> 1;
if (accum < INIT_ACCUM_SIZE)
accum = INIT_ACCUM_SIZE;
}
#ifdef wx_msw
/* Under Windows, the number of bitmaps matters, even if
they're small. */
if (accum_count <= 0) {
GC_gcollect();
accum_count = total_count >> 1;
if (accum_count < INIT_ACCUM_COUNT)
accum_count = INIT_ACCUM_COUNT;
}
#endif
p = (long *)GC_malloc_atomic(a);
*p = a;
return (void *)p;
}
void GC_free_accounting_shadow(void *p)
{
if (p) {
total -= *(long *)p;
accum += *(long *)p;
total_count -= 1;
accum_count += 1;
}
}
<|endoftext|>
|
<commit_before>#include "treeface/gl/program.h"
#include "treeface/gl/type.h"
#include "treeface/gl/vertexattrib.h"
#include "treeface/misc/stringcast.h"
#include <treejuce/Logger.h>
#include <treejuce/StringRef.h>
#include <cstdio>
using namespace std;
using namespace treejuce;
TREEFACE_NAMESPACE_BEGIN
struct Program::Impl
{
treejuce::Array<VertexAttrib> attr_info;
treejuce::HashMap<String, int32> attr_idx_by_name;
treejuce::Array<UniformInfo> uni_store;
treejuce::HashMap<String, int32> uni_idx_by_name; // name => index
treejuce::HashMap<GLint, int32> uni_idx_by_loc; // location => index
};
Program::Program(): m_impl(new Impl())
{
m_program = glCreateProgram();
if (m_program == 0)
die("failed to allocate program ID");
m_shader_vert = glCreateShader(GL_VERTEX_SHADER);
if (!m_shader_vert)
die("failed to allocate shader ID for vertex shader");
m_shader_frag = glCreateShader(GL_FRAGMENT_SHADER);
if (!m_shader_frag)
die("failed to allocate shader ID for fragment shader");
}
Program::~Program()
{
if (m_program)
glDeleteProgram(m_program);
if (m_shader_vert)
glDeleteShader(m_shader_vert);
if (m_shader_frag)
glDeleteShader(m_shader_frag);
if (m_impl)
delete m_impl;
}
treejuce::Result Program::build(const char* src_vert_raw, const char* src_frag_raw)
{
DBG("build program");
if (compiled_and_linked)
return Result::fail("attempt to build program which is already built");
// compile shaders
{
glShaderSource(m_shader_vert, 1, &src_vert_raw, nullptr);
glCompileShader(m_shader_vert);
treejuce::Result re = fetch_shader_error_log(m_shader_vert);
if (!re)
return Result::fail("failed to compile vertex shader:\n" +
re.getErrorMessage() + "\n" +
"==== vertex shader source ====\n\n" +
String(src_vert_raw) + "\n" +
"==============================\n");
glAttachShader(m_program, m_shader_vert);
}
{
glShaderSource(m_shader_frag, 1, &src_frag_raw, nullptr);
glCompileShader(m_shader_frag);
treejuce::Result re = fetch_shader_error_log(m_shader_frag);
if (!re)
return Result::fail("failed to compile fragment shader:\n" +
re.getErrorMessage() + "\n" +
"==== fragment shader source ====\n\n" +
String(src_frag_raw) + "\n" +
"================================\n");
glAttachShader(m_program, m_shader_frag);
}
// link program
glLinkProgram(m_program);
{
treejuce::Result re = fetch_program_error_log();
if (!re)
return Result::fail("failed to link shader:\n" +
re.getErrorMessage() + "\n");
}
// extract program attributes
int n_attr = -1;
glGetProgramiv(m_program, GL_ACTIVE_ATTRIBUTES, &n_attr);
if (n_attr == -1)
die("failed to get attribute number in program %u", m_program);
DBG("vertex attribute amount: "+String(n_attr));
for (int i_attr = 0; i_attr < n_attr; i_attr++)
{
char attr_name[256];
GLsizei attr_name_len = -1;
GLenum attr_type = 0;
GLsizei attr_size = -1;
glGetActiveAttrib(m_program, i_attr, 256,
&attr_name_len, &attr_size, &attr_type, attr_name);
DBG(" attribute "+String(i_attr)+": name "+String(attr_name)+", type "+gl_type_to_string(attr_type)+", size "+String(attr_size));
if (attr_name_len == -1)
die("failed to get info for attribute %d", i_attr);
if (attr_name_len >= 255)
die("attribute %d name is too long", i_attr);
m_impl->attr_info.add({treejuce::String(attr_name), attr_size, attr_type});
m_impl->attr_idx_by_name.set(treejuce::String(attr_name), i_attr);
}
// extract program uniforms
int n_uni = -1;
glGetProgramiv(m_program, GL_ACTIVE_UNIFORMS, &n_uni);
if (n_uni == -1)
die("failed to get uniform number from program %u", m_program);
DBG("uniform amount: "+String(n_uni));
for (int i_uni = 0; i_uni < n_uni; i_uni++)
{
// get uniform info
char uni_name[256];
GLsizei uni_name_len = -1;
GLsizei uni_size = -1;
GLenum uni_type = 0;
glGetActiveUniform(m_program, i_uni, 256,
&uni_name_len, &uni_size, &uni_type, uni_name);
if (uni_name_len == -1)
die("failed to get info for uniform %d", i_uni);
if (uni_name_len >= 255)
die("uniform %d name is too long", i_uni);
// get uniform location by name
GLint uni_loc = glGetUniformLocation(m_program, uni_name);
if (uni_loc == -1)
die("failed to get location for uniform %s", uni_name);
DBG(" uniform "+String(i_uni)+" "+String(uni_name)+" at " + String(uni_loc) + ": type "+gl_type_to_string(uni_type)+", size "+String(uni_size));
// store uniform info
m_impl->uni_store.add({uni_name, uni_size, uni_type, uni_loc});
m_impl->uni_idx_by_name.set(uni_name, i_uni);
m_impl->uni_idx_by_loc.set(uni_loc, i_uni);
}
compiled_and_linked = true;
return treejuce::Result::ok();
}
void Program::use() NOEXCEPT
{
glUseProgram(m_program);
}
treejuce::Result Program::fetch_shader_error_log(GLuint shader)
{
GLint result = -1;
glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
if (result == -1)
die("failed to fetch compile status from shader %u\n", shader);
if (result == GL_FALSE)
{
GLint log_len = -1;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
if (log_len > 0)
{
char* log = (char*) malloc(log_len+1);
GLsizei written = 0;
glGetShaderInfoLog(shader, log_len, &written, log);
treejuce::Result re = treejuce::Result::fail(log);
free(log);
return re;
}
else
{
die("failed to retrieve shader compile error log");
}
}
return treejuce::Result::ok();
}
treejuce::Result Program::fetch_program_error_log()
{
GLint result = -1;
glGetProgramiv(m_program, GL_LINK_STATUS, &result);
if (result == -1)
die("failed to fetch link status from program %u\n", m_program);
if (result == GL_FALSE)
{
GLint log_len = -1;
glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &log_len);
if (log_len > 0)
{
char* log = (char*) malloc(log_len + 1);
GLsizei written = 0;
glGetProgramInfoLog(m_program, log_len, &written, log);
treejuce::Result re = treejuce::Result::fail(log);
free(log);
return re;
}
else
{
die("failed to retrieve program link error log");
}
}
return treejuce::Result::ok();
}
void Program::instant_set_uniform(GLint uni_loc, GLint value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_INT ||
uni_info.type == GL_BOOL ||
uni_info.type == GL_SAMPLER_2D ||
uni_info.type == GL_SAMPLER_3D ||
uni_info.type == GL_SAMPLER_CUBE ||
uni_info.type == GL_SAMPLER_2D_SHADOW ||
uni_info.type == GL_SAMPLER_2D_ARRAY ||
uni_info.type == GL_SAMPLER_2D_ARRAY_SHADOW ||
uni_info.type == GL_SAMPLER_CUBE_SHADOW);
#endif
glUniform1i(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, GLuint value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_UNSIGNED_INT);
#endif
glUniform1ui(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, GLfloat value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT);
#endif
glUniform1f(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, const Sampler& sampler) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_SAMPLER_2D ||
uni_info.type == GL_SAMPLER_3D ||
uni_info.type == GL_SAMPLER_CUBE ||
uni_info.type == GL_SAMPLER_2D_SHADOW ||
uni_info.type == GL_SAMPLER_2D_ARRAY ||
uni_info.type == GL_SAMPLER_2D_ARRAY_SHADOW ||
uni_info.type == GL_SAMPLER_CUBE_SHADOW);
#endif
glUniform1i(uni_loc, sampler.m_sampler);
}
void Program::instant_set_uniform(GLint uni_loc, const Vec4f& value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT_VEC4);
#endif
glUniform4fv(uni_loc, 1, (const float*)&value);
}
void Program::instant_set_uniform(GLint uni_loc, const Mat4f& value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT_MAT4);
#endif
glUniformMatrix4fv(uni_loc, 1, false, (const float*) &value);
}
int Program::get_attribute_index(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->attr_idx_by_name.contains(name))
return m_impl->attr_idx_by_name[name];
else
return -1;
}
const VertexAttrib& Program::get_attribute_info(int i_attr) const NOEXCEPT
{
return m_impl->attr_info.getReference(i_attr);
}
int Program::get_uniform_index(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->uni_idx_by_name.contains(name))
return m_impl->uni_idx_by_name[name];
else
return -1;
}
int Program::get_uniform_index(const GLint uni_loc) const NOEXCEPT
{
if (m_impl->uni_idx_by_loc.contains(uni_loc))
return m_impl->uni_idx_by_loc[uni_loc];
else
return -1;
}
const UniformInfo& Program::get_uniform_info(int i_uni) const NOEXCEPT
{
return m_impl->uni_store.getReference(i_uni);
}
GLint Program::get_uniform_location(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->uni_idx_by_name.contains(name))
{
int index = m_impl->uni_idx_by_name[name];
return m_impl->uni_store.getReference(index).location;
}
else
{
return -1;
}
}
TREEFACE_NAMESPACE_END
<commit_msg>allow float and uint setters to set float uniform<commit_after>#include "treeface/gl/program.h"
#include "treeface/gl/type.h"
#include "treeface/gl/vertexattrib.h"
#include "treeface/misc/stringcast.h"
#include <treejuce/Logger.h>
#include <treejuce/StringRef.h>
#include <cstdio>
using namespace std;
using namespace treejuce;
TREEFACE_NAMESPACE_BEGIN
struct Program::Impl
{
treejuce::Array<VertexAttrib> attr_info;
treejuce::HashMap<String, int32> attr_idx_by_name;
treejuce::Array<UniformInfo> uni_store;
treejuce::HashMap<String, int32> uni_idx_by_name; // name => index
treejuce::HashMap<GLint, int32> uni_idx_by_loc; // location => index
};
Program::Program(): m_impl(new Impl())
{
m_program = glCreateProgram();
if (m_program == 0)
die("failed to allocate program ID");
m_shader_vert = glCreateShader(GL_VERTEX_SHADER);
if (!m_shader_vert)
die("failed to allocate shader ID for vertex shader");
m_shader_frag = glCreateShader(GL_FRAGMENT_SHADER);
if (!m_shader_frag)
die("failed to allocate shader ID for fragment shader");
}
Program::~Program()
{
if (m_program)
glDeleteProgram(m_program);
if (m_shader_vert)
glDeleteShader(m_shader_vert);
if (m_shader_frag)
glDeleteShader(m_shader_frag);
if (m_impl)
delete m_impl;
}
treejuce::Result Program::build(const char* src_vert_raw, const char* src_frag_raw)
{
DBG("build program");
if (compiled_and_linked)
return Result::fail("attempt to build program which is already built");
// compile shaders
{
glShaderSource(m_shader_vert, 1, &src_vert_raw, nullptr);
glCompileShader(m_shader_vert);
treejuce::Result re = fetch_shader_error_log(m_shader_vert);
if (!re)
return Result::fail("failed to compile vertex shader:\n" +
re.getErrorMessage() + "\n" +
"==== vertex shader source ====\n\n" +
String(src_vert_raw) + "\n" +
"==============================\n");
glAttachShader(m_program, m_shader_vert);
}
{
glShaderSource(m_shader_frag, 1, &src_frag_raw, nullptr);
glCompileShader(m_shader_frag);
treejuce::Result re = fetch_shader_error_log(m_shader_frag);
if (!re)
return Result::fail("failed to compile fragment shader:\n" +
re.getErrorMessage() + "\n" +
"==== fragment shader source ====\n\n" +
String(src_frag_raw) + "\n" +
"================================\n");
glAttachShader(m_program, m_shader_frag);
}
// link program
glLinkProgram(m_program);
{
treejuce::Result re = fetch_program_error_log();
if (!re)
return Result::fail("failed to link shader:\n" +
re.getErrorMessage() + "\n");
}
// extract program attributes
int n_attr = -1;
glGetProgramiv(m_program, GL_ACTIVE_ATTRIBUTES, &n_attr);
if (n_attr == -1)
die("failed to get attribute number in program %u", m_program);
DBG("vertex attribute amount: "+String(n_attr));
for (int i_attr = 0; i_attr < n_attr; i_attr++)
{
char attr_name[256];
GLsizei attr_name_len = -1;
GLenum attr_type = 0;
GLsizei attr_size = -1;
glGetActiveAttrib(m_program, i_attr, 256,
&attr_name_len, &attr_size, &attr_type, attr_name);
DBG(" attribute "+String(i_attr)+": name "+String(attr_name)+", type "+gl_type_to_string(attr_type)+", size "+String(attr_size));
if (attr_name_len == -1)
die("failed to get info for attribute %d", i_attr);
if (attr_name_len >= 255)
die("attribute %d name is too long", i_attr);
m_impl->attr_info.add({treejuce::String(attr_name), attr_size, attr_type});
m_impl->attr_idx_by_name.set(treejuce::String(attr_name), i_attr);
}
// extract program uniforms
int n_uni = -1;
glGetProgramiv(m_program, GL_ACTIVE_UNIFORMS, &n_uni);
if (n_uni == -1)
die("failed to get uniform number from program %u", m_program);
DBG("uniform amount: "+String(n_uni));
for (int i_uni = 0; i_uni < n_uni; i_uni++)
{
// get uniform info
char uni_name[256];
GLsizei uni_name_len = -1;
GLsizei uni_size = -1;
GLenum uni_type = 0;
glGetActiveUniform(m_program, i_uni, 256,
&uni_name_len, &uni_size, &uni_type, uni_name);
if (uni_name_len == -1)
die("failed to get info for uniform %d", i_uni);
if (uni_name_len >= 255)
die("uniform %d name is too long", i_uni);
// get uniform location by name
GLint uni_loc = glGetUniformLocation(m_program, uni_name);
if (uni_loc == -1)
die("failed to get location for uniform %s", uni_name);
DBG(" uniform "+String(i_uni)+" "+String(uni_name)+" at " + String(uni_loc) + ": type "+gl_type_to_string(uni_type)+", size "+String(uni_size));
// store uniform info
m_impl->uni_store.add({uni_name, uni_size, uni_type, uni_loc});
m_impl->uni_idx_by_name.set(uni_name, i_uni);
m_impl->uni_idx_by_loc.set(uni_loc, i_uni);
}
compiled_and_linked = true;
return treejuce::Result::ok();
}
void Program::use() NOEXCEPT
{
glUseProgram(m_program);
}
treejuce::Result Program::fetch_shader_error_log(GLuint shader)
{
GLint result = -1;
glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
if (result == -1)
die("failed to fetch compile status from shader %u\n", shader);
if (result == GL_FALSE)
{
GLint log_len = -1;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
if (log_len > 0)
{
char* log = (char*) malloc(log_len+1);
GLsizei written = 0;
glGetShaderInfoLog(shader, log_len, &written, log);
treejuce::Result re = treejuce::Result::fail(log);
free(log);
return re;
}
else
{
die("failed to retrieve shader compile error log");
}
}
return treejuce::Result::ok();
}
treejuce::Result Program::fetch_program_error_log()
{
GLint result = -1;
glGetProgramiv(m_program, GL_LINK_STATUS, &result);
if (result == -1)
die("failed to fetch link status from program %u\n", m_program);
if (result == GL_FALSE)
{
GLint log_len = -1;
glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &log_len);
if (log_len > 0)
{
char* log = (char*) malloc(log_len + 1);
GLsizei written = 0;
glGetProgramInfoLog(m_program, log_len, &written, log);
treejuce::Result re = treejuce::Result::fail(log);
free(log);
return re;
}
else
{
die("failed to retrieve program link error log");
}
}
return treejuce::Result::ok();
}
void Program::instant_set_uniform(GLint uni_loc, GLint value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_INT ||
uni_info.type == GL_BOOL ||
uni_info.type == GL_SAMPLER_2D ||
uni_info.type == GL_SAMPLER_3D ||
uni_info.type == GL_SAMPLER_CUBE ||
uni_info.type == GL_SAMPLER_2D_SHADOW ||
uni_info.type == GL_SAMPLER_2D_ARRAY ||
uni_info.type == GL_SAMPLER_2D_ARRAY_SHADOW ||
uni_info.type == GL_SAMPLER_CUBE_SHADOW);
#endif
glUniform1i(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, GLuint value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_UNSIGNED_INT ||
uni_info.type == GL_BOOL);
#endif
glUniform1ui(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, GLfloat value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT ||
uni_info.type == GL_BOOL);
#endif
glUniform1f(uni_loc, value);
}
void Program::instant_set_uniform(GLint uni_loc, const Sampler& sampler) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_SAMPLER_2D ||
uni_info.type == GL_SAMPLER_3D ||
uni_info.type == GL_SAMPLER_CUBE ||
uni_info.type == GL_SAMPLER_2D_SHADOW ||
uni_info.type == GL_SAMPLER_2D_ARRAY ||
uni_info.type == GL_SAMPLER_2D_ARRAY_SHADOW ||
uni_info.type == GL_SAMPLER_CUBE_SHADOW);
#endif
glUniform1i(uni_loc, sampler.m_sampler);
}
void Program::instant_set_uniform(GLint uni_loc, const Vec4f& value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT_VEC4);
#endif
glUniform4fv(uni_loc, 1, (const float*)&value);
}
void Program::instant_set_uniform(GLint uni_loc, const Mat4f& value) const NOEXCEPT
{
if (uni_loc == -1) return;
#ifdef JUCE_DEBUG
int i_uni = get_uniform_index(uni_loc);
jassert(i_uni >= 0);
const UniformInfo& uni_info = m_impl->uni_store.getReference(i_uni);
jassert(uni_info.n_elem == 1);
jassert(uni_info.type == GL_FLOAT_MAT4);
#endif
glUniformMatrix4fv(uni_loc, 1, false, (const float*) &value);
}
int Program::get_attribute_index(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->attr_idx_by_name.contains(name))
return m_impl->attr_idx_by_name[name];
else
return -1;
}
const VertexAttrib& Program::get_attribute_info(int i_attr) const NOEXCEPT
{
return m_impl->attr_info.getReference(i_attr);
}
int Program::get_uniform_index(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->uni_idx_by_name.contains(name))
return m_impl->uni_idx_by_name[name];
else
return -1;
}
int Program::get_uniform_index(const GLint uni_loc) const NOEXCEPT
{
if (m_impl->uni_idx_by_loc.contains(uni_loc))
return m_impl->uni_idx_by_loc[uni_loc];
else
return -1;
}
const UniformInfo& Program::get_uniform_info(int i_uni) const NOEXCEPT
{
return m_impl->uni_store.getReference(i_uni);
}
GLint Program::get_uniform_location(const treejuce::String& name) const NOEXCEPT
{
if (m_impl->uni_idx_by_name.contains(name))
{
int index = m_impl->uni_idx_by_name[name];
return m_impl->uni_store.getReference(index).location;
}
else
{
return -1;
}
}
TREEFACE_NAMESPACE_END
<|endoftext|>
|
<commit_before>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
// Created on behalf of Universal Robots A/S
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Exner exner@fzi.de
* \date 2019-10-21
*
*/
//----------------------------------------------------------------------
#include <regex>
#include <ur_client_library/log.h>
#include <ur_client_library/ur/dashboard_client.h>
#include <ur_client_library/exceptions.h>
namespace urcl
{
DashboardClient::DashboardClient(const std::string& host) : host_(host), port_(DASHBOARD_SERVER_PORT)
{
}
bool DashboardClient::connect()
{
if (getState() == comm::SocketState::Connected)
{
URCL_LOG_ERROR("%s", "Socket is already connected. Refusing to reconnect.");
return false;
}
bool ret_val = false;
if (TCPSocket::setup(host_, port_))
{
URCL_LOG_INFO("%s", read().c_str());
ret_val = true;
}
return ret_val;
}
void DashboardClient::disconnect()
{
URCL_LOG_INFO("Disconnecting from Dashboard server on %s:%d", host_.c_str(), port_);
TCPSocket::close();
}
bool DashboardClient::send(const std::string& text)
{
size_t len = text.size();
const uint8_t* data = reinterpret_cast<const uint8_t*>(text.c_str());
size_t written;
return TCPSocket::write(data, len, written);
}
std::string DashboardClient::read()
{
std::stringstream result;
char character;
size_t read_chars = 99;
while (read_chars > 0)
{
if (!TCPSocket::read((uint8_t*)&character, 1, read_chars))
{
disconnect();
throw TimeoutException("Did not receive answer from dashboard server in time. Disconnecting from dashboard "
"server.",
*recv_timeout_);
}
result << character;
if (character == '\n')
{
break;
}
}
return result.str();
}
std::string DashboardClient::sendAndReceive(const std::string& text)
{
std::string response = "ERROR";
std::lock_guard<std::mutex> lock(write_mutex_);
if (send(text))
{
response = read();
}
else
{
throw UrException("Failed to send request to dashboard server. Are you connected to the Dashboard Server?");
}
rtrim(response);
return response;
}
} // namespace urcl
<commit_msg>Initialized receive timeout and changed exception to warning (#118)<commit_after>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
// Created on behalf of Universal Robots A/S
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Exner exner@fzi.de
* \date 2019-10-21
*
*/
//----------------------------------------------------------------------
#include <regex>
#include <ur_client_library/log.h>
#include <ur_client_library/ur/dashboard_client.h>
#include <ur_client_library/exceptions.h>
namespace urcl
{
DashboardClient::DashboardClient(const std::string& host) : host_(host), port_(DASHBOARD_SERVER_PORT)
{
}
bool DashboardClient::connect()
{
if (getState() == comm::SocketState::Connected)
{
URCL_LOG_ERROR("%s", "Socket is already connected. Refusing to reconnect.");
return false;
}
bool ret_val = false;
if (TCPSocket::setup(host_, port_))
{
URCL_LOG_INFO("%s", read().c_str());
ret_val = true;
}
timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
TCPSocket::setReceiveTimeout(tv);
return ret_val;
}
void DashboardClient::disconnect()
{
URCL_LOG_INFO("Disconnecting from Dashboard server on %s:%d", host_.c_str(), port_);
TCPSocket::close();
}
bool DashboardClient::send(const std::string& text)
{
size_t len = text.size();
const uint8_t* data = reinterpret_cast<const uint8_t*>(text.c_str());
size_t written;
return TCPSocket::write(data, len, written);
}
std::string DashboardClient::read()
{
std::stringstream result;
char character;
size_t read_chars = 99;
while (read_chars > 0)
{
if (!TCPSocket::read((uint8_t*)&character, 1, read_chars))
{
disconnect();
throw TimeoutException("Did not receive answer from dashboard server in time. Disconnecting from dashboard "
"server.",
*recv_timeout_);
}
result << character;
if (character == '\n')
{
break;
}
}
return result.str();
}
std::string DashboardClient::sendAndReceive(const std::string& text)
{
std::string response = "ERROR";
std::lock_guard<std::mutex> lock(write_mutex_);
if (send(text))
{
response = read();
}
else
{
throw UrException("Failed to send request to dashboard server. Are you connected to the Dashboard Server?");
}
rtrim(response);
return response;
}
} // namespace urcl
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "7zAlloc.h"
#include "7zMyAlloc.h"
#include "7zFile.h"
#include "LzmaEnc.h"
#include "LzmaDec.h"
#include "Types.h"
ZString GetAppDir() {
char szPathName[MAX_PATH+48] = "";
GetModuleFileNameA(NULL, szPathName, MAX_PATH);
char* p = strrchr(szPathName, '\\');
p = (!p) ? szPathName : p+1;
strcpy(p,"");
return ZString(szPathName);
}
static void *SzAlloc(void *p, size_t size) { p = p; return MidAlloc(size); }
static void SzFree(void *p, void *address) { p = p; MidFree(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };
#define IN_BUF_SIZE (1 << 8)
#define OUT_BUF_SIZE (1 << 8)
static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
UInt64 unpackSize)
{
int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
Byte inBuf[IN_BUF_SIZE];
Byte outBuf[OUT_BUF_SIZE];
size_t inPos = 0, inSize = 0, outPos = 0;
LzmaDec_Init(state);
for (;;)
{
if (inPos == inSize)
{
inSize = IN_BUF_SIZE;
RINOK(inStream->Read(inStream, inBuf, &inSize));
inPos = 0;
}
{
SRes res;
SizeT inProcessed = inSize - inPos;
SizeT outProcessed = OUT_BUF_SIZE - outPos;
ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
ELzmaStatus status;
if (thereIsSize && outProcessed > unpackSize)
{
outProcessed = (SizeT)unpackSize;
finishMode = LZMA_FINISH_END;
}
res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
inBuf + inPos, &inProcessed, finishMode, &status);
inPos += inProcessed;
outPos += outProcessed;
unpackSize -= outProcessed;
if (outStream)
if (outStream->Write(outStream, outBuf, outPos) != outPos)
return SZ_ERROR_WRITE;
outPos = 0;
if (res != SZ_OK || thereIsSize && unpackSize == 0)
return res;
if (inProcessed == 0 && outProcessed == 0)
{
if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
return SZ_ERROR_DATA;
return res;
}
}
}
}
static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
UInt64 unpackSize;
int i;
SRes res = 0;
CLzmaDec state;
/* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
unsigned char header[LZMA_PROPS_SIZE + 8];
/* Read and parse header */
RINOK(SeqInStream_Read(inStream, header, sizeof(header)));
unpackSize = 0;
for (i = 0; i < 8; i++)
unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);
LzmaDec_Construct(&state);
RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
res = Decode2(&state, outStream, inStream, unpackSize);
LzmaDec_Free(&state, &g_Alloc);
return res;
}
static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
{
CLzmaEncHandle enc;
SRes res;
CLzmaEncProps props;
rs = rs;
enc = LzmaEnc_Create(&g_Alloc);
if (enc == 0)
return SZ_ERROR_MEM;
LzmaEncProps_Init(&props);
res = LzmaEnc_SetProps(enc, &props);
if (res == SZ_OK)
{
Byte header[LZMA_PROPS_SIZE + 8];
size_t headerSize = LZMA_PROPS_SIZE;
int i;
res = LzmaEnc_WriteProperties(enc, header, &headerSize);
for (i = 0; i < 8; i++)
header[headerSize++] = (Byte)(fileSize >> (8 * i));
if (outStream->Write(outStream, header, headerSize) != headerSize)
res = SZ_ERROR_WRITE;
else
{
if (res == SZ_OK)
res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
}
}
LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
return res;
}
int Extract7z(const char * sz7z, const char * szFile) {
CFileSeqInStream inStream;
CFileOutStream outStream;
int res = -1;
int res2 = -1;
UInt64 iLength = 0;
Bool useOutFile = False;
FileSeqInStream_CreateVTable(&inStream);
File_Construct(&inStream.file);
FileOutStream_CreateVTable(&outStream);
File_Construct(&outStream.file);
if (InFile_Open(&inStream.file, sz7z) == 0) {
if (OutFile_Open(&outStream.file, szFile) == 0) {
res = Decode(&outStream.s, &inStream.s);
res2 = File_GetLength(&outStream.file,&iLength);
File_Close(&outStream.file);
File_Close(&inStream.file);
}
}
return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}
int Create7z(const char * szFile, const char * sz7z) {
CFileSeqInStream inStream;
CFileOutStream outStream;
int res = -1;
int res2 = -1;
UInt64 iLength = 0;
Bool useOutFile = False;
FileSeqInStream_CreateVTable(&inStream);
File_Construct(&inStream.file);
FileOutStream_CreateVTable(&outStream);
File_Construct(&outStream.file);
if (InFile_Open(&inStream.file, szFile) == 0) {
if (OutFile_Open(&outStream.file, sz7z) == 0) {
UInt64 fileSize;
File_GetLength(&inStream.file, &fileSize);
char * rs = NULL;
res = Encode(&outStream.s, &inStream.s, fileSize, rs);
res2 = File_GetLength(&outStream.file,&iLength);
File_Close(&outStream.file);
File_Close(&inStream.file);
}
}
return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}
int Create7z(char * in, int srcLen, char * out) {
CLzmaEncProps props;
props.level = 2;
props.numThreads = 1;
props.dictSize = 1 << 12;
props.reduceSize = 4096;
LzmaEncProps_Init(&props);
Byte header[LZMA_PROPS_SIZE + 8];
size_t headerSize = LZMA_PROPS_SIZE;
size_t destLen = -1;
Byte * bout = new Byte[srcLen];
ZeroMemory(bout,srcLen);
if (SZ_OK == LzmaEncode((Byte*)bout, &destLen, (Byte*)in, srcLen, &props, header, &headerSize, 1, NULL, &g_Alloc, &g_Alloc)) {
for (int i = 0; i < 8; i++)
header[headerSize++] = (Byte)(srcLen >> (8 * i));
memcpy(out,header,headerSize);
memcpy(out+headerSize,bout,destLen);
}
return destLen + headerSize;
}
FileList FindDumps() {
FileList tlFiles;
tlFiles.SetEmpty();
WIN32_FIND_DATAA finddata;
ZeroMemory(&finddata,sizeof(WIN32_FIND_DATAA));
char szPathName[MAX_PATH+48] = "";
char szName[MAX_PATH+48] = "";
strcpy(szPathName,(PCC)GetAppDir());
strcpy(szName,szPathName);
strcat(szPathName, "*.dmp");
HANDLE hsearchFiles = 0;
FILETIME ftTime = {0,0};
hsearchFiles = FindFirstFileA(szPathName, &finddata);
if (INVALID_HANDLE_VALUE == hsearchFiles)
return tlFiles;
int iKBytes = 0;
while (INVALID_HANDLE_VALUE != hsearchFiles) {
if (finddata.cFileName[0] != '.') {
char* p = strrchr(szName, '\\');
p = (!p) ? szName : p+1;
strcpy(p, "");
strcat(szName, finddata.cFileName);
tlFiles.InsertSorted(finddata);
iKBytes += (finddata.nFileSizeHigh > 0) ? MAXINT : (finddata.nFileSizeLow / 1024);
if (iKBytes >= MAXINT)
return tlFiles;
}
if (!FindNextFileA(hsearchFiles, &finddata)){
FindClose(hsearchFiles);
hsearchFiles = INVALID_HANDLE_VALUE;
}
}
return tlFiles;
}
void DeleteDumps(bool bDelete) {
FileList tlFiles = FindDumps();
char szDir[MAX_PATH+52] = "";
strcpy(szDir,(PCC)GetAppDir());
if (!tlFiles.IsEmpty()) {
for (FileList::Iterator iterFile(tlFiles);
!iterFile.End(); iterFile.Next())
{
ZString zFile = ZString(szDir)+ZString(iterFile.Value().cFileName);
if (!bDelete) {
MoveFileA((PCC)zFile,zFile+ZString(".old"));
continue;
}
else {
debugf("**** Deleting %s\n",(PCC)zFile);
DeleteFileA(zFile);
}
}
}
}
<commit_msg>Replace midalloc and midfree with just malloc and free. hope to get build to pass. thanks imago!!<commit_after>#include "pch.h"
#include "7zAlloc.h"
#include "7zMyAlloc.h"
#include "7zFile.h"
#include "LzmaEnc.h"
#include "LzmaDec.h"
#include "Types.h"
ZString GetAppDir() {
char szPathName[MAX_PATH+48] = "";
GetModuleFileNameA(NULL, szPathName, MAX_PATH);
char* p = strrchr(szPathName, '\\');
p = (!p) ? szPathName : p+1;
strcpy(p,"");
return ZString(szPathName);
}
static void *SzAlloc(void *p, size_t size) { p = p; return malloc(size); }
static void SzFree(void *p, void *address) { p = p; free(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };
#define IN_BUF_SIZE (1 << 8)
#define OUT_BUF_SIZE (1 << 8)
static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
UInt64 unpackSize)
{
int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
Byte inBuf[IN_BUF_SIZE];
Byte outBuf[OUT_BUF_SIZE];
size_t inPos = 0, inSize = 0, outPos = 0;
LzmaDec_Init(state);
for (;;)
{
if (inPos == inSize)
{
inSize = IN_BUF_SIZE;
RINOK(inStream->Read(inStream, inBuf, &inSize));
inPos = 0;
}
{
SRes res;
SizeT inProcessed = inSize - inPos;
SizeT outProcessed = OUT_BUF_SIZE - outPos;
ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
ELzmaStatus status;
if (thereIsSize && outProcessed > unpackSize)
{
outProcessed = (SizeT)unpackSize;
finishMode = LZMA_FINISH_END;
}
res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
inBuf + inPos, &inProcessed, finishMode, &status);
inPos += inProcessed;
outPos += outProcessed;
unpackSize -= outProcessed;
if (outStream)
if (outStream->Write(outStream, outBuf, outPos) != outPos)
return SZ_ERROR_WRITE;
outPos = 0;
if (res != SZ_OK || thereIsSize && unpackSize == 0)
return res;
if (inProcessed == 0 && outProcessed == 0)
{
if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
return SZ_ERROR_DATA;
return res;
}
}
}
}
static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
UInt64 unpackSize;
int i;
SRes res = 0;
CLzmaDec state;
/* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
unsigned char header[LZMA_PROPS_SIZE + 8];
/* Read and parse header */
RINOK(SeqInStream_Read(inStream, header, sizeof(header)));
unpackSize = 0;
for (i = 0; i < 8; i++)
unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);
LzmaDec_Construct(&state);
RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
res = Decode2(&state, outStream, inStream, unpackSize);
LzmaDec_Free(&state, &g_Alloc);
return res;
}
static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
{
CLzmaEncHandle enc;
SRes res;
CLzmaEncProps props;
rs = rs;
enc = LzmaEnc_Create(&g_Alloc);
if (enc == 0)
return SZ_ERROR_MEM;
LzmaEncProps_Init(&props);
res = LzmaEnc_SetProps(enc, &props);
if (res == SZ_OK)
{
Byte header[LZMA_PROPS_SIZE + 8];
size_t headerSize = LZMA_PROPS_SIZE;
int i;
res = LzmaEnc_WriteProperties(enc, header, &headerSize);
for (i = 0; i < 8; i++)
header[headerSize++] = (Byte)(fileSize >> (8 * i));
if (outStream->Write(outStream, header, headerSize) != headerSize)
res = SZ_ERROR_WRITE;
else
{
if (res == SZ_OK)
res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
}
}
LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
return res;
}
int Extract7z(const char * sz7z, const char * szFile) {
CFileSeqInStream inStream;
CFileOutStream outStream;
int res = -1;
int res2 = -1;
UInt64 iLength = 0;
Bool useOutFile = False;
FileSeqInStream_CreateVTable(&inStream);
File_Construct(&inStream.file);
FileOutStream_CreateVTable(&outStream);
File_Construct(&outStream.file);
if (InFile_Open(&inStream.file, sz7z) == 0) {
if (OutFile_Open(&outStream.file, szFile) == 0) {
res = Decode(&outStream.s, &inStream.s);
res2 = File_GetLength(&outStream.file,&iLength);
File_Close(&outStream.file);
File_Close(&inStream.file);
}
}
return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}
int Create7z(const char * szFile, const char * sz7z) {
CFileSeqInStream inStream;
CFileOutStream outStream;
int res = -1;
int res2 = -1;
UInt64 iLength = 0;
Bool useOutFile = False;
FileSeqInStream_CreateVTable(&inStream);
File_Construct(&inStream.file);
FileOutStream_CreateVTable(&outStream);
File_Construct(&outStream.file);
if (InFile_Open(&inStream.file, szFile) == 0) {
if (OutFile_Open(&outStream.file, sz7z) == 0) {
UInt64 fileSize;
File_GetLength(&inStream.file, &fileSize);
char * rs = NULL;
res = Encode(&outStream.s, &inStream.s, fileSize, rs);
res2 = File_GetLength(&outStream.file,&iLength);
File_Close(&outStream.file);
File_Close(&inStream.file);
}
}
return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}
int Create7z(char * in, int srcLen, char * out) {
CLzmaEncProps props;
props.level = 2;
props.numThreads = 1;
props.dictSize = 1 << 12;
props.reduceSize = 4096;
LzmaEncProps_Init(&props);
Byte header[LZMA_PROPS_SIZE + 8];
size_t headerSize = LZMA_PROPS_SIZE;
size_t destLen = -1;
Byte * bout = new Byte[srcLen];
ZeroMemory(bout,srcLen);
if (SZ_OK == LzmaEncode((Byte*)bout, &destLen, (Byte*)in, srcLen, &props, header, &headerSize, 1, NULL, &g_Alloc, &g_Alloc)) {
for (int i = 0; i < 8; i++)
header[headerSize++] = (Byte)(srcLen >> (8 * i));
memcpy(out,header,headerSize);
memcpy(out+headerSize,bout,destLen);
}
return destLen + headerSize;
}
FileList FindDumps() {
FileList tlFiles;
tlFiles.SetEmpty();
WIN32_FIND_DATAA finddata;
ZeroMemory(&finddata,sizeof(WIN32_FIND_DATAA));
char szPathName[MAX_PATH+48] = "";
char szName[MAX_PATH+48] = "";
strcpy(szPathName,(PCC)GetAppDir());
strcpy(szName,szPathName);
strcat(szPathName, "*.dmp");
HANDLE hsearchFiles = 0;
FILETIME ftTime = {0,0};
hsearchFiles = FindFirstFileA(szPathName, &finddata);
if (INVALID_HANDLE_VALUE == hsearchFiles)
return tlFiles;
int iKBytes = 0;
while (INVALID_HANDLE_VALUE != hsearchFiles) {
if (finddata.cFileName[0] != '.') {
char* p = strrchr(szName, '\\');
p = (!p) ? szName : p+1;
strcpy(p, "");
strcat(szName, finddata.cFileName);
tlFiles.InsertSorted(finddata);
iKBytes += (finddata.nFileSizeHigh > 0) ? MAXINT : (finddata.nFileSizeLow / 1024);
if (iKBytes >= MAXINT)
return tlFiles;
}
if (!FindNextFileA(hsearchFiles, &finddata)){
FindClose(hsearchFiles);
hsearchFiles = INVALID_HANDLE_VALUE;
}
}
return tlFiles;
}
void DeleteDumps(bool bDelete) {
FileList tlFiles = FindDumps();
char szDir[MAX_PATH+52] = "";
strcpy(szDir,(PCC)GetAppDir());
if (!tlFiles.IsEmpty()) {
for (FileList::Iterator iterFile(tlFiles);
!iterFile.End(); iterFile.Next())
{
ZString zFile = ZString(szDir)+ZString(iterFile.Value().cFileName);
if (!bDelete) {
MoveFileA((PCC)zFile,zFile+ZString(".old"));
continue;
}
else {
debugf("**** Deleting %s\n",(PCC)zFile);
DeleteFileA(zFile);
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 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 "ui/views/widget/desktop_native_widget_aura.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/desktop_root_window_host.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, public:
DesktopNativeWidgetAura::DesktopNativeWidgetAura(
internal::NativeWidgetDelegate* delegate)
: desktop_root_window_host_(DesktopRootWindowHost::Create()),
window_(NULL),
ownership_(Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
}
DesktopNativeWidgetAura::~DesktopNativeWidgetAura() {
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation:
void DesktopNativeWidgetAura::InitNativeWidget(
const Widget::InitParams& params) {
}
NonClientFrameView* DesktopNativeWidgetAura::CreateNonClientFrameView() {
return NULL;
}
bool DesktopNativeWidgetAura::ShouldUseNativeFrame() const {
return false;
}
void DesktopNativeWidgetAura::FrameTypeChanged() {
}
Widget* DesktopNativeWidgetAura::GetWidget() {
return native_widget_delegate_->AsWidget();
}
const Widget* DesktopNativeWidgetAura::GetWidget() const {
return native_widget_delegate_->AsWidget();
}
gfx::NativeView DesktopNativeWidgetAura::GetNativeView() const {
return window_;
}
gfx::NativeWindow DesktopNativeWidgetAura::GetNativeWindow() const {
return window_;
}
Widget* DesktopNativeWidgetAura::GetTopLevelWidget() {
return GetWidget();
}
const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const {
return NULL;
}
ui::Compositor* DesktopNativeWidgetAura::GetCompositor() {
return NULL;
}
void DesktopNativeWidgetAura::CalculateOffsetToAncestorWithLayer(
gfx::Point* offset,
ui::Layer** layer_parent) {
}
void DesktopNativeWidgetAura::ViewRemoved(View* view) {
}
void DesktopNativeWidgetAura::SetNativeWindowProperty(const char* name,
void* value) {
}
void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const {
return NULL;
}
TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const {
return NULL;
}
bool DesktopNativeWidgetAura::IsScreenReaderActive() const {
return false;
}
void DesktopNativeWidgetAura::SendNativeAccessibilityEvent(
View* view,
ui::AccessibilityTypes::Event event_type) {
}
void DesktopNativeWidgetAura::SetCapture() {
}
void DesktopNativeWidgetAura::ReleaseCapture() {
}
bool DesktopNativeWidgetAura::HasCapture() const {
return false;
}
InputMethod* DesktopNativeWidgetAura::CreateInputMethod() {
return NULL;
}
internal::InputMethodDelegate*
DesktopNativeWidgetAura::GetInputMethodDelegate() {
return NULL;
}
void DesktopNativeWidgetAura::CenterWindow(const gfx::Size& size) {
}
void DesktopNativeWidgetAura::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* maximized) const {
}
void DesktopNativeWidgetAura::SetWindowTitle(const string16& title) {
}
void DesktopNativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
}
void DesktopNativeWidgetAura::SetAccessibleName(const string16& name) {
}
void DesktopNativeWidgetAura::SetAccessibleRole(
ui::AccessibilityTypes::Role role) {
}
void DesktopNativeWidgetAura::SetAccessibleState(
ui::AccessibilityTypes::State state) {
}
void DesktopNativeWidgetAura::InitModalType(ui::ModalType modal_type) {
}
gfx::Rect DesktopNativeWidgetAura::GetWindowBoundsInScreen() const {
return gfx::Rect(100, 100);
}
gfx::Rect DesktopNativeWidgetAura::GetClientAreaBoundsInScreen() const {
return gfx::Rect(100, 100);
}
gfx::Rect DesktopNativeWidgetAura::GetRestoredBounds() const {
return gfx::Rect(100, 100);
}
void DesktopNativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
}
void DesktopNativeWidgetAura::SetSize(const gfx::Size& size) {
}
void DesktopNativeWidgetAura::StackAbove(gfx::NativeView native_view) {
}
void DesktopNativeWidgetAura::StackAtTop() {
}
void DesktopNativeWidgetAura::StackBelow(gfx::NativeView native_view) {
}
void DesktopNativeWidgetAura::SetShape(gfx::NativeRegion shape) {
}
void DesktopNativeWidgetAura::Close() {
}
void DesktopNativeWidgetAura::CloseNow() {
}
void DesktopNativeWidgetAura::Show() {
}
void DesktopNativeWidgetAura::Hide() {
}
void DesktopNativeWidgetAura::ShowMaximizedWithBounds(
const gfx::Rect& restored_bounds) {
}
void DesktopNativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) {
}
bool DesktopNativeWidgetAura::IsVisible() const {
return false;
}
void DesktopNativeWidgetAura::Activate() {
}
void DesktopNativeWidgetAura::Deactivate() {
}
bool DesktopNativeWidgetAura::IsActive() const {
return false;
}
void DesktopNativeWidgetAura::SetAlwaysOnTop(bool always_on_top) {
}
void DesktopNativeWidgetAura::Maximize() {
}
void DesktopNativeWidgetAura::Minimize() {
}
bool DesktopNativeWidgetAura::IsMaximized() const {
return false;
}
bool DesktopNativeWidgetAura::IsMinimized() const {
return false;
}
void DesktopNativeWidgetAura::Restore() {
}
void DesktopNativeWidgetAura::SetFullscreen(bool fullscreen) {
}
bool DesktopNativeWidgetAura::IsFullscreen() const {
return false;
}
void DesktopNativeWidgetAura::SetOpacity(unsigned char opacity) {
}
void DesktopNativeWidgetAura::SetUseDragFrame(bool use_drag_frame) {
}
void DesktopNativeWidgetAura::FlashFrame(bool flash_frame) {
}
bool DesktopNativeWidgetAura::IsAccessibleWidget() const {
return false;
}
void DesktopNativeWidgetAura::RunShellDrag(View* view,
const ui::OSExchangeData& data,
const gfx::Point& location,
int operation) {
}
void DesktopNativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
}
void DesktopNativeWidgetAura::SetCursor(gfx::NativeCursor cursor) {
}
void DesktopNativeWidgetAura::ClearNativeFocus() {
}
void DesktopNativeWidgetAura::FocusNativeView(gfx::NativeView native_view) {
}
gfx::Rect DesktopNativeWidgetAura::GetWorkAreaBoundsInScreen() const {
return gfx::Rect(100, 100);
}
void DesktopNativeWidgetAura::SetInactiveRenderingDisabled(bool value) {
}
Widget::MoveLoopResult DesktopNativeWidgetAura::RunMoveLoop(
const gfx::Point& drag_offset) {
return Widget::MOVE_LOOP_CANCELED;
}
void DesktopNativeWidgetAura::EndMoveLoop() {
}
void DesktopNativeWidgetAura::SetVisibilityChangedAnimationsEnabled(
bool value) {
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDelegate implementation:
gfx::Size DesktopNativeWidgetAura::GetMinimumSize() const {
return gfx::Size(100, 100);
}
void DesktopNativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
}
void DesktopNativeWidgetAura::OnFocus(aura::Window* old_focused_window) {
}
void DesktopNativeWidgetAura::OnBlur() {
}
bool DesktopNativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
return false;
}
gfx::NativeCursor DesktopNativeWidgetAura::GetCursor(const gfx::Point& point) {
return NULL;
}
int DesktopNativeWidgetAura::GetNonClientComponent(
const gfx::Point& point) const {
return HTCLIENT;
}
bool DesktopNativeWidgetAura::ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) {
return true;
}
bool DesktopNativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
return false;
}
ui::TouchStatus DesktopNativeWidgetAura::OnTouchEvent(ui::TouchEvent* event) {
return ui::TOUCH_STATUS_UNKNOWN;
}
ui::EventResult DesktopNativeWidgetAura::OnGestureEvent(
ui::GestureEvent* event) {
return ui::ER_UNHANDLED;
}
bool DesktopNativeWidgetAura::CanFocus() {
return true;
}
void DesktopNativeWidgetAura::OnCaptureLost() {
}
void DesktopNativeWidgetAura::OnPaint(gfx::Canvas* canvas) {
}
void DesktopNativeWidgetAura::OnDeviceScaleFactorChanged(
float device_scale_factor) {
}
void DesktopNativeWidgetAura::OnWindowDestroying() {
}
void DesktopNativeWidgetAura::OnWindowDestroyed() {
}
void DesktopNativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {
}
bool DesktopNativeWidgetAura::HasHitTestMask() const {
return false;
}
void DesktopNativeWidgetAura::GetHitTestMask(gfx::Path* mask) const {
}
} // namespace views
<commit_msg>aura: Fix build on linux-aura.<commit_after>// Copyright (c) 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 "ui/views/widget/desktop_native_widget_aura.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/desktop_root_window_host.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, public:
DesktopNativeWidgetAura::DesktopNativeWidgetAura(
internal::NativeWidgetDelegate* delegate)
: desktop_root_window_host_(DesktopRootWindowHost::Create()),
window_(NULL),
ownership_(Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
}
DesktopNativeWidgetAura::~DesktopNativeWidgetAura() {
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation:
void DesktopNativeWidgetAura::InitNativeWidget(
const Widget::InitParams& params) {
}
NonClientFrameView* DesktopNativeWidgetAura::CreateNonClientFrameView() {
return NULL;
}
bool DesktopNativeWidgetAura::ShouldUseNativeFrame() const {
return false;
}
void DesktopNativeWidgetAura::FrameTypeChanged() {
}
Widget* DesktopNativeWidgetAura::GetWidget() {
return native_widget_delegate_->AsWidget();
}
const Widget* DesktopNativeWidgetAura::GetWidget() const {
return native_widget_delegate_->AsWidget();
}
gfx::NativeView DesktopNativeWidgetAura::GetNativeView() const {
return window_;
}
gfx::NativeWindow DesktopNativeWidgetAura::GetNativeWindow() const {
return window_;
}
Widget* DesktopNativeWidgetAura::GetTopLevelWidget() {
return GetWidget();
}
const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const {
return NULL;
}
ui::Compositor* DesktopNativeWidgetAura::GetCompositor() {
return NULL;
}
void DesktopNativeWidgetAura::CalculateOffsetToAncestorWithLayer(
gfx::Point* offset,
ui::Layer** layer_parent) {
}
void DesktopNativeWidgetAura::ViewRemoved(View* view) {
}
void DesktopNativeWidgetAura::SetNativeWindowProperty(const char* name,
void* value) {
}
void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const {
return NULL;
}
TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const {
return NULL;
}
bool DesktopNativeWidgetAura::IsScreenReaderActive() const {
return false;
}
void DesktopNativeWidgetAura::SendNativeAccessibilityEvent(
View* view,
ui::AccessibilityTypes::Event event_type) {
}
void DesktopNativeWidgetAura::SetCapture() {
}
void DesktopNativeWidgetAura::ReleaseCapture() {
}
bool DesktopNativeWidgetAura::HasCapture() const {
return false;
}
InputMethod* DesktopNativeWidgetAura::CreateInputMethod() {
return NULL;
}
internal::InputMethodDelegate*
DesktopNativeWidgetAura::GetInputMethodDelegate() {
return NULL;
}
void DesktopNativeWidgetAura::CenterWindow(const gfx::Size& size) {
}
void DesktopNativeWidgetAura::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* maximized) const {
}
void DesktopNativeWidgetAura::SetWindowTitle(const string16& title) {
}
void DesktopNativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
}
void DesktopNativeWidgetAura::SetAccessibleName(const string16& name) {
}
void DesktopNativeWidgetAura::SetAccessibleRole(
ui::AccessibilityTypes::Role role) {
}
void DesktopNativeWidgetAura::SetAccessibleState(
ui::AccessibilityTypes::State state) {
}
void DesktopNativeWidgetAura::InitModalType(ui::ModalType modal_type) {
}
gfx::Rect DesktopNativeWidgetAura::GetWindowBoundsInScreen() const {
return gfx::Rect(100, 100);
}
gfx::Rect DesktopNativeWidgetAura::GetClientAreaBoundsInScreen() const {
return gfx::Rect(100, 100);
}
gfx::Rect DesktopNativeWidgetAura::GetRestoredBounds() const {
return gfx::Rect(100, 100);
}
void DesktopNativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
}
void DesktopNativeWidgetAura::SetSize(const gfx::Size& size) {
}
void DesktopNativeWidgetAura::StackAbove(gfx::NativeView native_view) {
}
void DesktopNativeWidgetAura::StackAtTop() {
}
void DesktopNativeWidgetAura::StackBelow(gfx::NativeView native_view) {
}
void DesktopNativeWidgetAura::SetShape(gfx::NativeRegion shape) {
}
void DesktopNativeWidgetAura::Close() {
}
void DesktopNativeWidgetAura::CloseNow() {
}
void DesktopNativeWidgetAura::Show() {
}
void DesktopNativeWidgetAura::Hide() {
}
void DesktopNativeWidgetAura::ShowMaximizedWithBounds(
const gfx::Rect& restored_bounds) {
}
void DesktopNativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) {
}
bool DesktopNativeWidgetAura::IsVisible() const {
return false;
}
void DesktopNativeWidgetAura::Activate() {
}
void DesktopNativeWidgetAura::Deactivate() {
}
bool DesktopNativeWidgetAura::IsActive() const {
return false;
}
void DesktopNativeWidgetAura::SetAlwaysOnTop(bool always_on_top) {
}
void DesktopNativeWidgetAura::Maximize() {
}
void DesktopNativeWidgetAura::Minimize() {
}
bool DesktopNativeWidgetAura::IsMaximized() const {
return false;
}
bool DesktopNativeWidgetAura::IsMinimized() const {
return false;
}
void DesktopNativeWidgetAura::Restore() {
}
void DesktopNativeWidgetAura::SetFullscreen(bool fullscreen) {
}
bool DesktopNativeWidgetAura::IsFullscreen() const {
return false;
}
void DesktopNativeWidgetAura::SetOpacity(unsigned char opacity) {
}
void DesktopNativeWidgetAura::SetUseDragFrame(bool use_drag_frame) {
}
void DesktopNativeWidgetAura::FlashFrame(bool flash_frame) {
}
bool DesktopNativeWidgetAura::IsAccessibleWidget() const {
return false;
}
void DesktopNativeWidgetAura::RunShellDrag(View* view,
const ui::OSExchangeData& data,
const gfx::Point& location,
int operation) {
}
void DesktopNativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
}
void DesktopNativeWidgetAura::SetCursor(gfx::NativeCursor cursor) {
}
void DesktopNativeWidgetAura::ClearNativeFocus() {
}
void DesktopNativeWidgetAura::FocusNativeView(gfx::NativeView native_view) {
}
gfx::Rect DesktopNativeWidgetAura::GetWorkAreaBoundsInScreen() const {
return gfx::Rect(100, 100);
}
void DesktopNativeWidgetAura::SetInactiveRenderingDisabled(bool value) {
}
Widget::MoveLoopResult DesktopNativeWidgetAura::RunMoveLoop(
const gfx::Point& drag_offset) {
return Widget::MOVE_LOOP_CANCELED;
}
void DesktopNativeWidgetAura::EndMoveLoop() {
}
void DesktopNativeWidgetAura::SetVisibilityChangedAnimationsEnabled(
bool value) {
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDelegate implementation:
gfx::Size DesktopNativeWidgetAura::GetMinimumSize() const {
return gfx::Size(100, 100);
}
void DesktopNativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
}
void DesktopNativeWidgetAura::OnFocus(aura::Window* old_focused_window) {
}
void DesktopNativeWidgetAura::OnBlur() {
}
bool DesktopNativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
return false;
}
gfx::NativeCursor DesktopNativeWidgetAura::GetCursor(const gfx::Point& point) {
return gfx::kNullCursor;
}
int DesktopNativeWidgetAura::GetNonClientComponent(
const gfx::Point& point) const {
return HTCLIENT;
}
bool DesktopNativeWidgetAura::ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) {
return true;
}
bool DesktopNativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
return false;
}
ui::TouchStatus DesktopNativeWidgetAura::OnTouchEvent(ui::TouchEvent* event) {
return ui::TOUCH_STATUS_UNKNOWN;
}
ui::EventResult DesktopNativeWidgetAura::OnGestureEvent(
ui::GestureEvent* event) {
return ui::ER_UNHANDLED;
}
bool DesktopNativeWidgetAura::CanFocus() {
return true;
}
void DesktopNativeWidgetAura::OnCaptureLost() {
}
void DesktopNativeWidgetAura::OnPaint(gfx::Canvas* canvas) {
}
void DesktopNativeWidgetAura::OnDeviceScaleFactorChanged(
float device_scale_factor) {
}
void DesktopNativeWidgetAura::OnWindowDestroying() {
}
void DesktopNativeWidgetAura::OnWindowDestroyed() {
}
void DesktopNativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {
}
bool DesktopNativeWidgetAura::HasHitTestMask() const {
return false;
}
void DesktopNativeWidgetAura::GetHitTestMask(gfx::Path* mask) const {
}
} // namespace views
<|endoftext|>
|
<commit_before>#include <vw/Plate/ToastDem.h>
#include <vw/Plate/PlateManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Core.h>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <iostream>
using namespace std;
using namespace vw;
using namespace vw::platefile;
// There isn't much abstraction here. A Filter takes a platefile and writes a
// new platefile. This rules out lazy filters for the moment. The
// col/row/level/transaction_id is for the input value, the output can feel
// free to write things elsewhere.
// The function will be called for every input tile, including all transaction
// ids. The output function should feel no obligation to write a tile for every
// input.
template <typename ImplT>
struct FilterBase {
inline ImplT& impl() { return static_cast<ImplT&>(*this); }
inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); }
inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
return impl().init(output, input, output_transaction_id);
}
inline void fini(PlateFile& output, const PlateFile& input, int output_transaction_id) {
return impl().fini(output, input, output_transaction_id);
}
# define lookup(name, type) type name(type data) const { return impl().name(data); }
lookup(mode, string);
lookup(tile_size, int);
lookup(filetype, string);
lookup(pixel_format, PixelFormatEnum);
lookup(channel_type, ChannelTypeEnum);
# undef lookup
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
impl()(output, input, col, row, level, input_transaction_id, output_transaction_id);
}
};
struct Identity : public FilterBase<Identity> {
# define lookup(name, type) type name(type data) const { return data; }
lookup(mode, string);
lookup(tile_size, int);
lookup(filetype, string);
lookup(pixel_format, PixelFormatEnum);
lookup(channel_type, ChannelTypeEnum);
# undef lookup
inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); }
inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); }
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
ImageView<PixelRGBA<double> > tile;
TileHeader hdr = input.read(tile, col, row, level, input_transaction_id);
output.write_update(tile, col, row, level, output_transaction_id);
}
};
struct ToastDem : public FilterBase<ToastDem> {
string mode(string) const { return "toast_dem"; }
int tile_size(int) const { return 32; }
string filetype(string) const { return "toast_dem_v1"; }
PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; }
ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; }
inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
output.write_request();
// Write null tiles for the levels we don't have data for
int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5;
vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl;
uint64 bytes;
boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes);
for (int level = 0; level < level_difference; ++level) {
int region_size = 1 << level;
for (int col = 0; col < region_size; ++col)
for (int row = 0; row < region_size; ++row)
output.write_update(null_tile, bytes, col, row, level, output_transaction_id);
}
}
inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) {
output.write_complete();
}
struct DemWriter : public ToastDemWriter {
PlateFile& platefile;
DemWriter(PlateFile& output) : platefile(output) { }
inline void operator()(const boost::shared_array<uint8> data, uint64 data_size,
int32 dem_col, int32 dem_row,
int32 dem_level, int32 output_transaction_id) const {
platefile.write_update(data, data_size, dem_col, dem_row,
dem_level, output_transaction_id);
}
};
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
DemWriter writer(output);
make_toast_dem_tile(writer, input, col, row, level, input_transaction_id, output_transaction_id);
}
};
struct Options {
string input_name;
string output_name;
string mode;
string description;
int tile_size;
string filetype;
PixelFormatEnum pixel_format;
ChannelTypeEnum channel_type;
int bottom_level;
string filter;
Options() :
tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {}
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description options("Options");
options.add_options()
("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.")
("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.")
("file-type", po::value(&opt.filetype), "Output file type")
("mode", po::value(&opt.mode), "Output mode [toast, kml]")
("tile-size", po::value(&opt.tile_size), "Output size, in pixels")
("filter", po::value(&opt.filter), "Filters to run")
("bottom-level", po::value(&opt.bottom_level), "Bottom level to process")
("help,h", "Display this help message.");
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options );
}
if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty())
vw_throw(Usage() << options);
}
template <typename FilterT>
void run(Options& opt, FilterBase<FilterT>& filter) {
PlateFile input(opt.input_name);
// Use given option first, then use filter recommendation (it will probably
// just recommend the value from the input platefile)
if (opt.mode.empty())
opt.mode = filter.mode(input.index_header().type());
if (opt.tile_size == 0)
opt.tile_size = filter.tile_size(input.default_tile_size());
if (opt.filetype.empty())
opt.filetype = filter.filetype(input.default_file_type());
if (opt.pixel_format == VW_PIXEL_UNKNOWN)
opt.pixel_format = filter.pixel_format(input.pixel_format());
if (opt.channel_type == VW_CHANNEL_UNKNOWN)
opt.channel_type = filter.channel_type(input.channel_type());
PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type);
int output_transaction_id = output.transaction_request("plate2plate, reporting for duty", -1);
filter.init(output, input, output_transaction_id);
VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels");
int bottom_level = min(input.num_levels(), opt.bottom_level+1);
for (int level = 0; level < bottom_level; ++level) {
vw_out(InfoMessage) << "\nProcessing level " << level << " of " << bottom_level-1 << ". ";
TerminalProgressCallback tpc("plate.plate2plate.progress", "");
vw::Timer timer( "\t Processing time in seconds" );
// The entire region contains 2^level tiles.
int32 region_size = 1 << level;
int subdivided_region_size = 1024;
if (subdivided_region_size < region_size) subdivided_region_size = region_size;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> boxes1 = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
vw_out(InfoMessage) << "Region" << full_region << " has " << boxes1.size() << " bboxes\n";
float region_counter = 0;
BOOST_FOREACH( const BBox2i& region1, boxes1 ) {
std::cout << "\n\t--> Sub-region: " << region1 << "\n";
std::list<TileHeader> tiles = input.search_by_region(level, region1, 0,
input.transaction_cursor(), true);
// if (tiles.size() > 0)
// std::cout << "\t--> Region " << region1 << " has " << tiles.size() << " tiles.\n";
std::ostringstream ostr;
ostr << "\t Converting " << tiles.size() << " tiles: ";
tpc.set_progress_text(ostr.str());
SubProgressCallback sub_progress(tpc,
region_counter / boxes1.size(),
(region_counter+1.0) / boxes1.size());
BOOST_FOREACH( const TileHeader& tile, tiles ) {
// ++n;
// if (n % 100 == 0)
// std::cout << "n = " << n << " -- "<< tile.col() << " " << tile.row() << " " << tile.level() << " " << tile.transaction_id() << "\n";
filter(output, input, tile.col(), tile.row(), tile.level(),
tile.transaction_id(), output_transaction_id);
sub_progress.report_incremental_progress(1.0/tiles.size());
}
sub_progress.report_finished();
region_counter++;
}
tpc.report_finished();
output.sync();
}
filter.fini(output, input, output_transaction_id);
output.transaction_complete(output_transaction_id, true);
}
// Blah blah boilerplate
int main(int argc, char *argv[])
{
Options opt;
try {
handle_arguments(argc, argv, opt);
boost::to_lower(opt.filter);
if (opt.filter == "identity") {
Identity f;
run(opt, f);
} else if (opt.filter == "toast_dem") {
ToastDem f;
run(opt, f);
}
} catch (const Usage& e) {
std::cout << e.what() << std::endl;
return 1;
} catch (const Exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Added skim mode for plate2plate<commit_after>#include <vw/Plate/ToastDem.h>
#include <vw/Plate/PlateManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Core.h>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <iostream>
using namespace std;
using namespace vw;
using namespace vw::platefile;
// There isn't much abstraction here. A Filter takes a platefile and writes a
// new platefile. This rules out lazy filters for the moment. The
// col/row/level/transaction_id is for the input value, the output can feel
// free to write things elsewhere.
// The function will be called for every input tile, including all transaction
// ids. The output function should feel no obligation to write a tile for every
// input.
template <typename ImplT>
struct FilterBase {
inline ImplT& impl() { return static_cast<ImplT&>(*this); }
inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); }
inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
return impl().init(output, input, output_transaction_id);
}
inline void fini(PlateFile& output, const PlateFile& input, int output_transaction_id) {
return impl().fini(output, input, output_transaction_id);
}
# define lookup(name, type) type name(type data) const { return impl().name(data); }
lookup(mode, string);
lookup(tile_size, int);
lookup(filetype, string);
lookup(pixel_format, PixelFormatEnum);
lookup(channel_type, ChannelTypeEnum);
# undef lookup
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
impl()(output, input, col, row, level, input_transaction_id, output_transaction_id);
}
};
struct Identity : public FilterBase<Identity> {
# define lookup(name, type) type name(type data) const { return data; }
lookup(mode, string);
lookup(tile_size, int);
lookup(filetype, string);
lookup(pixel_format, PixelFormatEnum);
lookup(channel_type, ChannelTypeEnum);
# undef lookup
inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); }
inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); }
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
ImageView<PixelRGBA<double> > tile;
TileHeader hdr = input.read(tile, col, row, level, input_transaction_id);
output.write_update(tile, col, row, level, output_transaction_id);
}
};
struct ToastDem : public FilterBase<ToastDem> {
string mode(string) const { return "toast_dem"; }
int tile_size(int) const { return 32; }
string filetype(string) const { return "toast_dem_v1"; }
PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; }
ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; }
inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
output.write_request();
// Write null tiles for the levels we don't have data for
int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5;
vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl;
uint64 bytes;
boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes);
for (int level = 0; level < level_difference; ++level) {
int region_size = 1 << level;
for (int col = 0; col < region_size; ++col)
for (int row = 0; row < region_size; ++row)
output.write_update(null_tile, bytes, col, row, level, output_transaction_id);
}
}
inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) {
output.write_complete();
}
struct DemWriter : public ToastDemWriter {
PlateFile& platefile;
DemWriter(PlateFile& output) : platefile(output) { }
inline void operator()(const boost::shared_array<uint8> data, uint64 data_size,
int32 dem_col, int32 dem_row,
int32 dem_level, int32 output_transaction_id) const {
platefile.write_update(data, data_size, dem_col, dem_row,
dem_level, output_transaction_id);
}
};
inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
DemWriter writer(output);
make_toast_dem_tile(writer, input, col, row, level, input_transaction_id, output_transaction_id);
}
};
struct Options {
string input_name;
string output_name;
string mode;
string description;
int tile_size;
string filetype;
PixelFormatEnum pixel_format;
ChannelTypeEnum channel_type;
int bottom_level;
bool skim_mode;
string filter;
Options() :
tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {}
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description options("Options");
options.add_options()
("output-name,o", po::value(&opt.output_name), "Specify the URL of the input platefile.")
("input-name,i", po::value(&opt.input_name), "Specify the URL of the output platefile.")
("file-type", po::value(&opt.filetype), "Output file type")
("mode", po::value(&opt.mode), "Output mode [toast, kml]")
("tile-size", po::value(&opt.tile_size), "Output size, in pixels")
("filter", po::value(&opt.filter), "Filters to run [identity, toast_dem]")
("bottom-level", po::value(&opt.bottom_level), "Bottom level to process")
("skim-last-id-only", "Only process the last transaction id from the input")
("help,h", "Display this help message.");
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options );
}
opt.skim_mode = vm.count("skim-last-id-only");
if (opt.output_name.empty() || opt.input_name.empty())
vw_throw(Usage() << "Requires input and output defined!\n" << options);
if ( opt.filter.empty() )
vw_throw(Usage() << "Requires filter to be defined!\n" << options);
}
template <typename FilterT>
void run(Options& opt, FilterBase<FilterT>& filter) {
PlateFile input(opt.input_name);
// Use given option first, then use filter recommendation (it will probably
// just recommend the value from the input platefile)
if (opt.mode.empty())
opt.mode = filter.mode(input.index_header().type());
if (opt.tile_size == 0)
opt.tile_size = filter.tile_size(input.default_tile_size());
if (opt.filetype.empty())
opt.filetype = filter.filetype(input.default_file_type());
if (opt.pixel_format == VW_PIXEL_UNKNOWN)
opt.pixel_format = filter.pixel_format(input.pixel_format());
if (opt.channel_type == VW_CHANNEL_UNKNOWN)
opt.channel_type = filter.channel_type(input.channel_type());
PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type);
int output_transaction_id = output.transaction_request("plate2plate, reporting for duty", -1);
filter.init(output, input, output_transaction_id);
VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels");
int bottom_level = min(input.num_levels(), opt.bottom_level+1);
for (int level = 0; level < bottom_level; ++level) {
vw_out(InfoMessage) << "\nProcessing level " << level << " of " << bottom_level-1 << ". ";
TerminalProgressCallback tpc("plate.plate2plate.progress", "");
vw::Timer timer( "\t Processing time in seconds" );
// The entire region contains 2^level tiles.
int32 region_size = 1 << level;
int subdivided_region_size = 1024;
if (subdivided_region_size < region_size) subdivided_region_size = region_size;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> boxes1 = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
vw_out(InfoMessage) << "Region" << full_region << " has " << boxes1.size() << " bboxes\n";
float region_counter = 0;
BOOST_FOREACH( const BBox2i& region1, boxes1 ) {
std::cout << "\n\t--> Sub-region: " << region1 << "\n";
std::list<TileHeader> tiles;
if ( !opt.skim_mode )
tiles = input.search_by_region(level, region1, 0,
input.transaction_cursor(), true);
else
tiles = input.search_by_region(level, region1, -1, -1, true);
// if (tiles.size() > 0)
// std::cout << "\t--> Region " << region1 << " has " << tiles.size() << " tiles.\n";
std::ostringstream ostr;
ostr << "\t Converting " << tiles.size() << " tiles: ";
tpc.set_progress_text(ostr.str());
SubProgressCallback sub_progress(tpc,
region_counter / boxes1.size(),
(region_counter+1.0) / boxes1.size());
BOOST_FOREACH( const TileHeader& tile, tiles ) {
// ++n;
// if (n % 100 == 0)
// std::cout << "n = " << n << " -- "<< tile.col() << " " << tile.row() << " " << tile.level() << " " << tile.transaction_id() << "\n";
filter(output, input, tile.col(), tile.row(), tile.level(),
tile.transaction_id(), output_transaction_id);
sub_progress.report_incremental_progress(1.0/tiles.size());
}
sub_progress.report_finished();
region_counter++;
}
tpc.report_finished();
output.sync();
}
filter.fini(output, input, output_transaction_id);
output.transaction_complete(output_transaction_id, true);
}
// Blah blah boilerplate
int main(int argc, char *argv[])
{
Options opt;
try {
handle_arguments(argc, argv, opt);
boost::to_lower(opt.filter);
if (opt.filter == "identity") {
Identity f;
run(opt, f);
} else if (opt.filter == "toast_dem") {
ToastDem f;
run(opt, f);
}
} catch (const Usage& e) {
std::cout << e.what() << std::endl;
return 1;
} catch (const Exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/** @file edgeelement.cpp
* @brief Класс, представляющий связь на диаграмме
* */
#include <QtGui/QStyleOptionGraphicsItem>
#include <QtGui/QStyle>
#include <QtGui/QTextDocument>
#include <QtGui/QMenu>
#include <math.h>
#include "../view/editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "../model/model.h"
using namespace UML;
using namespace qReal;
#ifndef M_PI
/** @brief Константа ПИ */
#define M_PI 3.14159265358979323846264338327950288419717
/** @brief Константа 1/ПИ */
#define M_1_PI 1/M_PI;
// Реквестирую ещё массу бозона Хиггса!
// Here you are: The God's particle energy (in GeV)
#define HIGGS_BOSON_MASS_APPROX 251
#endif //M_PI
/** @brief Индикатор перемещения связи */
// static bool moving = false;
EdgeElement::EdgeElement()
: mPenStyle(Qt::SolidLine), mStartArrowStyle(NO_ARROW), mEndArrowStyle(NO_ARROW),
mSrc(NULL), mDst(NULL), mPortFrom(0), mPortTo(0),
mDragState(-1), mLongPart(0), mBeginning(NULL), mEnding(NULL)
{
setZValue(100);
setFlag(ItemIsMovable, true);
// FIXME: draws strangely...
setFlag(ItemClipsToShape, false);
mLine << QPointF(0, 0) << QPointF(200, 60);
}
EdgeElement::~EdgeElement()
{
if (mSrc)
mSrc->delEdge(this);
if (mDst)
mDst->delEdge(this);
}
QRectF EdgeElement::boundingRect() const
{
return mLine.boundingRect().adjusted(-20, -20, 20, 20);
}
static double lineAngle(const QLineF &line)
{
double angle = ::acos(line.dx() / line.length());
if (line.dy() >= 0)
angle = 2 * M_PI - angle;
return angle * 180 * M_1_PI;
}
void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
painter->save();
QPen pen = painter->pen();
pen.setColor(mColor);
pen.setStyle(mPenStyle);
pen.setWidth(1);
painter->setPen(pen);
painter->drawPolyline(mLine);
painter->restore();
painter->save();
painter->translate(mLine[0]);
painter->drawText(QPointF(10, 20), mFromMult);
painter->rotate(90 - lineAngle(QLineF(mLine[1], mLine[0])));
drawStartArrow(painter);
painter->restore();
painter->save();
painter->translate(mLine[mLine.size() - 1]);
painter->drawText(QPointF(10, 20), mToMult);
painter->rotate(90 - lineAngle(QLineF(mLine[mLine.size() - 2], mLine[mLine.size() - 1])));
drawEndArrow(painter);
painter->restore();
if (option->state & QStyle::State_Selected) {
painter->setBrush(Qt::SolidPattern);
foreach (QPointF const point, mLine) {
QPen pen;
QColor color;
color.setNamedColor("#c3dcc4");
pen.setWidth(11);
pen.setColor(color);
painter->setPen(pen);
painter->drawPoint(point);
color.setNamedColor("#465945");
pen.setWidth(3);
pen.setColor(color);
painter->setPen(pen);
painter->drawPoint(point);
}
}
if (!mText.isEmpty()) {
painter->save();
QLineF longest(mLine[mLongPart], mLine[mLongPart + 1]);
painter->translate(mLine[mLongPart]);
painter->rotate(-lineAngle(longest));
QTextDocument text;
text.setHtml(mText);
text.setTextWidth(longest.length());
text.drawContents(painter);
painter->restore();
}
}
bool canBeConnected(int linkID, int from, int to);
QPainterPath EdgeElement::shape() const
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.addPolygon(mLine);
path = ps.createStroke(path);
foreach (QPointF const point, mLine) {
path.addRect(getPortRect(point));
}
return path;
}
QRectF EdgeElement::getPortRect(QPointF const &point)
{
return QRectF(point - QPointF(kvadratik, kvadratik), QSizeF(kvadratik * 2, kvadratik * 2));
}
int EdgeElement::getPoint(const QPointF &location)
{
for (int i = 0; i < mLine.size(); ++i)
if (getPortRect(mLine[i]).contains(location))
return i;
return -1;
}
void EdgeElement::updateLongestPart()
{
qreal maxLen = 0.0;
int maxIdx = 0;
for (int i = 0; i < mLine.size() - 1; ++i) {
qreal newLen = QLineF(mLine[i], mLine[i + 1]).length();
if (newLen > maxLen) {
maxLen = newLen;
maxIdx = i;
}
}
mLongPart = maxIdx;
}
void EdgeElement::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
mDragState = -1;
if (isSelected())
mDragState = getPoint(event->pos());
if (mDragState == -1)
Element::mousePressEvent(event);
}
void EdgeElement::connectToPort()
{
model::Model *model = const_cast<model::Model *>(static_cast<model::Model const *>(mDataIndex.model())); // TODO: OMG!
setPos(pos() + mLine.first());
mLine.translate(-mLine.first());
mMoving = true;
// Now we check whether start or end have been connected
NodeElement *new_src = getNodeAt(mLine.first());
mPortFrom = new_src ? new_src->getPortId(mapToItem(new_src, mLine.first())) : -1.0;
if (mSrc) {
mSrc->delEdge(this);
mSrc = 0;
}
if (mPortFrom >= 0.0) {
mSrc = new_src;
mSrc->addEdge(this);
}
model->setData(mDataIndex, (mSrc ? mSrc->uuid() : ROOT_ID).toVariant(), roles::fromRole);
model->setData(mDataIndex, mPortFrom, roles::fromPortRole);
NodeElement *new_dst = getNodeAt(mLine.last());
mPortTo = new_dst ? new_dst->getPortId(mapToItem(new_dst, mLine.last())) : -1.0;
if (mDst) {
mDst->delEdge(this);
mDst = 0;
}
if (mPortTo >= 0.0) {
mDst = new_dst;
mDst->addEdge(this);
}
model->setData(mDataIndex, (mDst ? mDst->uuid() : ROOT_ID).toVariant(), roles::toRole);
model->setData(mDataIndex, mPortTo, roles::toPortRole);
setFlag(ItemIsMovable, !(mDst || mSrc));
model->setData(mDataIndex, pos(), roles::positionRole);
model->setData(mDataIndex, mLine.toPolygon(), roles::configurationRole);
mMoving = false;
adjustLink();
}
void EdgeElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
NodeElement *new_src = getNodeAt(mLine.first());
NodeElement *new_dst = getNodeAt(mLine.back());
if (mBeginning) {
if (mBeginning != new_src) {
mBeginning->setPortsVisible(false);
}
}
if (mEnding) {
if (mEnding != new_dst) {
mEnding->setPortsVisible(false);
}
}
mBeginning = new_src;
mEnding = new_dst;
if (mBeginning)
mBeginning->setPortsVisible(true);
if (mEnding)
mEnding->setPortsVisible(true);
if (mDragState == -1) {
Element::mouseMoveEvent(event);
} else {
prepareGeometryChange();
mLine[mDragState] = event->pos();
updateLongestPart();
}
}
void EdgeElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (mDragState == -1)
Element::mouseReleaseEvent(event);
else
mDragState = -1;
connectToPort();
if (mBeginning)
mBeginning->setPortsVisible(false);
if (mEnding)
mEnding->setPortsVisible(false);
// cleanup after moving/resizing
mBeginning = mEnding = NULL;
}
NodeElement *EdgeElement::getNodeAt(QPointF const &position)
{
QPainterPath circlePath;
circlePath.addEllipse(mapToScene(position), 12, 12);
foreach (QGraphicsItem *item, scene()->items(circlePath)) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if (e) {
return e;
}
}
return NULL;
}
void EdgeElement::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu menu;
QAction *addPointAction = menu.addAction("Add point");
QAction *delPointAction = menu.addAction("Remove point");
QAction *squarizeAction = menu.addAction("Squarize");
if (QAction *selectedAction = menu.exec(event->screenPos())) {
if (selectedAction == delPointAction) {
int pointIndex = getPoint(event->pos());
if (pointIndex != -1) {
prepareGeometryChange();
mLine.remove(pointIndex);
mLongPart = 0;
update();
}
} else if (selectedAction == addPointAction) {
for (int i = 0; i < mLine.size() - 1; ++i) {
QPainterPath path;
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.moveTo(mLine[i]);
path.lineTo(mLine[i+1]);
if (ps.createStroke(path).contains(event->pos())) {
mLine.insert(i + 1, event->pos());
update();
break;
}
}
} else if (selectedAction == squarizeAction) {
prepareGeometryChange();
for (int i = 0; i < mLine.size() - 1; ++i) {
QLineF line(mLine[i], mLine[i + 1]);
if (qAbs(line.dx()) < qAbs(line.dy())) {
mLine[i + 1].setX(mLine[i].x());
} else {
mLine[i + 1].setY(mLine[i].y());
}
}
adjustLink();
update();
}
}
}
void EdgeElement::adjustLink()
{
prepareGeometryChange();
if (mSrc)
mLine.first() = mapFromItem(mSrc, mSrc->getPortPos(mPortFrom));
if (mDst)
mLine.last() = mapFromItem(mDst, mDst->getPortPos(mPortTo));
updateLongestPart();
}
void EdgeElement::updateData()
{
if (mMoving)
return;
Element::updateData();
setPos(mDataIndex.data(roles::positionRole).toPointF());
QPolygonF newLine = mDataIndex.data(roles::configurationRole).value<QPolygon>();
if (!newLine.isEmpty())
mLine = newLine;
qReal::Id uuidFrom = mDataIndex.data(roles::fromRole).value<Id>();
qReal::Id uuidTo = mDataIndex.data(roles::toRole).value<Id>();
if (mSrc)
mSrc->delEdge(this);
if (mDst)
mDst->delEdge(this);
mSrc = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidFrom));
mDst = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidTo));
if (mSrc)
mSrc->addEdge(this);
if (mDst)
mDst->addEdge(this);
setFlag(ItemIsMovable, !(mDst || mSrc));
mPortFrom = mDataIndex.data(roles::fromPortRole).toDouble();
mPortTo = mDataIndex.data(roles::toPortRole).toDouble();
adjustLink();
}
void EdgeElement::removeLink(UML::NodeElement const *from)
{
if (mSrc == from)
mSrc = NULL;
if (mDst == from)
mDst = NULL;
}
<commit_msg>Яшины пожелания по поведению линков, +1 к юзабилити.<commit_after>/** @file edgeelement.cpp
* @brief Класс, представляющий связь на диаграмме
* */
#include <QtGui/QStyleOptionGraphicsItem>
#include <QtGui/QStyle>
#include <QtGui/QTextDocument>
#include <QtGui/QMenu>
#include <math.h>
#include "../view/editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "../model/model.h"
using namespace UML;
using namespace qReal;
#ifndef M_PI
/** @brief Константа ПИ */
#define M_PI 3.14159265358979323846264338327950288419717
/** @brief Константа 1/ПИ */
#define M_1_PI 1/M_PI;
// Реквестирую ещё массу бозона Хиггса!
// Here you are: The God's particle energy (in GeV)
#define HIGGS_BOSON_MASS_APPROX 251
#endif //M_PI
/** @brief Индикатор перемещения связи */
// static bool moving = false;
EdgeElement::EdgeElement()
: mPenStyle(Qt::SolidLine), mStartArrowStyle(NO_ARROW), mEndArrowStyle(NO_ARROW),
mSrc(NULL), mDst(NULL), mPortFrom(0), mPortTo(0),
mDragState(-1), mLongPart(0), mBeginning(NULL), mEnding(NULL)
{
setZValue(100);
setFlag(ItemIsMovable, true);
// FIXME: draws strangely...
setFlag(ItemClipsToShape, false);
mLine << QPointF(0, 0) << QPointF(200, 60);
}
EdgeElement::~EdgeElement()
{
if (mSrc)
mSrc->delEdge(this);
if (mDst)
mDst->delEdge(this);
}
QRectF EdgeElement::boundingRect() const
{
return mLine.boundingRect().adjusted(-20, -20, 20, 20);
}
static double lineAngle(const QLineF &line)
{
double angle = ::acos(line.dx() / line.length());
if (line.dy() >= 0)
angle = 2 * M_PI - angle;
return angle * 180 * M_1_PI;
}
void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
painter->save();
QPen pen = painter->pen();
pen.setColor(mColor);
pen.setStyle(mPenStyle);
pen.setWidth(1);
painter->setPen(pen);
painter->drawPolyline(mLine);
painter->restore();
painter->save();
painter->translate(mLine[0]);
painter->drawText(QPointF(10, 20), mFromMult);
painter->rotate(90 - lineAngle(QLineF(mLine[1], mLine[0])));
drawStartArrow(painter);
painter->restore();
painter->save();
painter->translate(mLine[mLine.size() - 1]);
painter->drawText(QPointF(10, 20), mToMult);
painter->rotate(90 - lineAngle(QLineF(mLine[mLine.size() - 2], mLine[mLine.size() - 1])));
drawEndArrow(painter);
painter->restore();
if (option->state & QStyle::State_Selected) {
painter->setBrush(Qt::SolidPattern);
foreach (QPointF const point, mLine) {
QPen pen;
QColor color;
color.setNamedColor("#c3dcc4");
pen.setWidth(11);
pen.setColor(color);
painter->setPen(pen);
painter->drawPoint(point);
color.setNamedColor("#465945");
pen.setWidth(3);
pen.setColor(color);
painter->setPen(pen);
painter->drawPoint(point);
}
}
if (!mText.isEmpty()) {
painter->save();
QLineF longest(mLine[mLongPart], mLine[mLongPart + 1]);
painter->translate(mLine[mLongPart]);
painter->rotate(-lineAngle(longest));
QTextDocument text;
text.setHtml(mText);
text.setTextWidth(longest.length());
text.drawContents(painter);
painter->restore();
}
}
bool canBeConnected(int linkID, int from, int to);
QPainterPath EdgeElement::shape() const
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.addPolygon(mLine);
path = ps.createStroke(path);
foreach (QPointF const point, mLine) {
path.addRect(getPortRect(point));
}
return path;
}
QRectF EdgeElement::getPortRect(QPointF const &point)
{
return QRectF(point - QPointF(kvadratik, kvadratik), QSizeF(kvadratik * 2, kvadratik * 2));
}
int EdgeElement::getPoint(const QPointF &location)
{
for (int i = 0; i < mLine.size(); ++i)
if (getPortRect(mLine[i]).contains(location))
return i;
return -1;
}
void EdgeElement::updateLongestPart()
{
qreal maxLen = 0.0;
int maxIdx = 0;
for (int i = 0; i < mLine.size() - 1; ++i) {
qreal newLen = QLineF(mLine[i], mLine[i + 1]).length();
if (newLen > maxLen) {
maxLen = newLen;
maxIdx = i;
}
}
mLongPart = maxIdx;
}
void EdgeElement::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
mDragState = -1;
mDragState = getPoint(event->pos());
setSelected(true);
if (mDragState == -1)
Element::mousePressEvent(event);
}
void EdgeElement::connectToPort()
{
model::Model *model = const_cast<model::Model *>(static_cast<model::Model const *>(mDataIndex.model())); // TODO: OMG!
setPos(pos() + mLine.first());
mLine.translate(-mLine.first());
mMoving = true;
// Now we check whether start or end have been connected
NodeElement *new_src = getNodeAt(mLine.first());
mPortFrom = new_src ? new_src->getPortId(mapToItem(new_src, mLine.first())) : -1.0;
if (mSrc) {
mSrc->delEdge(this);
mSrc = 0;
}
if (mPortFrom >= 0.0) {
mSrc = new_src;
mSrc->addEdge(this);
}
model->setData(mDataIndex, (mSrc ? mSrc->uuid() : ROOT_ID).toVariant(), roles::fromRole);
model->setData(mDataIndex, mPortFrom, roles::fromPortRole);
NodeElement *new_dst = getNodeAt(mLine.last());
mPortTo = new_dst ? new_dst->getPortId(mapToItem(new_dst, mLine.last())) : -1.0;
if (mDst) {
mDst->delEdge(this);
mDst = 0;
}
if (mPortTo >= 0.0) {
mDst = new_dst;
mDst->addEdge(this);
}
model->setData(mDataIndex, (mDst ? mDst->uuid() : ROOT_ID).toVariant(), roles::toRole);
model->setData(mDataIndex, mPortTo, roles::toPortRole);
setFlag(ItemIsMovable, !(mDst || mSrc));
model->setData(mDataIndex, pos(), roles::positionRole);
model->setData(mDataIndex, mLine.toPolygon(), roles::configurationRole);
mMoving = false;
adjustLink();
}
void EdgeElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
NodeElement *new_src = getNodeAt(mLine.first());
NodeElement *new_dst = getNodeAt(mLine.back());
if (mBeginning) {
if (mBeginning != new_src) {
mBeginning->setPortsVisible(false);
}
}
if (mEnding) {
if (mEnding != new_dst) {
mEnding->setPortsVisible(false);
}
}
mBeginning = new_src;
mEnding = new_dst;
if (mBeginning)
mBeginning->setPortsVisible(true);
if (mEnding)
mEnding->setPortsVisible(true);
if (mDragState == -1) {
Element::mouseMoveEvent(event);
} else {
prepareGeometryChange();
mLine[mDragState] = event->pos();
updateLongestPart();
}
}
void EdgeElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (mDragState == -1)
Element::mouseReleaseEvent(event);
else
mDragState = -1;
connectToPort();
if (mBeginning)
mBeginning->setPortsVisible(false);
if (mEnding)
mEnding->setPortsVisible(false);
// cleanup after moving/resizing
mBeginning = mEnding = NULL;
}
NodeElement *EdgeElement::getNodeAt(QPointF const &position)
{
QPainterPath circlePath;
circlePath.addEllipse(mapToScene(position), 12, 12);
foreach (QGraphicsItem *item, scene()->items(circlePath)) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if (e) {
return e;
}
}
return NULL;
}
void EdgeElement::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu menu;
QAction *addPointAction = menu.addAction("Add point");
QAction *delPointAction = menu.addAction("Remove point");
QAction *squarizeAction = menu.addAction("Squarize");
if (QAction *selectedAction = menu.exec(event->screenPos())) {
if (selectedAction == delPointAction) {
int pointIndex = getPoint(event->pos());
if (pointIndex != -1) {
prepareGeometryChange();
mLine.remove(pointIndex);
mLongPart = 0;
update();
}
} else if (selectedAction == addPointAction) {
for (int i = 0; i < mLine.size() - 1; ++i) {
QPainterPath path;
QPainterPathStroker ps;
ps.setWidth(kvadratik);
path.moveTo(mLine[i]);
path.lineTo(mLine[i+1]);
if (ps.createStroke(path).contains(event->pos())) {
mLine.insert(i + 1, event->pos());
update();
break;
}
}
} else if (selectedAction == squarizeAction) {
prepareGeometryChange();
for (int i = 0; i < mLine.size() - 1; ++i) {
QLineF line(mLine[i], mLine[i + 1]);
if (qAbs(line.dx()) < qAbs(line.dy())) {
mLine[i + 1].setX(mLine[i].x());
} else {
mLine[i + 1].setY(mLine[i].y());
}
}
adjustLink();
update();
}
}
}
void EdgeElement::adjustLink()
{
prepareGeometryChange();
if (mSrc)
mLine.first() = mapFromItem(mSrc, mSrc->getPortPos(mPortFrom));
if (mDst)
mLine.last() = mapFromItem(mDst, mDst->getPortPos(mPortTo));
updateLongestPart();
}
void EdgeElement::updateData()
{
if (mMoving)
return;
Element::updateData();
setPos(mDataIndex.data(roles::positionRole).toPointF());
QPolygonF newLine = mDataIndex.data(roles::configurationRole).value<QPolygon>();
if (!newLine.isEmpty())
mLine = newLine;
qReal::Id uuidFrom = mDataIndex.data(roles::fromRole).value<Id>();
qReal::Id uuidTo = mDataIndex.data(roles::toRole).value<Id>();
if (mSrc)
mSrc->delEdge(this);
if (mDst)
mDst->delEdge(this);
mSrc = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidFrom));
mDst = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidTo));
if (mSrc)
mSrc->addEdge(this);
if (mDst)
mDst->addEdge(this);
setFlag(ItemIsMovable, !(mDst || mSrc));
mPortFrom = mDataIndex.data(roles::fromPortRole).toDouble();
mPortTo = mDataIndex.data(roles::toPortRole).toDouble();
adjustLink();
}
void EdgeElement::removeLink(UML::NodeElement const *from)
{
if (mSrc == from)
mSrc = NULL;
if (mDst == from)
mDst = NULL;
}
<|endoftext|>
|
<commit_before>/*******************************
Copyright (C) 2013-2016 gregoire ANGERAND
This program is 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 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
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "MaterialCompiler.h"
#include <yave/shaders/ShaderModule.h>
#include <yave/mesh/Vertex.h>
#include <yave/Device.h>
#include <yave/shaders/ShaderProgram.h>
namespace yave {
MaterialCompiler::MaterialCompiler(DevicePtr dptr) : DeviceLinked(dptr) {
}
GraphicPipeline MaterialCompiler::compile(const Material& material, const RenderPass& render_pass, Viewport view) const {
auto modules = core::vector(material.get_data()._vert, material.get_data()._frag);
if(!material.get_data()._geom.is_empty()) {
modules << material.get_data()._geom;
}
ShaderProgram program(material.get_device(), modules);
auto pipeline_shader_stage = program.get_vk_pipeline_stage_info();
auto binding_description = vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(sizeof(Vertex))
.setInputRate(vk::VertexInputRate::eVertex)
;
auto pos_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(0)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, position))
;
auto nor_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(1)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, normal))
;
auto uv_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(2)
.setFormat(vk::Format::eR32G32Sfloat)
.setOffset(offsetof(Vertex, uv))
;
vk::VertexInputAttributeDescription attribs[] = {pos_attrib_description, nor_attrib_description, uv_attrib_description};
auto vertex_input = vk::PipelineVertexInputStateCreateInfo()
.setVertexAttributeDescriptionCount(3)
.setPVertexAttributeDescriptions(attribs)
.setVertexBindingDescriptionCount(1)
.setPVertexBindingDescriptions(&binding_description)
;
auto input_assembly = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList)
.setPrimitiveRestartEnable(false)
;
auto viewport = vk::Viewport()
.setWidth(view.extent.x())
.setHeight(view.extent.y())
.setX(view.offset.x())
.setY(view.offset.y())
.setMinDepth(view.depth.x())
.setMaxDepth(view.depth.y())
;
auto viewport_state = vk::PipelineViewportStateCreateInfo()
.setViewportCount(1)
.setPViewports(&viewport)
.setScissorCount(1)
;
auto rasterizer = vk::PipelineRasterizationStateCreateInfo()
.setCullMode(vk::CullModeFlagBits::eBack)
//.setCullMode(vk::CullModeFlagBits::eNone)
.setPolygonMode(vk::PolygonMode::eFill)
.setLineWidth(1.0f)
.setFrontFace(vk::FrontFace::eClockwise)
.setDepthBiasEnable(false)
.setDepthClampEnable(false)
;
auto multisampling = vk::PipelineMultisampleStateCreateInfo()
.setSampleShadingEnable(false)
.setRasterizationSamples(vk::SampleCountFlagBits::e1)
;
auto color_blend_attachment = vk::PipelineColorBlendAttachmentState()
.setBlendEnable(false)
.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eA)
;
auto att_blends = core::range(usize(0), render_pass.attachment_count()).map([=](usize) { return color_blend_attachment; }).collect<core::Vector>();
auto color_blending = vk::PipelineColorBlendStateCreateInfo()
.setLogicOpEnable(false)
.setLogicOp(vk::LogicOp::eCopy)
.setAttachmentCount(u32(att_blends.size()))
.setPAttachments(att_blends.begin())
.setBlendConstants({{0.0f, 0.0f, 0.0f, 0.0f}})
;
auto depth_testing = vk::PipelineDepthStencilStateCreateInfo()
.setDepthTestEnable(true)
.setDepthWriteEnable(true)
.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
;
auto pipeline_layout = get_device()->get_vk_device().createPipelineLayout(vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(u32(program.get_descriptor_layouts().size()))
.setPSetLayouts(program.get_descriptor_layouts().begin())
);
auto pipeline = get_device()->get_vk_device().createGraphicsPipeline(VK_NULL_HANDLE, vk::GraphicsPipelineCreateInfo()
.setStageCount(u32(pipeline_shader_stage.size()))
.setPStages(pipeline_shader_stage.begin())
.setPVertexInputState(&vertex_input)
.setPInputAssemblyState(&input_assembly)
.setPViewportState(&viewport_state)
.setPRasterizationState(&rasterizer)
.setPMultisampleState(&multisampling)
.setPColorBlendState(&color_blending)
.setPDepthStencilState(&depth_testing)
.setLayout(pipeline_layout)
.setRenderPass(render_pass.get_vk_render_pass())
.setSubpass(0)
.setBasePipelineIndex(-1)
);
return GraphicPipeline(material, pipeline, pipeline_layout);
}
}
<commit_msg>Fixed scisor test.<commit_after>/*******************************
Copyright (C) 2013-2016 gregoire ANGERAND
This program is 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 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
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "MaterialCompiler.h"
#include <yave/shaders/ShaderModule.h>
#include <yave/mesh/Vertex.h>
#include <yave/Device.h>
#include <yave/shaders/ShaderProgram.h>
namespace yave {
MaterialCompiler::MaterialCompiler(DevicePtr dptr) : DeviceLinked(dptr) {
}
GraphicPipeline MaterialCompiler::compile(const Material& material, const RenderPass& render_pass, Viewport view) const {
auto modules = core::vector(material.get_data()._vert, material.get_data()._frag);
if(!material.get_data()._geom.is_empty()) {
modules << material.get_data()._geom;
}
ShaderProgram program(material.get_device(), modules);
auto pipeline_shader_stage = program.get_vk_pipeline_stage_info();
auto binding_description = vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(sizeof(Vertex))
.setInputRate(vk::VertexInputRate::eVertex)
;
auto pos_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(0)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, position))
;
auto nor_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(1)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, normal))
;
auto uv_attrib_description = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(2)
.setFormat(vk::Format::eR32G32Sfloat)
.setOffset(offsetof(Vertex, uv))
;
vk::VertexInputAttributeDescription attribs[] = {pos_attrib_description, nor_attrib_description, uv_attrib_description};
auto vertex_input = vk::PipelineVertexInputStateCreateInfo()
.setVertexAttributeDescriptionCount(3)
.setPVertexAttributeDescriptions(attribs)
.setVertexBindingDescriptionCount(1)
.setPVertexBindingDescriptions(&binding_description)
;
auto input_assembly = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList)
.setPrimitiveRestartEnable(false)
;
auto viewport = vk::Viewport()
.setWidth(view.extent.x())
.setHeight(view.extent.y())
.setX(view.offset.x())
.setY(view.offset.y())
.setMinDepth(view.depth.x())
.setMaxDepth(view.depth.y())
;
auto viewport_state = vk::PipelineViewportStateCreateInfo()
.setViewportCount(1)
.setPViewports(&viewport)
.setScissorCount(0)
;
auto rasterizer = vk::PipelineRasterizationStateCreateInfo()
.setCullMode(vk::CullModeFlagBits::eBack)
//.setCullMode(vk::CullModeFlagBits::eNone)
.setPolygonMode(vk::PolygonMode::eFill)
.setLineWidth(1.0f)
.setFrontFace(vk::FrontFace::eClockwise)
.setDepthBiasEnable(false)
.setDepthClampEnable(false)
;
auto multisampling = vk::PipelineMultisampleStateCreateInfo()
.setSampleShadingEnable(false)
.setRasterizationSamples(vk::SampleCountFlagBits::e1)
;
auto color_blend_attachment = vk::PipelineColorBlendAttachmentState()
.setBlendEnable(false)
.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eA)
;
auto att_blends = core::range(usize(0), render_pass.attachment_count()).map([=](usize) { return color_blend_attachment; }).collect<core::Vector>();
auto color_blending = vk::PipelineColorBlendStateCreateInfo()
.setLogicOpEnable(false)
.setLogicOp(vk::LogicOp::eCopy)
.setAttachmentCount(u32(att_blends.size()))
.setPAttachments(att_blends.begin())
.setBlendConstants({{0.0f, 0.0f, 0.0f, 0.0f}})
;
auto depth_testing = vk::PipelineDepthStencilStateCreateInfo()
.setDepthTestEnable(true)
.setDepthWriteEnable(true)
.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
;
auto pipeline_layout = get_device()->get_vk_device().createPipelineLayout(vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(u32(program.get_descriptor_layouts().size()))
.setPSetLayouts(program.get_descriptor_layouts().begin())
);
auto pipeline = get_device()->get_vk_device().createGraphicsPipeline(VK_NULL_HANDLE, vk::GraphicsPipelineCreateInfo()
.setStageCount(u32(pipeline_shader_stage.size()))
.setPStages(pipeline_shader_stage.begin())
.setPVertexInputState(&vertex_input)
.setPInputAssemblyState(&input_assembly)
.setPViewportState(&viewport_state)
.setPRasterizationState(&rasterizer)
.setPMultisampleState(&multisampling)
.setPColorBlendState(&color_blending)
.setPDepthStencilState(&depth_testing)
.setLayout(pipeline_layout)
.setRenderPass(render_pass.get_vk_render_pass())
.setSubpass(0)
.setBasePipelineIndex(-1)
);
return GraphicPipeline(material, pipeline, pipeline_layout);
}
}
<|endoftext|>
|
<commit_before>#include "net/http/HttpContext.h"
#include "net/NetBuffer.h"
#include "base/Timestamp.h"
using zl::base::Timestamp;
NAMESPACE_ZL_NET_START
/// parse:
/// request line \r\n
/// request header \r\n
/// \r\n
/// request body
// 使用chorme浏览器请求127.0.0.1:8888/index.html时,server收到的http消息头
// GET /index.html HTTP/1.1
// Host: 127.0.0.1:8888
// Connection: keep-alive
// Cache-Control: max-age=0
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
// User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like
// Gecko) Chrome / 35.0.1916.153 Safari / 537.36
// Accept - Encoding : gzip, deflate, sdch
// Accept - Language : zh - CN, zh; q = 0.8
// RA - Ver: 2.2.22
// RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8
bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime)
{
static int count = 0;
HttpContext *context = this;
assert(context);
printf("----------------parseRequest------------[%d]\n", ++count);
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (context->expectRequestLine())
{
const char* crlf = buf->findCRLF();
if (crlf)
{
ok = processRequestLine(buf->peek(), crlf); // 解析请求行
if (ok)
{
//context->request().setReceiveTime(receiveTime);
buf->retrieveUntil(crlf + 2);
context->receiveRequestLine(); // 请求行解析完成,下一步要解析消息头中的参数
}
else
{
hasMore = false;
}
}
else
{
hasMore = false;
}
}
else if (context->expectHeaders()) // 解析消息头中的参数
{
printf("context->expectHeaders() [%d]\n", context);
const char* crlf = buf->findCRLF();
if (crlf) //按行添加消息头中的参数
{
//const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历
if(!processReqestHeader(buf->peek(), crlf))
{
// empty line, end of header
context->receiveHeaders(); // 消息头解析完成,下一步应该按get/post来区分是否解析消息体
hasMore = !context->gotAll();
printf("parse headers [%d]\n", hasMore);
map<string, string> headers = context->request().headers();
for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it)
std::cout << it->first << " : " << it->second << "\n";
}
buf->retrieveUntil(crlf + 2);
}
else
{
hasMore = false;
}
}
else if (context->expectBody()) // 解析消息体
{
// FIXME:
printf("context->expectBody() [%d]\n", context);
}
}
return ok;
}
/// request line: httpmethod path httpversion
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
bool succeed = false;
const char* start = begin;
const char* space = std::find(start, end, ' ');
HttpRequest& request = this->request();
string method(start, space);
if (space != end && request.setMethod(method))
{
start = space+1;
space = std::find(start, end, ' ');
if (space != end)
{
const char* question = std::find(start, space, '?');
if (question != space)
{
string u(start, question);
request.setPath(u);
u.assign(question, space);
request.setQuery(u);
}
else
{
string u(start, question);
request.setPath(u);
}
start = space+1;
succeed = end-start == 8 && std::equal(start, end-1, "HTTP/1.");
if (succeed)
{
if (*(end-1) == '1')
{
request.setVersion(HTTP_VERSION_1_1);
}
else if (*(end-1) == '0')
{
request.setVersion(HTTP_VERSION_1_0);
}
else
{
succeed = false;
}
}
}
}
printf("-----%d %s %d----\n", request.method(), request.path().c_str(), request.version());
return succeed;
}
/// request header
bool HttpContext::processReqestHeader(const char *begin, const char *end)
{
const char *colon = std::find(begin, end, ':'); //一行一行遍历
if (colon != end)
{
string field(begin, colon);
++colon;
while (colon < end && isspace(*colon))
{
++colon;
}
string value(colon, end);
while (!value.empty() && isspace(value[value.size()-1]))
{
value.resize(value.size()-1);
}
request_.addHeader(field, value);
return true;
}
else
{
// empty line, end of header
return false;
}
}
NAMESPACE_ZL_NET_END
<commit_msg>update HttpContext.cpp<commit_after>#include "net/http/HttpContext.h"
#include "net/NetBuffer.h"
#include "base/Timestamp.h"
using zl::base::Timestamp;
NAMESPACE_ZL_NET_START
/// parse:
/// request line \r\n
/// request header \r\n
/// \r\n
/// request body
// 使用chorme浏览器请求127.0.0.1:8888/index.html时,server收到的http消息头
// GET /index.html HTTP/1.1
// Host: 127.0.0.1:8888
// Connection: keep-alive
// Cache-Control: max-age=0
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
// User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like
// Gecko) Chrome / 35.0.1916.153 Safari / 537.36
// Accept - Encoding : gzip, deflate, sdch
// Accept - Language : zh - CN, zh; q = 0.8
// RA - Ver: 2.2.22
// RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8
bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime)
{
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (this->expectRequestLine())
{
const char* crlf = buf->findCRLF();
if (crlf)
{
ok = processRequestLine(buf->peek(), crlf); // 解析请求行
if (ok)
{
this->request().setReceiveTime(receiveTime);
buf->retrieveUntil(crlf + 2);
this->receiveRequestLine(); // 请求行解析完成,下一步要解析消息头中的参数
}
else
{
hasMore = false;
}
}
else
{
hasMore = false;
}
}
else if (this->expectHeaders()) // 解析消息头中的参数
{
printf("context->expectHeaders() [%d]\n", this);
const char* crlf = buf->findCRLF();
if (crlf) //按行添加消息头中的参数
{
//const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历
if(!processReqestHeader(buf->peek(), crlf))
{
// empty line, end of header
this->receiveHeaders(); // 消息头解析完成,下一步应该按get/post来区分是否解析消息体
hasMore = !this->gotAll();
printf("parse headers [%d]\n", hasMore);
map<string, string> headers = this->request().headers();
for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it)
std::cout << it->first << " : " << it->second << "\n";
}
buf->retrieveUntil(crlf + 2);
}
else
{
hasMore = false;
}
}
else if (this->expectBody()) // 解析消息体 // FIXME:
{
printf("context->expectBody() [%d]\n", this);
}
}
return ok;
}
/// request line: httpmethod path httpversion
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
const char* start = begin;
const char* space = std::find(start, end, ' ');
HttpRequest& request = this->request();
string method(start, space);
if (space != end && request.setMethod(method))
{
// parse url path
start = space+1;
space = std::find(start, end, ' ');
if (space != end)
{
const char* question = std::find(start, space, '?');
if (question != space)
{
string u(start, question);
request.setPath(u);
u.assign(question, space);
request.setQuery(u);
}
else
{
string u(start, question);
request.setPath(u);
}
// parse http version
start = space + 1;
if(end - start != 8) // neither HTTP/1.1 nor HTTP/1.0
{
return false;
}
if(std::equal(start, end, "HTTP/1.1"))
request.setVersion(HTTP_VERSION_1_1);
else if(std::equal(start, end, "HTTP/1.0"))
request.setVersion(HTTP_VERSION_1_0);
return true;
}
}
return false;
}
/// request header
bool HttpContext::processReqestHeader(const char *begin, const char *end)
{
//while(true) //TODO
{
const char *colon = std::find(begin, end, ':'); //一行一行遍历
if (colon != end)
{
string field(begin, colon);
++colon;
while (colon < end && isspace(*colon))
{
++colon;
}
string value(colon, end);
while (!value.empty() && isspace(value[value.size()-1]))
{
value.resize(value.size()-1);
}
request_.addHeader(field, value);
return true;
}
else
{
// empty line, end of header
return false;
}
}
}
NAMESPACE_ZL_NET_END<|endoftext|>
|
<commit_before>#include <vector>
#include <memory>
#include <iostream>
#include <cmath>
#include <ad/ad.h>
std::pair<Eigen::MatrixXd, Eigen::MatrixXd> GenDataset(int nb_examples) {
// dataset
Eigen::MatrixXd x(2, nb_examples);
Eigen::MatrixXd y(1, nb_examples);
for (int k = 0; k < nb_examples; ++k) {
float x1 = (rand() % 30 - 15) / 15.;
float x2 = (rand() % 30 - 15) / 15.;
x(0, k) = x1;
x(1, k) = x2;
y(0, k) = x1 * 8 + x2 * 3 + 5;
}
return std::make_pair(x, y);
}
int main() {
using namespace ad;
const int nb_examples = 1;
auto a_weights = std::make_shared<Eigen::MatrixXd>(1, 2);
*a_weights << 3, 4;
auto b_weights = std::make_shared<Eigen::MatrixXd>(1, 1);
*b_weights << 6;
for (int i = 0; i < 100; ++ i) {
ComputationGraph g;
auto dataset = GenDataset(nb_examples);
Var x = g.CreateParam(dataset.first);
Var y = g.CreateParam(dataset.second);
Var a = g.CreateParam(a_weights);
Var b = g.CreateParam(b_weights);
Var h = a * x + b;
Var j = MSE(h, y) + 0.001 * (Mean(EltSquare(a)) + Mean(EltSquare(b)));
std::cout << "COST = " << j.value() << "\n";
opt::SGD sgd(0.1 / nb_examples);
g.BackpropFrom(j);
g.Update(sgd, {&a, &b});
}
std::cout << "a = " << *a_weights << " b = " << *b_weights << std::endl;
return 0;
}
<commit_msg>Update linear regression example to use NN<commit_after>#include <vector>
#include <memory>
#include <iostream>
#include <cmath>
#include <ad/ad.h>
std::pair<Eigen::MatrixXd, Eigen::MatrixXd> GenDataset(int nb_examples) {
// dataset
Eigen::MatrixXd x(2, nb_examples);
Eigen::MatrixXd y(1, nb_examples);
for (int k = 0; k < nb_examples; ++k) {
float x1 = (rand() % 30 - 15) / 15.;
float x2 = (rand() % 30 - 15) / 15.;
x(0, k) = x1;
x(1, k) = x2;
y(0, k) = x1 * 8 + x2 * 3 + 5;
}
return std::make_pair(x, y);
}
int main() {
using namespace ad;
const int nb_examples = 1;
nn::FullyConnLayer fc(1, 2);
for (int i = 0; i < 100; ++ i) {
ComputationGraph g;
auto dataset = GenDataset(nb_examples);
Var x = g.CreateParam(dataset.first);
Var y = g.CreateParam(dataset.second);
auto input = nn::InputLayer(x);
auto output = fc.Compute(input);
Var j = MSE(output.out, y) + 0.001 * nn::L2ForAllParams(output);
std::cout << "COST = " << j.value() << "\n";
opt::SGD sgd(0.1 / nb_examples);
g.BackpropFrom(j);
g.Update(sgd, *output.params);
}
std::cout << "w = " << fc.w() << "\nb = " << fc.b() << "\n";
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2007 Carlo Todeschini - Metarete s.r.l. <info@metarete.it>
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.
*/
/*
Algorithm inspired by Vladimir Silva's "Secure Java apps on Linux using
MD5 crypt" article
(http://www-128.ibm.com/developerworks/linux/library/l-md5crypt/)
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QtDebug>
#include <stdio.h>
QString to64 ( long v , int size )
{
// Character set of the encrypted password: A-Za-z0-9./
QString itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
QString result;
while ( --size >= 0 )
{
result.append ( itoa64.at ( ( int )( v & 0x3f ) ) );
v = v >> 6;
}
return result;
}
int byte2unsigned ( int byteValue )
{
int integerToReturn;
integerToReturn = (int) byteValue & 0xff;
return integerToReturn;
}
QString qca_md5crypt( const QCA::SecureArray &password, const QCA::SecureArray &salt )
{
QCA::SecureArray finalState, magic_string = "$1$";
// The md5crypt algorithm uses two separate hashes
QCA::Hash hash1( "md5" );
QCA::Hash hash2( "md5" );
// MD5 Hash #1: pwd, magic string and salt
hash1.update ( password );
hash1.update ( magic_string );
hash1.update ( salt );
// MD5 Hash #2: password, salt, password
hash2.update ( password );
hash2.update ( salt );
hash2.update ( password );
finalState = hash2.final();
// Two sets of transformations based on the length of the password
for ( int i = password.size() ; i > 0 ; i -= 16 )
{
// Update hash1 from offset value (i > 16 ? 16 : i)
hash1.update( finalState.toByteArray().left(i > 16 ? 16 : i));
}
// Clear array bits
finalState.fill( 0 );
for ( int i = password.size() ; i != 0 ; i = i >> 1 )
{
if ( ( i & 1 ) != 0 )
{
hash1.update( finalState.toByteArray().left ( 1 ) );
}
else
{
hash1.update( password.toByteArray().left ( 1 ) );
}
}
finalState = hash1.final();
// Now build a 1000 entry dictionary...
for ( int i = 0 ; i < 1000 ; i++ )
{
hash2.clear();
if ((i & 1) != 0)
{
hash2.update ( password );
}
else
{
hash2.update ( finalState.toByteArray().left( 16 ));
}
if ((i % 3) != 0)
{
hash2.update ( salt );
}
if ((i % 7) != 0)
{
hash2.update ( password );
}
if ((i & 1) != 0)
{
hash2.update ( finalState.toByteArray().left( 16 ) );
}
else
{
hash2.update ( password );
}
finalState = hash2.final();
}
// Create an output string
// Salt is part of the encoded password ($1$<string>$)
QString encodedString;
encodedString.append ( magic_string.toByteArray() );
encodedString.append ( salt.toByteArray() );
encodedString.append ( "$" );
long l;
l = ( byte2unsigned (finalState.toByteArray().at(0) ) << 16 |
( byte2unsigned (finalState.toByteArray().at(6)) ) << 8 |
byte2unsigned (finalState.toByteArray().at(12)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(1)) << 16 |
( byte2unsigned (finalState.toByteArray().at(7))) << 8 |
byte2unsigned (finalState.toByteArray().at(13)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(2)) << 16 |
( byte2unsigned (finalState.toByteArray().at(8))) << 8 |
byte2unsigned (finalState.toByteArray().at(14)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(3)) << 16 |
( byte2unsigned (finalState.toByteArray().at(9))) << 8 |
byte2unsigned (finalState.toByteArray().at(15)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(4)) << 16 |
( byte2unsigned (finalState.toByteArray().at(10))) << 8 |
byte2unsigned (finalState.toByteArray().at(5)) );
encodedString.append ( to64 (l, 4) );
l = byte2unsigned (finalState.toByteArray().at(11));
encodedString.append ( to64 (l, 2) );
return encodedString;
}
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCA::SecureArray password, salt;
QCoreApplication app ( argc, argv );
if ( argc < 3 )
{
printf ( "Usage: %s password salt (salt without $1$)\n" , argv[0] );
return 1;
}
password.append( argv[1] );
salt.append( argv[2] );
// must always check that an algorithm is supported before using it
if( !QCA::isSupported( "md5" ) )
printf ("MD5 hash not supported!\n");
else
{
QString result = qca_md5crypt( password, salt );
printf ("md5crypt [ %s , %s ] = '%s'\n" , password.data(), salt.data() , qPrintable(result) );
// this is equivalent if you have GNU libc 2.0
// printf( "GNU md5crypt [ %s , %s ] = '%s'\n", password.data(), salt.data(), crypt( password.data(), ( "$1$"+salt ).data() ) );
}
return 0;
}
<commit_msg>don't create qca objects between initializer and qapp construction<commit_after>/*
Copyright (C) 2007 Carlo Todeschini - Metarete s.r.l. <info@metarete.it>
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.
*/
/*
Algorithm inspired by Vladimir Silva's "Secure Java apps on Linux using
MD5 crypt" article
(http://www-128.ibm.com/developerworks/linux/library/l-md5crypt/)
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QtDebug>
#include <stdio.h>
QString to64 ( long v , int size )
{
// Character set of the encrypted password: A-Za-z0-9./
QString itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
QString result;
while ( --size >= 0 )
{
result.append ( itoa64.at ( ( int )( v & 0x3f ) ) );
v = v >> 6;
}
return result;
}
int byte2unsigned ( int byteValue )
{
int integerToReturn;
integerToReturn = (int) byteValue & 0xff;
return integerToReturn;
}
QString qca_md5crypt( const QCA::SecureArray &password, const QCA::SecureArray &salt )
{
QCA::SecureArray finalState, magic_string = "$1$";
// The md5crypt algorithm uses two separate hashes
QCA::Hash hash1( "md5" );
QCA::Hash hash2( "md5" );
// MD5 Hash #1: pwd, magic string and salt
hash1.update ( password );
hash1.update ( magic_string );
hash1.update ( salt );
// MD5 Hash #2: password, salt, password
hash2.update ( password );
hash2.update ( salt );
hash2.update ( password );
finalState = hash2.final();
// Two sets of transformations based on the length of the password
for ( int i = password.size() ; i > 0 ; i -= 16 )
{
// Update hash1 from offset value (i > 16 ? 16 : i)
hash1.update( finalState.toByteArray().left(i > 16 ? 16 : i));
}
// Clear array bits
finalState.fill( 0 );
for ( int i = password.size() ; i != 0 ; i = i >> 1 )
{
if ( ( i & 1 ) != 0 )
{
hash1.update( finalState.toByteArray().left ( 1 ) );
}
else
{
hash1.update( password.toByteArray().left ( 1 ) );
}
}
finalState = hash1.final();
// Now build a 1000 entry dictionary...
for ( int i = 0 ; i < 1000 ; i++ )
{
hash2.clear();
if ((i & 1) != 0)
{
hash2.update ( password );
}
else
{
hash2.update ( finalState.toByteArray().left( 16 ));
}
if ((i % 3) != 0)
{
hash2.update ( salt );
}
if ((i % 7) != 0)
{
hash2.update ( password );
}
if ((i & 1) != 0)
{
hash2.update ( finalState.toByteArray().left( 16 ) );
}
else
{
hash2.update ( password );
}
finalState = hash2.final();
}
// Create an output string
// Salt is part of the encoded password ($1$<string>$)
QString encodedString;
encodedString.append ( magic_string.toByteArray() );
encodedString.append ( salt.toByteArray() );
encodedString.append ( "$" );
long l;
l = ( byte2unsigned (finalState.toByteArray().at(0) ) << 16 |
( byte2unsigned (finalState.toByteArray().at(6)) ) << 8 |
byte2unsigned (finalState.toByteArray().at(12)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(1)) << 16 |
( byte2unsigned (finalState.toByteArray().at(7))) << 8 |
byte2unsigned (finalState.toByteArray().at(13)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(2)) << 16 |
( byte2unsigned (finalState.toByteArray().at(8))) << 8 |
byte2unsigned (finalState.toByteArray().at(14)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(3)) << 16 |
( byte2unsigned (finalState.toByteArray().at(9))) << 8 |
byte2unsigned (finalState.toByteArray().at(15)) );
encodedString.append ( to64 (l, 4) );
l = ( byte2unsigned (finalState.toByteArray().at(4)) << 16 |
( byte2unsigned (finalState.toByteArray().at(10))) << 8 |
byte2unsigned (finalState.toByteArray().at(5)) );
encodedString.append ( to64 (l, 4) );
l = byte2unsigned (finalState.toByteArray().at(11));
encodedString.append ( to64 (l, 2) );
return encodedString;
}
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app ( argc, argv );
QCA::SecureArray password, salt;
if ( argc < 3 )
{
printf ( "Usage: %s password salt (salt without $1$)\n" , argv[0] );
return 1;
}
password.append( argv[1] );
salt.append( argv[2] );
// must always check that an algorithm is supported before using it
if( !QCA::isSupported( "md5" ) )
printf ("MD5 hash not supported!\n");
else
{
QString result = qca_md5crypt( password, salt );
printf ("md5crypt [ %s , %s ] = '%s'\n" , password.data(), salt.data() , qPrintable(result) );
// this is equivalent if you have GNU libc 2.0
// printf( "GNU md5crypt [ %s , %s ] = '%s'\n", password.data(), salt.data(), crypt( password.data(), ( "$1$"+salt ).data() ) );
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2009 Stephen John Bush
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.
*/
//C4530: C++ exception handler used, but unwind semantics are not enabled.
#pragma warning (disable: 4530)
#include <iostream>
#include <exodus/mv.h>
#include <exodus/mvutf.h>
#include <exodus/mvexceptions.h>
namespace exodus
{
//http://unicode.org/faq/utf_bom.html
#define STRICT_OR_LENIENT_CONVERSION lenientConversion
/*
TODO improve efficiency by avoiding new/copy/delete
TODO for speed determine utf32/16/8 by compile time macros instead of runtime sizeof(wchar_t)
http://www.firstobject.com/wchar_t-string-on-linux-osx-windows.htm
msvc: google: c++ "predefined macros" site:msdn.microsoft.com
gcc: gcc -dM -E - </dev/null
mingw: g++ -dM -E - <nul
*/
/*
iconv -f WINDOWS-1252 -t UTF-8
http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf#G13708
In UTF-16, if a pointer points to a leading surrogate, a single
backup is required. In UTF-8, if a pointer points to a byte starting with 10xxxxxx (in
binary), one to three backups are required to find the beginning of the character.
*/
DLL_PUBLIC
std::string var::tostring() const
{
THISIS(L"std::string var::tostring() const")
THISISSTRING()
int length = ( int) var_mvstr.length();
//TODO! convert from internal UTF16/32 to external UTF8
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
if (sizeof(wchar_t)==4)
{
return stringfromUTF32((UTF32*)((*this).towstring().data()), length); //ALN:TODO: try to move it into
} // var::toUTF8
else if (sizeof(wchar_t)==2)
{
return stringfromUTF16((UTF16*)( (*this).towstring().data() ), length);
}
else if (sizeof(wchar_t)==1)
{
std::string result(var_mvstr.begin(),var_mvstr.end());
return result;
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"var::tostring(): sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("var::tostring(): sizeof wchar_t " ^ var(int(sizeof(wchar_t))) ^ L" must be 1, 2 or 4");
}
}
std::string toUTF8(const std::wstring& wstr1)
{
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
if (sizeof(wchar_t)==4)
{
return stringfromUTF32((UTF32*)(wstr1.data()), (unsigned int) wstr1.length());
}
else if (sizeof(wchar_t)==2)
{
return stringfromUTF16((UTF16*)(wstr1.data()), (unsigned int) wstr1.length());
}
else if (sizeof(wchar_t)==1)
{
return std::string(wstr1.begin(),wstr1.end());
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"toUTF8: sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("toUTF8: sizeof wchar_t " ^ var(int(sizeof(wchar_t))) ^ L" must be 1, 2 or 4");
}
}
//if there was a way to insert nullcodecvt into character traits maybe could use
//wstring(string.begin(),string.end() but would this offer any advantage?
//http://stackoverflow.com/questions/1357374/locale-dependent-ordering-for-stdstring
std::wstring wstringfromchars(const char* sourcestart, const size_t sourcelength)
{
std::wstring wstr1;
wstr1.resize(sourcelength);
const char* sourceptr=sourcestart;
for (size_t charn=0; charn<sourcelength; ++charn) {
wstr1[charn]=int((unsigned char)(*(sourceptr++)));
}
return wstr1;
}
std::wstring wstringfromUTF8(const UTF8* sourcestart, const size_t sourcelength)
{
//ConversionResult ConvertUTF8toUTF16 (
// const UTF8** sourceStart, const UTF8* sourceEnd,
// UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
if (sizeof(wchar_t)==4)
{
UTF32* targetbuffer=new(UTF32[sourcelength]);
UTF32* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF8toUTF32 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
delete targetbuffer;
std::cerr<<"UTF Conversion Error - UTF32 to wstring"<<std::endl;
throw MVException("UTF Conversion Error - UTF32 to wstring");
}
std::wstring result((wchar_t*)targetbuffer,targetbufferptr-targetbuffer);
delete targetbuffer;
return result;
}
else if (sizeof(wchar_t)==2)
{
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
UTF16* targetbuffer=new(UTF16[sourcelength*4]);
UTF16* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF8toUTF16 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*2, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
delete targetbuffer;
std::cerr<<"UTF Conversion Error - UTF8 to wstring"<<std::endl;
throw MVException("UTF Conversion Error - UTF8 to wstring");
}
std::wstring result((wchar_t*)targetbuffer,targetbufferptr-targetbuffer);
delete targetbuffer;
return result;
}
else if (sizeof(wchar_t)==1)
{
//1 to 1
std::wstring result((wchar_t*)sourcestart,sourcelength);
return result;
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"wstringfromUTF8: sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("wstringfromUTF8: sizeof wchar_t must be 1, 2 or 4");
}
}
std::string stringfromUTF16(const UTF16* sourcestart, const size_t sourcelength)
{
//TODO improve efficiency by avoiding new/copy/delete
//ConversionResult ConvertUTF16toUTF8 (
// const UTF16** sourceStart, const UTF16* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
//allow for max 4 UTF8 bytes per utf16 2 byte char (utf8 max bytes is four)
//actually we will probably restrict ourselves to unicode code points 0000-FFFF
//in order to avoid any four byte UTF16 characters
//in order to ensure indexing characters in UTF16 strings can be lightning fast and proper
UTF8* targetbuffer=new UTF8[sourcelength*4];
UTF8* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF16toUTF8 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*4, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
delete [] targetbuffer;
//std::cout<<" UTF16>>8ERROR ";
std::cerr<<"UTF Conversion Error - UTF16 TO UTF8"<<std::endl;
throw MVException("UTF Conversion Error - UTF16 TO UTF8");
}
std::string result((char*)targetbuffer,targetbufferptr-targetbuffer);
delete [] targetbuffer;
return result;
}
std::string stringfromUTF32(const UTF32* sourcestart, const size_t sourcelength)
{
//TODO improve efficiency by avoiding new/copy/delete
//ConversionResult ConvertUTF32toUTF8 (
// const UTF32** sourceStart, const UTF32* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
//allow for max 4 UTF8 bytes per utf16 2 byte char (utf8 max bytes is four)
//actually we will probably restrict ourselves to unicode code points 0000-FFFF
//in order to avoid any four byte UTF16 characters
//in order to ensure indexing characters in UTF16 strings can be lightning fast and proper
UTF8* targetbuffer=new(UTF8[sourcelength*4]);
UTF8* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF32toUTF8 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*4, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
delete targetbuffer;
//std::cout<<" UTF32>>8ERROR ";
std::cerr<<"UTF Conversion Error - UTF32 TO UTF8 "<< conversionresult<<std::endl;
//throw MVException("UTF Conversion Error - UTF32 TO UTF8");
throw 1;//MVException("");
}
std::string result((char*)targetbuffer,targetbufferptr-targetbuffer);
delete targetbuffer;
return result;
}
}//of namespace exodus
<commit_msg>scoped_array in handling string buffers<commit_after>/*
Copyright (c) 2009 Stephen John Bush
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.
*/
//C4530: C++ exception handler used, but unwind semantics are not enabled.
#pragma warning (disable: 4530)
#include <iostream>
#include <boost/scoped_array.hpp>
#include <exodus/mv.h>
#include <exodus/mvutf.h>
#include <exodus/mvexceptions.h>
namespace exodus
{
//http://unicode.org/faq/utf_bom.html
#define STRICT_OR_LENIENT_CONVERSION lenientConversion
/*
TODO improve efficiency by avoiding new/copy/delete
TODO for speed determine utf32/16/8 by compile time macros instead of runtime sizeof(wchar_t)
http://www.firstobject.com/wchar_t-string-on-linux-osx-windows.htm
msvc: google: c++ "predefined macros" site:msdn.microsoft.com
gcc: gcc -dM -E - </dev/null
mingw: g++ -dM -E - <nul
*/
/*
iconv -f WINDOWS-1252 -t UTF-8
http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf#G13708
In UTF-16, if a pointer points to a leading surrogate, a single
backup is required. In UTF-8, if a pointer points to a byte starting with 10xxxxxx (in
binary), one to three backups are required to find the beginning of the character.
*/
DLL_PUBLIC
std::string var::tostring() const
{
THISIS(L"std::string var::tostring() const")
THISISSTRING()
int length = ( int) var_mvstr.length();
//TODO! convert from internal UTF16/32 to external UTF8
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
if (sizeof(wchar_t)==4)
{
return stringfromUTF32((UTF32*)((*this).towstring().data()), length); //ALN:TODO: try to move it into
} // var::toUTF8
else if (sizeof(wchar_t)==2)
{
return stringfromUTF16((UTF16*)( (*this).towstring().data() ), length);
}
else if (sizeof(wchar_t)==1)
{
std::string result(var_mvstr.begin(),var_mvstr.end());
return result;
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"var::tostring(): sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("var::tostring(): sizeof wchar_t " ^ var(int(sizeof(wchar_t))) ^ L" must be 1, 2 or 4");
}
}
std::string toUTF8(const std::wstring& wstr1)
{
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
if (sizeof(wchar_t)==4)
{
return stringfromUTF32((UTF32*)(wstr1.data()), (unsigned int) wstr1.length());
}
else if (sizeof(wchar_t)==2)
{
return stringfromUTF16((UTF16*)(wstr1.data()), (unsigned int) wstr1.length());
}
else if (sizeof(wchar_t)==1)
{
return std::string(wstr1.begin(),wstr1.end());
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"toUTF8: sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("toUTF8: sizeof wchar_t " ^ var(int(sizeof(wchar_t))) ^ L" must be 1, 2 or 4");
}
}
//if there was a way to insert nullcodecvt into character traits maybe could use
//wstring(string.begin(),string.end() but would this offer any advantage?
//http://stackoverflow.com/questions/1357374/locale-dependent-ordering-for-stdstring
std::wstring wstringfromchars(const char* sourcestart, const size_t sourcelength)
{
std::wstring wstr1;
wstr1.resize(sourcelength);
const char* sourceptr=sourcestart;
for (size_t charn=0; charn<sourcelength; ++charn) {
wstr1[charn]=int((unsigned char)(*(sourceptr++)));
}
return wstr1;
}
std::wstring wstringfromUTF8(const UTF8* sourcestart, const size_t sourcelength)
{
//ConversionResult ConvertUTF8toUTF16 (
// const UTF8** sourceStart, const UTF8* sourceEnd,
// UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
if (sizeof(wchar_t)==4)
{
//ALN:ML UTF32* targetbuffer=new(UTF32[sourcelength]);
boost::scoped_array<UTF32> UTF32buffer( new UTF32[sourcelength]);
UTF32* targetbuffer = UTF32buffer.get();
UTF32* targetbufferptr = targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF8toUTF32 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
//ALN:ML delete targetbuffer;
std::cerr<<"UTF Conversion Error - UTF32 to wstring"<<std::endl;
throw MVException("UTF Conversion Error - UTF32 to wstring");
}
std::wstring result((wchar_t*)targetbuffer,targetbufferptr-targetbuffer);
//ALN:ML delete targetbuffer;
return result;
}
else if (sizeof(wchar_t)==2)
{
//allow for max 4 bytes per single utf8 byte (utf16 max bytes is four)
boost::scoped_array<UTF16> UTF16buffer( new UTF16[sourcelength]);
//ALN:ML UTF16* targetbuffer=new(UTF16[sourcelength*4]);
UTF16* targetbuffer = UTF16buffer.get();
UTF16* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF8toUTF16 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*2, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
//ALN:ML delete targetbuffer;
std::cerr<<"UTF Conversion Error - UTF8 to wstring"<<std::endl;
throw MVException("UTF Conversion Error - UTF8 to wstring");
}
std::wstring result((wchar_t*)targetbuffer,targetbufferptr-targetbuffer);
//ALN:ML delete targetbuffer;
return result;
}
else if (sizeof(wchar_t)==1)
{
//1 to 1
std::wstring result((wchar_t*)sourcestart,sourcelength);
return result;
}
else
{
//std::cout<<" UTF8>>wstring ERROR ";
std::cerr<<"wstringfromUTF8: sizeof wchar_t must be 1, 2 or 4"<<std::endl;
throw MVException("wstringfromUTF8: sizeof wchar_t must be 1, 2 or 4");
}
}
std::string stringfromUTF16(const UTF16* sourcestart, const size_t sourcelength)
{
//TODO improve efficiency by avoiding new/copy/delete
//ConversionResult ConvertUTF16toUTF8 (
// const UTF16** sourceStart, const UTF16* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
//allow for max 4 UTF8 bytes per utf16 2 byte char (utf8 max bytes is four)
//actually we will probably restrict ourselves to unicode code points 0000-FFFF
//in order to avoid any four byte UTF16 characters
//in order to ensure indexing characters in UTF16 strings can be lightning fast and proper
//ALN:ML UTF8* targetbuffer=new UTF8[sourcelength*4];
boost::scoped_array<UTF8> UTF8buffer( new UTF8[sourcelength*4]);
UTF8* targetbuffer = UTF8buffer.get();
UTF8* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF16toUTF8 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*4, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
//ALN:ML delete [] targetbuffer;
//std::cout<<" UTF16>>8ERROR ";
std::cerr<<"UTF Conversion Error - UTF16 TO UTF8"<<std::endl;
throw MVException("UTF Conversion Error - UTF16 TO UTF8");
}
std::string result((char*)targetbuffer,targetbufferptr-targetbuffer);
//ALN:ML delete [] targetbuffer;
return result;
}
std::string stringfromUTF32(const UTF32* sourcestart, const size_t sourcelength)
{
//TODO improve efficiency by avoiding new/copy/delete
//ConversionResult ConvertUTF32toUTF8 (
// const UTF32** sourceStart, const UTF32* sourceEnd,
// UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
//allow for max 4 UTF8 bytes per utf16 2 byte char (utf8 max bytes is four)
//actually we will probably restrict ourselves to unicode code points 0000-FFFF
//in order to avoid any four byte UTF16 characters
//in order to ensure indexing characters in UTF16 strings can be lightning fast and proper
//ALN:ML UTF8* targetbuffer=new(UTF8[sourcelength*4]);
boost::scoped_array<UTF8> UTF8buffer( new UTF8[sourcelength*4]);
UTF8* targetbuffer = UTF8buffer.get();
UTF8* targetbufferptr=targetbuffer;
//TODO check if ok
ConversionResult conversionresult=ConvertUTF32toUTF8 (
&sourcestart, sourcestart+sourcelength,
&targetbufferptr, targetbuffer+sourcelength*4, STRICT_OR_LENIENT_CONVERSION);
//TODO check if ok
if (conversionresult)
{
//ALN:ML delete targetbuffer;
//std::cout<<" UTF32>>8ERROR ";
std::cerr<<"UTF Conversion Error - UTF32 TO UTF8 "<< conversionresult<<std::endl;
//throw MVException("UTF Conversion Error - UTF32 TO UTF8");
throw 1;//MVException("");
}
std::string result((char*)targetbuffer,targetbufferptr-targetbuffer);
//ALN:ML delete targetbuffer;
return result;
}
}//of namespace exodus
<|endoftext|>
|
<commit_before>#include "setupdialog.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QStandardPaths>
// This is used for QHostInfo::localHostName(). It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>
#include "ui_setupdialog.h"
WARNINGS_ENABLE
#include "debug.h"
#include "tasks-defs.h"
#include "utils.h"
#include <TSettings.h>
SetupDialog::SetupDialog(QWidget *parent)
: QDialog(parent), _ui(new Ui::SetupDialog)
{
_ui->setupUi(this);
setWindowFlags((windowFlags() | Qt::CustomizeWindowHint)
& ~Qt::WindowMaximizeButtonHint);
// These should be done before connecting objects to
// validateAdvancedSetupPage() to avoid calling that function
// unnecessarily.
_tarsnapDir = Utils::findTarsnapClientInPath("", true);
_ui->tarsnapPathLineEdit->setText(_tarsnapDir);
_ui->machineNameLineEdit->setText(QHostInfo::localHostName());
_ui->wizardStackedWidget->setCurrentWidget(_ui->welcomePage);
_appDataDir = QStandardPaths::writableLocation(APPDATA);
QDir keysDir(_appDataDir);
if(!keysDir.exists())
keysDir.mkpath(_appDataDir);
_ui->appDataPathLineEdit->setText(_appDataDir);
// find existing keys
for(const QFileInfo &file : Utils::findKeysInPath(_appDataDir))
_ui->machineKeyCombo->addItem(file.canonicalFilePath());
_tarsnapCacheDir =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
QDir cacheDir(_tarsnapCacheDir);
if(!cacheDir.exists())
cacheDir.mkpath(_tarsnapCacheDir);
_ui->tarsnapCacheLineEdit->setText(_tarsnapCacheDir);
_ui->advancedCLIWidget->hide();
// All pages
connect(_ui->backButton, &QPushButton::clicked, this,
&SetupDialog::backButtonClicked);
connect(_ui->nextButton, &QPushButton::clicked, this,
&SetupDialog::nextButtonClicked);
connect(_ui->welcomePageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->advancedPageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->registerPageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->donePageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->wizardStackedWidget, &QStackedWidget::currentChanged, this,
&SetupDialog::wizardPageChanged);
// Advanced setup page
connect(_ui->advancedCLIButton, &QPushButton::toggled,
_ui->advancedCLIWidget, &QWidget::setVisible);
connect(_ui->tarsnapPathBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showTarsnapPathBrowse);
connect(_ui->tarsnapPathLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
connect(_ui->tarsnapCacheBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showTarsnapCacheBrowse);
connect(_ui->tarsnapCacheLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
connect(_ui->appDataBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showAppDataBrowse);
connect(_ui->appDataPathLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
// Register page
connect(_ui->restoreNoButton, &QPushButton::clicked, this,
&SetupDialog::restoreNo);
connect(_ui->restoreYesButton, &QPushButton::clicked, this,
&SetupDialog::restoreYes);
connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->machineKeyCombo, &QComboBox::currentTextChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->browseKeyButton, &QPushButton::clicked, this,
&SetupDialog::registerHaveKeyBrowse);
wizardPageChanged(0);
}
SetupDialog::~SetupDialog()
{
delete _ui;
}
void SetupDialog::wizardPageChanged(int)
{
// Values which might be overwritten below.
_ui->backButton->setText(tr("Back"));
_ui->nextButton->setText(tr("Next"));
_ui->nextButton->setEnabled(true);
if(_ui->wizardStackedWidget->currentWidget() == _ui->welcomePage)
{
_ui->welcomePageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Setup wizard"));
_ui->backButton->setText(tr("Skip wizard"));
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->advancedPage)
{
_ui->advancedPageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Command-line utilities"));
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
{
_ui->registerPageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Register with server"));
_ui->nextButton->setText(tr("Register machine"));
if(_ui->machineKeyCombo->count() > 0)
{
_ui->restoreYesButton->setChecked(true);
restoreYes();
}
else
{
_ui->restoreNoButton->setChecked(true);
restoreNo();
}
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->donePage)
{
_ui->donePageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Setup complete!"));
_ui->nextButton->setText(tr("Start using Tarsnap"));
}
}
void SetupDialog::backButtonClicked()
{
int nextIndex = _ui->wizardStackedWidget->currentIndex() - 1;
if(nextIndex < 0)
commitSettings(true);
else
_ui->wizardStackedWidget->setCurrentIndex(nextIndex);
}
void SetupDialog::nextButtonClicked()
{
if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
registerMachine();
else if(_ui->wizardStackedWidget->currentWidget() == _ui->donePage)
commitSettings(false);
else
setNextPage();
}
void SetupDialog::skipToPage()
{
if(sender() == _ui->welcomePageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->welcomePage);
else if(sender() == _ui->advancedPageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->advancedPage);
else if(sender() == _ui->registerPageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->registerPage);
else if(sender() == _ui->donePageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->donePage);
}
void SetupDialog::setNextPage()
{
if(_ui->wizardStackedWidget->currentWidget() == _ui->welcomePage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->advancedPage);
_ui->advancedPageRadioButton->setEnabled(true);
bool advancedOk = validateAdvancedSetupPage();
_ui->advancedCLIButton->setChecked(!advancedOk);
if(advancedOk)
_ui->nextButton->setFocus();
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->advancedPage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->registerPage);
_ui->registerPageRadioButton->setEnabled(true);
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->donePage);
_ui->donePageRadioButton->setEnabled(true);
}
}
void SetupDialog::showTarsnapPathBrowse()
{
QString tarsnapPath =
QFileDialog::getExistingDirectory(this, tr("Find Tarsnap client"), "");
_ui->tarsnapPathLineEdit->setText(tarsnapPath);
}
void SetupDialog::showTarsnapCacheBrowse()
{
QString tarsnapCacheDir =
QFileDialog::getExistingDirectory(this, tr("Tarsnap cache location"),
_tarsnapCacheDir);
_ui->tarsnapCacheLineEdit->setText(tarsnapCacheDir);
}
void SetupDialog::showAppDataBrowse()
{
QString appDataDir =
QFileDialog::getExistingDirectory(this, tr("App data location"), "");
_ui->appDataPathLineEdit->setText(appDataDir);
}
bool SetupDialog::validateAdvancedSetupPage()
{
bool result = true;
_appDataDir = Utils::validateAppDataDir(_ui->appDataPathLineEdit->text());
if(_appDataDir.isEmpty())
{
_ui->advancedValidationLabel->setText(tr("Invalid App data directory "
"set."));
result = false;
}
_tarsnapCacheDir =
Utils::validateTarsnapCache(_ui->tarsnapCacheLineEdit->text());
if(result && _tarsnapCacheDir.isEmpty())
{
_ui->advancedValidationLabel->setText(
tr("Invalid Tarsnap cache directory"
" set."));
result = false;
}
_tarsnapDir =
Utils::findTarsnapClientInPath(_ui->tarsnapPathLineEdit->text(), true);
if(result && _tarsnapDir.isEmpty())
{
_ui->advancedValidationLabel->setText(
tr("Tarsnap utilities not found. Visit "
"<a href=\"https://tarsnap.com\">tarsnap.com</a> "
"for help with acquiring them."));
result = false;
}
else if(result)
{
TSettings settings;
settings.setValue("tarsnap/path", _tarsnapDir);
// Wipe previous version number before asking for a new one.
settings.setValue("tarsnap/version", "");
emit tarsnapVersionRequested();
}
_ui->nextButton->setEnabled(result);
return result;
}
void SetupDialog::restoreNo()
{
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->keyNoPage);
// Share machineNameLineEdit in both pages of the keyStackedWidget
_ui->gridKeyNoLayout->addWidget(_ui->machineNameLineEdit, 1, 1);
_ui->statusLabel->clear();
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
void SetupDialog::restoreYes()
{
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->keyYesPage);
// Share machineNameLineEdit in both pages of the keyStackedWidget
_ui->gridKeyYesLayout->addWidget(_ui->machineNameLineEdit, 1, 1);
_ui->statusLabel->clear();
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
bool SetupDialog::validateRegisterPage()
{
bool result = false;
if(_ui->restoreYesButton->isChecked())
{
// user specified key
QFileInfo machineKeyFile(_ui->machineKeyCombo->currentText());
if(!_ui->machineNameLineEdit->text().isEmpty()
&& machineKeyFile.exists() && machineKeyFile.isFile()
&& machineKeyFile.isReadable())
{
result = true;
}
}
else
{
if(!_ui->tarsnapUserLineEdit->text().isEmpty()
&& !_ui->tarsnapPasswordLineEdit->text().isEmpty()
&& !_ui->machineNameLineEdit->text().isEmpty())
{
result = true;
}
}
_ui->nextButton->setEnabled(result);
return result;
}
void SetupDialog::registerHaveKeyBrowse()
{
QString keyFilter = tr("Tarsnap key files (*.key *.keys)");
QString existingMachineKey =
QFileDialog::getOpenFileName(this,
tr("Browse for existing machine key"), "",
tr("All files (*);;") + keyFilter,
&keyFilter);
if(!existingMachineKey.isEmpty())
_ui->machineKeyCombo->setCurrentText(existingMachineKey);
}
void SetupDialog::registerMachine()
{
bool useExistingKeyfile = false;
_ui->nextButton->setEnabled(false);
_ui->statusLabel->clear();
_ui->statusLabel->setStyleSheet("");
if(_ui->restoreYesButton->isChecked())
{
useExistingKeyfile = true;
_ui->statusLabel->setText("Verifying archive integrity...");
_tarsnapKeyFile = _ui->machineKeyCombo->currentText();
}
else
{
_ui->statusLabel->setText("Generating keyfile...");
_tarsnapKeyFile =
_appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
+ "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
+ ".key";
}
TSettings settings;
settings.setValue("tarsnap/cache", _tarsnapCacheDir);
settings.setValue("tarsnap/key", _tarsnapKeyFile);
settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());
settings.setValue("tarsnap/machine", _ui->machineNameLineEdit->text());
emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
useExistingKeyfile);
}
void SetupDialog::registerMachineResponse(TaskStatus status, QString reason)
{
switch(status)
{
case TaskStatus::Completed:
_ui->statusLabel->clear();
_ui->doneKeyFileNameLabel->setText(
QString("<a href=\"%1\">%2</a>")
.arg(QUrl::fromLocalFile(
QFileInfo(_tarsnapKeyFile).absolutePath())
.toString())
.arg(_tarsnapKeyFile));
_ui->nextButton->setEnabled(true);
setNextPage();
break;
case TaskStatus::Failed:
_ui->statusLabel->setText(reason);
_ui->statusLabel->setStyleSheet("#statusLabel { color: darkred; }");
_ui->nextButton->setEnabled(true);
break;
default:
// We shouldn't receive anything else, so ignore it.
break;
}
}
void SetupDialog::updateLoadingAnimation(bool idle)
{
_ui->busyWidget->animate(!idle);
}
void SetupDialog::tarsnapVersionResponse(TaskStatus status,
QString versionString)
{
// Sanity check.
if(versionString.isEmpty())
status = TaskStatus::Failed;
// Handle response.
switch(status)
{
case TaskStatus::Completed:
_tarsnapVersion = versionString;
_ui->advancedValidationLabel->setText(
tr("Tarsnap CLI version ") + _tarsnapVersion + tr(" detected. ✔"));
break;
case TaskStatus::VersionTooLow:
// Don't record the too-low version number.
_ui->advancedValidationLabel->setText(
tr("Tarsnap CLI version ") + versionString
+ tr(" too low; must be at least %1").arg(TARSNAP_MIN_VERSION));
break;
case TaskStatus::Failed:
_ui->advancedValidationLabel->setText(
tr("Error retrieving Tarsnap CLI verison"));
break;
default:
break;
}
}
void SetupDialog::commitSettings(bool skipped)
{
TSettings settings;
settings.setValue("app/wizard_done", true);
if(!skipped)
{
settings.setValue("app/app_data", _appDataDir);
settings.setValue("tarsnap/version", _tarsnapVersion);
}
settings.sync();
// We initialize/verify the cache with fsck-prune for existing keys
// anyway, so we only need to initialize for new keys here.
if(!skipped && _ui->restoreNoButton->isChecked())
emit initializeCache();
accept();
}
<commit_msg>SetupDialog: clarify some version-related checks<commit_after>#include "setupdialog.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QStandardPaths>
// This is used for QHostInfo::localHostName(). It could be replaced with
// QSysInfo::machineHostName() to remove the dependency on the Qt network
// library, but only if we require Qt 5.6+.
#include <QHostInfo>
#include "ui_setupdialog.h"
WARNINGS_ENABLE
#include "debug.h"
#include "tasks-defs.h"
#include "utils.h"
#include <TSettings.h>
SetupDialog::SetupDialog(QWidget *parent)
: QDialog(parent), _ui(new Ui::SetupDialog)
{
_ui->setupUi(this);
setWindowFlags((windowFlags() | Qt::CustomizeWindowHint)
& ~Qt::WindowMaximizeButtonHint);
// These should be done before connecting objects to
// validateAdvancedSetupPage() to avoid calling that function
// unnecessarily.
_tarsnapDir = Utils::findTarsnapClientInPath("", true);
_ui->tarsnapPathLineEdit->setText(_tarsnapDir);
_ui->machineNameLineEdit->setText(QHostInfo::localHostName());
_ui->wizardStackedWidget->setCurrentWidget(_ui->welcomePage);
_appDataDir = QStandardPaths::writableLocation(APPDATA);
QDir keysDir(_appDataDir);
if(!keysDir.exists())
keysDir.mkpath(_appDataDir);
_ui->appDataPathLineEdit->setText(_appDataDir);
// find existing keys
for(const QFileInfo &file : Utils::findKeysInPath(_appDataDir))
_ui->machineKeyCombo->addItem(file.canonicalFilePath());
_tarsnapCacheDir =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
QDir cacheDir(_tarsnapCacheDir);
if(!cacheDir.exists())
cacheDir.mkpath(_tarsnapCacheDir);
_ui->tarsnapCacheLineEdit->setText(_tarsnapCacheDir);
_ui->advancedCLIWidget->hide();
// All pages
connect(_ui->backButton, &QPushButton::clicked, this,
&SetupDialog::backButtonClicked);
connect(_ui->nextButton, &QPushButton::clicked, this,
&SetupDialog::nextButtonClicked);
connect(_ui->welcomePageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->advancedPageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->registerPageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->donePageRadioButton, &QRadioButton::clicked, this,
&SetupDialog::skipToPage);
connect(_ui->wizardStackedWidget, &QStackedWidget::currentChanged, this,
&SetupDialog::wizardPageChanged);
// Advanced setup page
connect(_ui->advancedCLIButton, &QPushButton::toggled,
_ui->advancedCLIWidget, &QWidget::setVisible);
connect(_ui->tarsnapPathBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showTarsnapPathBrowse);
connect(_ui->tarsnapPathLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
connect(_ui->tarsnapCacheBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showTarsnapCacheBrowse);
connect(_ui->tarsnapCacheLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
connect(_ui->appDataBrowseButton, &QPushButton::clicked, this,
&SetupDialog::showAppDataBrowse);
connect(_ui->appDataPathLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateAdvancedSetupPage);
// Register page
connect(_ui->restoreNoButton, &QPushButton::clicked, this,
&SetupDialog::restoreNo);
connect(_ui->restoreYesButton, &QPushButton::clicked, this,
&SetupDialog::restoreYes);
connect(_ui->tarsnapUserLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->tarsnapPasswordLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->machineNameLineEdit, &QLineEdit::textChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->machineKeyCombo, &QComboBox::currentTextChanged, this,
&SetupDialog::validateRegisterPage);
connect(_ui->browseKeyButton, &QPushButton::clicked, this,
&SetupDialog::registerHaveKeyBrowse);
wizardPageChanged(0);
}
SetupDialog::~SetupDialog()
{
delete _ui;
}
void SetupDialog::wizardPageChanged(int)
{
// Values which might be overwritten below.
_ui->backButton->setText(tr("Back"));
_ui->nextButton->setText(tr("Next"));
_ui->nextButton->setEnabled(true);
if(_ui->wizardStackedWidget->currentWidget() == _ui->welcomePage)
{
_ui->welcomePageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Setup wizard"));
_ui->backButton->setText(tr("Skip wizard"));
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->advancedPage)
{
_ui->advancedPageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Command-line utilities"));
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
{
_ui->registerPageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Register with server"));
_ui->nextButton->setText(tr("Register machine"));
if(_ui->machineKeyCombo->count() > 0)
{
_ui->restoreYesButton->setChecked(true);
restoreYes();
}
else
{
_ui->restoreNoButton->setChecked(true);
restoreNo();
}
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->donePage)
{
_ui->donePageRadioButton->setChecked(true);
_ui->titleLabel->setText(tr("Setup complete!"));
_ui->nextButton->setText(tr("Start using Tarsnap"));
}
}
void SetupDialog::backButtonClicked()
{
int nextIndex = _ui->wizardStackedWidget->currentIndex() - 1;
if(nextIndex < 0)
commitSettings(true);
else
_ui->wizardStackedWidget->setCurrentIndex(nextIndex);
}
void SetupDialog::nextButtonClicked()
{
if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
registerMachine();
else if(_ui->wizardStackedWidget->currentWidget() == _ui->donePage)
commitSettings(false);
else
setNextPage();
}
void SetupDialog::skipToPage()
{
if(sender() == _ui->welcomePageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->welcomePage);
else if(sender() == _ui->advancedPageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->advancedPage);
else if(sender() == _ui->registerPageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->registerPage);
else if(sender() == _ui->donePageRadioButton)
_ui->wizardStackedWidget->setCurrentWidget(_ui->donePage);
}
void SetupDialog::setNextPage()
{
if(_ui->wizardStackedWidget->currentWidget() == _ui->welcomePage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->advancedPage);
_ui->advancedPageRadioButton->setEnabled(true);
// Disable this until we know the version number.
_ui->nextButton->setEnabled(false);
bool advancedOk = validateAdvancedSetupPage();
_ui->advancedCLIButton->setChecked(!advancedOk);
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->advancedPage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->registerPage);
_ui->registerPageRadioButton->setEnabled(true);
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
else if(_ui->wizardStackedWidget->currentWidget() == _ui->registerPage)
{
_ui->wizardStackedWidget->setCurrentWidget(_ui->donePage);
_ui->donePageRadioButton->setEnabled(true);
}
}
void SetupDialog::showTarsnapPathBrowse()
{
QString tarsnapPath =
QFileDialog::getExistingDirectory(this, tr("Find Tarsnap client"), "");
_ui->tarsnapPathLineEdit->setText(tarsnapPath);
}
void SetupDialog::showTarsnapCacheBrowse()
{
QString tarsnapCacheDir =
QFileDialog::getExistingDirectory(this, tr("Tarsnap cache location"),
_tarsnapCacheDir);
_ui->tarsnapCacheLineEdit->setText(tarsnapCacheDir);
}
void SetupDialog::showAppDataBrowse()
{
QString appDataDir =
QFileDialog::getExistingDirectory(this, tr("App data location"), "");
_ui->appDataPathLineEdit->setText(appDataDir);
}
bool SetupDialog::validateAdvancedSetupPage()
{
bool result = true;
_appDataDir = Utils::validateAppDataDir(_ui->appDataPathLineEdit->text());
if(_appDataDir.isEmpty())
{
_ui->advancedValidationLabel->setText(tr("Invalid App data directory "
"set."));
result = false;
}
_tarsnapCacheDir =
Utils::validateTarsnapCache(_ui->tarsnapCacheLineEdit->text());
if(result && _tarsnapCacheDir.isEmpty())
{
_ui->advancedValidationLabel->setText(
tr("Invalid Tarsnap cache directory"
" set."));
result = false;
}
_tarsnapDir =
Utils::findTarsnapClientInPath(_ui->tarsnapPathLineEdit->text(), true);
if(result && _tarsnapDir.isEmpty())
{
_ui->advancedValidationLabel->setText(
tr("Tarsnap utilities not found. Visit "
"<a href=\"https://tarsnap.com\">tarsnap.com</a> "
"for help with acquiring them."));
result = false;
}
else if(result)
{
TSettings settings;
settings.setValue("tarsnap/path", _tarsnapDir);
// Wipe previous version number before asking for a new one.
settings.setValue("tarsnap/version", "");
emit tarsnapVersionRequested();
}
// If `results` is true, then we might still be waiting for
// the result of tarsnapVersion, so we can't enable this yet.
if(!result)
_ui->nextButton->setEnabled(false);
return result;
}
void SetupDialog::restoreNo()
{
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->keyNoPage);
// Share machineNameLineEdit in both pages of the keyStackedWidget
_ui->gridKeyNoLayout->addWidget(_ui->machineNameLineEdit, 1, 1);
_ui->statusLabel->clear();
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
void SetupDialog::restoreYes()
{
_ui->registerKeyStackedWidget->setCurrentWidget(_ui->keyYesPage);
// Share machineNameLineEdit in both pages of the keyStackedWidget
_ui->gridKeyYesLayout->addWidget(_ui->machineNameLineEdit, 1, 1);
_ui->statusLabel->clear();
if(validateRegisterPage())
_ui->nextButton->setFocus();
}
bool SetupDialog::validateRegisterPage()
{
bool result = false;
if(_ui->restoreYesButton->isChecked())
{
// user specified key
QFileInfo machineKeyFile(_ui->machineKeyCombo->currentText());
if(!_ui->machineNameLineEdit->text().isEmpty()
&& machineKeyFile.exists() && machineKeyFile.isFile()
&& machineKeyFile.isReadable())
{
result = true;
}
}
else
{
if(!_ui->tarsnapUserLineEdit->text().isEmpty()
&& !_ui->tarsnapPasswordLineEdit->text().isEmpty()
&& !_ui->machineNameLineEdit->text().isEmpty())
{
result = true;
}
}
_ui->nextButton->setEnabled(result);
return result;
}
void SetupDialog::registerHaveKeyBrowse()
{
QString keyFilter = tr("Tarsnap key files (*.key *.keys)");
QString existingMachineKey =
QFileDialog::getOpenFileName(this,
tr("Browse for existing machine key"), "",
tr("All files (*);;") + keyFilter,
&keyFilter);
if(!existingMachineKey.isEmpty())
_ui->machineKeyCombo->setCurrentText(existingMachineKey);
}
void SetupDialog::registerMachine()
{
bool useExistingKeyfile = false;
_ui->nextButton->setEnabled(false);
_ui->statusLabel->clear();
_ui->statusLabel->setStyleSheet("");
if(_ui->restoreYesButton->isChecked())
{
useExistingKeyfile = true;
_ui->statusLabel->setText("Verifying archive integrity...");
_tarsnapKeyFile = _ui->machineKeyCombo->currentText();
}
else
{
_ui->statusLabel->setText("Generating keyfile...");
_tarsnapKeyFile =
_appDataDir + QDir::separator() + _ui->machineNameLineEdit->text()
+ "-" + QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")
+ ".key";
}
TSettings settings;
settings.setValue("tarsnap/cache", _tarsnapCacheDir);
settings.setValue("tarsnap/key", _tarsnapKeyFile);
settings.setValue("tarsnap/user", _ui->tarsnapUserLineEdit->text());
settings.setValue("tarsnap/machine", _ui->machineNameLineEdit->text());
emit registerMachineRequested(_ui->tarsnapPasswordLineEdit->text(),
useExistingKeyfile);
}
void SetupDialog::registerMachineResponse(TaskStatus status, QString reason)
{
switch(status)
{
case TaskStatus::Completed:
_ui->statusLabel->clear();
_ui->doneKeyFileNameLabel->setText(
QString("<a href=\"%1\">%2</a>")
.arg(QUrl::fromLocalFile(
QFileInfo(_tarsnapKeyFile).absolutePath())
.toString())
.arg(_tarsnapKeyFile));
_ui->nextButton->setEnabled(true);
setNextPage();
break;
case TaskStatus::Failed:
_ui->statusLabel->setText(reason);
_ui->statusLabel->setStyleSheet("#statusLabel { color: darkred; }");
_ui->nextButton->setEnabled(true);
break;
default:
// We shouldn't receive anything else, so ignore it.
break;
}
}
void SetupDialog::updateLoadingAnimation(bool idle)
{
_ui->busyWidget->animate(!idle);
}
void SetupDialog::tarsnapVersionResponse(TaskStatus status,
QString versionString)
{
// Sanity check.
if(versionString.isEmpty())
status = TaskStatus::Failed;
// Handle response.
switch(status)
{
case TaskStatus::Completed:
_tarsnapVersion = versionString;
_ui->advancedValidationLabel->setText(
tr("Tarsnap CLI version ") + _tarsnapVersion + tr(" detected. ✔"));
// Enable progress
_ui->nextButton->setEnabled(true);
_ui->nextButton->setFocus();
break;
case TaskStatus::VersionTooLow:
// Don't record the too-low version number.
_ui->advancedValidationLabel->setText(
tr("Tarsnap CLI version ") + versionString
+ tr(" too low; must be at least %1").arg(TARSNAP_MIN_VERSION));
break;
case TaskStatus::Failed:
_ui->advancedValidationLabel->setText(
tr("Error retrieving Tarsnap CLI verison"));
break;
default:
break;
}
}
void SetupDialog::commitSettings(bool skipped)
{
TSettings settings;
settings.setValue("app/wizard_done", true);
if(!skipped)
{
settings.setValue("app/app_data", _appDataDir);
settings.setValue("tarsnap/version", _tarsnapVersion);
}
settings.sync();
// We initialize/verify the cache with fsck-prune for existing keys
// anyway, so we only need to initialize for new keys here.
if(!skipped && _ui->restoreNoButton->isChecked())
emit initializeCache();
accept();
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "WrapHelper.h"
#include "../avgconfigwrapper.h"
#include "../conradrelais/ConradRelais.h"
#ifdef AVG_ENABLE_PARPORT
#include <linux/parport.h>
#endif
using namespace boost::python;
using namespace avg;
void export_devices()
{
class_<ConradRelais>("ConradRelais", init<Player*, int>())
.def("getNumCards", &ConradRelais::getNumCards)
.def("set", &ConradRelais::set)
.def("get", &ConradRelais::get)
;
}
<commit_msg>Removed unused file.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Create code.cpp<commit_after><|endoftext|>
|
<commit_before>/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 23:25:04
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];
ll solve()
{
ll ans = 0;
for (auto i = 0; i < Q; i++)
{
int maxi = 0;
for (auto j = l[i]; j <= r[i]; j++)
{
if (!used[j] && a[j] > maxi)
{
maxi = a[j];
}
}
// cerr << maxi << " ";
ans += maxi;
}
// cerr << ", ans = " << ans << endl;
return ans;
}
void solveA()
{
ll ans = 10000000000000;
for (auto i = 0; i < (1 << N); i++)
{
int cnt = 0;
for (auto j = 0; j < N; j++)
{
if ((i >> j) & 1)
{
cnt++;
}
}
if (cnt == M)
{
for (auto j = 0; j < N; j++)
{
used[j] = (i >> j) & 1;
}
ans = min(ans, solve());
}
}
cout << ans << endl;
}
void solveB()
{
fill(used, used + N, false);
int c[50];
fill(c, c + 50, 0);
for (auto i = 0; i < Q; i++)
{
for (auto j = l[i]; j <= r[i]; j++)
{
c[j]++;
}
}
vector< tuple<int, int> > V;
for (auto i = 0; i < N; i++)
{
V.push_back(make_tuple(c[i], i));
}
sort(V.begin(), V.end());
reverse(V.begin(), V.end());
for (auto i = 0; i < M; i++)
{
used[get<1>(V[i])] = true;
}
cout << solve() << endl;
}
int main()
{
cin >> N >> M >> Q;
for (auto i = 0; i < N; i++)
{
cin >> a[i];
}
for (auto i = 0; i < Q; i++)
{
cin >> l[i] >> r[i];
l[i]--;
r[i]--;
}
if (N <= 15)
{
solveA();
}
else
{
solveB();
}
}<commit_msg>submit F.cpp to 'F - Lunch Menu' (s8pc-5) [C++14 (GCC 5.4.1)]<commit_after>/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 23:25:04
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];
ll solve()
{
ll ans = 0;
for (auto i = 0; i < Q; i++)
{
int maxi = 0;
for (auto j = l[i]; j <= r[i]; j++)
{
if (!used[j] && a[j] > maxi)
{
maxi = a[j];
}
}
// cerr << maxi << " ";
ans += maxi;
}
// cerr << ", ans = " << ans << endl;
return ans;
}
void solveA()
{
ll ans = 10000000000000;
for (auto i = 0; i < (1 << N); i++)
{
int cnt = 0;
for (auto j = 0; j < N; j++)
{
if ((i >> j) & 1)
{
cnt++;
}
}
if (cnt == M)
{
for (auto j = 0; j < N; j++)
{
used[j] = (i >> j) & 1;
}
ans = min(ans, solve());
}
}
cout << ans << endl;
}
void solveB()
{
ll ans = 10000000000000;
ll master = (1 << M) - 1;
int cnt = 0;
for (auto k = 0; k < N; k++)
{
ll i = master << k;
for (auto j = 0; j < N; j++)
{
if ((i >> j) & 1)
{
cnt++;
}
}
if (cnt == M)
{
for (auto j = 0; j < N; j++)
{
used[j] = (i >> j) & 1;
}
ans = min(ans, solve());
}
cout << ans << endl;
}
}
int main()
{
cin >> N >> M >> Q;
for (auto i = 0; i < N; i++)
{
cin >> a[i];
}
for (auto i = 0; i < Q; i++)
{
cin >> l[i] >> r[i];
l[i]--;
r[i]--;
}
if (N <= 15)
{
solveA();
}
else
{
solveB();
}
}<|endoftext|>
|
<commit_before><commit_msg>submit C.cpp to 'C - Divide the Problems' (abc132) [C++14 (GCC 5.4.1)]<commit_after><|endoftext|>
|
<commit_before><commit_msg>tried B.cpp to 'B'<commit_after><|endoftext|>
|
<commit_before><commit_msg>submit C.cpp to 'C - Count Order' (abc150) [C++14 (GCC 5.4.1)]<commit_after><|endoftext|>
|
<commit_before><commit_msg>Added use method calling<commit_after><|endoftext|>
|
<commit_before>#include <cstdio>
#include <poll.h>
#include <unistd.h>
#include <algorithm>
#include <regex>
#include <fstream>
#include <map>
#include <system_error>
#include <kms++/kms++.h>
#include <kms++util/kms++util.h>
#include <kms++util/videodevice.h>
const uint32_t NUM_SRC_BUFS=2;
const uint32_t NUM_DST_BUFS=2;
using namespace std;
using namespace kms;
static const char* usage_str =
"Usage: wbm2m [OPTIONS]\n\n"
"Options:\n"
" -f, --format=4CC Output format\n"
" -c, --crop=CROP CROP is <x>,<y>-<w>x<h>\n"
" -h, --help Print this help\n"
;
const int bar_speed = 4;
const int bar_width = 10;
static unsigned get_bar_pos(DumbFramebuffer* fb, unsigned frame_num)
{
return (frame_num * bar_speed) % (fb->width() - bar_width + 1);
}
static void read_frame(DumbFramebuffer* fb, unsigned frame_num)
{
static map<DumbFramebuffer*, int> s_bar_pos_map;
int old_pos = -1;
if (s_bar_pos_map.find(fb) != s_bar_pos_map.end())
old_pos = s_bar_pos_map[fb];
int pos = get_bar_pos(fb, frame_num);
draw_color_bar(*fb, old_pos, pos, bar_width);
draw_text(*fb, fb->width() / 2, 0, to_string(frame_num), RGB(255, 255, 255));
s_bar_pos_map[fb] = pos;
}
static void parse_crop(const string& crop_str, uint32_t& c_left, uint32_t& c_top,
uint32_t& c_width, uint32_t& c_height)
{
const regex crop_re("(\\d+),(\\d+)-(\\d+)x(\\d+)"); // 400,400-400x400
smatch sm;
if (!regex_match(crop_str, sm, crop_re))
EXIT("Failed to parse crop option '%s'", crop_str.c_str());
c_left = stoul(sm[1]);
c_top = stoul(sm[2]);
c_width = stoul(sm[3]);
c_height = stoul(sm[4]);
}
int main(int argc, char** argv)
{
// XXX get from args
const uint32_t src_width = 800;
const uint32_t src_height = 480;
const auto src_fmt = PixelFormat::XRGB8888;
const uint32_t num_src_frames = 10;
const uint32_t dst_width = 800;
const uint32_t dst_height = 480;
uint32_t c_top, c_left, c_width, c_height;
auto dst_fmt = PixelFormat::XRGB8888;
bool use_selection = false;
OptionSet optionset = {
Option("f|format=", [&](string s)
{
dst_fmt = FourCCToPixelFormat(s);
}),
Option("c|crop=", [&](string s)
{
parse_crop(s, c_left, c_top, c_width, c_height);
use_selection = true;
}),
Option("h|help", [&]()
{
puts(usage_str);
exit(-1);
}),
};
optionset.parse(argc, argv);
if (optionset.params().size() > 0) {
puts(usage_str);
exit(-1);
}
printf("%ux%u-%s -> %ux%u-%s\n", src_width, src_height, PixelFormatToFourCC(src_fmt).c_str(),
dst_width, dst_height, PixelFormatToFourCC(dst_fmt).c_str());
const string filename = sformat("wb-out-%ux%u_%4.4s.raw", dst_width, dst_height,
PixelFormatToFourCC(dst_fmt).c_str());
printf("writing to %s\n", filename.c_str());
VideoDevice vid("/dev/video10");
Card card;
uint32_t src_frame_num = 0;
uint32_t dst_frame_num = 0;
VideoStreamer* out = vid.get_output_streamer();
VideoStreamer* in = vid.get_capture_streamer();
out->set_format(src_fmt, src_width, src_height);
in->set_format(dst_fmt, dst_width, dst_height);
if (use_selection) {
out->set_selection(c_left, c_top, c_width, c_height);
printf("crop -> %u,%u-%ux%u\n", c_left, c_top, c_width, c_height);
}
out->set_queue_size(NUM_SRC_BUFS);
in->set_queue_size(NUM_DST_BUFS);
for (unsigned i = 0; i < min(NUM_SRC_BUFS, num_src_frames); ++i) {
auto fb = new DumbFramebuffer(card, src_width, src_height, src_fmt);
read_frame(fb, src_frame_num++);
out->queue(fb);
}
for (unsigned i = 0; i < min(NUM_DST_BUFS, num_src_frames); ++i) {
auto fb = new DumbFramebuffer(card, dst_width, dst_height, dst_fmt);
in->queue(fb);
}
vector<pollfd> fds(3);
fds[0].fd = 0;
fds[0].events = POLLIN;
fds[1].fd = vid.fd();
fds[1].events = POLLIN;
fds[2].fd = card.fd();
fds[2].events = POLLIN;
ofstream os(filename, ofstream::binary);
out->stream_on();
in->stream_on();
while (true) {
int r = poll(fds.data(), fds.size(), -1);
ASSERT(r > 0);
if (fds[0].revents != 0)
break;
if (fds[1].revents) {
fds[1].revents = 0;
try {
DumbFramebuffer *dst_fb = in->dequeue();
printf("Writing frame %u\n", dst_frame_num);
for (unsigned i = 0; i < dst_fb->num_planes(); ++i)
os.write((char*)dst_fb->map(i), dst_fb->size(i));
in->queue(dst_fb);
dst_frame_num++;
if (dst_frame_num >= num_src_frames)
break;
} catch (system_error& se) {
if (se.code() != errc::resource_unavailable_try_again)
FAIL("dequeue failed: %s", se.what());
break;
}
DumbFramebuffer *src_fb = out->dequeue();
if (src_frame_num < num_src_frames) {
read_frame(src_fb, src_frame_num++);
out->queue(src_fb);
}
}
if (fds[2].revents) {
fds[2].revents = 0;
}
}
printf("exiting...\n");
}
<commit_msg>wbm2m: use fmt::format<commit_after>#include <cstdio>
#include <poll.h>
#include <unistd.h>
#include <algorithm>
#include <regex>
#include <fstream>
#include <map>
#include <system_error>
#include <fmt/format.h>
#include <kms++/kms++.h>
#include <kms++util/kms++util.h>
#include <kms++util/videodevice.h>
const uint32_t NUM_SRC_BUFS=2;
const uint32_t NUM_DST_BUFS=2;
using namespace std;
using namespace kms;
static const char* usage_str =
"Usage: wbm2m [OPTIONS]\n\n"
"Options:\n"
" -f, --format=4CC Output format\n"
" -c, --crop=CROP CROP is <x>,<y>-<w>x<h>\n"
" -h, --help Print this help\n"
;
const int bar_speed = 4;
const int bar_width = 10;
static unsigned get_bar_pos(DumbFramebuffer* fb, unsigned frame_num)
{
return (frame_num * bar_speed) % (fb->width() - bar_width + 1);
}
static void read_frame(DumbFramebuffer* fb, unsigned frame_num)
{
static map<DumbFramebuffer*, int> s_bar_pos_map;
int old_pos = -1;
if (s_bar_pos_map.find(fb) != s_bar_pos_map.end())
old_pos = s_bar_pos_map[fb];
int pos = get_bar_pos(fb, frame_num);
draw_color_bar(*fb, old_pos, pos, bar_width);
draw_text(*fb, fb->width() / 2, 0, to_string(frame_num), RGB(255, 255, 255));
s_bar_pos_map[fb] = pos;
}
static void parse_crop(const string& crop_str, uint32_t& c_left, uint32_t& c_top,
uint32_t& c_width, uint32_t& c_height)
{
const regex crop_re("(\\d+),(\\d+)-(\\d+)x(\\d+)"); // 400,400-400x400
smatch sm;
if (!regex_match(crop_str, sm, crop_re))
EXIT("Failed to parse crop option '%s'", crop_str.c_str());
c_left = stoul(sm[1]);
c_top = stoul(sm[2]);
c_width = stoul(sm[3]);
c_height = stoul(sm[4]);
}
int main(int argc, char** argv)
{
// XXX get from args
const uint32_t src_width = 800;
const uint32_t src_height = 480;
const auto src_fmt = PixelFormat::XRGB8888;
const uint32_t num_src_frames = 10;
const uint32_t dst_width = 800;
const uint32_t dst_height = 480;
uint32_t c_top, c_left, c_width, c_height;
auto dst_fmt = PixelFormat::XRGB8888;
bool use_selection = false;
OptionSet optionset = {
Option("f|format=", [&](string s)
{
dst_fmt = FourCCToPixelFormat(s);
}),
Option("c|crop=", [&](string s)
{
parse_crop(s, c_left, c_top, c_width, c_height);
use_selection = true;
}),
Option("h|help", [&]()
{
puts(usage_str);
exit(-1);
}),
};
optionset.parse(argc, argv);
if (optionset.params().size() > 0) {
puts(usage_str);
exit(-1);
}
printf("%ux%u-%s -> %ux%u-%s\n", src_width, src_height, PixelFormatToFourCC(src_fmt).c_str(),
dst_width, dst_height, PixelFormatToFourCC(dst_fmt).c_str());
const string filename = fmt::format("wb-out-{}x{}-{}.raw", dst_width, dst_height,
PixelFormatToFourCC(dst_fmt));
printf("writing to %s\n", filename.c_str());
VideoDevice vid("/dev/video10");
Card card;
uint32_t src_frame_num = 0;
uint32_t dst_frame_num = 0;
VideoStreamer* out = vid.get_output_streamer();
VideoStreamer* in = vid.get_capture_streamer();
out->set_format(src_fmt, src_width, src_height);
in->set_format(dst_fmt, dst_width, dst_height);
if (use_selection) {
out->set_selection(c_left, c_top, c_width, c_height);
printf("crop -> %u,%u-%ux%u\n", c_left, c_top, c_width, c_height);
}
out->set_queue_size(NUM_SRC_BUFS);
in->set_queue_size(NUM_DST_BUFS);
for (unsigned i = 0; i < min(NUM_SRC_BUFS, num_src_frames); ++i) {
auto fb = new DumbFramebuffer(card, src_width, src_height, src_fmt);
read_frame(fb, src_frame_num++);
out->queue(fb);
}
for (unsigned i = 0; i < min(NUM_DST_BUFS, num_src_frames); ++i) {
auto fb = new DumbFramebuffer(card, dst_width, dst_height, dst_fmt);
in->queue(fb);
}
vector<pollfd> fds(3);
fds[0].fd = 0;
fds[0].events = POLLIN;
fds[1].fd = vid.fd();
fds[1].events = POLLIN;
fds[2].fd = card.fd();
fds[2].events = POLLIN;
ofstream os(filename, ofstream::binary);
out->stream_on();
in->stream_on();
while (true) {
int r = poll(fds.data(), fds.size(), -1);
ASSERT(r > 0);
if (fds[0].revents != 0)
break;
if (fds[1].revents) {
fds[1].revents = 0;
try {
DumbFramebuffer *dst_fb = in->dequeue();
printf("Writing frame %u\n", dst_frame_num);
for (unsigned i = 0; i < dst_fb->num_planes(); ++i)
os.write((char*)dst_fb->map(i), dst_fb->size(i));
in->queue(dst_fb);
dst_frame_num++;
if (dst_frame_num >= num_src_frames)
break;
} catch (system_error& se) {
if (se.code() != errc::resource_unavailable_try_again)
FAIL("dequeue failed: %s", se.what());
break;
}
DumbFramebuffer *src_fb = out->dequeue();
if (src_frame_num < num_src_frames) {
read_frame(src_fb, src_frame_num++);
out->queue(src_fb);
}
}
if (fds[2].revents) {
fds[2].revents = 0;
}
}
printf("exiting...\n");
}
<|endoftext|>
|
<commit_before>#ifndef resplunk_event_Events_HeaderPlusPlus
#define resplunk_event_Events_HeaderPlusPlus
#include "resplunk/server/ServerSpecific.hpp"
#include "resplunk/util/TemplateImplRepo.hpp"
#include <cstdint>
#include <limits>
#include <type_traits>
#include <functional>
#include <memory>
#include <map>
#include <exception>
namespace resplunk
{
namespace event
{
struct Event;
struct ListenerPriority final
{
using Priority_t = std::intmax_t;
static constexpr ListenerPriority FIRST = std::numeric_limits<Priority_t>::min();
static constexpr ListenerPriority LAST = std::numeric_limits<Priority_t>::max();
constexpr ListenerPriority() = default;
constexpr ListenerPriority(Priority_t p)
: priority{p}
{
}
constexpr ListenerPriority(ListenerPriority const &) = default;
ListenerPriority &operator=(ListenerPriority const &) = delete;
constexpr ListenerPriority(ListenerPriority &&) = default;
ListenerPriority &operator=(ListenerPriority &&) = delete;
constexpr ~ListenerPriority() = default;
constexpr operator Priorty_t() const
{
return priority;
}
friend constexpr bool operator==(ListenerPriority const &a, ListenerPriority const &b)
{
return a.priority == b.priority;
}
friend constexpr bool operator<(ListenerPriority const &a, ListenerPriority const &b)
{
return a.priority < b.priority;
}
private:
Priority_t const priority;
};
template<typename EventT>
struct EventProcessor
: virtual server::ServerSpecific
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
EventProcessor() = default;
EventProcessor(ListenerPriority priority)
{
listen(priority);
}
EventProcessor(EventProcessor const &) = delete;
EventProcessor &operator=(EventProcessor const &) = delete;
EventProcessor(EventProcessor &&) = delete;
EventProcessor &operator=(EventProcessor &&) = delete;
virtual ~EventProcessor()
{
ignore();
}
protected:
virtual void listen(ListenerPriority priority = ListenerPriority{}) final
{
return E::listen(*this, priority);
}
virtual void ignore() final
{
return E::ignore(*this);
}
private:
virtual void onEvent(E &e) const = 0;
friend typename E::Registrar;
};
template<typename EventT>
struct LambdaEventProcessor
: EventProcessor<EventT>
{
using Lambda_t = std::function<void (E &e) const>;
protected:
LambdaEventProcessor(Lambda_t l)
: lambda(l)
{
}
virtual void onEvent(E &e) const override
{
return lambda(e);
}
private:
Lambda_t lambda;
};
template<typename EventT>
struct EventReactor
: virtual server::ServerSpecific
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
EventReactor() = default;
EventReactor(ListenerPriority priority)
{
listen(priority);
}
EventReactor(EventReactor const &) = delete;
EventReactor &operator=(EventReactor const &) = delete;
EventReactor(EventReactor &&) = delete;
EventReactor &operator=(EventReactor &&) = delete;
virtual ~EventReactor()
{
ignore();
}
protected:
virtual void listen(ListenerPriority priority = ListenerPriority{}) final
{
return E::listen(*this, priority);
}
virtual void ignore() final
{
return E::ignore(*this);
}
private:
virtual void onEvent(E const &e) = 0;
friend typename E::Registrar;
};
template<typename EventT>
struct LambdaEventReactor
: EventReactor<EventT>
{
using Lambda_t = std::function<void (E const &e)>;
protected:
LambdaEventReactor(Lambda_t l)
: lambda(l)
{
}
virtual void onEvent(E const &e) override
{
return lambda(e);
}
private:
Lambda_t lambda;
};
template<typename T>
struct DestructEvent;
template<typename EventT>
struct EventRegistrar final
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
EventRegistrar() = delete;
EventRegistrar(EventRegistrar const &) = delete;
EventRegistrar(EventRegistrar &&) = delete;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
processors(p.server()).emplace(priority, std::cref(p));
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
reactors(r.server()).emplace(priority, std::ref(r));
}
static void ignore(Processor const &p)
{
auto &procs = processors(p.server());
for(auto it = procs.begin(); it != procs.end(); )
{
if(std::addressof(p) == std::addressof(it->second.get()))
{
it = procs.erase(it);
}
else ++it;
}
}
static void ignore(Reactor &r)
{
auto &reacts = reactors(p.server());
for(auto it = reacts.begin(); it != reacts.end(); )
{
if(std::addressof(p) == std::addressof(it->second.get()))
{
it = reacts.erase(it);
}
else ++it;
}
}
static void process(E &e)
{
auto &procs = processors(e.server());
for(auto it = procs.begin(); it != procs.end(); ++it)
{
try
{
it->second.get().onEvent(e);
}
catch(std::exception &e)
{
//
}
catch(...)
{
//
}
}
}
static void react(E const &e)
{
auto &reacts = reactors(p.server());
for(auto it = reacts.begin(); it != reacts.end(); ++it)
{
try
{
it->second.get().onEvent(e);
}
catch(std::exception &e)
{
//
}
catch(...)
{
//
}
}
}
private:
struct Key final {};
using Processors_t = std::map<Server const *, std::multimap<ListenerPriority, std::reference_wrapper<Processor const>>>;
using Reactors_t = std::map<Server const *, std::multimap<ListenerPriority, std::reference_wrapper<Reactor>>>;
using SDReactors_t = std::map<Server const *, std::unique_ptr<ServerDestructReactor>>;
static Processors_t &processors()
{
return TemplateImplRepo::get<Key, Processors_t>();
}
static Reactors_t &reactors()
{
return TemplateImplRepo::get<Key, Reactors_t>();
}
static ServerDestructReactors_t &sdreactors()
{
return TemplateImplRepo::get<Key, SDReactors_t>();
}
static void sdreactors(Server &s)
{
if(sdreactors().find(&s) == sdreactors().end())
{
sdreactors().emplace
(
SDReactors_t::key_type{&s},
SDReactors_t::mapped_type{new ServerDestructReactor{s}}
);
}
else if(!sdreactors()[&s])
{
sdreactors().erase(&s);
}
}
static Processors_t::mapped_type &processors(Server &s)
{
if(processors().find(&s) == processors().end())
{
sdreactors(s);
}
return processors()[&s];
}
static Reactors_t::mapped_type &reactors(Server &s)
{
if(reactors().find(&s) == reactors().end())
{
sdreactors(s);
}
return reactors()[&s];
}
static Processors_t::mapped_type &processors(Server const &s)
{
auto it = processors().find(&s);
if(it != processors().end())
{
return it->second;
}
return {};
}
static Reactors_t::mapped_type &reactors(Server const &s)
{
auto it = reactors().find(&s);
if(it != reactors().end())
{
return it->second;
}
return {};
}
struct ServerDestructReactor final
: private EventReactor<DestructEvent<Server>>
{
ServerDestructReactor(Server &s)
: ServerSpecific(s)
, EventReactor<DestructEvent<Server>>(ListenerPriority::LAST)
{
}
private:
virtual void onEvent(E const &e) override
{
auto This = std::move(sdreactors()[&server()]);
processors().erase(&e.instance());
reactors().erase(&e.instance());
}
};
};
template<typename EventT, typename ParentT>
struct EventImplementor
: virtual ParentT
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
static_assert(std::is_base_of<Event, ParentT>::value, "ParentT must derive from Event");
static_assert(std::is_base_of<EventT, ParentT>::value, "EventT must derive from ParentT");
using E = EventT;
using ParentE = ParentT;
using Implementor = EventImplementor;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
using Registrar = EventRegistrar<EventT>;
EventImplementor() = default;
virtual ~EventImplementor() = 0;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(p, priority);
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(r, priority);
}
static void ignore(Processor const &p)
{
return Registrar::ignore(p);
}
static void ignore(Reactor &r)
{
return Registrar::ignore(r);
}
virtual void process() override
{
ParentE::process();
return Registrar::process(*this);
}
virtual void react() const override
{
ParentE::react();
return Registrar::react(*this);
}
};
template<typename EventT, typename ParentT>
EventImplementor::~EventImplementor() = default;
template<typename EventT>
struct EventImplementor<EventT, void>
: virtual server::ServerSpecific
{
static_assert(std::is_same<EventT, Event>::value, "This can only be derived by Event");
using E = EventT;
using ParentE = void;
using Implementor = EventImplementor;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
using Registrar = EventRegistrar<EventT>;
EventImplementor() = default;
EventImplementor(EventImplementor const &) = delete;
EventImplementor &operator=(EventImplementor const &) = delete;
EventImplementor(EventImplementor &&) = delete;
EventImplementor &operator=(EventImplementor &&) = delete;
virtual ~EventImplementor() = 0;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(p, priority);
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(r, priority);
}
static void ignore(Processor const &p)
{
return Registrar::ignore(p);
}
static void ignore(Reactor &r)
{
return Registrar::ignore(r);
}
virtual void process()
{
return Registrar::process(*this);
}
virtual void react() const
{
return Registrar::react(*this);
}
};
template<typename EventT>
EventImplementor<EventT, void>::~EventImplementor<EventT, void>() = default;
}
}
#endif
<commit_msg>Fix using wrong access notation<commit_after>#ifndef resplunk_event_Events_HeaderPlusPlus
#define resplunk_event_Events_HeaderPlusPlus
#include "resplunk/server/ServerSpecific.hpp"
#include "resplunk/util/TemplateImplRepo.hpp"
#include <cstdint>
#include <limits>
#include <type_traits>
#include <functional>
#include <memory>
#include <map>
#include <exception>
namespace resplunk
{
namespace event
{
struct Event;
struct ListenerPriority final
{
using Priority_t = std::intmax_t;
static constexpr ListenerPriority FIRST = std::numeric_limits<Priority_t>::min();
static constexpr ListenerPriority LAST = std::numeric_limits<Priority_t>::max();
constexpr ListenerPriority() = default;
constexpr ListenerPriority(Priority_t p)
: priority{p}
{
}
constexpr ListenerPriority(ListenerPriority const &) = default;
ListenerPriority &operator=(ListenerPriority const &) = delete;
constexpr ListenerPriority(ListenerPriority &&) = default;
ListenerPriority &operator=(ListenerPriority &&) = delete;
constexpr ~ListenerPriority() = default;
constexpr operator Priorty_t() const
{
return priority;
}
friend constexpr bool operator==(ListenerPriority const &a, ListenerPriority const &b)
{
return a.priority == b.priority;
}
friend constexpr bool operator<(ListenerPriority const &a, ListenerPriority const &b)
{
return a.priority < b.priority;
}
private:
Priority_t const priority;
};
template<typename EventT>
struct EventProcessor
: virtual server::ServerSpecific
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
EventProcessor() = default;
EventProcessor(ListenerPriority priority)
{
listen(priority);
}
EventProcessor(EventProcessor const &) = delete;
EventProcessor &operator=(EventProcessor const &) = delete;
EventProcessor(EventProcessor &&) = delete;
EventProcessor &operator=(EventProcessor &&) = delete;
virtual ~EventProcessor()
{
ignore();
}
protected:
virtual void listen(ListenerPriority priority = ListenerPriority{}) final
{
return E::listen(*this, priority);
}
virtual void ignore() final
{
return E::ignore(*this);
}
private:
virtual void onEvent(E &e) const = 0;
friend typename E::Registrar;
};
template<typename EventT>
struct LambdaEventProcessor
: EventProcessor<EventT>
{
using Lambda_t = std::function<void (E &e) const>;
protected:
LambdaEventProcessor(Lambda_t l)
: lambda(l)
{
}
virtual void onEvent(E &e) const override
{
return lambda(e);
}
private:
Lambda_t lambda;
};
template<typename EventT>
struct EventReactor
: virtual server::ServerSpecific
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
EventReactor() = default;
EventReactor(ListenerPriority priority)
{
listen(priority);
}
EventReactor(EventReactor const &) = delete;
EventReactor &operator=(EventReactor const &) = delete;
EventReactor(EventReactor &&) = delete;
EventReactor &operator=(EventReactor &&) = delete;
virtual ~EventReactor()
{
ignore();
}
protected:
virtual void listen(ListenerPriority priority = ListenerPriority{}) final
{
return E::listen(*this, priority);
}
virtual void ignore() final
{
return E::ignore(*this);
}
private:
virtual void onEvent(E const &e) = 0;
friend typename E::Registrar;
};
template<typename EventT>
struct LambdaEventReactor
: EventReactor<EventT>
{
using Lambda_t = std::function<void (E const &e)>;
protected:
LambdaEventReactor(Lambda_t l)
: lambda(l)
{
}
virtual void onEvent(E const &e) override
{
return lambda(e);
}
private:
Lambda_t lambda;
};
template<typename T>
struct DestructEvent;
template<typename EventT>
struct EventRegistrar final
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
using E = EventT;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
EventRegistrar() = delete;
EventRegistrar(EventRegistrar const &) = delete;
EventRegistrar(EventRegistrar &&) = delete;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
processors(p.server()).emplace(priority, std::cref(p));
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
reactors(r.server()).emplace(priority, std::ref(r));
}
static void ignore(Processor const &p)
{
auto &procs = processors(p.server());
for(auto it = procs.begin(); it != procs.end(); )
{
if(std::addressof(p) == std::addressof(it->second.get()))
{
it = procs.erase(it);
}
else ++it;
}
}
static void ignore(Reactor &r)
{
auto &reacts = reactors(p.server());
for(auto it = reacts.begin(); it != reacts.end(); )
{
if(std::addressof(p) == std::addressof(it->second.get()))
{
it = reacts.erase(it);
}
else ++it;
}
}
static void process(E &e)
{
auto &procs = processors(e.server());
for(auto it = procs.begin(); it != procs.end(); ++it)
{
try
{
it->second.get()->onEvent(e);
}
catch(std::exception &e)
{
//
}
catch(...)
{
//
}
}
}
static void react(E const &e)
{
auto &reacts = reactors(p.server());
for(auto it = reacts.begin(); it != reacts.end(); ++it)
{
try
{
it->second.get()->onEvent(e);
}
catch(std::exception &e)
{
//
}
catch(...)
{
//
}
}
}
private:
struct Key final {};
using Processors_t = std::map<Server const *, std::multimap<ListenerPriority, std::reference_wrapper<Processor const>>>;
using Reactors_t = std::map<Server const *, std::multimap<ListenerPriority, std::reference_wrapper<Reactor>>>;
using SDReactors_t = std::map<Server const *, std::unique_ptr<ServerDestructReactor>>;
static Processors_t &processors()
{
return TemplateImplRepo::get<Key, Processors_t>();
}
static Reactors_t &reactors()
{
return TemplateImplRepo::get<Key, Reactors_t>();
}
static ServerDestructReactors_t &sdreactors()
{
return TemplateImplRepo::get<Key, SDReactors_t>();
}
static void sdreactors(Server &s)
{
if(sdreactors().find(&s) == sdreactors().end())
{
sdreactors().emplace
(
SDReactors_t::key_type{&s},
SDReactors_t::mapped_type{new ServerDestructReactor{s}}
);
}
else if(!sdreactors()[&s])
{
sdreactors().erase(&s);
}
}
static Processors_t::mapped_type &processors(Server &s)
{
if(processors().find(&s) == processors().end())
{
sdreactors(s);
}
return processors()[&s];
}
static Reactors_t::mapped_type &reactors(Server &s)
{
if(reactors().find(&s) == reactors().end())
{
sdreactors(s);
}
return reactors()[&s];
}
static Processors_t::mapped_type &processors(Server const &s)
{
auto it = processors().find(&s);
if(it != processors().end())
{
return it->second;
}
return {};
}
static Reactors_t::mapped_type &reactors(Server const &s)
{
auto it = reactors().find(&s);
if(it != reactors().end())
{
return it->second;
}
return {};
}
struct ServerDestructReactor final
: private EventReactor<DestructEvent<Server>>
{
ServerDestructReactor(Server &s)
: ServerSpecific(s)
, EventReactor<DestructEvent<Server>>(ListenerPriority::LAST)
{
}
private:
virtual void onEvent(E const &e) override
{
auto This = std::move(sdreactors()[&server()]);
processors().erase(&e.instance());
reactors().erase(&e.instance());
}
};
};
template<typename EventT, typename ParentT>
struct EventImplementor
: virtual ParentT
{
static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event");
static_assert(std::is_base_of<Event, ParentT>::value, "ParentT must derive from Event");
static_assert(std::is_base_of<EventT, ParentT>::value, "EventT must derive from ParentT");
using E = EventT;
using ParentE = ParentT;
using Implementor = EventImplementor;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
using Registrar = EventRegistrar<EventT>;
EventImplementor() = default;
virtual ~EventImplementor() = 0;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(p, priority);
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(r, priority);
}
static void ignore(Processor const &p)
{
return Registrar::ignore(p);
}
static void ignore(Reactor &r)
{
return Registrar::ignore(r);
}
virtual void process() override
{
ParentE::process();
return Registrar::process(*this);
}
virtual void react() const override
{
ParentE::react();
return Registrar::react(*this);
}
};
template<typename EventT, typename ParentT>
EventImplementor::~EventImplementor() = default;
template<typename EventT>
struct EventImplementor<EventT, void>
: virtual server::ServerSpecific
{
static_assert(std::is_same<EventT, Event>::value, "This can only be derived by Event");
using E = EventT;
using ParentE = void;
using Implementor = EventImplementor;
using Processor = EventProcessor<EventT>;
using Reactor = EventReactor<EventT>;
using Registrar = EventRegistrar<EventT>;
EventImplementor() = default;
EventImplementor(EventImplementor const &) = delete;
EventImplementor &operator=(EventImplementor const &) = delete;
EventImplementor(EventImplementor &&) = delete;
EventImplementor &operator=(EventImplementor &&) = delete;
virtual ~EventImplementor() = 0;
static void listen(Processor const &p, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(p, priority);
}
static void listen(Reactor &r, ListenerPriority priority = ListenerPriority{})
{
return Registrar::listen(r, priority);
}
static void ignore(Processor const &p)
{
return Registrar::ignore(p);
}
static void ignore(Reactor &r)
{
return Registrar::ignore(r);
}
virtual void process()
{
return Registrar::process(*this);
}
virtual void react() const
{
return Registrar::react(*this);
}
};
template<typename EventT>
EventImplementor<EventT, void>::~EventImplementor<EventT, void>() = default;
}
}
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkMinimumImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkTestingMacros.h"
int itkMinimumImageFilterTest( int, char* [] )
{
// Define the dimension of the images
const unsigned int Dimension = 3;
typedef unsigned char PixelType;
// Declare the types of the images
typedef itk::Image< PixelType, Dimension > ImageType;
// Declare the type of the index to access images
typedef itk::Index< Dimension > IndexType;
// Declare the type of the size
typedef itk::Size< Dimension > SizeType;
// Declare the type of the Region
typedef itk::ImageRegion< Dimension > RegionType;
// Declare the type for the MULTIPLY filter
typedef itk::MinimumImageFilter< ImageType, ImageType,
ImageType > MinimumFilterType;
// Create two images
ImageType::Pointer inputImageA = ImageType::New();
ImageType::Pointer inputImageB = ImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImageA->SetLargestPossibleRegion( region );
inputImageA->SetBufferedRegion( region );
inputImageA->SetRequestedRegion( region );
inputImageA->Allocate();
// Initialize Image B
inputImageB->SetLargestPossibleRegion( region );
inputImageB->SetBufferedRegion( region );
inputImageB->SetRequestedRegion( region );
inputImageB->Allocate();
// Define the pixel values for each image
PixelType largePixelValue = 3.0;
PixelType smallPixelValue = 2.0;
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
// Create one iterator for Image A (this is a light object)
IteratorType it1( inputImageA, inputImageA->GetBufferedRegion() );
// Initialize the content of Image A
while( !it1.IsAtEnd() )
{
it1.Set( smallPixelValue );
++it1;
}
// Create one iterator for Image B (this is a light object)
IteratorType it2( inputImageB, inputImageB->GetBufferedRegion() );
// Initialize the content of Image B
while( !it2.IsAtEnd() )
{
it2.Set( largePixelValue );
++it2;
}
// Create the filter
MinimumFilterType::Pointer minimumImageFilter = MinimumFilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( minimumImageFilter, MinimumImageFilter,
BinaryFunctorImageFilter);
// Connect the input images
minimumImageFilter->SetInput1( inputImageA );
minimumImageFilter->SetInput2( inputImageB );
// Get the Smart Pointer to the filter output
ImageType::Pointer outputImage = minimumImageFilter->GetOutput();
minimumImageFilter->SetFunctor( minimumImageFilter->GetFunctor() );
// Execute the filter
minimumImageFilter->Update();
// Test some pixels in the result image
// Note that we are not comparing the entirety of the filter output in order
// to keep compile time as small as possible
ImageType::IndexType pixelIndex = {{0, 1, 1}};
TEST_EXPECT_EQUAL( outputImage->GetPixel( start ), smallPixelValue );
TEST_EXPECT_EQUAL( outputImage->GetPixel( pixelIndex ), smallPixelValue );
// All objects should be automatically destroyed at this point
return EXIT_SUCCESS;
}
<commit_msg>COMP: Fix double to unsigned char conversion warning.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkMinimumImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkTestingMacros.h"
int itkMinimumImageFilterTest( int, char* [] )
{
// Define the dimension of the images
const unsigned int Dimension = 3;
typedef unsigned char PixelType;
// Declare the types of the images
typedef itk::Image< PixelType, Dimension > ImageType;
// Declare the type of the index to access images
typedef itk::Index< Dimension > IndexType;
// Declare the type of the size
typedef itk::Size< Dimension > SizeType;
// Declare the type of the Region
typedef itk::ImageRegion< Dimension > RegionType;
// Declare the type for the MULTIPLY filter
typedef itk::MinimumImageFilter< ImageType, ImageType,
ImageType > MinimumFilterType;
// Create two images
ImageType::Pointer inputImageA = ImageType::New();
ImageType::Pointer inputImageB = ImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImageA->SetLargestPossibleRegion( region );
inputImageA->SetBufferedRegion( region );
inputImageA->SetRequestedRegion( region );
inputImageA->Allocate();
// Initialize Image B
inputImageB->SetLargestPossibleRegion( region );
inputImageB->SetBufferedRegion( region );
inputImageB->SetRequestedRegion( region );
inputImageB->Allocate();
// Define the pixel values for each image
PixelType largePixelValue = 3;
PixelType smallPixelValue = 2;
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
// Create one iterator for Image A (this is a light object)
IteratorType it1( inputImageA, inputImageA->GetBufferedRegion() );
// Initialize the content of Image A
while( !it1.IsAtEnd() )
{
it1.Set( smallPixelValue );
++it1;
}
// Create one iterator for Image B (this is a light object)
IteratorType it2( inputImageB, inputImageB->GetBufferedRegion() );
// Initialize the content of Image B
while( !it2.IsAtEnd() )
{
it2.Set( largePixelValue );
++it2;
}
// Create the filter
MinimumFilterType::Pointer minimumImageFilter = MinimumFilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( minimumImageFilter, MinimumImageFilter,
BinaryFunctorImageFilter);
// Connect the input images
minimumImageFilter->SetInput1( inputImageA );
minimumImageFilter->SetInput2( inputImageB );
// Get the Smart Pointer to the filter output
ImageType::Pointer outputImage = minimumImageFilter->GetOutput();
minimumImageFilter->SetFunctor( minimumImageFilter->GetFunctor() );
// Execute the filter
minimumImageFilter->Update();
// Test some pixels in the result image
// Note that we are not comparing the entirety of the filter output in order
// to keep compile time as small as possible
ImageType::IndexType pixelIndex = {{0, 1, 1}};
TEST_EXPECT_EQUAL( outputImage->GetPixel( start ), smallPixelValue );
TEST_EXPECT_EQUAL( outputImage->GetPixel( pixelIndex ), smallPixelValue );
// All objects should be automatically destroyed at this point
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "../../local/include/gtest/gtest.h"
#include <vector>
// uncomment to use threads
//#define THREADED
#ifdef THREADED
// Tron
//#define NUM_CORES 4
// Clue
#define NUM_CORES 12
#include <thread>
#include <future>
#endif // THREADED
#include "genetic.h"
#include "genetic_circuit.h"
#include "circuit.h"
#include "utility.h"
TEST(InnocuousAttempt, XOR) {
BooleanTable expected_o = {{false},
{true},
{false},
{true}};
BooleanTable expected_o = {{false},
{true},
{true},
{false}};
std::mt19937 rand(std::random_device{}());
// std::minstd_rand0 rand(std::random_device{}());
GeneticCircuit* c = new GeneticCircuit(2, 1, &rand);
BooleanTable answer = c->evaluateAllInputs();
int i = 0;
// #ifdef THREADED
// std::vector<std::future<BooleanTable>> boolean_table_futures;
// #endif THREADED
while ((answer != expected_o) || (answer != expected_o_bar)) {
// #ifdef THREADED
// for (int i = 0; i < (NUM_CORES - 1); ++i) {
// boolean_table_futures.push_back(
// std::async(std::launch::async, , points));
// }
// #endif THREADED
// std::vector<Path> paths; // vector of possible paths
// // Calculate a path on main thread while waiting for other threads
// // If we're doing more than 1 set, do NUM_SETS random path calculations
// on
// // main thread
// for (int i = 0; i < NUM_SETS; i++) {
// paths.push_back(FindRandomPath(points));
// }
// // Get Paths from threads
// for (auto& pathfuture : pathfutures) {
// paths.push_back(pathfuture.get());
// }
delete c;
c = new GeneticCircuit(2, 1, &rand);
std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
// std::cerr << *c << std::endl;
answer = c->evaluateAllInputs();
}
}
TEST(InnocuousAttempt, FullAdder) {
BooleanTable expected_o = {{false, false},
{false, true},
{false, true},
{true, false},
{false, true},
{true, false},
{true, false},
{true, true}};
BooleanTable expected_o_bar = {{false, false},
{true, false},
{true, false},
{false, true},
{true, false},
{false, true},
{false, true},
{true, true}};
std::mt19937 rand(std::random_device{}());
// std::minstd_rand0 rand(std::random_device{}());
GeneticCircuit* c = new GeneticCircuit(3, 2, &rand);
BooleanTable answer = c->evaluateAllInputs();
int i = 0;
// #ifdef THREADED
// std::vector<std::future<BooleanTable>> boolean_table_futures;
// #endif THREADED
while ((answer != expected_o) || (answer != expected_o_bar)) {
// #ifdef THREADED
// for (int i = 0; i < (NUM_CORES - 1); ++i) {
// boolean_table_futures.push_back(
// std::async(std::launch::async, , points));
// }
// #endif THREADED
// std::vector<Path> paths; // vector of possible paths
// // Calculate a path on main thread while waiting for other threads
// // If we're doing more than 1 set, do NUM_SETS random path calculations
// on
// // main thread
// for (int i = 0; i < NUM_SETS; i++) {
// paths.push_back(FindRandomPath(points));
// }
// // Get Paths from threads
// for (auto& pathfuture : pathfutures) {
// paths.push_back(pathfuture.get());
// }
delete c;
c = new GeneticCircuit(3, 2, &rand);
std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
// std::cerr << *c << std::endl;
answer = c->evaluateAllInputs();
}
}
// TEST(InnocuousAttempt, InvertInputs) {
// BooleanTable expected_o = {{true, true, true},
// {true, true, false},
// {true, false, true},
// {true, false, false},
// {false, true, true},
// {false, true, false},
// {false, false, true},
// {false, false, false}};
// std::mt19937 rand(std::random_device{}());
// // std::minstd_rand0 rand(std::random_device{}());
// GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);
// while (c->evaluateAllInputs() != expected_o) {
// delete c;
// c = new GeneticCircuit(3, 3, &rand);
// std::cerr << *c << std::endl;
// }
// }
<commit_msg>fixed expected_o_bar name<commit_after>#include "../../local/include/gtest/gtest.h"
#include <vector>
// uncomment to use threads
//#define THREADED
#ifdef THREADED
// Tron
//#define NUM_CORES 4
// Clue
#define NUM_CORES 12
#include <thread>
#include <future>
#endif // THREADED
#include "genetic.h"
#include "genetic_circuit.h"
#include "circuit.h"
#include "utility.h"
TEST(InnocuousAttempt, XOR) {
BooleanTable expected_o = {{false}, {true}, {false}, {true}};
BooleanTable expected_o_bar = {{false}, {true}, {true}, {false}};
std::mt19937 rand(std::random_device{}());
// std::minstd_rand0 rand(std::random_device{}());
GeneticCircuit* c = new GeneticCircuit(2, 1, &rand);
BooleanTable answer = c->evaluateAllInputs();
int i = 0;
// #ifdef THREADED
// std::vector<std::future<BooleanTable>> boolean_table_futures;
// #endif THREADED
while ((answer != expected_o) || (answer != expected_o_bar)) {
// #ifdef THREADED
// for (int i = 0; i < (NUM_CORES - 1); ++i) {
// boolean_table_futures.push_back(
// std::async(std::launch::async, , points));
// }
// #endif THREADED
// std::vector<Path> paths; // vector of possible paths
// // Calculate a path on main thread while waiting for other threads
// // If we're doing more than 1 set, do NUM_SETS random path calculations
// on
// // main thread
// for (int i = 0; i < NUM_SETS; i++) {
// paths.push_back(FindRandomPath(points));
// }
// // Get Paths from threads
// for (auto& pathfuture : pathfutures) {
// paths.push_back(pathfuture.get());
// }
delete c;
c = new GeneticCircuit(2, 1, &rand);
std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
// std::cerr << *c << std::endl;
answer = c->evaluateAllInputs();
}
}
TEST(InnocuousAttempt, FullAdder) {
BooleanTable expected_o = {{false, false},
{false, true},
{false, true},
{true, false},
{false, true},
{true, false},
{true, false},
{true, true}};
BooleanTable expected_o_bar = {{false, false},
{true, false},
{true, false},
{false, true},
{true, false},
{false, true},
{false, true},
{true, true}};
std::mt19937 rand(std::random_device{}());
// std::minstd_rand0 rand(std::random_device{}());
GeneticCircuit* c = new GeneticCircuit(3, 2, &rand);
BooleanTable answer = c->evaluateAllInputs();
int i = 0;
// #ifdef THREADED
// std::vector<std::future<BooleanTable>> boolean_table_futures;
// #endif THREADED
while ((answer != expected_o) || (answer != expected_o_bar)) {
// #ifdef THREADED
// for (int i = 0; i < (NUM_CORES - 1); ++i) {
// boolean_table_futures.push_back(
// std::async(std::launch::async, , points));
// }
// #endif THREADED
// std::vector<Path> paths; // vector of possible paths
// // Calculate a path on main thread while waiting for other threads
// // If we're doing more than 1 set, do NUM_SETS random path calculations
// on
// // main thread
// for (int i = 0; i < NUM_SETS; i++) {
// paths.push_back(FindRandomPath(points));
// }
// // Get Paths from threads
// for (auto& pathfuture : pathfutures) {
// paths.push_back(pathfuture.get());
// }
delete c;
c = new GeneticCircuit(3, 2, &rand);
std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
// std::cerr << *c << std::endl;
answer = c->evaluateAllInputs();
}
}
// TEST(InnocuousAttempt, InvertInputs) {
// BooleanTable expected_o = {{true, true, true},
// {true, true, false},
// {true, false, true},
// {true, false, false},
// {false, true, true},
// {false, true, false},
// {false, false, true},
// {false, false, false}};
// std::mt19937 rand(std::random_device{}());
// // std::minstd_rand0 rand(std::random_device{}());
// GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);
// while (c->evaluateAllInputs() != expected_o) {
// delete c;
// c = new GeneticCircuit(3, 3, &rand);
// std::cerr << *c << std::endl;
// }
// }
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <limits.h>
#include <vector>
#include <string>
#include <iostream>
#include "api/BamReader.h"
#include "api/BamWriter.h"
#include "../OutSources/fasta/Fasta.h"
#include "../OutSources/stripedSW/ssw_cpp.h"
using namespace std;
const StripedSmithWaterman::Filter kFilter(false, false, 0, 32467);
const int kAlignmentMapSize = 10000;
struct Alignment {
BamTools::BamAlignment bam_alignment;
bool hit_insertion;
string ins_prefix;
Alignment()
: bam_alignment()
, hit_insertion(false)
, ins_prefix()
{}
void Clear() {
hit_insertion = false;
ins_prefix.clear();
}
};
void ShowHelp() {
fprintf(stderr, "Usage: tangram_bam <in_bam> <ref_fa> <out_bam>\n\n");
fprintf(stderr, "tangram_bam will generate ZA tags for bams");
fprintf(stderr, " that are not generated by MOSAIK.\n");
fprintf(stderr, "<ref_fa> is a fasta file containing insertion sequences\n");
fprintf(stderr, " that we are going to detect them.\n");
}
bool OpenBams(
const string& infilename,
const string& outfilename,
const int& no_arg,
char** arguments,
BamTools::BamReader* reader,
BamTools::BamWriter* writer) {
reader->Open(infilename);
if (!reader->IsOpen()) {
fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", infilename.c_str());
return false;
}
// Load header and ref
string header = reader->GetHeaderText();
size_t pos1 = header.find("SO:");
if (pos1 != string::npos) {
size_t pos2 = header.find("SO:queryname");
if (pos2 != string::npos) header.replace(pos2, 12, "SO:unsorted");
pos2 = header.find("SO:coordinate");
if (pos2 != string::npos) header.replace(pos2, 13, "SO:unsorted");
}
header += "@PG\tID:tangram_bam\tCL:";
for (int i = 0; i < no_arg; ++i) {
header += arguments[i];
}
header += "\n";
BamTools::RefVector ref = reader->GetReferenceData();
if (!writer->Open(outfilename, header, ref)) {
fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", outfilename.c_str());
reader->Close();
return false;
}
return true;
}
inline bool LoadReference(const char* fa, FastaReference* fasta) {
string filename = fa;
fasta->open(filename);
return true;
}
bool BuildAligner(
FastaReference* fasta,
vector<StripedSmithWaterman::Aligner*>* aligners,
vector<string>* ref_names) {
for (vector<string>::const_iterator ite = fasta->index->sequenceNames.begin();
ite != fasta->index->sequenceNames.end(); ++ite) {
StripedSmithWaterman::Aligner* al_ptr = new StripedSmithWaterman::Aligner;
al_ptr->SetReferenceSequence(fasta->getSequence(*ite).c_str(),
fasta->sequenceLength(*ite));
aligners->push_back(al_ptr);
ref_names->push_back(*ite);
}
return true;
}
void GetReverseComplement(const string& query, string* reverse) {
reverse->clear();
for (string::const_reverse_iterator ite = query.rbegin(); ite != query.rend(); ++ite) {
switch(*ite) {
case 'A': *reverse += 'T'; break;
case 'C': *reverse += 'G'; break;
case 'G': *reverse += 'C'; break;
case 'T': *reverse += 'A'; break;
default: *reverse += 'N';
}
}
}
void Align(
const string& query,
const vector<StripedSmithWaterman::Aligner*>& aligners,
vector<StripedSmithWaterman::Alignment>* alignments) {
for (unsigned int i = 0; i < aligners.size(); ++i) {
(*alignments)[i].Clear();
aligners[i]->Align(query.c_str(), kFilter, &((*alignments)[i]));
}
}
int PickBestAlignment(
const int& request_score,
const vector<StripedSmithWaterman::Alignment>& alignments) {
int sw_score_max = INT_MIN;
int index = 0;
for (unsigned int i = 0; i < alignments.size(); ++i) {
if (alignments[i].sw_score > sw_score_max) {
sw_score_max = alignments[i].sw_score;
index = i;
}
}
if (sw_score_max > request_score) return index;
else return -1;
}
void GetZa(const Alignment& al, const Alignment& mate, string* za) {
const bool mate1 = al.bam_alignment.IsFirstMate();
Alignment const *mate1_ptr, *mate2_ptr;
if (mate1) {
*za = "<@;";
mate1_ptr = &al;
mate2_ptr = &mate;
} else {
*za = "<&;";
mate1_ptr = &mate;
mate2_ptr = &al;
}
*za += (std::to_string(mate1_ptr->bam_alignment.MapQuality) + ";;"
+ (mate1_ptr->hit_insertion ? mate1_ptr->ins_prefix : "")
+ ";1;");
if (mate1) {
*za += ";><&;";
} else {
*za += ";><@;";
}
*za += (std::to_string(mate2_ptr->bam_alignment.MapQuality) + ";;"
+ (mate2_ptr->hit_insertion ? mate2_ptr->ins_prefix : "")
+ ";1;;>");
}
void WriteAlignment(
const Alignment& mate,
Alignment* al,
BamTools::BamWriter* writer) {
string za;
GetZa(*al, mate, &za);
al->bam_alignment.AddTag("ZA","Z",za);
writer->SaveAlignment(al->bam_alignment);
}
void WriteAlignment(map<string, Alignment>* al_map_ite,
BamTools::BamWriter* writer) {
for (map<string, Alignment>::iterator ite = al_map_ite->begin();
ite != al_map_ite->end(); ++ite) {
Alignment* al = &(ite->second);
string za;
if (al->bam_alignment.IsPaired()) {
if (al->bam_alignment.IsFirstMate()) {
za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>"
+ "<&;;;;;;>";
} else {
za = "<&;;;;;;><@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
}
} else {
za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
}
al->bam_alignment.AddTag("ZA","Z",za);
writer->SaveAlignment(al->bam_alignment);
}
}
void StoreAlignment(
Alignment* al,
map<string, Alignment> *al_map_cur,
map<string, Alignment> *al_map_pre,
BamTools::BamWriter* writer) {
if ((static_cast<int>(al_map_cur->size()) > kAlignmentMapSize)) {
WriteAlignment(al_map_pre, writer);
al_map_pre->clear();
map<string, Alignment> *tmp = al_map_pre;
al_map_pre = al_map_cur;
al_map_cur = tmp;
}
map<string, Alignment>::iterator ite_cur = al_map_cur->find(al->bam_alignment.Name);
if (ite_cur == al_map_cur->end()) {
if (!al_map_pre) {
map<string, Alignment>::iterator ite_pre = al_map_pre->find(al->bam_alignment.Name);
if (ite_pre == al_map_pre->end()) { // al is not found in cur or pre either
(*al_map_cur)[al->bam_alignment.Name] = *al;
} else { // find the mate in al_map_pre
WriteAlignment(ite_pre->second, al, writer);
WriteAlignment(*al, &(ite_pre->second), writer);
al_map_pre->erase(ite_pre);
}
} else { // al is not found in cur and pre is NULL
(*al_map_cur)[al->bam_alignment.Name] = *al;
}
} else { // find the mate in al_map_cur
WriteAlignment(ite_cur->second, al, writer);
WriteAlignment(*al, &(ite_cur->second), writer);
al_map_cur->erase(ite_cur);
}
}
int main(int argc, char** argv) {
if (argc != 4) {
ShowHelp();
return 1;
}
// Open input bam
string infilename = argv[1];
string outfilename = argv[3];
BamTools::BamReader reader;
BamTools::BamWriter writer;
if (!OpenBams(infilename, outfilename, argc, argv, &reader, &writer)) return 1;
// Open fasta
FastaReference fasta;
LoadReference(argv[2], &fasta);
// Build SSW aligners for every reference in fasta
vector<StripedSmithWaterman::Aligner*> aligners;
vector<string> ref_names;
BuildAligner(&fasta, &aligners, &ref_names);
// Prepare alignment vector
vector<StripedSmithWaterman::Alignment> alignments(aligners.size());
// CORE ALGORITHM
BamTools::BamAlignment bam_alignment;
map<string, Alignment> al_map1, al_map2;
map<string, Alignment> *al_map_cur = &al_map1, *al_map_pre = &al_map2;
Alignment al;
while (reader.GetNextAlignment(bam_alignment)) {
Align(bam_alignment.QueryBases, aligners, &alignments);
int index = PickBestAlignment(bam_alignment.Length, alignments);
if (index == -1) {
string reverse;
GetReverseComplement(bam_alignment.QueryBases, &reverse);
Align(reverse, aligners, &alignments);
index = PickBestAlignment(bam_alignment.Length, alignments);
}
al.Clear();
al.bam_alignment = bam_alignment;
al.hit_insertion = (index == -1) ? false: true;
al.ins_prefix = (index == -1) ? "" : ref_names[index].substr(8,2);
StoreAlignment(&al, al_map_cur, al_map_pre, &writer);
}
// Close
WriteAlignment(&al_map1, &writer);
WriteAlignment(&al_map2, &writer);
al_map1.clear();
al_map2.clear();
reader.Close();
writer.Close();
for (vector<StripedSmithWaterman::Aligner*>::iterator ite = aligners.begin();
ite != aligners.end(); ++ite)
free(*ite);
}
<commit_msg>Tangram_bam concatenates special references for ssw<commit_after>#include "tangram_bam.h"
#include <stdio.h>
#include <limits.h>
#include <getopt.h>
#include <vector>
#include <string>
#include <iostream>
#include "api/BamReader.h"
#include "api/BamWriter.h"
#include "../OutSources/fasta/Fasta.h"
#include "../OutSources/stripedSW/ssw_cpp.h"
using namespace std;
void ShowHelp() {
fprintf(stderr, "Usage: tangram_bam <in_bam> <ref_fa> <out_bam>\n\n");
fprintf(stderr, "tangram_bam will generate ZA tags for bams");
fprintf(stderr, " that are not generated by MOSAIK.\n");
fprintf(stderr, "<ref_fa> is a fasta file containing insertion sequences\n");
fprintf(stderr, " that we are going to detect them.\n");
}
bool OpenBams(
const string& infilename,
const string& outfilename,
const string& command_line,
BamTools::BamReader* reader,
BamTools::BamWriter* writer) {
reader->Open(infilename);
if (!reader->IsOpen()) {
fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", infilename.c_str());
return false;
}
// Load header and ref
string header = reader->GetHeaderText();
size_t pos1 = header.find("SO:");
if (pos1 != string::npos) {
size_t pos2 = header.find("SO:queryname");
if (pos2 != string::npos) header.replace(pos2, 12, "SO:unsorted");
pos2 = header.find("SO:coordinate");
if (pos2 != string::npos) header.replace(pos2, 13, "SO:unsorted");
}
header += "@PG\tID:tangram_bam\tCL:";
header += (command_line + '\n');
BamTools::RefVector ref = reader->GetReferenceData();
if (!writer->Open(outfilename, header, ref)) {
fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", outfilename.c_str());
reader->Close();
return false;
}
return true;
}
inline bool LoadReference(const char* fa, FastaReference* fasta) {
string filename = fa;
fasta->open(filename);
return true;
}
bool ConcatenateSpecialReference(
FastaReference* fasta,
SpecialReference* s_ref) {
int total_len = 0;
for (vector<string>::const_iterator ite = fasta->index->sequenceNames.begin();
ite != fasta->index->sequenceNames.end(); ++ite) {
s_ref->concatnated += fasta->getSequence(*ite).c_str();
s_ref->ref_lens.push_back(fasta->sequenceLength(*ite));
s_ref->ref_names.push_back(*ite);
total_len += fasta->sequenceLength(*ite);
}
s_ref->concatnated_len = total_len;
return true;
}
void GetReverseComplement(const string& query, string* reverse) {
reverse->clear();
for (string::const_reverse_iterator ite = query.rbegin(); ite != query.rend(); ++ite) {
switch(*ite) {
case 'A': *reverse += 'T'; break;
case 'C': *reverse += 'G'; break;
case 'G': *reverse += 'C'; break;
case 'T': *reverse += 'A'; break;
default: *reverse += 'N';
}
}
}
void Align(
const string& query,
const StripedSmithWaterman::Aligner& aligner,
StripedSmithWaterman::Alignment* alignment) {
alignment->Clear();
aligner.Align(query.c_str(), kFilter, alignment);
}
void GetZa(const Alignment& al, const Alignment& mate, string* za) {
const bool mate1 = al.bam_alignment.IsFirstMate();
Alignment const *mate1_ptr, *mate2_ptr;
if (mate1) {
*za = "<@;";
mate1_ptr = &al;
mate2_ptr = &mate;
} else {
*za = "<&;";
mate1_ptr = &mate;
mate2_ptr = &al;
}
*za += (std::to_string(mate1_ptr->bam_alignment.MapQuality) + ";;"
+ (mate1_ptr->hit_insertion ? mate1_ptr->ins_prefix : "")
+ ";1;");
if (mate1) {
*za += ";><&;";
} else {
*za += ";><@;";
}
*za += (std::to_string(mate2_ptr->bam_alignment.MapQuality) + ";;"
+ (mate2_ptr->hit_insertion ? mate2_ptr->ins_prefix : "")
+ ";1;;>");
}
void WriteAlignment(
const bool& add_za,
const Alignment& mate,
Alignment* al,
BamTools::BamWriter* writer) {
if (add_za) {
string za;
GetZa(*al, mate, &za);
al->bam_alignment.AddTag("ZA","Z",za);
}
writer->SaveAlignment(al->bam_alignment);
}
void WriteAlignment(const bool& add_za,
map<string, Alignment>* al_map_ite,
BamTools::BamWriter* writer) {
for (map<string, Alignment>::iterator ite = al_map_ite->begin();
ite != al_map_ite->end(); ++ite) {
Alignment* al = &(ite->second);
if (add_za) {
string za;
if (al->bam_alignment.IsPaired()) { // paired-end read
if (al->bam_alignment.IsFirstMate()) {
za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>"
+ "<&;0;;;0;;>";
} else {
za = "<&;0;;;0;;><@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
}
} else { // sinle-end read
za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
+ (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
}
al->bam_alignment.AddTag("ZA","Z",za);
}
writer->SaveAlignment(al->bam_alignment);
}
}
// Return true if an alignment contains too many soft clips
inline bool IsTooManyClips (const BamTools::BamAlignment& al) {
if (al.CigarData.empty()) return true;
int clip = 0;
if ((al.CigarData.begin())->Type == 'S') clip += (al.CigarData.begin())->Length;
if ((al.CigarData.rbegin())->Type == 'S') clip += (al.CigarData.rbegin())->Length;
if (clip > (al.Length * kSoftClipRate)) return true;
else return false;
}
inline void MarkAsUnmapped (BamTools::BamAlignment* al, BamTools::BamAlignment* mate) {
const bool al_unmapped = IsTooManyClips(*al);
const bool mate_unmapped = IsTooManyClips(*mate);
if (!al_unmapped && !mate_unmapped) {
// nothing
} else {
al->SetIsMapped(!al_unmapped);
mate->SetIsMapped(!mate_unmapped);
al->SetIsMateMapped(!mate_unmapped);
mate->SetIsMateMapped(!al_unmapped);
}
}
void StoreAlignment(
const bool& add_za,
Alignment* al,
map<string, Alignment> *al_map_cur,
map<string, Alignment> *al_map_pre,
BamTools::BamWriter* writer) {
// Clear up the buffers once the al_map_cur buffer is full
// 1. Clear up al_map_pre
// 2. move al_map_cur to al_map_pre
if ((static_cast<int>(al_map_cur->size()) > kAlignmentMapSize)) {
WriteAlignment(add_za, al_map_pre, writer);
al_map_pre->clear();
map<string, Alignment> *tmp = al_map_pre;
al_map_pre = al_map_cur;
al_map_cur = tmp;
}
map<string, Alignment>::iterator ite_cur = al_map_cur->find(al->bam_alignment.Name);
if (ite_cur == al_map_cur->end()) {
if (!al_map_pre) {
map<string, Alignment>::iterator ite_pre = al_map_pre->find(al->bam_alignment.Name);
if (ite_pre == al_map_pre->end()) { // al is not found in cur or pre either
(*al_map_cur)[al->bam_alignment.Name] = *al;
} else { // find the mate in al_map_pre
MarkAsUnmapped(&(al->bam_alignment), &(ite_pre->second.bam_alignment));
WriteAlignment(add_za, ite_pre->second, al, writer);
WriteAlignment(add_za, *al, &(ite_pre->second), writer);
al_map_pre->erase(ite_pre);
}
} else { // al is not found in cur and pre is NULL
(*al_map_cur)[al->bam_alignment.Name] = *al;
}
} else { // find the mate in al_map_cur
MarkAsUnmapped(&(al->bam_alignment), &(ite_cur->second.bam_alignment));
WriteAlignment(add_za, ite_cur->second, al, writer);
WriteAlignment(add_za, *al, &(ite_cur->second), writer);
al_map_cur->erase(ite_cur);
}
}
bool ParseArguments(const int argc, char* const * argv, Param* param) {
if (argc == 1) { // no argument
ShowHelp();
return false;
}
// record command line
param->command_line = argv[0];
for ( int i = 1; i < argc; ++i ) {
param->command_line += " ";
param->command_line += argv[i];
}
const char *short_option = "hi:o:r:z";
const struct option long_option[] = {
{"help", no_argument, NULL, 'h'},
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"ref", required_argument, NULL, 'r'},
{"no-za-add", no_argument, NULL, 'z'},
{0, 0, 0, 0}
};
int c = 0;
bool show_help = false;
while (true) {
int option_index = 0;
c = getopt_long(argc, argv, short_option, long_option, &option_index);
if (c == -1) // end of options
break;
switch (c) {
case 'h': show_help = true; break;
case 'i': param->in_bam = optarg; break;
case 'o': param->out_bam = optarg; break;
case 'r': param->ref_fasta = optarg; break;
case 'z': param->za_add = false; break;
}
}
if (show_help || param->in_bam.empty()
|| param->out_bam.empty() || param->ref_fasta.empty()) {
ShowHelp();
return false;
}
return true;
}
int PickBestAlignment(const int& request_score,
const StripedSmithWaterman::Alignment& alignment,
const SpecialReference& s_ref) {
if (alignment.sw_score < request_score) {
return -1; // no proper alignment is found
} else {
int accu_len = 0;
for (unsigned int i = 0; i < s_ref.ref_lens.size(); ++i) {
accu_len += s_ref.ref_lens[i];
if (alignment.ref_begin < accu_len) {
if (alignment.ref_end < accu_len) return i;
else return -1;
}
}
}
return -1;
}
int main(int argc, char** argv) {
Param param;
if (!ParseArguments(argc, argv, ¶m)) return 1;
// Open input bam
string infilename = param.in_bam;
string outfilename = param.out_bam;
BamTools::BamReader reader;
BamTools::BamWriter writer;
if (!OpenBams(infilename, outfilename, param.command_line, &reader, &writer)) return 1;
// Open fasta
FastaReference fasta;
LoadReference(param.ref_fasta.c_str(), &fasta);
// Build SSW aligners for every reference in fasta
SpecialReference s_ref;
ConcatenateSpecialReference(&fasta, &s_ref);
// Build SSW aligner
StripedSmithWaterman::Aligner aligner;
aligner.SetReferenceSequence(s_ref.concatnated.c_str(), s_ref.concatnated_len);
// CORE ALGORITHM
BamTools::BamAlignment bam_alignment;
map<string, Alignment> al_map1, al_map2;
map<string, Alignment> *al_map_cur = &al_map1, *al_map_pre = &al_map2;
StripedSmithWaterman::Alignment alignment;
Alignment al;
while (reader.GetNextAlignment(bam_alignment)) {
int index = -1;
if (param.za_add) {
Align(bam_alignment.QueryBases, aligner, &alignment);
index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
if (index == -1) { // try the reverse complement sequences
string reverse;
GetReverseComplement(bam_alignment.QueryBases, &reverse);
Align(reverse, aligner, &alignment);
index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
}
}
al.Clear();
al.bam_alignment = bam_alignment;
al.hit_insertion = (index == -1) ? false: true;
al.ins_prefix = (index == -1) ? "" : s_ref.ref_names[index].substr(8,2);
StoreAlignment(param.za_add, &al, al_map_cur, al_map_pre, &writer);
}
// Close
WriteAlignment(param.za_add, &al_map1, &writer);
WriteAlignment(param.za_add, &al_map2, &writer);
al_map1.clear();
al_map2.clear();
reader.Close();
writer.Close();
}
<|endoftext|>
|
<commit_before><commit_msg>[TritonCTS] Fix TechChar logs<commit_after><|endoftext|>
|
<commit_before><commit_msg>Update de_web_plugin.cpp<commit_after><|endoftext|>
|
<commit_before>
#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>
#include <ionApplication.h>
using namespace ion;
using namespace ion::Scene;
using namespace ion::Graphics;
int main()
{
////////////////////
// ionEngine Init //
////////////////////
Log::AddDefaultOutputs();
SingletonPointer<CGraphicsAPI> GraphicsAPI;
SingletonPointer<CWindowManager> WindowManager;
SingletonPointer<CTimeManager> TimeManager;
SingletonPointer<CSceneManager> SceneManager;
SingletonPointer<CAssetManager> AssetManager;
GraphicsAPI->Init(new Graphics::COpenGLImplementation());
WindowManager->Init(GraphicsAPI);
TimeManager->Init(WindowManager);
SceneManager->Init(GraphicsAPI);
AssetManager->Init(GraphicsAPI);
CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed);
AssetManager->SetAssetPath("Assets/");
AssetManager->SetShaderPath("Shaders/");
AssetManager->SetTexturePath("Images/");
SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window);
SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer();
RenderTarget->SetClearColor(color3f(0.3f));
/////////////////
// Load Assets //
/////////////////
CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere();
CSimpleMesh * SkySphereMesh = CGeometryCreator::CreateSkySphere();
CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f));
SharedPointer<IShaderProgram> DiffuseShader = AssetManager->LoadShader("Diffuse");
SharedPointer<IShaderProgram> SimpleShader = AssetManager->LoadShader("Simple");
SharedPointer<IShaderProgram> SpecularShader = AssetManager->LoadShader("Specular");
SharedPointer<IShaderProgram> SkySphereShader = AssetManager->LoadShader("SkySphere");
SharedPointer<ITexture2D> SkyMap = AssetManager->LoadTexture("SkyMap.jpg");
SkyMap->SetMagFilter(ITexture::EFilter::Nearest);
////////////////////
// ionScene Setup //
////////////////////
CRenderPass * RenderPass = new CRenderPass(Context);
RenderPass->SetRenderTarget(RenderTarget);
SceneManager->AddRenderPass(RenderPass);
CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio());
Camera->SetPosition(vec3f(0, 3, -5));
Camera->SetFocalLength(0.4f);
RenderPass->SetActiveCamera(Camera);
CCameraController * Controller = new CCameraController(Camera);
Controller->SetTheta(15.f * Constants32::Pi / 48.f);
Controller->SetPhi(-Constants32::Pi / 16.f);
Window->AddListener(Controller);
TimeManager->MakeUpdateTick(0.02)->AddListener(Controller);
/////////////////
// Add Objects //
/////////////////
CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject();
LightSphere1->SetMesh(SphereMesh);
LightSphere1->SetShader(SimpleShader);
LightSphere1->SetPosition(vec3f(0, 1, 0));
RenderPass->AddSceneObject(LightSphere1);
CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject();
LightSphere2->SetMesh(SphereMesh);
LightSphere2->SetShader(SimpleShader);
LightSphere2->SetPosition(vec3f(4, 2, 0));
RenderPass->AddSceneObject(LightSphere2);
CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject();
LightSphere3->SetMesh(SphereMesh);
LightSphere3->SetShader(SimpleShader);
LightSphere3->SetPosition(vec3f(12, 3, 0));
RenderPass->AddSceneObject(LightSphere3);
CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject();
SpecularSphere->SetMesh(SphereMesh);
SpecularSphere->SetShader(SpecularShader);
SpecularSphere->SetPosition(vec3f(3, 3, 6));
RenderPass->AddSceneObject(SpecularSphere);
CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject();
PlaneObject->SetMesh(PlaneMesh);
PlaneObject->SetShader(DiffuseShader);
RenderPass->AddSceneObject(PlaneObject);
CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject();
SkySphereObject->SetMesh(SkySphereMesh);
SkySphereObject->SetShader(SkySphereShader);
SkySphereObject->SetTexture("uTexture", SkyMap);
RenderPass->AddSceneObject(SkySphereObject);
CPointLight * Light1 = new CPointLight();
Light1->SetPosition(vec3f(0, 1, 0));
Light1->SetColor(Colors::Red);
RenderPass->AddLight(Light1);
CPointLight * Light2 = new CPointLight();
Light2->SetPosition(vec3f(4, 2, 0));
Light2->SetColor(Colors::Green);
RenderPass->AddLight(Light2);
CPointLight * Light3 = new CPointLight();
Light3->SetPosition(vec3f(12, 3, 0));
Light3->SetColor(Colors::Blue);
RenderPass->AddLight(Light3);
///////////////
// Main Loop //
///////////////
TimeManager->Init(WindowManager);
while (WindowManager->Run())
{
TimeManager->Update();
float const MinimumBrightness = 0.2f;
float const MaximumBrightness = 1.f - MinimumBrightness;
float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness;
float const Radius = Brightness * 10.f;
Light1->SetRadius(Radius);
Light2->SetRadius(Radius);
Light3->SetRadius(Radius);
float const Bright = 1;
float const Dim = 0.5f;
LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness;
LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness;
LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness;
LightSphere1->SetScale(Brightness);
LightSphere2->SetScale(Brightness);
LightSphere3->SetScale(Brightness);
SkySphereObject->SetPosition(Camera->GetPosition());
RenderTarget->ClearColorAndDepth();
SceneManager->DrawAll();
Window->SwapBuffers();
}
return 0;
}
<commit_msg>[Demo05] Fix materials<commit_after>
#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>
#include <ionApplication.h>
using namespace ion;
using namespace ion::Scene;
using namespace ion::Graphics;
int main()
{
////////////////////
// ionEngine Init //
////////////////////
Log::AddDefaultOutputs();
SingletonPointer<CGraphicsAPI> GraphicsAPI;
SingletonPointer<CWindowManager> WindowManager;
SingletonPointer<CTimeManager> TimeManager;
SingletonPointer<CSceneManager> SceneManager;
SingletonPointer<CAssetManager> AssetManager;
GraphicsAPI->Init(new Graphics::COpenGLImplementation());
WindowManager->Init(GraphicsAPI);
TimeManager->Init(WindowManager);
SceneManager->Init(GraphicsAPI);
AssetManager->Init(GraphicsAPI);
CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed);
AssetManager->SetAssetPath("Assets/");
AssetManager->SetShaderPath("Shaders/");
AssetManager->SetTexturePath("Images/");
SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window);
SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer();
RenderTarget->SetClearColor(color3f(0.3f));
/////////////////
// Load Assets //
/////////////////
CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere();
CSimpleMesh * SkySphereMesh = CGeometryCreator::CreateSkySphere();
CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f));
SharedPointer<IShaderProgram> DiffuseShader = AssetManager->LoadShader("Diffuse");
SharedPointer<IShaderProgram> SimpleShader = AssetManager->LoadShader("Simple");
SharedPointer<IShaderProgram> SpecularShader = AssetManager->LoadShader("Specular");
SharedPointer<IShaderProgram> SkySphereShader = AssetManager->LoadShader("SkySphere");
SharedPointer<ITexture2D> SkyMap = AssetManager->LoadTexture("SkyMap.jpg");
SkyMap->SetMagFilter(ITexture::EFilter::Nearest);
////////////////////
// ionScene Setup //
////////////////////
CRenderPass * RenderPass = new CRenderPass(Context);
RenderPass->SetRenderTarget(RenderTarget);
SceneManager->AddRenderPass(RenderPass);
CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio());
Camera->SetPosition(vec3f(0, 3, -5));
Camera->SetFocalLength(0.4f);
RenderPass->SetActiveCamera(Camera);
CCameraController * Controller = new CCameraController(Camera);
Controller->SetTheta(15.f * Constants32::Pi / 48.f);
Controller->SetPhi(-Constants32::Pi / 16.f);
Window->AddListener(Controller);
TimeManager->MakeUpdateTick(0.02)->AddListener(Controller);
/////////////////
// Add Objects //
/////////////////
CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject();
LightSphere1->SetMesh(SphereMesh);
LightSphere1->SetShader(SimpleShader);
LightSphere1->SetPosition(vec3f(0, 1, 0));
RenderPass->AddSceneObject(LightSphere1);
CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject();
LightSphere2->SetMesh(SphereMesh);
LightSphere2->SetShader(SimpleShader);
LightSphere2->SetPosition(vec3f(4, 2, 0));
RenderPass->AddSceneObject(LightSphere2);
CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject();
LightSphere3->SetMesh(SphereMesh);
LightSphere3->SetShader(SimpleShader);
LightSphere3->SetPosition(vec3f(12, 3, 0));
RenderPass->AddSceneObject(LightSphere3);
CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject();
SpecularSphere->SetMesh(SphereMesh);
SpecularSphere->SetShader(SpecularShader);
SpecularSphere->SetPosition(vec3f(3, 3, 6));
SpecularSphere->GetMaterial().Ambient = vec3f(0.05f);
RenderPass->AddSceneObject(SpecularSphere);
CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject();
PlaneObject->SetMesh(PlaneMesh);
PlaneObject->SetShader(DiffuseShader);
PlaneObject->GetMaterial().Ambient = vec3f(0.05f);
RenderPass->AddSceneObject(PlaneObject);
CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject();
SkySphereObject->SetMesh(SkySphereMesh);
SkySphereObject->SetShader(SkySphereShader);
SkySphereObject->SetTexture("uTexture", SkyMap);
RenderPass->AddSceneObject(SkySphereObject);
CPointLight * Light1 = new CPointLight();
Light1->SetPosition(vec3f(0, 1, 0));
Light1->SetColor(Colors::Red);
RenderPass->AddLight(Light1);
CPointLight * Light2 = new CPointLight();
Light2->SetPosition(vec3f(4, 2, 0));
Light2->SetColor(Colors::Green);
RenderPass->AddLight(Light2);
CPointLight * Light3 = new CPointLight();
Light3->SetPosition(vec3f(12, 3, 0));
Light3->SetColor(Colors::Blue);
RenderPass->AddLight(Light3);
///////////////
// Main Loop //
///////////////
TimeManager->Init(WindowManager);
while (WindowManager->Run())
{
TimeManager->Update();
float const MinimumBrightness = 0.2f;
float const MaximumBrightness = 1.f - MinimumBrightness;
float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness;
float const Radius = Brightness * 10.f;
Light1->SetRadius(Radius);
Light2->SetRadius(Radius);
Light3->SetRadius(Radius);
float const Bright = 1;
float const Dim = 0.5f;
LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness;
LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness;
LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness;
LightSphere1->SetScale(Brightness);
LightSphere2->SetScale(Brightness);
LightSphere3->SetScale(Brightness);
SkySphereObject->SetPosition(Camera->GetPosition());
RenderTarget->ClearColorAndDepth();
SceneManager->DrawAll();
Window->SwapBuffers();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <QtSerialPort/QtSerialPort>
#include <iostream>
#include "PositionDispatcher.h"
#include "MavState.h"
#define DISPATCH_INTERVAL 100 //ms
PositionDispatcher::PositionDispatcher(QObject *parent) :
QObject(parent),
_serial(this)
{
_serial.setPortName("/dev/ttyUSB0");
// Open serial port
if(!_serial.open(QSerialPort::ReadWrite)) {
qCritical() << "Error opening serial port";
emit finished();
return;
}
_serial.setBaudRate(QSerialPort::Baud57600);
_serial.setFlowControl(QSerialPort::NoFlowControl);
// Start dispatch time counter
_dispatchTime.start();
qDebug() << "Connected to MavLink Radio...";
}
PositionDispatcher::~PositionDispatcher()
{
_serial.close();
qDebug() << "Serial Port closed";
}
void PositionDispatcher::sendPosition(int64_t ts, geometry::pose vision, geometry::pose sp, bool visionValid, bool spValid)
{
mavlink_message_t msg1;
mavlink_message_t msg2;
MavState conv;
conv.setOrientation(vision.orientation[0],vision.orientation[1],vision.orientation[2],vision.orientation[3]);
float roll,pitch,yaw;
conv.orientation(&roll,&pitch,&yaw);
mavlink_msg_vision_position_estimate_pack(
1,
MAV_COMP_ID_ALL, &msg1,
(uint64_t) ts * 1000,
(float)vision.position[0],
(float)vision.position[1],
(float)vision.position[2],
roll, //rad
pitch, //rad
yaw); //rad
/*
mavlink_msg_vicon_position_estimate_pack(
1,
MAV_COMP_ID_ALL, &msg2,
(uint64_t) ts * 1000,
(float)sp.position[0],
(float)sp.position[1],
(float)sp.position[2],
0, //rad
0,//rad
sp.yaw); //rad
*/
mavlink_msg_set_position_target_local_ned_pack(
1,
MAV_COMP_ID_ALL,
&msg2,
(uint64_t) ts * 1000,
1,
MAV_COMP_ID_ALL,
MAV_FRAME_LOCAL_NED,
0b0000001111111000,
1,
2,
3,
0,
0,
0,
0,
0,
0,
0,
0);
if(_dispatchTime.elapsed() >= DISPATCH_INTERVAL){
// if(visionValid) {
_sendMavlinkMessage(&msg1);
std::cout << "Vision estimate: " << vision.position[0] << " " << vision.position[1] <<
" " << vision.position[2] <<" \\ " <<roll <<" " <<pitch <<" " <<" " <<yaw << std::endl;
//}
if(spValid){
_sendMavlinkMessage(&msg2);
std::cout << "Position SP: " << sp.position[0] << " " <<sp.position[1] <<
" " << sp.position[2] << std::endl;
}
_dispatchTime.restart();
}
}
void PositionDispatcher::_sendMavlinkMessage(mavlink_message_t *msg)
{
// Initialize the required buffers
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Copy the message to the send buffer
uint16_t len = mavlink_msg_to_send_buffer(buf, msg);
// Send the message
QByteArray sendBuff((const char*)buf, len);
int written = _serial.write(sendBuff);
//Wait for data to be sent
if(!_serial.waitForBytesWritten(500)) {
qCritical() << "Serial unable to send data";
emit finished();
}
}
<commit_msg>pack position set point<commit_after>#include <QtSerialPort/QtSerialPort>
#include <iostream>
#include "PositionDispatcher.h"
#include "MavState.h"
#define DISPATCH_INTERVAL 100 //ms
PositionDispatcher::PositionDispatcher(QObject *parent) :
QObject(parent),
_serial(this)
{
_serial.setPortName("/dev/ttyUSB0");
// Open serial port
if(!_serial.open(QSerialPort::ReadWrite)) {
qCritical() << "Error opening serial port";
emit finished();
return;
}
_serial.setBaudRate(QSerialPort::Baud57600);
_serial.setFlowControl(QSerialPort::NoFlowControl);
// Start dispatch time counter
_dispatchTime.start();
qDebug() << "Connected to MavLink Radio...";
}
PositionDispatcher::~PositionDispatcher()
{
_serial.close();
qDebug() << "Serial Port closed";
}
void PositionDispatcher::sendPosition(int64_t ts, geometry::pose vision, geometry::pose sp, bool visionValid, bool spValid)
{
mavlink_message_t msg1;
mavlink_message_t msg2;
MavState conv;
conv.setOrientation(vision.orientation[0],vision.orientation[1],vision.orientation[2],vision.orientation[3]);
float roll,pitch,yaw;
conv.orientation(&roll,&pitch,&yaw);
mavlink_msg_vision_position_estimate_pack(
1,
MAV_COMP_ID_ALL, &msg1,
(uint64_t) ts * 1000,
(float)vision.position[0],
(float)vision.position[1],
(float)vision.position[2],
roll, //rad
pitch, //rad
yaw); //rad
/*
mavlink_msg_vicon_position_estimate_pack(
1,
MAV_COMP_ID_ALL, &msg2,
(uint64_t) ts * 1000,
(float)sp.position[0],
(float)sp.position[1],
(float)sp.position[2],
0, //rad
0,//rad
sp.yaw); //rad
*/
mavlink_msg_set_position_target_local_ned_pack(
1,
MAV_COMP_ID_ALL,
&msg2,
(uint64_t) ts * 1000,
1,
MAV_COMP_ID_ALL,
MAV_FRAME_LOCAL_NED,
0b0000001111111000,
sp.position[0], //x [m]
sp.position[1], //y
sp.position[2], //z Be careful, z is directed downwards!!
0, //vx [m/s]
0, //vy
0, //vz
0, //ax [m/s^2]
0, //ay
0, //az
0, //yaw [rad]
0); //yaw_rate [rad/s]
if(_dispatchTime.elapsed() >= DISPATCH_INTERVAL){
// if(visionValid) {
_sendMavlinkMessage(&msg1);
std::cout << "Vision estimate: " << vision.position[0] << " " << vision.position[1] <<
" " << vision.position[2] <<" \\ " <<roll <<" " <<pitch <<" " <<" " <<yaw << std::endl;
//}
if(spValid){
_sendMavlinkMessage(&msg2);
std::cout << "Position SP: " << sp.position[0] << " " <<sp.position[1] <<
" " << sp.position[2] << std::endl;
}
_dispatchTime.restart();
}
}
void PositionDispatcher::_sendMavlinkMessage(mavlink_message_t *msg)
{
// Initialize the required buffers
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Copy the message to the send buffer
uint16_t len = mavlink_msg_to_send_buffer(buf, msg);
// Send the message
QByteArray sendBuff((const char*)buf, len);
int written = _serial.write(sendBuff);
//Wait for data to be sent
if(!_serial.waitForBytesWritten(500)) {
qCritical() << "Serial unable to send data";
emit finished();
}
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////
/// @file ClickEventHandler.cpp
/// @author Chris L Baker (clb) <chris@chimail.net>
/// @date 2015.01.13
/// @brief Handle Click Events
///
/// @attention Copyright (C) 2015
/// @attention All rights reserved
/////////////////////////////////////////////////////////////////
#include "ClickEventHandler.h"
namespace d3
{
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
ClickEventHandler::ClickEventHandler() :
Parent_t()
{
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
ClickEventHandler::~ClickEventHandler()
{
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
bool ClickEventHandler::add(const osgGA::GUIEventAdapter::MouseButtonMask& button,
const std::function<bool(const osgGA::GUIEventAdapter&)>& func,
const std::string& description)
{
// add this click handler to the map
m_clickFuncMap[button].push_back({button, func, description});
return true;
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
bool ClickEventHandler::handle(const osgGA::GUIEventAdapter& eventAdapter,
osgGA::GUIActionAdapter&)
{
// find this handler
ClickMap_t::iterator itt( m_clickFuncMap.find((osgGA::GUIEventAdapter::MouseButtonMask)eventAdapter.getButton()) );
if ( m_clickFuncMap.end() == itt ) return false;
// envoke the function(s)
bool rv(true);
for ( const auto& entry : itt->second )
rv &= entry.func(eventAdapter);
return rv;
};
} // namespace d3
<commit_msg>catching the :bug: where, if no event handler was registered, we would incorrectly report the action as being handled<commit_after>/////////////////////////////////////////////////////////////////
/// @file ClickEventHandler.cpp
/// @author Chris L Baker (clb) <chris@chimail.net>
/// @date 2015.01.13
/// @brief Handle Click Events
///
/// @attention Copyright (C) 2015
/// @attention All rights reserved
/////////////////////////////////////////////////////////////////
#include "ClickEventHandler.h"
namespace d3
{
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
ClickEventHandler::ClickEventHandler() :
Parent_t()
{
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
ClickEventHandler::~ClickEventHandler()
{
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
bool ClickEventHandler::add(const osgGA::GUIEventAdapter::MouseButtonMask& button,
const std::function<bool(const osgGA::GUIEventAdapter&)>& func,
const std::string& description)
{
// add this click handler to the map
m_clickFuncMap[button].push_back({button, func, description});
return true;
};
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
bool ClickEventHandler::handle(const osgGA::GUIEventAdapter& eventAdapter,
osgGA::GUIActionAdapter&)
{
if ( 0x7 & eventAdapter.getButton() )
{
// find this handler
ClickMap_t::iterator itt( m_clickFuncMap.find((osgGA::GUIEventAdapter::MouseButtonMask)eventAdapter.getButton()) );
if ( m_clickFuncMap.end() == itt ) return false;
// envoke the function(s)
bool rv(false);
if ( not itt->second.empty() )
{
rv = true;
for ( const auto& entry : itt->second )
rv &= entry.func(eventAdapter);
}
return rv;
}
return false;
};
} // namespace d3
<|endoftext|>
|
<commit_before>
#include "Output.h"
#include "../ObjectStore.h"
#include "../EspConnection.h"
#include "../../IPC/Message.h"
#include "../../IPOCS/Message.h"
#include "../../IPOCS/Packets/SetOutputPacket.h"
#include "../log.h"
Output::Output(): lastOrderTime(0), offDelay(0), outputPin(0),
lastSentState(IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF) {
}
void Output::handleOrder(IPOCS::Packet* basePacket)
{
if (basePacket->RNID_PACKET == 13) {
IPOCS::SetOutputPacket* packet = (IPOCS::SetOutputPacket*)basePacket;
// Set output high
this->lastOrderTime = millis();
if (packet->RQ_OUTPUT_COMMAND == IPOCS::SetOutputPacket::E_RQ_OUTPUT_COMMAND::ON) {
this->offDelay = packet->RT_DURATION;
digitalWrite(this->outputPin, HIGH);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON;
this->sendStatus();
}
} else {
this->offDelay = 0;
digitalWrite(this->outputPin, LOW);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF;
this->sendStatus();
}
}
} else if (basePacket->RNID_PACKET == 7) {
this->sendStatus();
} else {
// TODO: Send alarm or something about invalid packet type.
}
}
IPOCS::Packet* Output::getStatusPacket() {
IPOCS::OutputStatusPacket* pkt = (IPOCS::OutputStatusPacket*)IPOCS::OutputStatusPacket::create();
pkt->RQ_OUTPUT_STATE = this->lastSentState;
return pkt;
}
void Output::loop() {
if ((offDelay != 0) && (millis() - this->lastOrderTime) >= offDelay) {
this->offDelay = 0;
digitalWrite(this->outputPin, LOW);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF;
this->sendStatus();
}
}
}
void Output::objectInit(const uint8_t configData[], int configDataLen)
{
this->outputPin = configData[0] + 1;
pinMode(this->outputPin, OUTPUT);
digitalWrite(this->outputPin, LOW);
}
static BasicObject* createOutput()
{
return new Output();
}
__attribute__((constructor))
static void initialize_output() {
ObjectStore::getInstance().registerType(10, &createOutput);
}
<commit_msg>Fix bug with output order duration<commit_after>
#include "Output.h"
#include "../ObjectStore.h"
#include "../EspConnection.h"
#include "../../IPC/Message.h"
#include "../../IPOCS/Message.h"
#include "../../IPOCS/Packets/SetOutputPacket.h"
#include "../log.h"
Output::Output(): lastOrderTime(0), offDelay(0), outputPin(0),
lastSentState(IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF) {
}
void Output::handleOrder(IPOCS::Packet* basePacket)
{
if (basePacket->RNID_PACKET == 13) {
IPOCS::SetOutputPacket* packet = (IPOCS::SetOutputPacket*)basePacket;
// Set output high
this->lastOrderTime = millis();
if (packet->RQ_OUTPUT_COMMAND == IPOCS::SetOutputPacket::E_RQ_OUTPUT_COMMAND::ON) {
this->offDelay = packet->RT_DURATION;
digitalWrite(this->outputPin, HIGH);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON;
this->sendStatus();
}
} else {
this->offDelay = 0;
digitalWrite(this->outputPin, LOW);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF;
this->sendStatus();
}
}
} else if (basePacket->RNID_PACKET == 7) {
this->sendStatus();
} else {
// TODO: Send alarm or something about invalid packet type.
}
}
IPOCS::Packet* Output::getStatusPacket() {
IPOCS::OutputStatusPacket* pkt = (IPOCS::OutputStatusPacket*)IPOCS::OutputStatusPacket::create();
pkt->RQ_OUTPUT_STATE = this->lastSentState;
return pkt;
}
void Output::loop() {
if ((offDelay != 0) && (millis() - this->lastOrderTime) >= this->offDelay * 100) {
this->offDelay = 0;
digitalWrite(this->outputPin, LOW);
if (this->lastSentState == IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::ON) {
this->lastSentState = IPOCS::OutputStatusPacket::E_RQ_OUTPUT_STATE::OFF;
this->sendStatus();
}
}
}
void Output::objectInit(const uint8_t configData[], int configDataLen)
{
this->outputPin = configData[0] + 1;
pinMode(this->outputPin, OUTPUT);
digitalWrite(this->outputPin, LOW);
}
static BasicObject* createOutput()
{
return new Output();
}
__attribute__((constructor))
static void initialize_output() {
ObjectStore::getInstance().registerType(10, &createOutput);
}
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.
//
// 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 <atria/prelude/comp.hpp>
#include <atria/testing/gtest.hpp>
namespace atria {
namespace prelude {
TEST(comp, compose_one_fn)
{
auto fn = comp(
[](int x) { return x + 1; });
EXPECT_EQ(fn(1), 2);
EXPECT_EQ(fn(42), 43);
}
TEST(comp, compose_two_fn)
{
auto fn = comp(
[](int x) { return x + 1; },
[](int x) { return x * 2; });
EXPECT_EQ(fn(3), 7);
EXPECT_EQ(fn(42), 85);
}
TEST(comp, compose_three_fn)
{
auto fn = comp(
[](int x) { return x + 1; },
[](int x) { return x * 2; },
[](int x) { return x - 1; });
EXPECT_EQ(fn(3), 5);
EXPECT_EQ(fn(42), 83);
}
TEST(comp, various_types)
{
auto fn = comp(
[](double x) { return x + 1; },
[](std::string) { return 42.0; },
[](int x) { return std::to_string(x); });
EXPECT_EQ(fn(3), 43.0);
EXPECT_EQ(fn(42), 43.0);
}
namespace
{
struct thingy
{
int value;
thingy& times2() { value *= 2; return *this; }
thingy& plus2() { value += 2; return *this; }
int extract() { return value; }
};
int free_func(int x, int y) { return x - y; }
} // anon
TEST(comp, uses_invoke)
{
auto res = comp(
&thingy::extract,
&thingy::times2,
&thingy::plus2,
[](int x) { return thingy{x}; },
free_func);
EXPECT_EQ(res(10, 5), 14);
}
} // namespace prelude
} // namespace atria
<commit_msg>prelude: oops! fix stupid UB in `comp` unit test<commit_after>//
// Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.
//
// 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 <atria/prelude/comp.hpp>
#include <atria/testing/gtest.hpp>
namespace atria {
namespace prelude {
TEST(comp, compose_one_fn)
{
auto fn = comp(
[](int x) { return x + 1; });
EXPECT_EQ(fn(1), 2);
EXPECT_EQ(fn(42), 43);
}
TEST(comp, compose_two_fn)
{
auto fn = comp(
[](int x) { return x + 1; },
[](int x) { return x * 2; });
EXPECT_EQ(fn(3), 7);
EXPECT_EQ(fn(42), 85);
}
TEST(comp, compose_three_fn)
{
auto fn = comp(
[](int x) { return x + 1; },
[](int x) { return x * 2; },
[](int x) { return x - 1; });
EXPECT_EQ(fn(3), 5);
EXPECT_EQ(fn(42), 83);
}
TEST(comp, various_types)
{
auto fn = comp(
[](double x) { return x + 1; },
[](std::string) { return 42.0; },
[](int x) { return std::to_string(x); });
EXPECT_EQ(fn(3), 43.0);
EXPECT_EQ(fn(42), 43.0);
}
namespace
{
struct thingy
{
int value;
thingy times2() { value *= 2; return *this; }
thingy plus2() { value += 2; return *this; }
int extract() { return value; }
};
int free_func(int x, int y) { return x - y; }
} // anon
TEST(comp, uses_invoke)
{
auto res = comp(
&thingy::extract,
&thingy::times2,
&thingy::plus2,
[](int x) { return thingy{x}; },
free_func);
EXPECT_EQ(res(10, 5), 14);
}
} // namespace prelude
} // namespace atria
<|endoftext|>
|
<commit_before>/*
Copyright 2015-2020 Igor Petrovic
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 "board/Board.h"
#include "board/common/io/Helpers.h"
#include "board/Internal.h"
#include "core/src/general/Helpers.h"
#include "core/src/general/Atomic.h"
#include "Pins.h"
#include "io/leds/LEDs.h"
///
/// \brief Total number of states between fully off and fully on for LEDs.
///
#define NUMBER_OF_LED_TRANSITIONS 64
namespace
{
#if !defined(NUMBER_OF_OUT_SR) || defined(NUMBER_OF_LED_COLUMNS)
core::io::mcuPin_t pin;
#endif
///
/// \brief Variables holding calculated current LED index and state.
/// Used only to avoid stack usage in interrupt.
/// @{
#if defined(NUMBER_OF_LED_COLUMNS) || defined(NUMBER_OF_OUT_SR)
uint8_t ledIndex;
#endif
#ifdef NUMBER_OF_LED_COLUMNS
bool ledStateSingle;
#endif
/// @}
uint8_t ledState[MAX_NUMBER_OF_LEDS];
#ifdef LED_FADING
volatile uint8_t pwmSteps;
volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS];
///
/// \brief Array holding values needed to achieve more natural LED transition between states.
///
const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
8,
9,
10,
11,
12,
13,
14,
16,
17,
19,
21,
23,
25,
28,
30,
33,
36,
40,
44,
48,
52,
57,
62,
68,
74,
81,
89,
97,
106,
115,
126,
138,
150,
164,
179,
195,
213,
255
};
#endif
#ifndef NUMBER_OF_LED_COLUMNS
///
/// \brief Used to indicate whether or not outputs should be updated.
/// Set to true in ::writeState if the new state differs from the current one.
///
volatile bool updateOutputs = false;
#else
///
/// \brief Holds value of currently active output matrix column.
///
volatile uint8_t activeOutColumn;
///
/// \brief Switches to next LED matrix column.
///
inline void activateOutputColumn()
{
BIT_READ(activeOutColumn, 0) ? CORE_IO_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_IO_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN);
BIT_READ(activeOutColumn, 1) ? CORE_IO_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_IO_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN);
BIT_READ(activeOutColumn, 2) ? CORE_IO_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_IO_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN);
}
///
/// \brief Used to turn the given LED row off.
///
inline void ledRowOff(uint8_t row)
{
#ifdef LED_FADING
//turn off pwm
core::io::pwmOff(Board::detail::map::pwmChannel(row));
#endif
pin = Board::detail::map::led(row);
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
///
/// \brief Used to turn the given LED row on.
/// If led fading is supported on board, intensity must be specified as well.
///
inline void ledRowOn(uint8_t row
#ifdef LED_FADING
,
uint8_t intensity
#endif
)
{
#ifdef LED_FADING
if (intensity == 255)
#endif
{
pin = Board::detail::map::led(row);
//max value, don't use pwm
EXT_LED_ON(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#ifdef LED_FADING
else
{
#ifdef LED_EXT_INVERT
intensity = 255 - intensity;
#endif
core::io::pwmOn(Board::detail::map::pwmChannel(row), intensity);
}
#endif
}
#endif
} // namespace
namespace Board
{
namespace io
{
void writeLEDstate(uint8_t ledID, bool state)
{
ATOMIC_SECTION
{
ledState[ledID] = state;
#ifndef NUMBER_OF_LED_COLUMNS
updateOutputs = true;
#endif
}
}
#ifdef LED_FADING
void setLEDfadeSpeed(uint8_t transitionSpeed)
{
//reset transition counter
ATOMIC_SECTION
{
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
transitionCounter[i] = 0;
pwmSteps = transitionSpeed;
}
}
#else
__attribute__((weak)) void setLEDfadeSpeed(uint8_t transitionSpeed)
{
}
#endif
uint8_t getRGBaddress(uint8_t rgbID, Board::io::rgbIndex_t index)
{
#ifdef NUMBER_OF_LED_COLUMNS
uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS;
uint8_t row = (rgbID / NUMBER_OF_LED_COLUMNS) * 3;
uint8_t address = column + NUMBER_OF_LED_COLUMNS * row;
switch (index)
{
case rgbIndex_t::r:
return address;
case rgbIndex_t::g:
return address + NUMBER_OF_LED_COLUMNS * 1;
case rgbIndex_t::b:
return address + NUMBER_OF_LED_COLUMNS * 2;
}
return 0;
#else
return rgbID * 3 + static_cast<uint8_t>(index);
#endif
}
uint8_t getRGBID(uint8_t ledID)
{
#ifdef NUMBER_OF_LED_COLUMNS
uint8_t row = ledID / NUMBER_OF_LED_COLUMNS;
uint8_t mod = row % 3;
row -= mod;
uint8_t column = ledID % NUMBER_OF_LED_COLUMNS;
uint8_t result = (row * NUMBER_OF_LED_COLUMNS) / 3 + column;
if (result >= MAX_NUMBER_OF_RGB_LEDS)
return MAX_NUMBER_OF_RGB_LEDS - 1;
else
return result;
#else
uint8_t result = ledID / 3;
if (result >= MAX_NUMBER_OF_RGB_LEDS)
return MAX_NUMBER_OF_RGB_LEDS - 1;
else
return result;
#endif
}
} // namespace io
namespace detail
{
namespace io
{
#ifdef NUMBER_OF_LED_COLUMNS
void checkDigitalOutputs()
{
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
ledRowOff(i);
activateOutputColumn();
//if there is an active LED in current column, turn on LED row
//do fancy transitions here
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
{
ledIndex = activeOutColumn + i * NUMBER_OF_LED_COLUMNS;
ledStateSingle = ledState[ledIndex] && (NUMBER_OF_LED_TRANSITIONS - 1);
//don't bother with pwm if it's disabled
if (!pwmSteps && ledStateSingle)
{
ledRowOn(i
#ifdef LED_FADING
,
255
#endif
);
}
else
{
if (ledTransitionScale[transitionCounter[ledIndex]])
ledRowOn(i
#ifdef LED_FADING
,
ledTransitionScale[transitionCounter[ledIndex]]
#endif
);
if (transitionCounter[ledIndex] != ledStateSingle)
{
//fade up
if (transitionCounter[ledIndex] < ledStateSingle)
{
transitionCounter[ledIndex] += pwmSteps;
if (transitionCounter[ledIndex] > ledStateSingle)
transitionCounter[ledIndex] = ledStateSingle;
}
else
{
//fade down
transitionCounter[ledIndex] -= pwmSteps;
if (transitionCounter[ledIndex] < 0)
transitionCounter[ledIndex] = 0;
}
}
}
}
if (++activeOutColumn == NUMBER_OF_LED_COLUMNS)
activeOutColumn = 0;
}
#elif defined(NUMBER_OF_OUT_SR)
///
/// \brief Checks if any LED state has been changed and writes changed state to output shift registers.
///
void checkDigitalOutputs()
{
if (updateOutputs)
{
CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
for (int j = 0; j < NUMBER_OF_OUT_SR; j++)
{
for (int i = 0; i < NUMBER_OF_OUT_SR_INPUTS; i++)
{
ledIndex = i + j * NUMBER_OF_OUT_SR_INPUTS;
ledState[ledIndex] ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);
CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
_NOP();
_NOP();
CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
}
}
CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
updateOutputs = false;
}
}
#else
void checkDigitalOutputs()
{
if (updateOutputs)
{
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
{
pin = Board::detail::map::led(i);
if (ledState[i])
EXT_LED_ON(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
else
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
updateOutputs = false;
}
}
#endif
} // namespace io
} // namespace detail
} // namespace Board<commit_msg>board: make sure led control can be compiled in matrix setup without fade support<commit_after>/*
Copyright 2015-2020 Igor Petrovic
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 "board/Board.h"
#include "board/common/io/Helpers.h"
#include "board/Internal.h"
#include "core/src/general/Helpers.h"
#include "core/src/general/Atomic.h"
#include "Pins.h"
#include "io/leds/LEDs.h"
///
/// \brief Total number of states between fully off and fully on for LEDs.
///
#define NUMBER_OF_LED_TRANSITIONS 64
namespace
{
#if !defined(NUMBER_OF_OUT_SR) || defined(NUMBER_OF_LED_COLUMNS)
core::io::mcuPin_t pin;
#endif
///
/// \brief Variables holding calculated current LED index and state.
/// Used only to avoid stack usage in interrupt.
/// @{
#if defined(NUMBER_OF_LED_COLUMNS) || defined(NUMBER_OF_OUT_SR)
uint8_t ledIndex;
#endif
#ifdef NUMBER_OF_LED_COLUMNS
bool ledStateSingle;
#endif
/// @}
uint8_t ledState[MAX_NUMBER_OF_LEDS];
#ifdef LED_FADING
volatile uint8_t pwmSteps;
volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS];
///
/// \brief Array holding values needed to achieve more natural LED transition between states.
///
const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
8,
9,
10,
11,
12,
13,
14,
16,
17,
19,
21,
23,
25,
28,
30,
33,
36,
40,
44,
48,
52,
57,
62,
68,
74,
81,
89,
97,
106,
115,
126,
138,
150,
164,
179,
195,
213,
255
};
#endif
#ifndef NUMBER_OF_LED_COLUMNS
///
/// \brief Used to indicate whether or not outputs should be updated.
/// Set to true in ::writeState if the new state differs from the current one.
///
volatile bool updateOutputs = false;
#else
///
/// \brief Holds value of currently active output matrix column.
///
volatile uint8_t activeOutColumn;
///
/// \brief Switches to next LED matrix column.
///
inline void activateOutputColumn()
{
BIT_READ(activeOutColumn, 0) ? CORE_IO_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_IO_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN);
BIT_READ(activeOutColumn, 1) ? CORE_IO_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_IO_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN);
BIT_READ(activeOutColumn, 2) ? CORE_IO_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_IO_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN);
}
///
/// \brief Used to turn the given LED row off.
///
inline void ledRowOff(uint8_t row)
{
#ifdef LED_FADING
//turn off pwm
core::io::pwmOff(Board::detail::map::pwmChannel(row));
#endif
pin = Board::detail::map::led(row);
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
///
/// \brief Used to turn the given LED row on.
/// If led fading is supported on board, intensity must be specified as well.
///
inline void ledRowOn(uint8_t row
#ifdef LED_FADING
,
uint8_t intensity
#endif
)
{
#ifdef LED_FADING
if (intensity == 255)
#endif
{
pin = Board::detail::map::led(row);
//max value, don't use pwm
EXT_LED_ON(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#ifdef LED_FADING
else
{
#ifdef LED_EXT_INVERT
intensity = 255 - intensity;
#endif
core::io::pwmOn(Board::detail::map::pwmChannel(row), intensity);
}
#endif
}
#endif
} // namespace
namespace Board
{
namespace io
{
void writeLEDstate(uint8_t ledID, bool state)
{
ATOMIC_SECTION
{
ledState[ledID] = state;
#ifndef NUMBER_OF_LED_COLUMNS
updateOutputs = true;
#endif
}
}
#ifdef LED_FADING
void setLEDfadeSpeed(uint8_t transitionSpeed)
{
//reset transition counter
ATOMIC_SECTION
{
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
transitionCounter[i] = 0;
pwmSteps = transitionSpeed;
}
}
#else
__attribute__((weak)) void setLEDfadeSpeed(uint8_t transitionSpeed)
{
}
#endif
uint8_t getRGBaddress(uint8_t rgbID, Board::io::rgbIndex_t index)
{
#ifdef NUMBER_OF_LED_COLUMNS
uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS;
uint8_t row = (rgbID / NUMBER_OF_LED_COLUMNS) * 3;
uint8_t address = column + NUMBER_OF_LED_COLUMNS * row;
switch (index)
{
case rgbIndex_t::r:
return address;
case rgbIndex_t::g:
return address + NUMBER_OF_LED_COLUMNS * 1;
case rgbIndex_t::b:
return address + NUMBER_OF_LED_COLUMNS * 2;
}
return 0;
#else
return rgbID * 3 + static_cast<uint8_t>(index);
#endif
}
uint8_t getRGBID(uint8_t ledID)
{
#ifdef NUMBER_OF_LED_COLUMNS
uint8_t row = ledID / NUMBER_OF_LED_COLUMNS;
uint8_t mod = row % 3;
row -= mod;
uint8_t column = ledID % NUMBER_OF_LED_COLUMNS;
uint8_t result = (row * NUMBER_OF_LED_COLUMNS) / 3 + column;
if (result >= MAX_NUMBER_OF_RGB_LEDS)
return MAX_NUMBER_OF_RGB_LEDS - 1;
else
return result;
#else
uint8_t result = ledID / 3;
if (result >= MAX_NUMBER_OF_RGB_LEDS)
return MAX_NUMBER_OF_RGB_LEDS - 1;
else
return result;
#endif
}
} // namespace io
namespace detail
{
namespace io
{
#ifdef NUMBER_OF_LED_COLUMNS
void checkDigitalOutputs()
{
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
ledRowOff(i);
activateOutputColumn();
//if there is an active LED in current column, turn on LED row
//do fancy transitions here
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
{
ledIndex = activeOutColumn + i * NUMBER_OF_LED_COLUMNS;
ledStateSingle = ledState[ledIndex] && (NUMBER_OF_LED_TRANSITIONS - 1);
//don't bother with pwm if it's disabled
#ifdef LED_FADING
if (!pwmSteps && ledStateSingle)
{
ledRowOn(i, 255);
}
else
{
if (ledTransitionScale[transitionCounter[ledIndex]])
ledRowOn(i, ledTransitionScale[transitionCounter[ledIndex]]);
if (transitionCounter[ledIndex] != ledStateSingle)
{
//fade up
if (transitionCounter[ledIndex] < ledStateSingle)
{
transitionCounter[ledIndex] += pwmSteps;
if (transitionCounter[ledIndex] > ledStateSingle)
transitionCounter[ledIndex] = ledStateSingle;
}
else
{
//fade down
transitionCounter[ledIndex] -= pwmSteps;
if (transitionCounter[ledIndex] < 0)
transitionCounter[ledIndex] = 0;
}
}
}
#else
if (ledStateSingle)
ledRowOn(i);
#endif
}
if (++activeOutColumn == NUMBER_OF_LED_COLUMNS)
activeOutColumn = 0;
}
#elif defined(NUMBER_OF_OUT_SR)
///
/// \brief Checks if any LED state has been changed and writes changed state to output shift registers.
///
void checkDigitalOutputs()
{
if (updateOutputs)
{
CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
for (int j = 0; j < NUMBER_OF_OUT_SR; j++)
{
for (int i = 0; i < NUMBER_OF_OUT_SR_INPUTS; i++)
{
ledIndex = i + j * NUMBER_OF_OUT_SR_INPUTS;
ledState[ledIndex] ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);
CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
_NOP();
_NOP();
CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
}
}
CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
updateOutputs = false;
}
}
#else
void checkDigitalOutputs()
{
if (updateOutputs)
{
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
{
pin = Board::detail::map::led(i);
if (ledState[i])
EXT_LED_ON(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
else
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
updateOutputs = false;
}
}
#endif
} // namespace io
} // namespace detail
} // namespace Board<|endoftext|>
|
<commit_before>//===---- tools/extra/ToolTemplate.cpp - Template for refactoring tool ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements an empty refactoring tool using the clang tooling.
// The goal is to lower the "barrier to entry" for writing refactoring tools.
//
// Usage:
// tool-template <cmake-output-dir> <file1> <file2> ...
//
// Where <cmake-output-dir> is a CMake build directory in which a file named
// compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in
// CMake to get this output).
//
// <file1> ... specify the paths of files in the CMake source tree. This path
// is looked up in the compile command database. If the path of a file is
// absolute, it needs to point into CMake's source tree. If the path is
// relative, the current working directory needs to be in the CMake source
// tree and the file must be in a subdirectory of the current working
// directory. "./" prefixes in the relative files will be automatically
// removed, but the rest of a relative path must be a suffix of a path in
// the compile command line database.
//
// For example, to use tool-template on all files in a subtree of the
// source tree, use:
//
// /path/in/subtree $ find . -name '*.cpp'|
// xargs tool-template /path/to/build
//
//===----------------------------------------------------------------------===//
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/Lexer.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include <iostream>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
namespace {
class ToolTemplateCallback : public MatchFinder::MatchCallback {
public:
ToolTemplateCallback(Replacements *Replace) : Replace(Replace) {}
void run(const MatchFinder::MatchResult &Result) override {
// TODO: This routine will get called for each thing that the matchers find.
// At this point, you can examine the match, and do whatever you want,
// including replacing the matched text with other text
(void)Replace; // This to prevent an "unused member variable" warning;
auto tuDecl = Result.Context->getTranslationUnitDecl();
tuDecl->dump();
}
private:
Replacements *Replace;
};
class OdrASTConsumer : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(DeclGroupRef D) override {
llvm::outs() << __FUNCTION__ << "\n";
for (auto decl : D) {
decl->dump();
}
return true;
}
};
class ClangOdrCheckerFactory : public clang::ASTFrontendAction {
public:
std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override {
return llvm::make_unique<OdrASTConsumer>();
}
};
} // end anonymous namespace
// Set up the command line options
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ToolTemplateCategory("odr-check options");
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
auto FrontendFactory = newFrontendActionFactory<ClangOdrCheckerFactory>();
return Tool.run(FrontendFactory.get());
}
<commit_msg>Added initial implementation of checking two CXXRecordDecl objects.<commit_after>//===---- tools/extra/ToolTemplate.cpp - Template for refactoring tool ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements an empty refactoring tool using the clang tooling.
// The goal is to lower the "barrier to entry" for writing refactoring tools.
//
// Usage:
// tool-template <cmake-output-dir> <file1> <file2> ...
//
// Where <cmake-output-dir> is a CMake build directory in which a file named
// compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in
// CMake to get this output).
//
// <file1> ... specify the paths of files in the CMake source tree. This path
// is looked up in the compile command database. If the path of a file is
// absolute, it needs to point into CMake's source tree. If the path is
// relative, the current working directory needs to be in the CMake source
// tree and the file must be in a subdirectory of the current working
// directory. "./" prefixes in the relative files will be automatically
// removed, but the rest of a relative path must be a suffix of a path in
// the compile command line database.
//
// For example, to use tool-template on all files in a subtree of the
// source tree, use:
//
// /path/in/subtree $ find . -name '*.cpp'|
// xargs tool-template /path/to/build
//
//===----------------------------------------------------------------------===//
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Lex/Lexer.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Serialization/ASTWriter.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
namespace odr_check {
typedef std::vector<std::unique_ptr<ASTUnit>> ASTList;
class OdrCheckingStrategy {
public:
virtual bool Check(ASTList& ASTs) = 0;
};
class OdrCheckAction : public ToolAction {
public:
private:
ASTList ASTs;
public:
OdrCheckAction(){}
bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
DiagnosticConsumer *DiagConsumer) override {
std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Invocation, CompilerInstance::createDiagnostics(
&Invocation->getDiagnosticOpts(), DiagConsumer,
/*ShouldOwnClient=*/false));
if (!AST)
return false;
ASTs.push_back(std::move(AST));
return true;
}
ASTList& getASTList() {
return ASTs;
}
virtual std::unique_ptr<OdrCheckingStrategy> createOdrCheckingStrategy() = 0;
};
class OdrCheckTool : private ClangTool {
public:
OdrCheckTool(const CompilationDatabase &Compilations,
ArrayRef<std::string> SourcePaths)
: ClangTool(Compilations, SourcePaths) {
}
int runOdrCheck(OdrCheckAction *action) {
int Res = run(action);
if (Res != EXIT_SUCCESS) {
return Res;
}
auto CheckingStrategy = action->createOdrCheckingStrategy();
return CheckOdr(CheckingStrategy.get(), action->getASTList());
}
private:
int CheckOdr(OdrCheckingStrategy* CheckingStrategy, ASTList& ASTs) {
if (!CheckingStrategy->Check(ASTs)) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
};
class SimpleComparisonCheckingStrategy : public OdrCheckingStrategy {
public:
virtual bool Check(ASTList &ASTs) override {
for (auto& leftAstIt : ASTs) {
for (auto& rightAstIt : ASTs) {
if (leftAstIt != rightAstIt) {
if (!CheckOdrForAsts(*leftAstIt, *rightAstIt)) {
return EXIT_FAILURE;
}
}
}
}
return EXIT_SUCCESS;
}
private:
bool CheckOdrForAsts(ASTUnit& left, ASTUnit& right) const {
return false;
}
};
class FindCxxRecordDecl : public RecursiveASTVisitor<FindCxxRecordDecl>
{
public:
FindCxxRecordDecl(CXXRecordDecl* root, raw_ostream& out) : Root(root), Out(out) {
}
bool VisitCXXRecordDecl(CXXRecordDecl* D) {
if (D->getName() == Root->getName()) {
Out << "found decl with name [" << D->getName() << "]\n";
Out.flush();
}
return true;
}
private:
CXXRecordDecl* Root;
raw_ostream& Out;
};
class RootVisitor : public RecursiveASTVisitor<RootVisitor>
{
public:
RootVisitor(TranslationUnitDecl* other, raw_ostream& out): Other(other), Out(out) {
}
#if 0
bool VisitDecl(Decl *D) {
Out << "decl begin {\n";
Out.flush();
D->dump(Out);
Out.flush();
Out << "} cxx record end\n";
Out.flush();
return true;
}
#endif //0
bool VisitCXXRecordDecl(CXXRecordDecl* D) {
FindCxxRecordDecl other(D, Out);
return other.TraverseDecl(Other);
#if 0
Out << "cxx record begin {\n";
Out.flush();
D->dump(Out);
Out.flush();
Out << "} cxx record end\n";
Out.flush();
return true;
#endif //0
}
private:
TranslationUnitDecl* Other;
raw_ostream& Out;
};
class ASTMergingCheckingStrategy : public OdrCheckingStrategy {
public:
virtual bool Check(ASTList &ASTs) override {
if (ASTs.empty()) {
return true;
}
auto& rootAST = ASTs.front();
for (auto astIt = ASTs.begin() + 1; astIt != ASTs.end(); ++astIt) {
if (!MergeAsts(rootAST.get(), astIt->get())) {
return false;
}
}
return EXIT_SUCCESS;
}
private:
bool MergeAsts(ASTUnit* root, ASTUnit* other) const {
ASTContext& rootCtx = root->getASTContext();
ASTContext& otherCtx = other->getASTContext();
TranslationUnitDecl* rootTuDecl = rootCtx.getTranslationUnitDecl();
TranslationUnitDecl* otherTuDecl = otherCtx.getTranslationUnitDecl();
raw_ostream& out = outs();
out << "root\n";
out.flush();
rootTuDecl->dump(out);
out.flush();
out << "\nother\n";
out.flush();
otherTuDecl->dump();
out.flush();
out << "\nvisitor\n";
out.flush();
RootVisitor V(otherTuDecl, out);
V.TraverseDecl(rootTuDecl);
return false;
}
};
class MergeAstsAction : public OdrCheckAction {
public:
std::unique_ptr<OdrCheckingStrategy> createOdrCheckingStrategy() override {
return std::unique_ptr<OdrCheckingStrategy>(new ASTMergingCheckingStrategy);
}
};
} // odr_check namespace
using namespace odr_check;
// Set up the command line options
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ToolTemplateCategory("odr-check options");
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory);
OdrCheckTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
MergeAstsAction Action;
return Tool.runOdrCheck(&Action);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003-2007 Funambol
*
* This program is 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/Log.h"
#include "base/util/utils.h"
#define FUNAMBOL_HEADER "Funambol Windows Mobile Plug-in Log"
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static char logFullName[512] = "\\" LOG_NAME ;
static char logName[128] = LOG_NAME;
static char logPath[256] = "\\" ;
//-------------------------------------------------------------- Static Functions
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static char* createCurrentTime(BOOL complete) {
SYSTEMTIME sys_time;
TIME_ZONE_INFORMATION timezone;
GetLocalTime(&sys_time);
GetTimeZoneInformation(&timezone);
char fmtComplete[] = "%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d";
char fmt[] = "%02d:%02d:%02d GMT %c%d:%02d";
char* ret = new char [64];
// calculate offset from UTC/GMT in hours:min, positive value
// means east of Greenwich (e.g. CET = GMT +1)
char direction = timezone.Bias <= 0 ? '+' : '-';
int hours = abs(timezone.Bias / 60) ;
int minutes = abs(timezone.Bias % 60);
if (complete) {
sprintf(ret, fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
} else {
sprintf(ret, fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
}
return ret;
}
//------------------------------------------------------------------ Constructors
Log::Log(BOOL resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
if (resetLog) {
reset(FUNAMBOL_HEADER);
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
//---------------------------------------------------------------- Public methods
void Log::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
sprintf(logPath, "%s/", configLogPath);
} else {
sprintf(logPath, "%s", "./");
}
}
void Log::setLogName(const char* configLogName) {
if (configLogName != NULL) {
sprintf(logName, "%s", configLogName);
}
else {
sprintf(logName, "%s", LOG_NAME);
}
}
void Log::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void Log::info(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_INFO) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void Log::debug(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_DEBUG) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void Log::trace(const char* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const char* level, const char* msg, va_list argList) {
char* currentTime = createCurrentTime(false);
logFile = fopen(logFullName, "a+");
fprintf(logFile, "%s [%s] - ", currentTime, level);
vfprintf(logFile, msg, argList);
fprintf(logFile, "\n");
fclose(logFile);
delete[] currentTime;
}
void Log::reset(const char* title) {
const char *t = (title) ? title : FUNAMBOL_HEADER;
char* currentTime = createCurrentTime(true);
memset(logFullName, 0, 512*sizeof(char));
sprintf(logFullName, "%s%s", logPath, logName);
logFile = fopen(logFullName, "w+");
fprintf(logFile, "%s - %s\n", t, currentTime);
fclose(logFile);
delete[] currentTime;
}
<commit_msg>Code reformatted<commit_after>/*
* Copyright (C) 2003-2007 Funambol
*
* This program is 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.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/Log.h"
#include "base/util/utils.h"
#define FUNAMBOL_HEADER "Funambol Windows Mobile Plug-in Log"
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static char logFullName[512] = "\\" LOG_NAME ;
static char logName[128] = LOG_NAME;
static char logPath[256] = "\\" ;
//-------------------------------------------------------------- Static Functions
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static char* createCurrentTime(BOOL complete) {
SYSTEMTIME sys_time;
TIME_ZONE_INFORMATION timezone;
GetLocalTime(&sys_time);
GetTimeZoneInformation(&timezone);
char fmtComplete[] = "%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d";
char fmt[] = "%02d:%02d:%02d GMT %c%d:%02d";
char* ret = new char [64];
// calculate offset from UTC/GMT in hours:min, positive value
// means east of Greenwich (e.g. CET = GMT +1)
char direction = timezone.Bias <= 0 ? '+' : '-';
int hours = abs(timezone.Bias / 60) ;
int minutes = abs(timezone.Bias % 60);
if (complete) {
sprintf(ret, fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
} else {
sprintf(ret, fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
}
return ret;
}
//------------------------------------------------------------------ Constructors
Log::Log(BOOL resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
if (resetLog) {
reset(FUNAMBOL_HEADER);
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
//---------------------------------------------------------------- Public methods
void Log::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
sprintf(logPath, "%s/", configLogPath);
} else {
sprintf(logPath, "%s", "./");
}
}
void Log::setLogName(const char* configLogName) {
if (configLogName != NULL) {
sprintf(logName, "%s", configLogName);
}
else {
sprintf(logName, "%s", LOG_NAME);
}
}
void Log::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void Log::info(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_INFO) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void Log::debug(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_DEBUG) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void Log::trace(const char* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const char* level, const char* msg, va_list argList) {
char* currentTime = createCurrentTime(false);
logFile = fopen(logFullName, "a+");
fprintf(logFile, "%s [%s] - ", currentTime, level);
vfprintf(logFile, msg, argList);
fprintf(logFile, "\n");
fclose(logFile);
delete[] currentTime;
}
void Log::reset(const char* title) {
const char *t = (title) ? title : FUNAMBOL_HEADER;
char* currentTime = createCurrentTime(true);
memset(logFullName, 0, 512*sizeof(char));
sprintf(logFullName, "%s%s", logPath, logName);
logFile = fopen(logFullName, "w+");
fprintf(logFile, "%s - %s\n", t, currentTime);
fclose(logFile);
delete[] currentTime;
}
<|endoftext|>
|
<commit_before>//****************************************************************************//
// morphtargetmixer.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// 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. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/error.h"
#include "cal3d/morphtargetmixer.h"
#include "cal3d/mesh.h"
#include "cal3d/submesh.h"
#include "cal3d/coremesh.h"
#include "cal3d/coresubmesh.h"
/*****************************************************************************/
/** Constructs the morph target mixer instance.
*
* This function is the default constructor of the morph target mixer instance.
*****************************************************************************/
CalMorphTargetMixer::CalMorphTargetMixer()
: m_pMesh(0)
{
}
/*****************************************************************************/
/** Destructs the morph target mixer instance.
*
* This function is the destructor of the morph target mixer instance.
*****************************************************************************/
CalMorphTargetMixer::~CalMorphTargetMixer()
{
}
/*****************************************************************************/
/** Interpolates the weight of a morph target.
*
* This function interpolates the weight of a morph target a new value
* in a given amount of time.
*
* @param id The ID of the morph target that should be blended.
* @param weight The weight to interpolate the morph target to.
* @param delay The time in seconds until the new weight should be reached.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::blend(int id, float weight, float delay)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
float currentWeight = 1.0f - m_vectorCurrentWeight[id];
float endWeight = 1.0f - weight;
if(currentWeight != 0.0f)
{
float factor = endWeight/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = endWeight/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_vectorEndWeight[id] = weight;
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Interpolates the weight of the base vertices.
*
* This function interpolates the weight of the base vertices a new value
* in a given amount of time.
*
* @param weight The weight to interpolate the base vertices to.
* @param delay The time in seconds until the new weight should be reached.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::blendBase(float weight, float delay)
{
float currentWeight = 0.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight +=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
float endWeight = 1.0f - weight;
if(currentWeight != 0.0f)
{
float factor = endWeight/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = endWeight/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Fades a morph target out.
*
* This function fades a morph target out in a given amount of time.
*
* @param id The ID of the morph target that should be faded out.
* @param delay The time in seconds until the the morph target is
* completely removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::clear(int id, float delay)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
float currentWeight = 1.0f - m_vectorCurrentWeight[id];
if(currentWeight != 0.0f)
{
float factor = 1.0f/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = 1.0f/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_vectorEndWeight[id] = 0.0f;
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Fades the base vertices out.
*
* This function fades the base vertices out in a given amount of time.
*
* @param delay The time in seconds until the the base vertices is
* completely removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::clearBase(float delay)
{
float currentWeight = 0.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight +=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
if(currentWeight != 0.0f)
{
float factor = 1.0f/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = 1.0f/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Get the weight of a morph target.
*
* @param id The id of the morph target which weight you want.
*
* @return The weight of the morph target with the given id.
*****************************************************************************/
float CalMorphTargetMixer::getCurrentWeight(int id)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
return m_vectorCurrentWeight[id];
}
/*****************************************************************************/
/** Get the weight of the base vertices.
*
* @return The weight of the base vertices.
*****************************************************************************/
float CalMorphTargetMixer::getCurrentWeightBase()
{
float currentWeight = 1.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight -=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
return currentWeight;
}
/*****************************************************************************/
/** Creates the morph target mixer instance.
*
* This function creates the mixer instance.
*
* @param pMesh A pointer to the mesh that should be managed with this
* morph target mixer instance.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::create(CalMesh *pMesh)
{
if(pMesh == 0)
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
m_pMesh = pMesh;
CalCoreSubmesh *coreSubmesh = pMesh->getCoreMesh()->getCoreSubmesh(0);
if (coreSubmesh == 0)
{
CalError::setLastError(CalError::INTERNAL, __FILE__, __LINE__);//HMMM
return false;
}
int subMorphTargetCount = coreSubmesh->getCoreSubMorphTargetCount();
// reserve the space needed in all the vectors
m_vectorCurrentWeight.reserve(subMorphTargetCount);
m_vectorCurrentWeight.resize(subMorphTargetCount);
m_vectorEndWeight.reserve(subMorphTargetCount);
m_vectorEndWeight.resize(subMorphTargetCount);
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) = 0.0f;
(*iteratorEndWeight) = 0.0f;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
m_duration = 0.0f;
return true;
}
/*****************************************************************************/
/** Destroys the morph target mixer instance.
*
* This function destroys all data stored in the mixer instance and frees all
* allocated memory.
*****************************************************************************/
void CalMorphTargetMixer::destroy()
{
m_pMesh = 0;
}
/*****************************************************************************/
/** Updates all morph targets.
*
* This function updates all morph targets of the mixer instance for a
* given amount of time.
*
* @param deltaTime The elapsed time in seconds since the last update.
*****************************************************************************/
void CalMorphTargetMixer::update(float deltaTime)
{
if(deltaTime >= m_duration)
{
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) = (*iteratorEndWeight);
++iteratorCurrentWeight;
++iteratorEndWeight;
}
m_duration = 0.0f;
}
else
{
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) += ((*iteratorEndWeight)-(*iteratorCurrentWeight))*deltaTime/m_duration;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
m_duration -= deltaTime;
}
std::vector<CalSubmesh *> &vectorSubmesh = m_pMesh->getVectorSubmesh();
int morphTargetCount = m_vectorCurrentWeight.size();
int submeshCount = vectorSubmesh.size();
int submeshId;
for(submeshId=0;submeshId<submeshCount;++submeshId)
{
int morphTargetId;
for(morphTargetId=0;morphTargetId<morphTargetCount;++morphTargetId)
{
vectorSubmesh[submeshId]->setMorphTargetWeight(morphTargetId,m_vectorCurrentWeight[morphTargetId]);
}
}
}
/*****************************************************************************/
/** Returns the number of morph targets this morph target mixer mixes.
*
* @return The number of morph targets this morph target mixer mixes.
*****************************************************************************/
int CalMorphTargetMixer::getMorphTargetCount()
{
return m_vectorCurrentWeight.size();
}
//****************************************************************************//
<commit_msg>Made the code a bit more robust.<commit_after>//****************************************************************************//
// morphtargetmixer.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// 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. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/error.h"
#include "cal3d/morphtargetmixer.h"
#include "cal3d/mesh.h"
#include "cal3d/submesh.h"
#include "cal3d/coremesh.h"
#include "cal3d/coresubmesh.h"
/*****************************************************************************/
/** Constructs the morph target mixer instance.
*
* This function is the default constructor of the morph target mixer instance.
*****************************************************************************/
CalMorphTargetMixer::CalMorphTargetMixer()
: m_pMesh(0)
{
}
/*****************************************************************************/
/** Destructs the morph target mixer instance.
*
* This function is the destructor of the morph target mixer instance.
*****************************************************************************/
CalMorphTargetMixer::~CalMorphTargetMixer()
{
}
/*****************************************************************************/
/** Interpolates the weight of a morph target.
*
* This function interpolates the weight of a morph target a new value
* in a given amount of time.
*
* @param id The ID of the morph target that should be blended.
* @param weight The weight to interpolate the morph target to.
* @param delay The time in seconds until the new weight should be reached.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::blend(int id, float weight, float delay)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
float currentWeight = 1.0f - m_vectorCurrentWeight[id];
float endWeight = 1.0f - weight;
if(currentWeight != 0.0f)
{
float factor = endWeight/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = endWeight/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_vectorEndWeight[id] = weight;
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Interpolates the weight of the base vertices.
*
* This function interpolates the weight of the base vertices a new value
* in a given amount of time.
*
* @param weight The weight to interpolate the base vertices to.
* @param delay The time in seconds until the new weight should be reached.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::blendBase(float weight, float delay)
{
float currentWeight = 0.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight +=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
float endWeight = 1.0f - weight;
if(currentWeight != 0.0f)
{
float factor = endWeight/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = endWeight/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Fades a morph target out.
*
* This function fades a morph target out in a given amount of time.
*
* @param id The ID of the morph target that should be faded out.
* @param delay The time in seconds until the the morph target is
* completely removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::clear(int id, float delay)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
float currentWeight = 1.0f - m_vectorCurrentWeight[id];
if(currentWeight != 0.0f)
{
float factor = 1.0f/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = 1.0f/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_vectorEndWeight[id] = 0.0f;
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Fades the base vertices out.
*
* This function fades the base vertices out in a given amount of time.
*
* @param delay The time in seconds until the the base vertices is
* completely removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::clearBase(float delay)
{
float currentWeight = 0.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight +=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
if(currentWeight != 0.0f)
{
float factor = 1.0f/currentWeight;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorEndWeight) = (*iteratorCurrentWeight)*factor;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
else
{
float factor = 1.0f/((float)m_vectorEndWeight.size());
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorEndWeight!=m_vectorEndWeight.end())
{
(*iteratorEndWeight) = factor;
++iteratorEndWeight;
}
}
m_duration = delay;
return true;
}
/*****************************************************************************/
/** Get the weight of a morph target.
*
* @param id The id of the morph target which weight you want.
*
* @return The weight of the morph target with the given id.
*****************************************************************************/
float CalMorphTargetMixer::getCurrentWeight(int id)
{
if((id < 0) || (id >= (int)m_vectorCurrentWeight.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
return m_vectorCurrentWeight[id];
}
/*****************************************************************************/
/** Get the weight of the base vertices.
*
* @return The weight of the base vertices.
*****************************************************************************/
float CalMorphTargetMixer::getCurrentWeightBase()
{
float currentWeight = 1.0f;
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
currentWeight -=(*iteratorCurrentWeight);
++iteratorCurrentWeight;
}
return currentWeight;
}
/*****************************************************************************/
/** Creates the morph target mixer instance.
*
* This function creates the mixer instance.
*
* @param pMesh A pointer to the mesh that should be managed with this
* morph target mixer instance.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMorphTargetMixer::create(CalMesh *pMesh)
{
if(pMesh == 0)
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
m_pMesh = pMesh;
if(pMesh->getCoreMesh()->getCoreSubmeshCount() != 0)
{
CalCoreSubmesh *coreSubmesh = pMesh->getCoreMesh()->getCoreSubmesh(0);
if (coreSubmesh == 0)
{
CalError::setLastError(CalError::INTERNAL, __FILE__, __LINE__);//HMMM
return false;
}
int subMorphTargetCount = coreSubmesh->getCoreSubMorphTargetCount();
// reserve the space needed in all the vectors
m_vectorCurrentWeight.reserve(subMorphTargetCount);
m_vectorCurrentWeight.resize(subMorphTargetCount);
m_vectorEndWeight.reserve(subMorphTargetCount);
m_vectorEndWeight.resize(subMorphTargetCount);
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) = 0.0f;
(*iteratorEndWeight) = 0.0f;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
}
m_duration = 0.0f;
return true;
}
/*****************************************************************************/
/** Destroys the morph target mixer instance.
*
* This function destroys all data stored in the mixer instance and frees all
* allocated memory.
*****************************************************************************/
void CalMorphTargetMixer::destroy()
{
m_pMesh = 0;
}
/*****************************************************************************/
/** Updates all morph targets.
*
* This function updates all morph targets of the mixer instance for a
* given amount of time.
*
* @param deltaTime The elapsed time in seconds since the last update.
*****************************************************************************/
void CalMorphTargetMixer::update(float deltaTime)
{
if(deltaTime >= m_duration)
{
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) = (*iteratorEndWeight);
++iteratorCurrentWeight;
++iteratorEndWeight;
}
m_duration = 0.0f;
}
else
{
std::vector<float>::iterator iteratorCurrentWeight = m_vectorCurrentWeight.begin();
std::vector<float>::iterator iteratorEndWeight = m_vectorEndWeight.begin();
while(iteratorCurrentWeight!=m_vectorCurrentWeight.end())
{
(*iteratorCurrentWeight) += ((*iteratorEndWeight)-(*iteratorCurrentWeight))*deltaTime/m_duration;
++iteratorCurrentWeight;
++iteratorEndWeight;
}
m_duration -= deltaTime;
}
std::vector<CalSubmesh *> &vectorSubmesh = m_pMesh->getVectorSubmesh();
int morphTargetCount = m_vectorCurrentWeight.size();
int submeshCount = vectorSubmesh.size();
int submeshId;
for(submeshId=0;submeshId<submeshCount;++submeshId)
{
int morphTargetId;
for(morphTargetId=0;morphTargetId<morphTargetCount;++morphTargetId)
{
vectorSubmesh[submeshId]->setMorphTargetWeight(morphTargetId,m_vectorCurrentWeight[morphTargetId]);
}
}
}
/*****************************************************************************/
/** Returns the number of morph targets this morph target mixer mixes.
*
* @return The number of morph targets this morph target mixer mixes.
*****************************************************************************/
int CalMorphTargetMixer::getMorphTargetCount()
{
return m_vectorCurrentWeight.size();
}
//****************************************************************************//
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------------
** This software is implemented as part of the course Dynamic Algorithms
** (Q4 2015) at Aarhus Univerity Denmark.
**
** TD_EAGER.cpp
** Implementation of a truly dynamic algorithm for dynamic transitive closure
** based on Shankowsis randomized reduction of dynamic transitive closure to dynamic matrix adjoint.
**
** Author: Martin Storgaard and Konstantinos Mampentzidis
** -------------------------------------------------------------------------*/
#include "TD_EAGER.h"
using namespace std;
void TD_EAGER::init(int n) {
//initialize the adjacency matrix where we will store all the edges that are part of the graph
//we need it in case our randomized algorithm fails (division by zero) to be able to reconstruct
//the
if(adjacency_matrix != NULL) delete[] adjacency_matrix;
this->n = n;
adjacency_matrix = new uint32_t[n*n];
memset(adjacency_matrix, 0, n*n*sizeof(uint32_t));
//initialize the inverse matrix to be I-A, A is zero at first at the moment so I-A = I.
inverse_matrix = new uint32_t[n*n];
memset(inverse_matrix, 0, n*n*sizeof(uint32_t));
for(int i=0;i<n;i++) {
inverse_matrix[i*n + i] = 1;
adjacency_matrix[i*n + i] = 1;
}
//initialize the counter to be 0 since no edges are part of the transitive closure within a graph with 0
//edges.
count = 0;
}
void TD_EAGER::updateInverseMatrix(int i, int j, uint32_t u)
{
uint32_t v = 1;
int k,m;
//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
uint32_t *a = new uint32_t[n];
for(k=0;k<n;k++)
a[k] = mod_mul(inverse_matrix[k*n+i],u);
//find (v^T*A^(-1)) => pick j-th row of A^(-1) and multiply every value by v
uint32_t *b = new uint32_t[n];
for(k=0;k<n;k++)
b[k] = mod_mul(inverse_matrix[j*n+k],v);
//find v^T*A^(-1)*u
uint32_t c = 0;
for(k=0;k<n;k++)
c = mod_add(c, mod_mul(a[k],b[k]));
//find the denominator of sherman morisson formula
uint32_t d = mod_add(c,1);
if(d == 0){
std::cout<<"Division by zero!!!!!!!!"<<std::endl;
exit(1);
}
//find the nominator of sherman morisson formula and divide with the denominator at the same time.
uint32_t *e = new uint32_t[n*n];
for(k=0;k<n;k++)
for(m=0;m<n;m++)
e[k*n+m] = mod_mul(mod_inv(d),mod_mul(a[k],b[m]));
//update the inverse matrix and counter
count = 0;
for(k=0;k<n;k++){
for(m=0;m<n;m++){
int index = k*n+m;
inverse_matrix[index] = mod_sub(inverse_matrix[index], e[index]);
if(inverse_matrix[index]!=0) count++;
}
}
delete[] a;
delete[] b;
delete[] e;
}
void TD_EAGER::ins(int i, int j) {
uint32_t v = next();
adjacency_matrix[i*n + j] = v;
updateInverseMatrix(i,j, v);
/*cout << "INSERT" << endl;
printMatrix(adjacency_matrix, n);
printMatrix(inverse_matrix, n);
cout << endl << endl;*/
}
void TD_EAGER::del(int i, int j) {
updateInverseMatrix(i, j, (uint32_t) (P - adjacency_matrix[i*n + j]));
adjacency_matrix[i*n + j] = 0;
cout << "DELETE" << endl;
printMatrix(adjacency_matrix, n);
printMatrix(inverse_matrix, n);
cout << endl << endl;
}
unsigned int TD_EAGER::query() {
return count;
}
<commit_msg>attempt to fix delete function<commit_after>/* ---------------------------------------------------------------------------
** This software is implemented as part of the course Dynamic Algorithms
** (Q4 2015) at Aarhus Univerity Denmark.
**
** TD_EAGER.cpp
** Implementation of a truly dynamic algorithm for dynamic transitive closure
** based on Shankowsis randomized reduction of dynamic transitive closure to dynamic matrix adjoint.
**
** Author: Martin Storgaard and Konstantinos Mampentzidis
** -------------------------------------------------------------------------*/
#include "TD_EAGER.h"
using namespace std;
void TD_EAGER::init(int n) {
//initialize the adjacency matrix where we will store all the edges that are part of the graph
//we need it in case our randomized algorithm fails (division by zero) to be able to reconstruct
//the
if(adjacency_matrix != NULL) delete[] adjacency_matrix;
this->n = n;
adjacency_matrix = new uint32_t[n*n];
memset(adjacency_matrix, 0, n*n*sizeof(uint32_t));
//initialize the inverse matrix to be I-A, A is zero at first at the moment so I-A = I.
inverse_matrix = new uint32_t[n*n];
memset(inverse_matrix, 0, n*n*sizeof(uint32_t));
for(int i=0;i<n;i++) {
inverse_matrix[i*n + i] = 1;
adjacency_matrix[i*n + i] = 1;
}
//initialize the counter to be 0 since no edges are part of the transitive closure within a graph with 0
//edges.
count = 0;
}
void TD_EAGER::updateInverseMatrix(int i, int j, uint32_t u)
{
uint32_t v = 1;
int k,m;
//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
uint32_t *a = new uint32_t[n];
for(k=0;k<n;k++)
a[k] = mod_mul(inverse_matrix[k*n+i],u);
//find (v^T*A^(-1)) => pick j-th row of A^(-1) and multiply every value by v
uint32_t *b = new uint32_t[n];
for(k=0;k<n;k++)
b[k] = mod_mul(inverse_matrix[j*n+k],v);
//find v^T*A^(-1)*u
uint32_t c = 0;
for(k=0;k<n;k++)
c = mod_add(c, mod_mul(a[k],b[k]));
//find the denominator of sherman morisson formula
uint32_t d = mod_add(c,1);
if(d == 0){
std::cout<<"Division by zero!!!!!!!!"<<std::endl;
exit(1);
}
//find the nominator of sherman morisson formula and divide with the denominator at the same time.
uint32_t *e = new uint32_t[n*n];
for(k=0;k<n;k++)
for(m=0;m<n;m++)
e[k*n+m] = mod_mul(mod_inv(d),mod_mul(a[k],b[m]));
//update the inverse matrix and counter
count = 0;
for(k=0;k<n;k++){
for(m=0;m<n;m++){
int index = k*n+m;
inverse_matrix[index] = mod_sub(inverse_matrix[index], e[index]);
if(inverse_matrix[index]!=0) count++;
}
}
delete[] a;
delete[] b;
delete[] e;
}
void TD_EAGER::ins(int i, int j) {
uint32_t u = next();
adjacency_matrix[i*n + j] = u;
//update the inverse matrix
uint32_t v = 1;
int k,m;
//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
uint32_t *a = new uint32_t[n];
for(k=0;k<n;k++)
a[k] = mod_mul(inverse_matrix[k*n+i],u);
//find (v^T*A^(-1)) => pick j-th row of A^(-1) and multiply every value by v
uint32_t *b = new uint32_t[n];
for(k=0;k<n;k++)
b[k] = mod_mul(inverse_matrix[j*n+k],v);
//find v^T*A^(-1)*u
uint32_t c = 0;
for(k=0;k<n;k++)
c = mod_add(c, mod_mul(a[k],b[k]));
//find the denominator of sherman morisson formula
uint32_t d = mod_add(c,1);
if(d == 0){
std::cout<<"Division by zero!!!!!!!!"<<std::endl;
exit(1);
}
//find the nominator of sherman morisson formula and divide with the denominator at the same time.
uint32_t *e = new uint32_t[n*n];
for(k=0;k<n;k++)
for(m=0;m<n;m++)
e[k*n+m] = mod_mul(mod_inv(d),mod_mul(a[k],b[m]));
//update the inverse matrix and counter
count = 0;
for(k=0;k<n;k++){
for(m=0;m<n;m++){
int index = k*n+m;
inverse_matrix[index] = mod_sub(inverse_matrix[index], e[index]);
if(inverse_matrix[index]!=0) count++;
}
}
delete[] a;
delete[] b;
delete[] e;
/*cout << "INSERT" << endl;
printMatrix(adjacency_matrix, n);
printMatrix(inverse_matrix, n);
cout << endl << endl;*/
}
void TD_EAGER::del(int i, int j) {
//update inverse matrix
uint32_t u = adjacency_matrix[i*n + j];
adjacency_matrix[i*n + j] = 0;
//update the inverse matrix
uint32_t v = 1;
int k,m;
//find (A^(-1)*u) => pick i-th column of A^(-1) and multiply every value by u
uint32_t *a = new uint32_t[n];
for(k=0;k<n;k++)
a[k] = mod_mul(inverse_matrix[k*n+i],u);
//find (v^T*A^(-1)) => pick j-th row of A^(-1) and multiply every value by v
uint32_t *b = new uint32_t[n];
for(k=0;k<n;k++)
b[k] = mod_mul(inverse_matrix[j*n+k],v);
//find v^T*A^(-1)*u
uint32_t c = 0;
for(k=0;k<n;k++)
c = mod_add(c, mod_mul(a[k],b[k]));
//find the denominator of sherman morisson formula
uint32_t d = mod_sub(1,c);
if(d == 0){
std::cout<<"Division by zero!!!!!!!!"<<std::endl;
exit(1);
}
//find the nominator of sherman morisson formula and divide with the denominator at the same time.
uint32_t *e = new uint32_t[n*n];
for(k=0;k<n;k++)
for(m=0;m<n;m++)
e[k*n+m] = mod_mul(mod_inv(d),mod_mul(a[k],b[m]));
//update the inverse matrix and counter
count = 0;
for(k=0;k<n;k++){
for(m=0;m<n;m++){
int index = k*n+m;
inverse_matrix[index] = mod_add(inverse_matrix[index], e[index]);
if(inverse_matrix[index]!=0) count++;
}
}
delete[] a;
delete[] b;
delete[] e;
/*cout << "DELETE" << endl;
printMatrix(adjacency_matrix, n);
printMatrix(inverse_matrix, n);
cout << endl << endl;*/
}
unsigned int TD_EAGER::query() {
return count;
}
<|endoftext|>
|
<commit_before>#include "Expression.hpp"
#include "gtest/gtest.h"
TEST(LMCh04Ex05, DISABLED_willAddNumbers)
{
auto expression = lm::Expression("1.0 + 2.0");
ASSERT_DOUBLE_EQ(3.0, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willSubtractNumbers)
{
auto expression = lm::Expression("3.1 - 5.3");
ASSERT_DOUBLE_EQ(-2.2, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willMultiplyNumbers)
{
auto expression = lm::Expression("20.1 * -0.128");
ASSERT_DOUBLE_EQ(-2.5728, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willDivideNumbers)
{
auto expression = lm::Expression("128.0 / 64.0");
ASSERT_DOUBLE_EQ(2.0, expression.getResult());
}
TEST(LMCh04Ex05, willThrowExceptionOnUnknownOp)
{
std::cout << "start test" << std::endl;
auto expression = lm::Expression("12.0 ^ 14.1");
std::cout << "before throw" << std::endl;
ASSERT_THROW(expression.getResult(), std::runtime_error);
std::cout << "after throw" << std::endl;
}
<commit_msg>travis test<commit_after>#include "Expression.hpp"
#include "gtest/gtest.h"
TEST(LMCh04Ex05, DISABLED_willAddNumbers)
{
auto expression = lm::Expression("1.0 + 2.0");
ASSERT_DOUBLE_EQ(3.0, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willSubtractNumbers)
{
auto expression = lm::Expression("3.1 - 5.3");
ASSERT_DOUBLE_EQ(-2.2, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willMultiplyNumbers)
{
auto expression = lm::Expression("20.1 * -0.128");
ASSERT_DOUBLE_EQ(-2.5728, expression.getResult());
}
TEST(LMCh04Ex05, DISABLED_willDivideNumbers)
{
auto expression = lm::Expression("128.0 / 64.0");
ASSERT_DOUBLE_EQ(2.0, expression.getResult());
}
TEST(LMCh04Ex05, willThrowExceptionOnUnknownOp)
{
std::cout << "start test" << std::endl;
std::string input{"12.0 ^ 14.1"};
auto expression = lm::Expression(input);
std::cout << "before throw" << std::endl;
ASSERT_THROW(expression.getResult(), std::runtime_error);
std::cout << "after throw" << std::endl;
}
<|endoftext|>
|
<commit_before>#include "Triangle.h"
void Triangle::Move(uint16_t dirX, uint16_t dirY)
{
{
lastX = X;
lastY = Y;
X += dirX;
X += dirY;
HasMoved = true;
}
}
void Triangle::Update()
{
}
void Triangle::Render(Adafruit_ST7735 *tftDisplay, boolean clear)
{
/* In this method we only draw the rectangle if it has moved.
* We also only clear where the last triangle was instead of the whole frame,
* this is is because it is slow to write to the display, so we have to keep it to the minimum.
*/
if (!HasMoved) return;
/* Clear old triangle */
if (clear) Clear(tftDisplay);
/* Draw new triangle */
DrawTriangle(tftDisplay);
/* Set back the HasMoved flag because it has now been drawn.*/
lastX = X;
lastY = Y;
PrevDirection = Direction;
HasMoved = false;
}
void Triangle::Clear(Adafruit_ST7735 *tftDisplay)
{
// I'm using rectangle to fill so that I don't have to calculate diagonal lines.
tftDisplay->fillRect(lastX -1, lastY -1, Width + 4, Height + 4, ClearColor);
}
void Triangle::DrawTriangle(Adafruit_ST7735 *tftDisplay)
{
switch (Direction)
{
case GLB_LEFT:
tftDisplay->fillTriangle(X, Y, X, Y + Height, X + Width, Y + Height / 2 , Color);
break;
case GLB_RIGHT:
tftDisplay->fillTriangle(X, Y + Height / 2, X + Width, Y + Height, X + Width, Y, Color);
break;
case GLB_UP:
tftDisplay->fillTriangle(X, Y, X + Width / 2, Y + Height, X + Width, Y, Color);
break;
case GLB_DOWN:
tftDisplay->fillTriangle(X, Y + Height, X + Width / 2, Y, X + Width, Y + Height, Color);
break;
default:
break;
}
}
<commit_msg>fixed wrong draw direction on triangle<commit_after>#include "Triangle.h"
void Triangle::Move(uint16_t dirX, uint16_t dirY)
{
{
lastX = X;
lastY = Y;
X += dirX;
X += dirY;
HasMoved = true;
}
}
void Triangle::Update()
{
}
void Triangle::Render(Adafruit_ST7735 *tftDisplay, boolean clear)
{
/* In this method we only draw the rectangle if it has moved.
* We also only clear where the last triangle was instead of the whole frame,
* this is is because it is slow to write to the display, so we have to keep it to the minimum.
*/
if (!HasMoved) return;
/* Clear old triangle */
if (clear) Clear(tftDisplay);
/* Draw new triangle */
DrawTriangle(tftDisplay);
/* Set back the HasMoved flag because it has now been drawn.*/
lastX = X;
lastY = Y;
PrevDirection = Direction;
HasMoved = false;
}
void Triangle::Clear(Adafruit_ST7735 *tftDisplay)
{
// I'm using rectangle to fill so that I don't have to calculate diagonal lines.
tftDisplay->fillRect(lastX -1, lastY -1, Width + 4, Height + 4, ClearColor);
}
void Triangle::DrawTriangle(Adafruit_ST7735 *tftDisplay)
{
switch (Direction)
{
case GLB_LEFT:
tftDisplay->fillTriangle(X, Y, X, Y + Height, X + Width, Y + Height / 2 , Color);
break;
case GLB_RIGHT:
tftDisplay->fillTriangle(X, Y + Height / 2, X + Width, Y + Height, X + Width, Y, Color);
break;
case GLB_DOWN:
tftDisplay->fillTriangle(X, Y, X + Width / 2, Y + Height, X + Width, Y, Color);
break;
case GLB_UP:
tftDisplay->fillTriangle(X, Y + Height, X + Width / 2, Y, X + Width, Y + Height, Color);
break;
default:
break;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006, 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.
// macho_walker.cc: Iterate over the load commands in a mach-o file
//
// See macho_walker.h for documentation
//
// Author: Dan Waylonis
#include <assert.h>
#include <fcntl.h>
#include <mach-o/arch.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#include <string.h>
#include <unistd.h>
#include "common/mac/macho_walker.h"
#include "common/mac/macho_utilities.h"
namespace MacFileUtilities {
MachoWalker::MachoWalker(const char *path, LoadCommandCallback callback,
void *context)
: callback_(callback),
callback_context_(context) {
file_ = open(path, O_RDONLY);
}
MachoWalker::~MachoWalker() {
if (file_ != -1)
close(file_);
}
int MachoWalker::ValidateCPUType(int cpu_type) {
// If the user didn't specify, try to use the local architecture. If that
// fails, use the base type for the executable.
if (cpu_type == 0) {
const NXArchInfo *arch = NXGetLocalArchInfo();
if (arch)
cpu_type = arch->cputype;
else
#if __ppc__
cpu_type = CPU_TYPE_POWERPC;
#elif __i386__
cpu_type = CPU_TYPE_X86;
#else
#error Unknown architecture -- are you on a PDP-11?
#endif
}
return cpu_type;
}
bool MachoWalker::WalkHeader(int cpu_type) {
int valid_cpu_type = ValidateCPUType(cpu_type);
off_t offset;
if (FindHeader(valid_cpu_type, offset)) {
if (cpu_type & CPU_ARCH_ABI64)
return WalkHeader64AtOffset(offset);
return WalkHeaderAtOffset(offset);
}
return false;
}
bool MachoWalker::ReadBytes(void *buffer, size_t size, off_t offset) {
return pread(file_, buffer, size, offset) == (ssize_t)size;
}
bool MachoWalker::CurrentHeader(struct mach_header_64 *header, off_t *offset) {
if (current_header_) {
memcpy(header, current_header_, sizeof(mach_header_64));
*offset = current_header_offset_;
return true;
}
return false;
}
bool MachoWalker::FindHeader(int cpu_type, off_t &offset) {
int valid_cpu_type = ValidateCPUType(cpu_type);
// Read the magic bytes that's common amongst all mach-o files
uint32_t magic;
if (!ReadBytes(&magic, sizeof(magic), 0))
return false;
offset = sizeof(magic);
// Figure out what type of file we've got
bool is_fat = false;
if (magic == FAT_MAGIC || magic == FAT_CIGAM) {
is_fat = true;
}
else if (magic != MH_MAGIC && magic != MH_CIGAM && magic != MH_MAGIC_64 &&
magic != MH_CIGAM_64) {
return false;
}
if (!is_fat) {
// If we don't have a fat header, check if the cpu type matches the single
// header
cpu_type_t header_cpu_type;
if (!ReadBytes(&header_cpu_type, sizeof(header_cpu_type), offset))
return false;
if (magic == MH_CIGAM || magic == MH_CIGAM_64)
header_cpu_type = NXSwapInt(header_cpu_type);
if (valid_cpu_type != header_cpu_type)
return false;
offset = 0;
return true;
} else {
// Read the fat header and find an appropriate architecture
offset = 0;
struct fat_header fat;
if (!ReadBytes(&fat, sizeof(fat), offset))
return false;
if (NXHostByteOrder() != NX_BigEndian)
swap_fat_header(&fat, NXHostByteOrder());
offset += sizeof(fat);
// Search each architecture for the desired one
struct fat_arch arch;
for (uint32_t i = 0; i < fat.nfat_arch; ++i) {
if (!ReadBytes(&arch, sizeof(arch), offset))
return false;
if (NXHostByteOrder() != NX_BigEndian)
swap_fat_arch(&arch, 1, NXHostByteOrder());
if (arch.cputype == valid_cpu_type) {
offset = arch.offset;
return true;
}
offset += sizeof(arch);
}
}
return false;
}
bool MachoWalker::WalkHeaderAtOffset(off_t offset) {
struct mach_header header;
if (!ReadBytes(&header, sizeof(header), offset))
return false;
bool swap = (header.magic == MH_CIGAM);
if (swap)
swap_mach_header(&header, NXHostByteOrder());
// Copy the data into the mach_header_64 structure. Since the 32-bit and
// 64-bit only differ in the last field (reserved), this is safe to do.
struct mach_header_64 header64;
memcpy((void *)&header64, (const void *)&header, sizeof(header));
header64.reserved = 0;
current_header_ = &header64;
current_header_size_ = sizeof(header); // 32-bit, not 64-bit
current_header_offset_ = offset;
offset += current_header_size_;
bool result = WalkHeaderCore(offset, header.ncmds, swap);
current_header_ = NULL;
current_header_size_ = 0;
current_header_offset_ = 0;
return result;
}
bool MachoWalker::WalkHeader64AtOffset(off_t offset) {
struct mach_header_64 header;
if (!ReadBytes(&header, sizeof(header), offset))
return false;
bool swap = (header.magic == MH_CIGAM_64);
if (swap)
breakpad_swap_mach_header_64(&header, NXHostByteOrder());
current_header_ = &header;
current_header_size_ = sizeof(header);
current_header_offset_ = offset;
offset += current_header_size_;
bool result = WalkHeaderCore(offset, header.ncmds, swap);
current_header_ = NULL;
current_header_size_ = 0;
current_header_offset_ = 0;
return result;
}
bool MachoWalker::WalkHeaderCore(off_t offset, uint32_t number_of_commands,
bool swap) {
for (uint32_t i = 0; i < number_of_commands; ++i) {
struct load_command cmd;
if (!ReadBytes(&cmd, sizeof(cmd), offset))
return false;
if (swap)
swap_load_command(&cmd, NXHostByteOrder());
// Call the user callback
if (callback_ && !callback_(this, &cmd, offset, swap, callback_context_))
break;
offset += cmd.cmdsize;
}
return true;
}
} // namespace MacFileUtilities
<commit_msg>Issue 197: reviewed by Waylonis<commit_after>// Copyright (c) 2006, 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.
// macho_walker.cc: Iterate over the load commands in a mach-o file
//
// See macho_walker.h for documentation
//
// Author: Dan Waylonis
extern "C" { // necessary for Leopard
#include <assert.h>
#include <fcntl.h>
#include <mach-o/arch.h>
#include <mach-o/loader.h>
#include <mach-o/swap.h>
#include <string.h>
#include <unistd.h>
}
#include "common/mac/macho_walker.h"
#include "common/mac/macho_utilities.h"
namespace MacFileUtilities {
MachoWalker::MachoWalker(const char *path, LoadCommandCallback callback,
void *context)
: callback_(callback),
callback_context_(context) {
file_ = open(path, O_RDONLY);
}
MachoWalker::~MachoWalker() {
if (file_ != -1)
close(file_);
}
int MachoWalker::ValidateCPUType(int cpu_type) {
// If the user didn't specify, try to use the local architecture. If that
// fails, use the base type for the executable.
if (cpu_type == 0) {
const NXArchInfo *arch = NXGetLocalArchInfo();
if (arch)
cpu_type = arch->cputype;
else
#if __ppc__
cpu_type = CPU_TYPE_POWERPC;
#elif __i386__
cpu_type = CPU_TYPE_X86;
#else
#error Unknown architecture -- are you on a PDP-11?
#endif
}
return cpu_type;
}
bool MachoWalker::WalkHeader(int cpu_type) {
int valid_cpu_type = ValidateCPUType(cpu_type);
off_t offset;
if (FindHeader(valid_cpu_type, offset)) {
if (cpu_type & CPU_ARCH_ABI64)
return WalkHeader64AtOffset(offset);
return WalkHeaderAtOffset(offset);
}
return false;
}
bool MachoWalker::ReadBytes(void *buffer, size_t size, off_t offset) {
return pread(file_, buffer, size, offset) == (ssize_t)size;
}
bool MachoWalker::CurrentHeader(struct mach_header_64 *header, off_t *offset) {
if (current_header_) {
memcpy(header, current_header_, sizeof(mach_header_64));
*offset = current_header_offset_;
return true;
}
return false;
}
bool MachoWalker::FindHeader(int cpu_type, off_t &offset) {
int valid_cpu_type = ValidateCPUType(cpu_type);
// Read the magic bytes that's common amongst all mach-o files
uint32_t magic;
if (!ReadBytes(&magic, sizeof(magic), 0))
return false;
offset = sizeof(magic);
// Figure out what type of file we've got
bool is_fat = false;
if (magic == FAT_MAGIC || magic == FAT_CIGAM) {
is_fat = true;
}
else if (magic != MH_MAGIC && magic != MH_CIGAM && magic != MH_MAGIC_64 &&
magic != MH_CIGAM_64) {
return false;
}
if (!is_fat) {
// If we don't have a fat header, check if the cpu type matches the single
// header
cpu_type_t header_cpu_type;
if (!ReadBytes(&header_cpu_type, sizeof(header_cpu_type), offset))
return false;
if (magic == MH_CIGAM || magic == MH_CIGAM_64)
header_cpu_type = NXSwapInt(header_cpu_type);
if (valid_cpu_type != header_cpu_type)
return false;
offset = 0;
return true;
} else {
// Read the fat header and find an appropriate architecture
offset = 0;
struct fat_header fat;
if (!ReadBytes(&fat, sizeof(fat), offset))
return false;
if (NXHostByteOrder() != NX_BigEndian)
swap_fat_header(&fat, NXHostByteOrder());
offset += sizeof(fat);
// Search each architecture for the desired one
struct fat_arch arch;
for (uint32_t i = 0; i < fat.nfat_arch; ++i) {
if (!ReadBytes(&arch, sizeof(arch), offset))
return false;
if (NXHostByteOrder() != NX_BigEndian)
swap_fat_arch(&arch, 1, NXHostByteOrder());
if (arch.cputype == valid_cpu_type) {
offset = arch.offset;
return true;
}
offset += sizeof(arch);
}
}
return false;
}
bool MachoWalker::WalkHeaderAtOffset(off_t offset) {
struct mach_header header;
if (!ReadBytes(&header, sizeof(header), offset))
return false;
bool swap = (header.magic == MH_CIGAM);
if (swap)
swap_mach_header(&header, NXHostByteOrder());
// Copy the data into the mach_header_64 structure. Since the 32-bit and
// 64-bit only differ in the last field (reserved), this is safe to do.
struct mach_header_64 header64;
memcpy((void *)&header64, (const void *)&header, sizeof(header));
header64.reserved = 0;
current_header_ = &header64;
current_header_size_ = sizeof(header); // 32-bit, not 64-bit
current_header_offset_ = offset;
offset += current_header_size_;
bool result = WalkHeaderCore(offset, header.ncmds, swap);
current_header_ = NULL;
current_header_size_ = 0;
current_header_offset_ = 0;
return result;
}
bool MachoWalker::WalkHeader64AtOffset(off_t offset) {
struct mach_header_64 header;
if (!ReadBytes(&header, sizeof(header), offset))
return false;
bool swap = (header.magic == MH_CIGAM_64);
if (swap)
breakpad_swap_mach_header_64(&header, NXHostByteOrder());
current_header_ = &header;
current_header_size_ = sizeof(header);
current_header_offset_ = offset;
offset += current_header_size_;
bool result = WalkHeaderCore(offset, header.ncmds, swap);
current_header_ = NULL;
current_header_size_ = 0;
current_header_offset_ = 0;
return result;
}
bool MachoWalker::WalkHeaderCore(off_t offset, uint32_t number_of_commands,
bool swap) {
for (uint32_t i = 0; i < number_of_commands; ++i) {
struct load_command cmd;
if (!ReadBytes(&cmd, sizeof(cmd), offset))
return false;
if (swap)
swap_load_command(&cmd, NXHostByteOrder());
// Call the user callback
if (callback_ && !callback_(this, &cmd, offset, swap, callback_context_))
break;
offset += cmd.cmdsize;
}
return true;
}
} // namespace MacFileUtilities
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Copyright (C) 2008-2011 Massachusetts Institute of Technology *
* *
* 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 *
* *
* This source code is part of the PetaBricks project: *
* http://projects.csail.mit.edu/petabricks/ *
* *
*****************************************************************************/
#include "syntheticrule.h"
#include "codegenerator.h"
#include "iterationorders.h"
#include "maximawrapper.h"
#include "transform.h"
void petabricks::SyntheticRule::compileRuleBody(Transform&, RIRScope&){}
void petabricks::SyntheticRule::initialize(Transform&){}
petabricks::RuleFlags::PriorityT petabricks::SyntheticRule::priority() const {
return RuleFlags::PRIORITY_DEFAULT;
}
bool petabricks::SyntheticRule::isRecursive() const {
return true;
}
bool petabricks::SyntheticRule::hasWhereClause() const {
return false;
}
petabricks::FormulaPtr petabricks::SyntheticRule::getWhereClause() const {
return NULL;
}
std::string petabricks::SyntheticRule::getLabel() const {
return "synthetic";
}
bool petabricks::SyntheticRule::canProvide(const MatrixDefPtr&) const {
UNIMPLEMENTED();
return false;
}
void petabricks::SyntheticRule::getApplicableRegionDescriptors(RuleDescriptorList&, const MatrixDefPtr&, int, const RulePtr&) {
UNIMPLEMENTED();
}
//
// void petabricks::SyntheticRule::generateCallCode(const std::string&,
// Transform&,
// CodeGenerator& o,
// const SimpleRegionPtr&,
// RuleFlavor,
// std::vector<RegionNodeGroup>&,
// int, int){
// o.comment("synthetic generateCallCode");
// }
//
void petabricks::SyntheticRule::generateDeclCode(Transform&, CodeGenerator&, RuleFlavor) {}
//void petabricks::SyntheticRule::generateTrampCode(Transform&, CodeGenerator&, RuleFlavor) {}
void petabricks::SyntheticRule::markRecursive() {
UNIMPLEMENTED();
}
const petabricks::FormulaPtr& petabricks::SyntheticRule::recursiveHint() const {
return FormulaPtr::null();
}
void petabricks::SyntheticRule::print(std::ostream& os) const {
os << "SyntheticRule " << _id << std::endl;;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//WrapperSyntheticRule:
void petabricks::WrapperSyntheticRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
_rule->generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
}
void petabricks::WrapperSyntheticRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf){
_rule->generateTrampCode(trans, o, rf);
}
bool petabricks::WrapperSyntheticRule::isSingleElement() const {
return _rule->isSingleElement();
}
int petabricks::WrapperSyntheticRule::dimensions() const {
return _rule->dimensions();
}
petabricks::DependencyDirection petabricks::WrapperSyntheticRule::getSelfDependency() const {
return _rule->getSelfDependency();
}
petabricks::FormulaPtr petabricks::WrapperSyntheticRule::getSizeOfRuleIn(int d) {
return _rule->getSizeOfRuleIn(d);
}
void petabricks::WrapperSyntheticRule::collectDependencies(StaticScheduler& scheduler) {
_rule->collectDependencies(scheduler);
}
petabricks::RuleFlags::PriorityT petabricks::WrapperSyntheticRule::priority() const {
return _rule->priority();
}
bool petabricks::WrapperSyntheticRule::isRecursive() const {
return _rule->isRecursive();
}
bool petabricks::WrapperSyntheticRule::hasWhereClause() const {
return _rule->hasWhereClause();
}
petabricks::FormulaPtr petabricks::WrapperSyntheticRule::getWhereClause() const {
return _rule->getWhereClause();
}
bool petabricks::WrapperSyntheticRule::canProvide(const MatrixDefPtr& md) const {
return _rule->canProvide(md);
}
void petabricks::WrapperSyntheticRule::getApplicableRegionDescriptors(RuleDescriptorList& rdl, const MatrixDefPtr& md, int i, const RulePtr& rule) {
_rule->getApplicableRegionDescriptors(rdl, md, i, rule);
}
const petabricks::FormulaPtr& petabricks::WrapperSyntheticRule::recursiveHint() const {
return _rule->recursiveHint();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for WhereExpansionRule
void petabricks::WhereExpansionRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>&,
int,
int){
SRCPOSSCOPE();
switch(flavor) {
case RuleFlavor::SEQUENTIAL:
o.callSpatial(codename()+"_"+flavor.str(), region);
break;
case RuleFlavor::WORKSTEALING:
case RuleFlavor::DISTRIBUTED:
o.mkSpatialTask(name, trans.instClassName(), codename()+"_"+flavor.str(), region);
break;
default:
UNIMPLEMENTED();
}
}
void petabricks::WhereExpansionRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor flavor){
IterationDefinition iterdef(*this, getSelfDependency() , false);
std::vector<std::string> packedargs = iterdef.packedargs();
o.beginFunc("petabricks::DynamicTaskPtr", codename()+"_"+flavor.str(), packedargs);
if(RuleFlavor::SEQUENTIAL != flavor) {
o.write("DynamicTaskPtr _spawner = new NullDynamicTask();");
o.write("DynamicTaskPtr _last = NULL;");
}
iterdef.unpackargs(o);
iterdef.genLoopBegin(o);
genWhereSwitch(trans, o, flavor);
iterdef.genLoopEnd(o);
if(RuleFlavor::SEQUENTIAL != flavor){
o.write("_spawner->dependsOn(_last);");
o.write("return _spawner;");
}
else o.write("return NULL;");
o.endFunc();
}
void petabricks::WhereExpansionRule::genWhereSwitch(Transform& trans, CodeGenerator& o, RuleFlavor rf){
RuleSet::iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i){
for(int d=0; d<(*i)->dimensions(); ++d){
o._define((*i)->getOffsetVar(d)->toString(), getOffsetVar(d)->toString());
}
FormulaPtr wc = (*i)->getWhereClause();
if(!wc)
o.elseIf();
else if(i==_rules.begin())
o.beginIf(wc->toCppString());
else
o.elseIf(wc->toCppString());
(*i)->generateTrampCellCodeSimple(trans, o, rf);
for(int d=0; d<(*i)->dimensions(); ++d){
o._undefine((*i)->getOffsetVar(d)->toString());
}
if(!wc){
o.endIf();
return; //we reached an unconditioned rule
}
}
o.elseIf();
o.write("JASSERT(false).Text(\"All where clauses failed, no rule to compute region\");");
o.endIf();
}
bool petabricks::WhereExpansionRule::isSingleElement() const {
return false;
}
int petabricks::WhereExpansionRule::dimensions() const {
RuleSet::const_iterator i=_rules.begin();
int rv = (*i)->dimensions();
for(++i ;i!=_rules.end(); ++i)
JASSERT(rv==(*i)->dimensions())(rv)((*i)->dimensions())
.Text("where clauses only work with common number of dimensions");;
return rv;
}
petabricks::DependencyDirection petabricks::WhereExpansionRule::getSelfDependency() const {
DependencyDirection rv;
RuleSet::const_iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i)
rv.addDirection((*i)->getSelfDependency());
return rv;
}
petabricks::FormulaPtr petabricks::WhereExpansionRule::getSizeOfRuleIn(int d) {
RuleSet::const_iterator i=_rules.begin();
FormulaPtr rv = (*i)->getSizeOfRuleIn(d);
for(++i ;i!=_rules.end(); ++i)
JASSERT(MAXIMA.compare(rv,"=", (*i)->getSizeOfRuleIn(d)))
.Text("where clauses only work with common sizes in each choice");;
return rv;
}
std::string petabricks::WhereExpansionRule::codename() const {
return "whereExpansion"+jalib::XToString(_id);
}
void petabricks::WhereExpansionRule::collectDependencies(StaticScheduler& scheduler) {
RuleSet::const_iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i)
(*i)->collectDependencies(scheduler);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for DuplicateExpansionRule
void petabricks::DuplicateExpansionRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
SRCPOSSCOPE();
size_t old = _rule->setDuplicateNumber(_dup);
WrapperSyntheticRule::generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
_rule->setDuplicateNumber(old);
}
void petabricks::DuplicateExpansionRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf){
size_t old = _rule->setDuplicateNumber(_dup);
WrapperSyntheticRule::generateTrampCode(trans, o, rf);
_rule->setDuplicateNumber(old);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for CallInSequenceRule
void petabricks::CallInSequenceRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
SRCPOSSCOPE();
if(flavor != RuleFlavor::SEQUENTIAL)
o.write("{ DynamicTaskPtr __last;");
RuleList::iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i){
(*i)->generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
if(flavor != RuleFlavor::SEQUENTIAL) {
if(i!=_rules.begin()) {
o.write(name+"->dependsOn(__last);");
o.write("__last->enqueue();");
}
o.write("__last = "+name+";");
}
}
if(flavor != RuleFlavor::SEQUENTIAL)
o.write("}");
}
void petabricks::CallInSequenceRule::generateTrampCode(Transform& /*trans*/, CodeGenerator& /*o*/, RuleFlavor){
UNIMPLEMENTED();
}
bool petabricks::CallInSequenceRule::isSingleElement() const { UNIMPLEMENTED(); return false; }
int petabricks::CallInSequenceRule::dimensions() const { UNIMPLEMENTED(); return -1; }
petabricks::FormulaPtr petabricks::CallInSequenceRule::getSizeOfRuleIn(int /*d*/) { UNIMPLEMENTED(); return 0; }
std::string petabricks::CallInSequenceRule::codename() const { UNIMPLEMENTED(); return ""; }
void petabricks::CallInSequenceRule::collectDependencies(StaticScheduler& /*scheduler*/) { UNIMPLEMENTED(); }
void petabricks::CallInSequenceRule::genWhereSwitch(Transform& /*trans*/, CodeGenerator& /*o*/) { UNIMPLEMENTED(); }
petabricks::DependencyDirection petabricks::CallInSequenceRule::getSelfDependency() const { UNIMPLEMENTED(); return 0; }
<commit_msg>Mark WhereExpansionRule::generateTrampCode as UNIMPLEMENTED()<commit_after>/*****************************************************************************
* Copyright (C) 2008-2011 Massachusetts Institute of Technology *
* *
* 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 *
* *
* This source code is part of the PetaBricks project: *
* http://projects.csail.mit.edu/petabricks/ *
* *
*****************************************************************************/
#include "syntheticrule.h"
#include "codegenerator.h"
#include "iterationorders.h"
#include "maximawrapper.h"
#include "transform.h"
void petabricks::SyntheticRule::compileRuleBody(Transform&, RIRScope&){}
void petabricks::SyntheticRule::initialize(Transform&){}
petabricks::RuleFlags::PriorityT petabricks::SyntheticRule::priority() const {
return RuleFlags::PRIORITY_DEFAULT;
}
bool petabricks::SyntheticRule::isRecursive() const {
return true;
}
bool petabricks::SyntheticRule::hasWhereClause() const {
return false;
}
petabricks::FormulaPtr petabricks::SyntheticRule::getWhereClause() const {
return NULL;
}
std::string petabricks::SyntheticRule::getLabel() const {
return "synthetic";
}
bool petabricks::SyntheticRule::canProvide(const MatrixDefPtr&) const {
UNIMPLEMENTED();
return false;
}
void petabricks::SyntheticRule::getApplicableRegionDescriptors(RuleDescriptorList&, const MatrixDefPtr&, int, const RulePtr&) {
UNIMPLEMENTED();
}
//
// void petabricks::SyntheticRule::generateCallCode(const std::string&,
// Transform&,
// CodeGenerator& o,
// const SimpleRegionPtr&,
// RuleFlavor,
// std::vector<RegionNodeGroup>&,
// int, int){
// o.comment("synthetic generateCallCode");
// }
//
void petabricks::SyntheticRule::generateDeclCode(Transform&, CodeGenerator&, RuleFlavor) {}
//void petabricks::SyntheticRule::generateTrampCode(Transform&, CodeGenerator&, RuleFlavor) {}
void petabricks::SyntheticRule::markRecursive() {
UNIMPLEMENTED();
}
const petabricks::FormulaPtr& petabricks::SyntheticRule::recursiveHint() const {
return FormulaPtr::null();
}
void petabricks::SyntheticRule::print(std::ostream& os) const {
os << "SyntheticRule " << _id << std::endl;;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//WrapperSyntheticRule:
void petabricks::WrapperSyntheticRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
_rule->generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
}
void petabricks::WrapperSyntheticRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf){
_rule->generateTrampCode(trans, o, rf);
}
bool petabricks::WrapperSyntheticRule::isSingleElement() const {
return _rule->isSingleElement();
}
int petabricks::WrapperSyntheticRule::dimensions() const {
return _rule->dimensions();
}
petabricks::DependencyDirection petabricks::WrapperSyntheticRule::getSelfDependency() const {
return _rule->getSelfDependency();
}
petabricks::FormulaPtr petabricks::WrapperSyntheticRule::getSizeOfRuleIn(int d) {
return _rule->getSizeOfRuleIn(d);
}
void petabricks::WrapperSyntheticRule::collectDependencies(StaticScheduler& scheduler) {
_rule->collectDependencies(scheduler);
}
petabricks::RuleFlags::PriorityT petabricks::WrapperSyntheticRule::priority() const {
return _rule->priority();
}
bool petabricks::WrapperSyntheticRule::isRecursive() const {
return _rule->isRecursive();
}
bool petabricks::WrapperSyntheticRule::hasWhereClause() const {
return _rule->hasWhereClause();
}
petabricks::FormulaPtr petabricks::WrapperSyntheticRule::getWhereClause() const {
return _rule->getWhereClause();
}
bool petabricks::WrapperSyntheticRule::canProvide(const MatrixDefPtr& md) const {
return _rule->canProvide(md);
}
void petabricks::WrapperSyntheticRule::getApplicableRegionDescriptors(RuleDescriptorList& rdl, const MatrixDefPtr& md, int i, const RulePtr& rule) {
_rule->getApplicableRegionDescriptors(rdl, md, i, rule);
}
const petabricks::FormulaPtr& petabricks::WrapperSyntheticRule::recursiveHint() const {
return _rule->recursiveHint();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for WhereExpansionRule
void petabricks::WhereExpansionRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>&,
int,
int){
SRCPOSSCOPE();
switch(flavor) {
case RuleFlavor::SEQUENTIAL:
o.callSpatial(codename()+"_"+flavor.str(), region);
break;
case RuleFlavor::WORKSTEALING:
case RuleFlavor::DISTRIBUTED:
o.mkSpatialTask(name, trans.instClassName(), codename()+"_"+flavor.str(), region);
break;
default:
UNIMPLEMENTED();
}
}
void petabricks::WhereExpansionRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor flavor){
// TODO: This should create IterationTrampTask like in UserRule::generateTrampCode
UNIMPLEMENTED();
IterationDefinition iterdef(*this, getSelfDependency() , false);
std::vector<std::string> packedargs = iterdef.packedargs();
o.beginFunc("petabricks::DynamicTaskPtr", codename()+"_"+flavor.str(), packedargs);
if(RuleFlavor::SEQUENTIAL != flavor) {
o.write("DynamicTaskPtr _spawner = new NullDynamicTask();");
o.write("DynamicTaskPtr _last = NULL;");
}
iterdef.unpackargs(o);
iterdef.genLoopBegin(o);
genWhereSwitch(trans, o, flavor);
iterdef.genLoopEnd(o);
if(RuleFlavor::SEQUENTIAL != flavor){
o.write("_spawner->dependsOn(_last);");
o.write("return _spawner;");
}
else o.write("return NULL;");
o.endFunc();
}
void petabricks::WhereExpansionRule::genWhereSwitch(Transform& trans, CodeGenerator& o, RuleFlavor rf){
RuleSet::iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i){
for(int d=0; d<(*i)->dimensions(); ++d){
o._define((*i)->getOffsetVar(d)->toString(), getOffsetVar(d)->toString());
}
FormulaPtr wc = (*i)->getWhereClause();
if(!wc)
o.elseIf();
else if(i==_rules.begin())
o.beginIf(wc->toCppString());
else
o.elseIf(wc->toCppString());
(*i)->generateTrampCellCodeSimple(trans, o, rf);
for(int d=0; d<(*i)->dimensions(); ++d){
o._undefine((*i)->getOffsetVar(d)->toString());
}
if(!wc){
o.endIf();
return; //we reached an unconditioned rule
}
}
o.elseIf();
o.write("JASSERT(false).Text(\"All where clauses failed, no rule to compute region\");");
o.endIf();
}
bool petabricks::WhereExpansionRule::isSingleElement() const {
return false;
}
int petabricks::WhereExpansionRule::dimensions() const {
RuleSet::const_iterator i=_rules.begin();
int rv = (*i)->dimensions();
for(++i ;i!=_rules.end(); ++i)
JASSERT(rv==(*i)->dimensions())(rv)((*i)->dimensions())
.Text("where clauses only work with common number of dimensions");;
return rv;
}
petabricks::DependencyDirection petabricks::WhereExpansionRule::getSelfDependency() const {
DependencyDirection rv;
RuleSet::const_iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i)
rv.addDirection((*i)->getSelfDependency());
return rv;
}
petabricks::FormulaPtr petabricks::WhereExpansionRule::getSizeOfRuleIn(int d) {
RuleSet::const_iterator i=_rules.begin();
FormulaPtr rv = (*i)->getSizeOfRuleIn(d);
for(++i ;i!=_rules.end(); ++i)
JASSERT(MAXIMA.compare(rv,"=", (*i)->getSizeOfRuleIn(d)))
.Text("where clauses only work with common sizes in each choice");;
return rv;
}
std::string petabricks::WhereExpansionRule::codename() const {
return "whereExpansion"+jalib::XToString(_id);
}
void petabricks::WhereExpansionRule::collectDependencies(StaticScheduler& scheduler) {
RuleSet::const_iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i)
(*i)->collectDependencies(scheduler);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for DuplicateExpansionRule
void petabricks::DuplicateExpansionRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
SRCPOSSCOPE();
size_t old = _rule->setDuplicateNumber(_dup);
WrapperSyntheticRule::generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
_rule->setDuplicateNumber(old);
}
void petabricks::DuplicateExpansionRule::generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf){
size_t old = _rule->setDuplicateNumber(_dup);
WrapperSyntheticRule::generateTrampCode(trans, o, rf);
_rule->setDuplicateNumber(old);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO: consider new file for CallInSequenceRule
void petabricks::CallInSequenceRule::generateCallCode(const std::string& name,
Transform& trans,
CodeGenerator& o,
const SimpleRegionPtr& region,
RuleFlavor flavor,
std::vector<RegionNodeGroup>& regionNodesGroups,
int nodeID,
int gpuCopyOut){
SRCPOSSCOPE();
if(flavor != RuleFlavor::SEQUENTIAL)
o.write("{ DynamicTaskPtr __last;");
RuleList::iterator i;
for(i=_rules.begin(); i!=_rules.end(); ++i){
(*i)->generateCallCode(name, trans, o, region, flavor, regionNodesGroups, nodeID, gpuCopyOut);
if(flavor != RuleFlavor::SEQUENTIAL) {
if(i!=_rules.begin()) {
o.write(name+"->dependsOn(__last);");
o.write("__last->enqueue();");
}
o.write("__last = "+name+";");
}
}
if(flavor != RuleFlavor::SEQUENTIAL)
o.write("}");
}
void petabricks::CallInSequenceRule::generateTrampCode(Transform& /*trans*/, CodeGenerator& /*o*/, RuleFlavor){
UNIMPLEMENTED();
}
bool petabricks::CallInSequenceRule::isSingleElement() const { UNIMPLEMENTED(); return false; }
int petabricks::CallInSequenceRule::dimensions() const { UNIMPLEMENTED(); return -1; }
petabricks::FormulaPtr petabricks::CallInSequenceRule::getSizeOfRuleIn(int /*d*/) { UNIMPLEMENTED(); return 0; }
std::string petabricks::CallInSequenceRule::codename() const { UNIMPLEMENTED(); return ""; }
void petabricks::CallInSequenceRule::collectDependencies(StaticScheduler& /*scheduler*/) { UNIMPLEMENTED(); }
void petabricks::CallInSequenceRule::genWhereSwitch(Transform& /*trans*/, CodeGenerator& /*o*/) { UNIMPLEMENTED(); }
petabricks::DependencyDirection petabricks::CallInSequenceRule::getSelfDependency() const { UNIMPLEMENTED(); return 0; }
<|endoftext|>
|
<commit_before>#include <time.h>
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "imds2.h"
#include "fileinfo2.h"
#include "fileindex2.h"
u_lint IMDS::GetNumFiles()
{
return FileStats.GetNumFiles();
}
int IMDS::LockStatus(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
return Index.LockStatus(machine_IP, owner_name, file_name);
}
void IMDS::Lock(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
file_state state)
{
file_node* file_ptr;
file_info_node* file_data;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL) {
file_data = file_ptr->file_data;
file_data->lock = EXCLUSIVE_LOCK;
file_data->data.state = state;
}
}
void IMDS::Unlock(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
file_node* file_ptr;
file_info_node* file_data;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL) {
file_data = file_ptr->file_data;
file_data->lock = UNLOCKED;
file_data->data.state = ON_SERVER;
}
}
int IMDS::AddFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
u_lint file_size,
file_state state)
{
file_node* file_ptr;
file_info_node* file_data;
char pathname[MAX_PATHNAME_LENGTH];
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL)
{
file_data = file_ptr->file_data;
if (file_data->lock != UNLOCKED)
return FILE_LOCKED;
sprintf(pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
file_data->data.machine_IP_name, owner_name, file_name);
if ((state == NOT_PRESENT) || (state == LOADING))
remove(pathname); // Do not care if fails
file_data->data.size = file_size;
file_data->data.last_modified_time = time(NULL);
file_data->data.state = state;
file_data->lock = EXCLUSIVE_LOCK;
}
else
{
file_data = FileStats.AddFileInfo(machine_IP, owner_name, file_name,
file_size, state, NULL);
(void) Index.AddNewFile(machine_IP, owner_name, file_name, file_data);
}
return CREATED;
}
int IMDS::RenameFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
const char* new_file_name)
{
file_node* old_fn;
file_node* new_fn;
file_info_node* old_file_ptr;
file_info_node* new_file_ptr;
char new_pathname[MAX_PATHNAME_LENGTH];
char old_pathname[MAX_PATHNAME_LENGTH];
old_fn = Index.GetFileNode(machine_IP, owner_name, file_name);
if (old_fn == NULL)
return DOES_NOT_EXIST;
old_file_ptr = old_fn->file_data;
if (old_file_ptr->lock != UNLOCKED)
return FILE_LOCKED;
sprintf(old_pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
old_file_ptr->data.machine_IP_name, owner_name, file_name);
sprintf(new_pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
old_file_ptr->data.machine_IP_name, owner_name, new_file_name);
new_fn = Index.GetFileNode(machine_IP, owner_name, new_file_name);
if (new_fn == NULL) {
if (rename(old_pathname, new_pathname) != 0)
return CANNOT_RENAME_FILE;
strncpy(old_file_ptr->data.machine_IP_name, new_file_name,
MAX_CONDOR_FILENAME_LENGTH);
old_file_ptr->data.last_modified_time = time(NULL);
(void) Index.AddNewFile(machine_IP, owner_name, new_file_name,
old_file_ptr);
} else {
new_file_ptr = new_fn->file_data;
if (new_file_ptr->lock != UNLOCKED)
return FILE_LOCKED;
if (rename(old_pathname, new_pathname) != 0)
return CANNOT_RENAME_FILE;
new_file_ptr->data.size = old_file_ptr->data.size;
new_file_ptr->data.state = old_file_ptr->data.state;
new_file_ptr->data.last_modified_time = time(NULL);
(void) FileStats.RemoveFileInfo(old_file_ptr);
}
(void) Index.DeleteFile(machine_IP, owner_name, file_name);
/* return RENAMED; */
return OK;
}
u_short IMDS::RemoveFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
file_node* file_ptr;
int d_ret_code;
int i_ret_code;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr == NULL)
return DOES_NOT_EXIST;
d_ret_code = FileStats.RemoveFileInfo(file_ptr->file_data);
if (d_ret_code != REMOVED_FILE)
return (u_short) d_ret_code;
i_ret_code = Index.DeleteFile(machine_IP, owner_name, file_name);
return (u_short) i_ret_code;
}
void IMDS::TransferFileInfo(int socket_desc)
{
FileStats.TransferFileInfo(socket_desc);
}
<commit_msg>Files should be unlocked when they are added to the imds. Otherwise, the files get all locked up when the server restarts.<commit_after>#include <time.h>
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "imds2.h"
#include "fileinfo2.h"
#include "fileindex2.h"
u_lint IMDS::GetNumFiles()
{
return FileStats.GetNumFiles();
}
int IMDS::LockStatus(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
return Index.LockStatus(machine_IP, owner_name, file_name);
}
void IMDS::Lock(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
file_state state)
{
file_node* file_ptr;
file_info_node* file_data;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL) {
file_data = file_ptr->file_data;
file_data->lock = EXCLUSIVE_LOCK;
file_data->data.state = state;
}
}
void IMDS::Unlock(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
file_node* file_ptr;
file_info_node* file_data;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL) {
file_data = file_ptr->file_data;
file_data->lock = UNLOCKED;
file_data->data.state = ON_SERVER;
}
}
int IMDS::AddFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
u_lint file_size,
file_state state)
{
file_node* file_ptr;
file_info_node* file_data;
char pathname[MAX_PATHNAME_LENGTH];
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr != NULL)
{
file_data = file_ptr->file_data;
if (file_data->lock != UNLOCKED)
return FILE_LOCKED;
sprintf(pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
file_data->data.machine_IP_name, owner_name, file_name);
if ((state == NOT_PRESENT) || (state == LOADING))
remove(pathname); // Do not care if fails
file_data->data.size = file_size;
file_data->data.last_modified_time = time(NULL);
file_data->data.state = state;
file_data->lock = UNLOCKED;
}
else
{
file_data = FileStats.AddFileInfo(machine_IP, owner_name, file_name,
file_size, state, NULL);
(void) Index.AddNewFile(machine_IP, owner_name, file_name, file_data);
}
return CREATED;
}
int IMDS::RenameFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name,
const char* new_file_name)
{
file_node* old_fn;
file_node* new_fn;
file_info_node* old_file_ptr;
file_info_node* new_file_ptr;
char new_pathname[MAX_PATHNAME_LENGTH];
char old_pathname[MAX_PATHNAME_LENGTH];
old_fn = Index.GetFileNode(machine_IP, owner_name, file_name);
if (old_fn == NULL)
return DOES_NOT_EXIST;
old_file_ptr = old_fn->file_data;
if (old_file_ptr->lock != UNLOCKED)
return FILE_LOCKED;
sprintf(old_pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
old_file_ptr->data.machine_IP_name, owner_name, file_name);
sprintf(new_pathname, "%s%s/%s/%s", LOCAL_DRIVE_PREFIX,
old_file_ptr->data.machine_IP_name, owner_name, new_file_name);
new_fn = Index.GetFileNode(machine_IP, owner_name, new_file_name);
if (new_fn == NULL) {
if (rename(old_pathname, new_pathname) != 0)
return CANNOT_RENAME_FILE;
strncpy(old_file_ptr->data.machine_IP_name, new_file_name,
MAX_CONDOR_FILENAME_LENGTH);
old_file_ptr->data.last_modified_time = time(NULL);
(void) Index.AddNewFile(machine_IP, owner_name, new_file_name,
old_file_ptr);
} else {
new_file_ptr = new_fn->file_data;
if (new_file_ptr->lock != UNLOCKED)
return FILE_LOCKED;
if (rename(old_pathname, new_pathname) != 0)
return CANNOT_RENAME_FILE;
new_file_ptr->data.size = old_file_ptr->data.size;
new_file_ptr->data.state = old_file_ptr->data.state;
new_file_ptr->data.last_modified_time = time(NULL);
(void) FileStats.RemoveFileInfo(old_file_ptr);
}
(void) Index.DeleteFile(machine_IP, owner_name, file_name);
/* return RENAMED; */
return OK;
}
u_short IMDS::RemoveFile(struct in_addr machine_IP,
const char* owner_name,
const char* file_name)
{
file_node* file_ptr;
int d_ret_code;
int i_ret_code;
file_ptr = Index.GetFileNode(machine_IP, owner_name, file_name);
if (file_ptr == NULL)
return DOES_NOT_EXIST;
d_ret_code = FileStats.RemoveFileInfo(file_ptr->file_data);
if (d_ret_code != REMOVED_FILE)
return (u_short) d_ret_code;
i_ret_code = Index.DeleteFile(machine_IP, owner_name, file_name);
return (u_short) i_ret_code;
}
void IMDS::TransferFileInfo(int socket_desc)
{
FileStats.TransferFileInfo(socket_desc);
}
<|endoftext|>
|
<commit_before>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <stdlib.h>
#include "config/applier/endpoint.hh"
#include "exceptions/basic.hh"
#include "io/acceptor.hh"
#include "io/connector.hh"
#include "io/protocols.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::config::applier;
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Default constructor.
*/
endpoint::endpoint() : QObject() {}
/**
* @brief Copy constructor.
*
* Any call to this constructor will result in a call to abort().
*
* @param[in] e Object to copy.
*/
endpoint::endpoint(endpoint const& e) : QObject() {
(void)e;
assert(false);
abort();
}
/**
* @brief Assignment operator.
*
* Any call to this method will result in a call to abort().
*
* @param[in] e Object to copy.
*
* @return This object.
*/
endpoint& endpoint::operator=(endpoint const& e) {
(void)e;
assert(false);
abort();
return (*this);
}
/**
* Create and register an endpoint according to configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_output true if the endpoint will act as output.
*/
void endpoint::_create_endpoint(config::endpoint const& cfg, bool is_output) {
// Create endpoint object.
QSharedPointer<io::endpoint> endp;
bool is_acceptor;
int level;
for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(),
end = io::protocols::instance().end();
it != end;
++it) {
if ((it.value().osi_to == 7)
&& it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output)) {
endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor));
level = it.value().osi_from - 1;
break ;
}
}
if (endp.isNull())
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
// Create remaining objects.
io::endpoint* prev(endp.data());
while (level > 0) {
// Browse protocol list.
QMap<QString, io::protocols::protocol>::const_iterator it(io::protocols::instance().begin());
QMap<QString, io::protocols::protocol>::const_iterator end(io::protocols::instance().end());
while (it != end) {
if ((it.value().osi_from == level)
&& (it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output))) {
if (is_acceptor) {
QSharedPointer<io::acceptor> current(static_cast<io::acceptor*>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor)));
static_cast<io::acceptor*>(prev)->on(current);
prev = current.data();
}
else {
QSharedPointer<io::connector> current(static_cast<io::connector*>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor)));
static_cast<io::connector*>(prev)->from(current);
prev = current.data();
}
level = it.value().osi_to;
break ;
}
++it;
}
if ((1 == level) && (it == end))
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
--level;
}
// Create thread.
QScopedPointer<processing::failover> fo(new processing::failover(is_output));
fo->set_endpoint(endp);
// Connect thread.
connect(fo.data(), SIGNAL(finished()), fo.data(), SLOT(deleteLater()));
if (!is_output) {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_input()));
_inputs[cfg] = fo.data();
}
else {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_output()));
_outputs[cfg] = fo.data();
}
// Run thread.
fo.take()->start();
return ;
}
/**
* Diff the current configuration with the new configuration.
*
* @param[in] current Current endpoints.
* @param[in] new_endpoints New endpoints configuration.
* @param[out] to_create Endpoints that should be created.
*/
void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current,
QList<config::endpoint> const& new_endpoints,
QList<config::endpoint>& to_create) {
// Find which endpoints will be kept, created and deleted.
QMap<config::endpoint, processing::failover*> to_delete(current);
for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(),
end = new_endpoints.end();
it != end;
++it) {
QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it));
if (endp != to_delete.end())
to_delete.erase(endp);
else
to_create.push_back(*it);
}
// Remove old endpoints.
for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(),
end = to_delete.end();
it != end;
++it) {
// XXX : send only termination request, object will
// be destroyed by event loop on termination.
// But wait for threads, because
}
return ;
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Destructor.
*/
endpoint::~endpoint() {}
/**
* Apply the endpoint configuration.
*
* @param[in] inputs Inputs configuration.
* @param[in] outputs Outputs configuration.
*/
void endpoint::apply(QList<config::endpoint> const& inputs,
QList<config::endpoint> const& outputs) {
// Remove old inputs and generate inputs to create.
QList<config::endpoint> in_to_create;
_diff_endpoints(_inputs, inputs, in_to_create);
// Remove old outputs and generate outputs to create.
QList<config::endpoint> out_to_create;
_diff_endpoints(_outputs, outputs, out_to_create);
// Create new outputs.
for (QList<config::endpoint>::iterator it = out_to_create.begin(),
end = out_to_create.end();
it != end;
++it)
_create_endpoint(*it, true);
// Create new inputs.
for (QList<config::endpoint>::iterator it = in_to_create.begin(),
end = in_to_create.end();
it != end;
++it)
_create_endpoint(*it, false);
return ;
}
/**
* Get the class instance.
*
* @return Class instance.
*/
endpoint& endpoint::instance() {
static endpoint gl_endpoint;
return (gl_endpoint);
}
/**
* An input thread finished executing.
*/
void endpoint::terminated_input() {
// XXX
}
/**
* An output thread finished executing.
*/
void endpoint::terminated_output() {
// XXX
}
<commit_msg>Bugfix.<commit_after>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <stdlib.h>
#include "config/applier/endpoint.hh"
#include "exceptions/basic.hh"
#include "io/acceptor.hh"
#include "io/connector.hh"
#include "io/protocols.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::config::applier;
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Default constructor.
*/
endpoint::endpoint() : QObject() {}
/**
* @brief Copy constructor.
*
* Any call to this constructor will result in a call to abort().
*
* @param[in] e Object to copy.
*/
endpoint::endpoint(endpoint const& e) : QObject() {
(void)e;
assert(false);
abort();
}
/**
* @brief Assignment operator.
*
* Any call to this method will result in a call to abort().
*
* @param[in] e Object to copy.
*
* @return This object.
*/
endpoint& endpoint::operator=(endpoint const& e) {
(void)e;
assert(false);
abort();
return (*this);
}
/**
* Create and register an endpoint according to configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_output true if the endpoint will act as output.
*/
void endpoint::_create_endpoint(config::endpoint const& cfg, bool is_output) {
// Create endpoint object.
QSharedPointer<io::endpoint> endp;
bool is_acceptor;
int level;
for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(),
end = io::protocols::instance().end();
it != end;
++it) {
if ((it.value().osi_to == 7)
&& it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output)) {
endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor));
level = it.value().osi_from - 1;
break ;
}
}
if (endp.isNull())
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
// Create remaining objects.
io::endpoint* prev(endp.data());
while (level > 0) {
// Browse protocol list.
QMap<QString, io::protocols::protocol>::const_iterator it(io::protocols::instance().begin());
QMap<QString, io::protocols::protocol>::const_iterator end(io::protocols::instance().end());
while (it != end) {
if ((it.value().osi_to == level)
&& (it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output))) {
if (is_acceptor) {
QSharedPointer<io::acceptor> current(static_cast<io::acceptor*>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor)));
static_cast<io::acceptor*>(prev)->on(current);
prev = current.data();
}
else {
QSharedPointer<io::connector> current(static_cast<io::connector*>(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor)));
static_cast<io::connector*>(prev)->from(current);
prev = current.data();
}
level = it.value().osi_from;
break ;
}
++it;
}
if ((1 == level) && (it == end))
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
--level;
}
// Create thread.
QScopedPointer<processing::failover> fo(new processing::failover(is_output));
fo->set_endpoint(endp);
// Connect thread.
connect(fo.data(), SIGNAL(finished()), fo.data(), SLOT(deleteLater()));
if (!is_output) {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_input()));
_inputs[cfg] = fo.data();
}
else {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_output()));
_outputs[cfg] = fo.data();
}
// Run thread.
fo.take()->start();
return ;
}
/**
* Diff the current configuration with the new configuration.
*
* @param[in] current Current endpoints.
* @param[in] new_endpoints New endpoints configuration.
* @param[out] to_create Endpoints that should be created.
*/
void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current,
QList<config::endpoint> const& new_endpoints,
QList<config::endpoint>& to_create) {
// Find which endpoints will be kept, created and deleted.
QMap<config::endpoint, processing::failover*> to_delete(current);
for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(),
end = new_endpoints.end();
it != end;
++it) {
QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it));
if (endp != to_delete.end())
to_delete.erase(endp);
else
to_create.push_back(*it);
}
// Remove old endpoints.
for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(),
end = to_delete.end();
it != end;
++it) {
// XXX : send only termination request, object will
// be destroyed by event loop on termination.
// But wait for threads, because
}
return ;
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Destructor.
*/
endpoint::~endpoint() {}
/**
* Apply the endpoint configuration.
*
* @param[in] inputs Inputs configuration.
* @param[in] outputs Outputs configuration.
*/
void endpoint::apply(QList<config::endpoint> const& inputs,
QList<config::endpoint> const& outputs) {
// Remove old inputs and generate inputs to create.
QList<config::endpoint> in_to_create;
_diff_endpoints(_inputs, inputs, in_to_create);
// Remove old outputs and generate outputs to create.
QList<config::endpoint> out_to_create;
_diff_endpoints(_outputs, outputs, out_to_create);
// Create new outputs.
for (QList<config::endpoint>::iterator it = out_to_create.begin(),
end = out_to_create.end();
it != end;
++it)
_create_endpoint(*it, true);
// Create new inputs.
for (QList<config::endpoint>::iterator it = in_to_create.begin(),
end = in_to_create.end();
it != end;
++it)
_create_endpoint(*it, false);
return ;
}
/**
* Get the class instance.
*
* @return Class instance.
*/
endpoint& endpoint::instance() {
static endpoint gl_endpoint;
return (gl_endpoint);
}
/**
* An input thread finished executing.
*/
void endpoint::terminated_input() {
// XXX
}
/**
* An output thread finished executing.
*/
void endpoint::terminated_output() {
// XXX
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.