text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "yaml-cpp/yaml.h"
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#define YAML_ERROR 0
#define YAML_SUCCESS 1
#define SYSTEM_SUCCESS 0
#define SYSTEM_ERROR 1
#define FILE_ERROR 0
#define ALPHA_NUMBER 200
#define STATES_NUMBER 200
#define NUM_CHARS 10
#define FIN_YAML 0
#define NO_FIN_YAML 1
enum tags {
AUTOMATA,
DESCRIPTION,
ALPHA,
STATES,
START,
FINAL,
DELTA,
NODE,
TRANS,
IN,
NEXT
};
struct flujo_nodos{
std::string entrada;
std::string sig_estado;
};
struct transicion_nodos {
std::list<flujo_nodos> list_flujo_nodos;
};
struct nodo_automata{
char id;
std::list<transicion_nodos> list_transiciones;
};
struct automata_desc{
std::string nombre;
std::string descripcion;
std::list<std::string> alfabeto;
int sizeAlfabeto;
std::list<std::string> estados;
int sizeEstados;
std::string estadoinicial;
std::list<std::string> final;
int sizeFinal;
std::list<nodo_automata> nodos_automata;
};
typedef enum tags tag;
typedef struct automata_desc automata;
typedef struct automata_desc* p_type_automata;
typedef struct nodo_automata nodo;
typedef struct nodo_automata* p_type_nodo;
typedef struct flujo_nodos flujo;
typedef struct flujo_nodos* p_type_flujo;
typedef struct transicion_nodos transicion;
typedef struct transicion_nodos* p_type_transicion;
void parseDescriptionSection( YAML::Node file ){
p_type_automata pautomata = ( p_type_automata ) malloc( sizeof( automata ) );
// std::cout << file;
std::cout << file["automata"].as<std::string>();
printf("Entro 1\n");
const std::string name= file["automata"].as<std::string>();
printf("Entro 2\n");
pautomata->descripcion = file["description"].as<std::string>();
printf("Entro 3\n");
pautomata->alfabeto = file["alpha"].as< std::list<std::string> >();
printf("Entro 4\n");
pautomata->estados = file["states"].as< std::list<std::string> >();
printf("Entro 5\n");
pautomata->estadoinicial = file["start"].as<std::string>();
printf("Entro 6\n");
pautomata->final = file["final"].as<std::list<std::string> >();
std::cout << "Nombre: \n" << pautomata->nombre;
std::cout << "Descripcion: \n" << pautomata->descripcion;
std::cout << "Alfabeto: \n";
std::list<std::string>::const_iterator it = pautomata->alfabeto.begin();
for (; it != pautomata->alfabeto.end(); ++it)
{
std::cout << it->c_str();
}
}
int main(int argc, char const *argv[]){
if ( argc < 2 ){
fprintf(stdout, "There is no file to parse, try again\n");
return SYSTEM_ERROR;
}
FILE *yaml_file = fopen( argv[1], "r" );
YAML::Node file = YAML::Load(argv[1]);
// YAML::Node file = YAML::LoadFile(argv[1]);
parseDescriptionSection( file );
std::ofstream fout(argv[1]);
fout << file;
return SYSTEM_SUCCESS;
}<commit_msg>parser cpp with yaml0.5, doesn't work with yaml '-'<commit_after>#include "yaml-cpp/yaml.h"
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#define YAML_ERROR 0
#define YAML_SUCCESS 1
#define SYSTEM_SUCCESS 0
#define SYSTEM_ERROR 1
#define FILE_ERROR 0
#define ALPHA_NUMBER 200
#define STATES_NUMBER 200
#define NUM_CHARS 10
#define FIN_YAML 0
#define NO_FIN_YAML 1
enum tags {
AUTOMATA,
DESCRIPTION,
ALPHA,
STATES,
START,
FINAL,
DELTA,
NODE,
TRANS,
IN,
NEXT
};
struct flujo_nodos{
std::string entrada;
std::string sig_estado;
};
struct transicion_nodos {
std::list<flujo_nodos> list_flujo_nodos;
};
struct nodo_automata{
char id;
std::list<transicion_nodos> list_transiciones;
};
struct automata_desc{
std::string nombre;
std::string descripcion;
std::list<std::string> alfabeto;
int sizeAlfabeto;
std::list<std::string> estados;
int sizeEstados;
std::string estadoinicial;
std::list<std::string> final;
int sizeFinal;
std::list<nodo_automata> nodos_automata;
};
typedef enum tags tag;
typedef struct automata_desc automata;
typedef struct automata_desc* p_type_automata;
typedef struct nodo_automata nodo;
typedef struct nodo_automata* p_type_nodo;
typedef struct flujo_nodos flujo;
typedef struct flujo_nodos* p_type_flujo;
typedef struct transicion_nodos transicion;
typedef struct transicion_nodos* p_type_transicion;
void parseDescriptionSection( YAML::Node *file ){
p_type_automata pautomata = ( p_type_automata ) malloc( sizeof( automata ) );
// std::cout << file;
std::cout << (*file)["automata"].as<std::string>();
printf("Entro 1\n");
const std::string name= (*file)["automata"].as<std::string>();
printf("Entro 2\n");
pautomata->descripcion = (*file)["description"].as<std::string>();
printf("Entro 3\n");
pautomata->alfabeto = (*file)["alpha"].as< std::list<std::string> >();
printf("Entro 4\n");
pautomata->estados = (*file)["states"].as< std::list<std::string> >();
printf("Entro 5\n");
pautomata->estadoinicial = (*file)["start"].as<std::string>();
printf("Entro 6\n");
pautomata->final = (*file)["final"].as<std::list<std::string> >();
std::cout << "Nombre: \n" << pautomata->nombre;
std::cout << "Descripcion: \n" << pautomata->descripcion;
std::cout << "Alfabeto: \n";
std::list<std::string>::const_iterator it = pautomata->alfabeto.begin();
for (; it != pautomata->alfabeto.end(); ++it)
{
std::cout << it->c_str();
}
}
int main(int argc, char const *argv[]){
if ( argc < 2 ){
fprintf(stdout, "There is no file to parse, try again\n");
return SYSTEM_ERROR;
}
YAML::Node file = YAML::LoadFile(argv[1]);
parseDescriptionSection( &file );
std::ofstream fout(argv[1]);
fout << file;
return SYSTEM_SUCCESS;
}<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "cpuid.hpp"
#include "cache.hpp"
#include "features.hpp"
#include "standard.hpp"
#include "topology.hpp"
#include <map>
#include <iostream>
#include <iomanip>
#include <gsl/gsl>
#include <fmt/format.h>
template<std::size_t N, std::size_t... Is>
constexpr std::array<char, N - 1> to_array(const char(&str)[N], std::index_sequence<Is...>) {
return { str[Is]... };
}
template<std::size_t N>
constexpr std::array<char, N - 1> to_array(const char(&str)[N]) {
return to_array(str, std::make_index_sequence<N - 1>{});
}
vendor_t get_vendor_from_name(const register_set_t& regs) {
static const std::map<std::array<char, 12>, vendor_t> vendors = {
{ to_array("AMDisbetter!"), amd },
{ to_array("AuthenticAMD"), amd },
{ to_array("CentaurHauls"), centaur },
{ to_array("CyrixInstead"), cyrix },
{ to_array("GenuineIntel"), intel },
{ to_array("TransmetaCPU"), transmeta },
{ to_array("GenuineTMx86"), transmeta },
{ to_array("Geode by NSC"), nat_semi },
{ to_array("NexGenDriven"), nexgen },
{ to_array("RiseRiseRise"), rise },
{ to_array("SiS SiS SiS "), sis },
{ to_array("UMC UMC UMC "), umc },
{ to_array("VIA VIA VIA "), via },
{ to_array("Vortex86 SoC"), vortex },
{ to_array("bhyve byhve "), bhyve },
{ to_array("KVMKVMKVM\0\0\0"), kvm },
{ to_array("Microsoft hv"), hyper_v },
{ to_array(" lrpepyh vr\0"), parallels },
{ to_array("VMwareVMware"), vmware },
{ to_array("XenVMMXenVMM"), xen_hvm }
};
union
{
std::array<char, 12> vndr;
std::array<std::int32_t, 3> registers;
} data;
data.registers[0] = regs[ebx];
data.registers[1] = regs[edx];
data.registers[2] = regs[ecx];
auto it = vendors.find(data.vndr);
return it != vendors.end() ? it->second : unknown;
}
model_t get_model(vendor_t vendor, const register_set_t& regs) noexcept {
union
{
std::uint32_t raw;
split_model_t m;
} split_model;
split_model.raw = regs[eax];
model_t model = {};
model.family = split_model.m.family;
model.model = split_model.m.model;
model.stepping = split_model.m.stepping;
switch(vendor) {
case intel:
{
if(split_model.m.family == 0xf) {
model.family += split_model.m.extended_family;
}
if(split_model.m.family == 0x6 || split_model.m.family == 0xf) {
model.model += (split_model.m.extended_model << 4ui32);
}
}
break;
case amd:
{
model.family += split_model.m.extended_family;
model.model += split_model.m.extended_model << 4ui32;
}
break;
default:
break;
}
return model;
}
using leaf_print = void(*)(const cpu_t& cpu);
using leaf_enumerate = void(*)(cpu_t& cpu);
struct leaf_descriptor_t
{
bool has_subleaves;
leaf_enumerate enumerator;
leaf_print printer;
};
const std::map<leaf_t, leaf_descriptor_t> descriptors = {
{ basic_info , { false, nullptr , print_basic_info } },
{ version_info , { false, nullptr , print_version_info } },
{ cache_and_tlb , { false, nullptr , print_cache_tlb_info } },
{ serial_number , { false, nullptr , print_serial_number } },
{ deterministic_cache , { true , enumerate_deterministic_cache, print_deterministic_cache } },
{ monitor_mwait , { false, nullptr , print_mwait_parameters } },
{ thermal_and_power , { false, nullptr , print_thermal_and_power } },
{ extended_features , { true , enumerate_extended_features , print_extended_features } },
{ direct_cache_access , { false, nullptr , print_direct_cache_access } },
{ performance_monitoring , { false, nullptr , print_performance_monitoring } },
{ extended_topology , { true , enumerate_extended_topology , print_extended_topology } },
{ reserved_2 , { false, nullptr , nullptr } },
{ extended_state , { true , nullptr , nullptr } },
{ reserved_3 , { false, nullptr , nullptr } },
{ resource_director_monitoring , { true , nullptr , nullptr } },
{ cache_allocation_technology , { true , nullptr , nullptr } },
{ reserved_4 , { false, nullptr , nullptr } },
{ sgx_info , { true , nullptr , nullptr } },
{ reserved_5 , { false, nullptr , nullptr } },
{ processor_trace , { true , nullptr , nullptr } },
{ time_stamp_counter , { false, nullptr , nullptr } },
{ processor_frequency , { false, nullptr , nullptr } },
{ system_on_chip_vendor , { true , nullptr , nullptr } },
{ deterministic_address_translation , { true , nullptr , nullptr } },
{ extended_limit , { false, nullptr , nullptr } },
{ extended_signature_and_features , { false, nullptr , nullptr } },
{ brand_string_0 , { false, nullptr , nullptr } },
{ brand_string_1 , { false, nullptr , nullptr } },
{ brand_string_2 , { false, nullptr , nullptr } },
{ l1_cache_identifiers , { false, nullptr , nullptr } },
{ l2_cache_identifiers , { false, nullptr , nullptr } },
{ advanced_power_management , { false, nullptr , nullptr } },
{ address_limits , { false, nullptr , nullptr } },
{ secure_virtual_machine , { false, nullptr , nullptr } },
{ tlb_1g_identifiers , { false, nullptr , nullptr } },
{ performance_optimization , { false, nullptr , nullptr } },
{ instruction_based_sampling , { false, nullptr , nullptr } },
{ cache_properties , { false, nullptr , nullptr } },
{ extended_apic , { false, nullptr , nullptr } },
{ secure_memory_encryption , { false, nullptr , nullptr } }
};
int main(int, char*[]) {
HANDLE output = ::GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
::GetConsoleMode(output, &mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
::SetConsoleMode(output, mode);
::SetConsoleCP(CP_UTF8);
::SetConsoleOutputCP(CP_UTF8);
std::cout.rdbuf()->pubsetbuf(nullptr, 1024);
::SetThreadAffinityMask(::GetCurrentThread(), 0x4);
cpu_t cpu = {};
register_set_t regs = { 0 };
cpuid(regs, leaf_t::basic_info, subleaf_t::zero);
cpu.highest_leaf = gsl::narrow_cast<std::uint32_t>(regs[eax]);
cpu.vendor = get_vendor_from_name(regs);
cpuid(regs, leaf_t::version_info, subleaf_t::zero);
cpu.model = get_model(cpu.vendor, regs);
for(leaf_t lf = leaf_t::basic_info; lf <= cpu.highest_leaf; ++lf) {
auto it = descriptors.find(lf);
if(it != descriptors.end()) {
if(it->second.has_subleaves && it->second.enumerator) {
it->second.enumerator(cpu);
} else {
cpuid(regs, lf, subleaf_t::zero);
cpu.features[lf][subleaf_t::zero] = regs;
}
}
}
cpuid(regs, leaf_t::extended_limit, subleaf_t::zero);
cpu.highest_extended_leaf = regs[eax];
for(leaf_t lf = leaf_t::extended_limit; lf <= cpu.highest_extended_leaf; ++lf) {
auto it = descriptors.find(lf);
if(it != descriptors.end()) {
if(it->second.has_subleaves && it->second.enumerator) {
it->second.enumerator(cpu);
} else {
cpuid(regs, lf, subleaf_t::zero);
cpu.features[lf][subleaf_t::zero] = regs;
}
}
}
for(const auto& lf : cpu.features) {
auto it = descriptors.find(lf.first);
if(it != descriptors.end()) {
if(it->second.printer) {
it->second.printer(cpu);
}
}
}
}
<commit_msg>Thread shenanigans<commit_after>#include "stdafx.h"
#include "cpuid.hpp"
#include "cache.hpp"
#include "features.hpp"
#include "standard.hpp"
#include "topology.hpp"
#include <map>
#include <iostream>
#include <iomanip>
#include <gsl/gsl>
#include <fmt/format.h>
template<std::size_t N, std::size_t... Is>
constexpr std::array<char, N - 1> to_array(const char(&str)[N], std::index_sequence<Is...>) {
return { str[Is]... };
}
template<std::size_t N>
constexpr std::array<char, N - 1> to_array(const char(&str)[N]) {
return to_array(str, std::make_index_sequence<N - 1>{});
}
vendor_t get_vendor_from_name(const register_set_t& regs) {
static const std::map<std::array<char, 12>, vendor_t> vendors = {
{ to_array("AMDisbetter!"), amd },
{ to_array("AuthenticAMD"), amd },
{ to_array("CentaurHauls"), centaur },
{ to_array("CyrixInstead"), cyrix },
{ to_array("GenuineIntel"), intel },
{ to_array("TransmetaCPU"), transmeta },
{ to_array("GenuineTMx86"), transmeta },
{ to_array("Geode by NSC"), nat_semi },
{ to_array("NexGenDriven"), nexgen },
{ to_array("RiseRiseRise"), rise },
{ to_array("SiS SiS SiS "), sis },
{ to_array("UMC UMC UMC "), umc },
{ to_array("VIA VIA VIA "), via },
{ to_array("Vortex86 SoC"), vortex },
{ to_array("bhyve byhve "), bhyve },
{ to_array("KVMKVMKVM\0\0\0"), kvm },
{ to_array("Microsoft hv"), hyper_v },
{ to_array(" lrpepyh vr\0"), parallels },
{ to_array("VMwareVMware"), vmware },
{ to_array("XenVMMXenVMM"), xen_hvm }
};
union
{
std::array<char, 12> vndr;
std::array<std::int32_t, 3> registers;
} data;
data.registers[0] = regs[ebx];
data.registers[1] = regs[edx];
data.registers[2] = regs[ecx];
auto it = vendors.find(data.vndr);
return it != vendors.end() ? it->second : unknown;
}
model_t get_model(vendor_t vendor, const register_set_t& regs) noexcept {
union
{
std::uint32_t raw;
split_model_t m;
} split_model;
split_model.raw = regs[eax];
model_t model = {};
model.family = split_model.m.family;
model.model = split_model.m.model;
model.stepping = split_model.m.stepping;
switch(vendor) {
case intel:
{
if(split_model.m.family == 0xf) {
model.family += split_model.m.extended_family;
}
if(split_model.m.family == 0x6 || split_model.m.family == 0xf) {
model.model += (split_model.m.extended_model << 4ui32);
}
}
break;
case amd:
{
model.family += split_model.m.extended_family;
model.model += split_model.m.extended_model << 4ui32;
}
break;
default:
break;
}
return model;
}
using leaf_print = void(*)(const cpu_t& cpu);
using leaf_enumerate = void(*)(cpu_t& cpu);
struct leaf_descriptor_t
{
bool has_subleaves;
leaf_enumerate enumerator;
leaf_print printer;
};
const std::map<leaf_t, leaf_descriptor_t> descriptors = {
{ basic_info , { false, nullptr , print_basic_info } },
{ version_info , { false, nullptr , print_version_info } },
{ cache_and_tlb , { false, nullptr , print_cache_tlb_info } },
{ serial_number , { false, nullptr , print_serial_number } },
{ deterministic_cache , { true , enumerate_deterministic_cache, print_deterministic_cache } },
{ monitor_mwait , { false, nullptr , print_mwait_parameters } },
{ thermal_and_power , { false, nullptr , print_thermal_and_power } },
{ extended_features , { true , enumerate_extended_features , print_extended_features } },
{ direct_cache_access , { false, nullptr , print_direct_cache_access } },
{ performance_monitoring , { false, nullptr , print_performance_monitoring } },
{ extended_topology , { true , enumerate_extended_topology , print_extended_topology } },
{ reserved_2 , { false, nullptr , nullptr } },
{ extended_state , { true , nullptr , nullptr } },
{ reserved_3 , { false, nullptr , nullptr } },
{ resource_director_monitoring , { true , nullptr , nullptr } },
{ cache_allocation_technology , { true , nullptr , nullptr } },
{ reserved_4 , { false, nullptr , nullptr } },
{ sgx_info , { true , nullptr , nullptr } },
{ reserved_5 , { false, nullptr , nullptr } },
{ processor_trace , { true , nullptr , nullptr } },
{ time_stamp_counter , { false, nullptr , nullptr } },
{ processor_frequency , { false, nullptr , nullptr } },
{ system_on_chip_vendor , { true , nullptr , nullptr } },
{ deterministic_address_translation , { true , nullptr , nullptr } },
{ extended_limit , { false, nullptr , nullptr } },
{ extended_signature_and_features , { false, nullptr , nullptr } },
{ brand_string_0 , { false, nullptr , nullptr } },
{ brand_string_1 , { false, nullptr , nullptr } },
{ brand_string_2 , { false, nullptr , nullptr } },
{ l1_cache_identifiers , { false, nullptr , nullptr } },
{ l2_cache_identifiers , { false, nullptr , nullptr } },
{ advanced_power_management , { false, nullptr , nullptr } },
{ address_limits , { false, nullptr , nullptr } },
{ secure_virtual_machine , { false, nullptr , nullptr } },
{ tlb_1g_identifiers , { false, nullptr , nullptr } },
{ performance_optimization , { false, nullptr , nullptr } },
{ instruction_based_sampling , { false, nullptr , nullptr } },
{ cache_properties , { false, nullptr , nullptr } },
{ extended_apic , { false, nullptr , nullptr } },
{ secure_memory_encryption , { false, nullptr , nullptr } }
};
int main(int, char*[]) {
HANDLE output = ::GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
::GetConsoleMode(output, &mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
::SetConsoleMode(output, mode);
::SetConsoleCP(CP_UTF8);
::SetConsoleOutputCP(CP_UTF8);
std::cout.rdbuf()->pubsetbuf(nullptr, 1024);
::SetThreadAffinityMask(::GetCurrentThread(), 0x8);
cpu_t cpu = {};
register_set_t regs = { 0 };
cpuid(regs, leaf_t::basic_info, subleaf_t::zero);
cpu.highest_leaf = gsl::narrow_cast<std::uint32_t>(regs[eax]);
cpu.vendor = get_vendor_from_name(regs);
cpuid(regs, leaf_t::version_info, subleaf_t::zero);
cpu.model = get_model(cpu.vendor, regs);
for(leaf_t lf = leaf_t::basic_info; lf <= cpu.highest_leaf; ++lf) {
auto it = descriptors.find(lf);
if(it != descriptors.end()) {
if(it->second.has_subleaves && it->second.enumerator) {
it->second.enumerator(cpu);
} else {
cpuid(regs, lf, subleaf_t::zero);
cpu.features[lf][subleaf_t::zero] = regs;
}
}
}
cpuid(regs, leaf_t::extended_limit, subleaf_t::zero);
cpu.highest_extended_leaf = regs[eax];
for(leaf_t lf = leaf_t::extended_limit; lf <= cpu.highest_extended_leaf; ++lf) {
auto it = descriptors.find(lf);
if(it != descriptors.end()) {
if(it->second.has_subleaves && it->second.enumerator) {
it->second.enumerator(cpu);
} else {
cpuid(regs, lf, subleaf_t::zero);
cpu.features[lf][subleaf_t::zero] = regs;
}
}
}
for(const auto& lf : cpu.features) {
auto it = descriptors.find(lf.first);
if(it != descriptors.end()) {
if(it->second.printer) {
it->second.printer(cpu);
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2016 Filipe Coelho <falktx@falktx.com>
*
* This program 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.
*
* 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 Lesser General Public License for more details.
*
* For a full copy of the license see the LGPL.txt file
*/
#include "DistrhoPluginInternal.hpp"
#if DISTRHO_PLUGIN_HAS_UI
# include "DistrhoUIInternal.hpp"
#endif
#include "CarlaNative.hpp"
// -----------------------------------------------------------------------
START_NAMESPACE_DISTRHO
#if DISTRHO_PLUGIN_HAS_UI
// -----------------------------------------------------------------------
// Carla UI
#if ! DISTRHO_PLUGIN_WANT_STATE
static const setStateFunc setStateCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_IS_SYNTH
static const sendNoteFunc sendNoteCallback = nullptr;
#endif
class UICarla
{
public:
UICarla(const NativeHostDescriptor* const host, PluginExporter* const plugin)
: fHost(host),
fUI(this, 0, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer())
{
fUI.setWindowTitle(host->uiName);
if (host->uiParentId != 0)
fUI.setWindowTransientWinId(host->uiParentId);
}
~UICarla()
{
fUI.quit();
}
// ---------------------------------------------
void carla_show(const bool yesNo)
{
fUI.setWindowVisible(yesNo);
}
bool carla_idle()
{
return fUI.idle();
}
void carla_setParameterValue(const uint32_t index, const float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void carla_setMidiProgram(const uint32_t realProgram)
{
fUI.programLoaded(realProgram);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void carla_setCustomData(const char* const key, const char* const value)
{
fUI.stateChanged(key, value);
}
#endif
void carla_setUiTitle(const char* const uiTitle)
{
fUI.setWindowTitle(uiTitle);
}
// ---------------------------------------------
protected:
void handleEditParameter(const uint32_t, const bool)
{
// TODO
}
void handleSetParameterValue(const uint32_t rindex, const float value)
{
fHost->ui_parameter_changed(fHost->handle, rindex, value);
}
void handleSetState(const char* const key, const char* const value)
{
fHost->ui_custom_data_changed(fHost->handle, key, value);
}
void handleSendNote(const uint8_t, const uint8_t, const uint8_t)
{
// TODO
}
void handleSetSize(const uint width, const uint height)
{
fUI.setWindowSize(width, height);
}
// ---------------------------------------------
private:
// Plugin stuff
const NativeHostDescriptor* const fHost;
// UI
UIExporter fUI;
// ---------------------------------------------
// Callbacks
#define handlePtr ((UICarla*)ptr)
static void editParameterCallback(void* ptr, uint32_t index, bool started)
{
handlePtr->handleEditParameter(index, started);
}
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
handlePtr->handleSetParameterValue(rindex, value);
}
#if DISTRHO_PLUGIN_WANT_STATE
static void setStateCallback(void* ptr, const char* key, const char* value)
{
handlePtr->handleSetState(key, value);
}
#endif
#if DISTRHO_PLUGIN_IS_SYNTH
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
handlePtr->handleSendNote(channel, note, velocity);
}
#endif
static void setSizeCallback(void* ptr, uint width, uint height)
{
handlePtr->handleSetSize(width, height);
}
#undef handlePtr
CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UICarla)
};
#endif // DISTRHO_PLUGIN_HAS_UI
// -----------------------------------------------------------------------
// Carla Plugin
class PluginCarla : public NativePluginClass
{
public:
PluginCarla(const NativeHostDescriptor* const host)
: NativePluginClass(host)
{
#if DISTRHO_PLUGIN_HAS_UI
fUiPtr = nullptr;
#endif
}
~PluginCarla() override
{
#if DISTRHO_PLUGIN_HAS_UI
if (fUiPtr != nullptr)
{
delete fUiPtr;
fUiPtr = nullptr;
}
#endif
}
protected:
// -------------------------------------------------------------------
// Plugin parameter calls
uint32_t getParameterCount() const override
{
return fPlugin.getParameterCount();
}
const NativeParameter* getParameterInfo(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), nullptr);
static NativeParameter param;
param.scalePointCount = 0;
param.scalePoints = nullptr;
{
int nativeParamHints = ::NATIVE_PARAMETER_IS_ENABLED;
const uint32_t paramHints = fPlugin.getParameterHints(index);
if (paramHints & kParameterIsAutomable)
nativeParamHints |= ::NATIVE_PARAMETER_IS_AUTOMABLE;
if (paramHints & kParameterIsBoolean)
nativeParamHints |= ::NATIVE_PARAMETER_IS_BOOLEAN;
if (paramHints & kParameterIsInteger)
nativeParamHints |= ::NATIVE_PARAMETER_IS_INTEGER;
if (paramHints & kParameterIsLogarithmic)
nativeParamHints |= ::NATIVE_PARAMETER_IS_LOGARITHMIC;
if (paramHints & kParameterIsOutput)
nativeParamHints |= ::NATIVE_PARAMETER_IS_OUTPUT;
param.hints = static_cast<NativeParameterHints>(nativeParamHints);
}
param.name = fPlugin.getParameterName(index);
param.unit = fPlugin.getParameterUnit(index);
{
const ParameterRanges& ranges(fPlugin.getParameterRanges(index));
param.ranges.def = ranges.def;
param.ranges.min = ranges.min;
param.ranges.max = ranges.max;
}
return ¶m;
}
float getParameterValue(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), 0.0f);
return fPlugin.getParameterValue(index);
}
// -------------------------------------------------------------------
// Plugin midi-program calls
#if DISTRHO_PLUGIN_WANT_PROGRAMS
uint32_t getMidiProgramCount() const override
{
return fPlugin.getProgramCount();
}
const NativeMidiProgram* getMidiProgramInfo(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getMidiProgramCount(), nullptr);
static NativeMidiProgram midiProgram;
midiProgram.bank = index / 128;
midiProgram.program = index % 128;
midiProgram.name = fPlugin.getProgramName(index);
return &midiProgram;
}
#endif
// -------------------------------------------------------------------
// Plugin state calls
void setParameterValue(const uint32_t index, const float value) override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),);
fPlugin.setParameterValue(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void setMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override
{
const uint32_t realProgram(bank * 128 + program);
CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),);
fPlugin.loadProgram(realProgram);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void setCustomData(const char* const key, const char* const value) override
{
CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
fPlugin.setState(key, value);
}
#endif
// -------------------------------------------------------------------
// Plugin process calls
void activate() override
{
fPlugin.activate();
}
void deactivate() override
{
fPlugin.deactivate();
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const midiEvents, const uint32_t midiEventCount) override
{
MidiEvent realMidiEvents[midiEventCount];
for (uint32_t i=0; i < midiEventCount; ++i)
{
const NativeMidiEvent& midiEvent(midiEvents[i]);
MidiEvent& realMidiEvent(realMidiEvents[i]);
realMidiEvent.frame = midiEvent.time;
realMidiEvent.size = midiEvent.size;
uint8_t j=0;
for (; j<midiEvent.size; ++j)
realMidiEvent.data[j] = midiEvent.data[j];
for (; j<midiEvent.size; ++j)
realMidiEvent.data[j] = midiEvent.data[j];
realMidiEvent.dataExt = nullptr;
}
fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames, realMidiEvents, midiEventCount);
}
#else
void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const, const uint32_t) override
{
fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames);
}
#endif
// -------------------------------------------------------------------
// Plugin UI calls
#if DISTRHO_PLUGIN_HAS_UI
void uiShow(const bool show) override
{
if (show)
{
createUiIfNeeded();
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
fUiPtr->carla_show(show);
}
else if (fUiPtr != nullptr)
{
delete fUiPtr;
fUiPtr = nullptr;
}
}
void uiIdle() override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
if (! fUiPtr->carla_idle())
{
uiClosed();
delete fUiPtr;
fUiPtr = nullptr;
}
}
void uiSetParameterValue(const uint32_t index, const float value) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),);
fUiPtr->carla_setParameterValue(index, value);
}
# if DISTRHO_PLUGIN_WANT_PROGRAMS
void uiSetMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
const uint32_t realProgram(bank * 128 + program);
CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),);
fUiPtr->carla_setMidiProgram(realProgram);
}
# endif
# if DISTRHO_PLUGIN_WANT_STATE
void uiSetCustomData(const char* const key, const char* const value) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
fUiPtr->carla_setCustomData(key, value);
}
# endif
#endif
// -------------------------------------------------------------------
// Plugin dispatcher calls
void bufferSizeChanged(const uint32_t bufferSize) override
{
fPlugin.setBufferSize(bufferSize, true);
}
void sampleRateChanged(const double sampleRate) override
{
fPlugin.setSampleRate(sampleRate, true);
}
#if DISTRHO_PLUGIN_HAS_UI
void uiNameChanged(const char* const uiName) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
fUiPtr->carla_setUiTitle(uiName);
}
#endif
// -------------------------------------------------------------------
private:
PluginExporter fPlugin;
#if DISTRHO_PLUGIN_HAS_UI
// UI
UICarla* fUiPtr;
void createUiIfNeeded()
{
if (fUiPtr == nullptr)
{
d_lastUiSampleRate = getSampleRate();
fUiPtr = new UICarla(getHostHandle(), &fPlugin);
}
}
#endif
CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginCarla)
// -------------------------------------------------------------------
public:
static NativePluginHandle _instantiate(const NativeHostDescriptor* host)
{
d_lastBufferSize = host->get_buffer_size(host->handle);
d_lastSampleRate = host->get_sample_rate(host->handle);
return new PluginCarla(host);
}
static void _cleanup(NativePluginHandle handle)
{
delete (PluginCarla*)handle;
}
};
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
<commit_msg>Update carla format code, fix license<commit_after>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2018 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoPluginInternal.hpp"
#if DISTRHO_PLUGIN_HAS_UI
# include "DistrhoUIInternal.hpp"
#endif
#include "CarlaNative.hpp"
// -----------------------------------------------------------------------
START_NAMESPACE_DISTRHO
#if DISTRHO_PLUGIN_HAS_UI
// -----------------------------------------------------------------------
// Carla UI
#if ! DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
static const writeMidiFunc writeMidiCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_WANT_STATE
static const setStateFunc setStateCallback = nullptr;
#endif
#if ! DISTRHO_PLUGIN_IS_SYNTH
static const sendNoteFunc sendNoteCallback = nullptr;
#endif
class UICarla
{
public:
UICarla(const NativeHostDescriptor* const host, PluginExporter* const plugin)
: fHost(host),
fUI(this, 0, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer())
{
fUI.setWindowTitle(host->uiName);
if (host->uiParentId != 0)
fUI.setWindowTransientWinId(host->uiParentId);
}
~UICarla()
{
fUI.quit();
}
// ---------------------------------------------
void carla_show(const bool yesNo)
{
fUI.setWindowVisible(yesNo);
}
bool carla_idle()
{
return fUI.idle();
}
void carla_setParameterValue(const uint32_t index, const float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void carla_setMidiProgram(const uint32_t realProgram)
{
fUI.programLoaded(realProgram);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void carla_setCustomData(const char* const key, const char* const value)
{
fUI.stateChanged(key, value);
}
#endif
void carla_setUiTitle(const char* const uiTitle)
{
fUI.setWindowTitle(uiTitle);
}
// ---------------------------------------------
protected:
void handleEditParameter(const uint32_t, const bool)
{
// TODO
}
void handleSetParameterValue(const uint32_t rindex, const float value)
{
fHost->ui_parameter_changed(fHost->handle, rindex, value);
}
#if DISTRHO_PLUGIN_WANT_STATE
void handleSetState(const char* const key, const char* const value)
{
fHost->ui_custom_data_changed(fHost->handle, key, value);
}
#endif
#if DISTRHO_PLUGIN_IS_SYNTH
void handleSendNote(const uint8_t, const uint8_t, const uint8_t)
{
// TODO
}
#endif
void handleSetSize(const uint width, const uint height)
{
fUI.setWindowSize(width, height);
}
// ---------------------------------------------
private:
// Plugin stuff
const NativeHostDescriptor* const fHost;
// UI
UIExporter fUI;
// ---------------------------------------------
// Callbacks
#define handlePtr ((UICarla*)ptr)
static void editParameterCallback(void* ptr, uint32_t index, bool started)
{
handlePtr->handleEditParameter(index, started);
}
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
handlePtr->handleSetParameterValue(rindex, value);
}
#if DISTRHO_PLUGIN_WANT_STATE
static void setStateCallback(void* ptr, const char* key, const char* value)
{
handlePtr->handleSetState(key, value);
}
#endif
#if DISTRHO_PLUGIN_IS_SYNTH
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
handlePtr->handleSendNote(channel, note, velocity);
}
#endif
static void setSizeCallback(void* ptr, uint width, uint height)
{
handlePtr->handleSetSize(width, height);
}
#undef handlePtr
CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UICarla)
};
#endif // DISTRHO_PLUGIN_HAS_UI
// -----------------------------------------------------------------------
// Carla Plugin
class PluginCarla : public NativePluginClass
{
public:
PluginCarla(const NativeHostDescriptor* const host)
: NativePluginClass(host),
fPlugin(this, writeMidiCallback),
fScalePointsCache(nullptr)
{
#if DISTRHO_PLUGIN_HAS_UI
fUiPtr = nullptr;
#endif
}
~PluginCarla() override
{
#if DISTRHO_PLUGIN_HAS_UI
if (fUiPtr != nullptr)
{
delete fUiPtr;
fUiPtr = nullptr;
}
#endif
if (fScalePointsCache != nullptr)
{
delete[] fScalePointsCache;
fScalePointsCache = nullptr;
}
}
protected:
// -------------------------------------------------------------------
// Plugin parameter calls
uint32_t getParameterCount() const override
{
return fPlugin.getParameterCount();
}
const NativeParameter* getParameterInfo(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), nullptr);
static NativeParameter param;
param.scalePointCount = 0;
param.scalePoints = nullptr;
{
int nativeParamHints = ::NATIVE_PARAMETER_IS_ENABLED;
const uint32_t paramHints = fPlugin.getParameterHints(index);
if (paramHints & kParameterIsAutomable)
nativeParamHints |= ::NATIVE_PARAMETER_IS_AUTOMABLE;
if (paramHints & kParameterIsBoolean)
nativeParamHints |= ::NATIVE_PARAMETER_IS_BOOLEAN;
if (paramHints & kParameterIsInteger)
nativeParamHints |= ::NATIVE_PARAMETER_IS_INTEGER;
if (paramHints & kParameterIsLogarithmic)
nativeParamHints |= ::NATIVE_PARAMETER_IS_LOGARITHMIC;
if (paramHints & kParameterIsOutput)
nativeParamHints |= ::NATIVE_PARAMETER_IS_OUTPUT;
param.hints = static_cast<NativeParameterHints>(nativeParamHints);
}
param.name = fPlugin.getParameterName(index);
param.unit = fPlugin.getParameterUnit(index);
{
const ParameterRanges& ranges(fPlugin.getParameterRanges(index));
param.ranges.def = ranges.def;
param.ranges.min = ranges.min;
param.ranges.max = ranges.max;
}
{
const ParameterEnumerationValues& enumValues(fPlugin.getParameterEnumValues(index));
if (const uint32_t scalePointCount = enumValues.count)
{
NativeParameterScalePoint* const scalePoints = new NativeParameterScalePoint[scalePointCount];
for (uint32_t i=0; i<scalePointCount; ++i)
{
scalePoints[i].label = enumValues.values[i].label.buffer();
scalePoints[i].value = enumValues.values[i].value;
}
param.scalePoints = scalePoints;
param.scalePointCount = scalePointCount;
if (enumValues.restrictedMode)
param.hints = static_cast<NativeParameterHints>(param.hints|::NATIVE_PARAMETER_USES_SCALEPOINTS);
}
else if (fScalePointsCache != nullptr)
{
delete[] fScalePointsCache;
fScalePointsCache = nullptr;
}
}
return ¶m;
}
float getParameterValue(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), 0.0f);
return fPlugin.getParameterValue(index);
}
// -------------------------------------------------------------------
// Plugin midi-program calls
#if DISTRHO_PLUGIN_WANT_PROGRAMS
uint32_t getMidiProgramCount() const override
{
return fPlugin.getProgramCount();
}
const NativeMidiProgram* getMidiProgramInfo(const uint32_t index) const override
{
CARLA_SAFE_ASSERT_RETURN(index < getMidiProgramCount(), nullptr);
static NativeMidiProgram midiProgram;
midiProgram.bank = index / 128;
midiProgram.program = index % 128;
midiProgram.name = fPlugin.getProgramName(index);
return &midiProgram;
}
#endif
// -------------------------------------------------------------------
// Plugin state calls
void setParameterValue(const uint32_t index, const float value) override
{
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),);
fPlugin.setParameterValue(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void setMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override
{
const uint32_t realProgram(bank * 128 + program);
CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),);
fPlugin.loadProgram(realProgram);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void setCustomData(const char* const key, const char* const value) override
{
CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
fPlugin.setState(key, value);
}
#endif
// -------------------------------------------------------------------
// Plugin process calls
void activate() override
{
fPlugin.activate();
}
void deactivate() override
{
fPlugin.deactivate();
}
#if DISTRHO_PLUGIN_WANT_MIDI_INPUT
void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const midiEvents, const uint32_t midiEventCount) override
{
MidiEvent realMidiEvents[midiEventCount];
for (uint32_t i=0; i < midiEventCount; ++i)
{
const NativeMidiEvent& midiEvent(midiEvents[i]);
MidiEvent& realMidiEvent(realMidiEvents[i]);
realMidiEvent.frame = midiEvent.time;
realMidiEvent.size = midiEvent.size;
uint8_t j=0;
for (; j<midiEvent.size; ++j)
realMidiEvent.data[j] = midiEvent.data[j];
for (; j<midiEvent.size; ++j)
realMidiEvent.data[j] = midiEvent.data[j];
realMidiEvent.dataExt = nullptr;
}
fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames, realMidiEvents, midiEventCount);
}
#else
void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const, const uint32_t) override
{
fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames);
}
#endif
// -------------------------------------------------------------------
// Plugin UI calls
#if DISTRHO_PLUGIN_HAS_UI
void uiShow(const bool show) override
{
if (show)
{
createUiIfNeeded();
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
fUiPtr->carla_show(show);
}
else if (fUiPtr != nullptr)
{
delete fUiPtr;
fUiPtr = nullptr;
}
}
void uiIdle() override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
if (! fUiPtr->carla_idle())
{
uiClosed();
delete fUiPtr;
fUiPtr = nullptr;
}
}
void uiSetParameterValue(const uint32_t index, const float value) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),);
fUiPtr->carla_setParameterValue(index, value);
}
# if DISTRHO_PLUGIN_WANT_PROGRAMS
void uiSetMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
const uint32_t realProgram(bank * 128 + program);
CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),);
fUiPtr->carla_setMidiProgram(realProgram);
}
# endif
# if DISTRHO_PLUGIN_WANT_STATE
void uiSetCustomData(const char* const key, const char* const value) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
fUiPtr->carla_setCustomData(key, value);
}
# endif
#endif
// -------------------------------------------------------------------
// Plugin dispatcher calls
void bufferSizeChanged(const uint32_t bufferSize) override
{
fPlugin.setBufferSize(bufferSize, true);
}
void sampleRateChanged(const double sampleRate) override
{
fPlugin.setSampleRate(sampleRate, true);
}
#if DISTRHO_PLUGIN_HAS_UI
void uiNameChanged(const char* const uiName) override
{
CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,);
fUiPtr->carla_setUiTitle(uiName);
}
#endif
// -------------------------------------------------------------------
private:
PluginExporter fPlugin;
mutable NativeParameterScalePoint* fScalePointsCache;
#if DISTRHO_PLUGIN_HAS_UI
// UI
UICarla* fUiPtr;
void createUiIfNeeded()
{
if (fUiPtr == nullptr)
{
d_lastUiSampleRate = getSampleRate();
fUiPtr = new UICarla(getHostHandle(), &fPlugin);
}
}
#endif
#if DISTRHO_PLUGIN_WANT_MIDI_OUTPUT
static bool writeMidiCallback(void* ptr, const MidiEvent& midiEvent)
{
if (midiEvent.size > 4)
return;
const NativeMidiEvent event = {
midiEvent.frame, 0, midiEvent.size, midiEvent.data
};
return ((PluginCarla*)ptr)->fPlugin.writeMidiEvent(midiEvent);
}
#endif
CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginCarla)
// -------------------------------------------------------------------
public:
static NativePluginHandle _instantiate(const NativeHostDescriptor* host)
{
d_lastBufferSize = host->get_buffer_size(host->handle);
d_lastSampleRate = host->get_sample_rate(host->handle);
return new PluginCarla(host);
}
static void _cleanup(NativePluginHandle handle)
{
delete (PluginCarla*)handle;
}
};
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* <x0/HttpConnection.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpListener.h>
#include <x0/http/HttpRequest.h>
#include <x0/SocketDriver.h>
#include <x0/StackTrace.h>
#include <x0/Socket.h>
#include <x0/Types.h>
#include <x0/sysconfig.h>
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#if 0 // !defined(NDEBUG)
# define TRACE(msg...) DEBUG("HttpConnection: " msg)
#else
# define TRACE(msg...)
#endif
#define X0_HTTP_STRICT 1
namespace x0 {
/**
* \class HttpConnection
* \brief represents an HTTP connection handling incoming requests.
*
* The \p HttpConnection object is to be allocated once an HTTP client connects
* to the HTTP server and was accepted by the \p HttpListener.
* It will also own the respective request and response objects created to serve
* the requests passed through this connection.
*/
/** initializes a new connection object, created by given listener.
* \param lst the listener object that created this connection.
* \note This triggers the onConnectionOpen event.
*/
HttpConnection::HttpConnection(HttpListener& lst, HttpWorker& w, int fd) :
HttpMessageProcessor(HttpMessageProcessor::REQUEST),
secure(false),
listener_(lst),
worker_(w),
socket_(0),
active_(true), // when this is constricuted, it *must* be active right now :)
buffer_(8192),
offset_(0),
request_count_(0),
request_(0),
source_(),
sink_(NULL),
onWriteComplete_(),
bytesTransferred_(0)
#if !defined(NDEBUG)
, ctime_(ev_now(loop()))
#endif
{
socket_ = listener_.socketDriver()->create(loop(), fd, lst.addressFamily());
sink_.setSocket(socket_);
TRACE("(%p): fd=%d", this, socket_->handle());
#if defined(TCP_NODELAY)
if (worker_.server_.tcp_nodelay())
socket_->setTcpNoDelay(true);
#endif
worker_.server_.onConnectionOpen(this);
}
/** releases all connection resources and triggers the onConnectionClose event.
*/
HttpConnection::~HttpConnection()
{
delete request_;
request_ = 0;
TRACE("~(%p)", this);
//TRACE("Stack Trace:\n%s", StackTrace().c_str());
worker_.release(this);
try
{
worker_.server_.onConnectionClose(this); // we cannot pass a shared pointer here as use_count is already zero and it would just lead into an exception though
}
catch (...)
{
TRACE("~HttpConnection(%p): unexpected exception", this);
}
if (socket_)
{
delete socket_;
#if !defined(NDEBUG)
socket_ = 0;
#endif
}
}
void HttpConnection::io(Socket *)
{
TRACE("(%p).io(mode=%s)", this, socket_->mode_str());
active_ = true;
switch (socket_->mode())
{
case Socket::READ:
processInput();
break;
case Socket::WRITE:
processOutput();
break;
default:
break;
}
if (isClosed())
delete this;
else
active_ = false;
}
void HttpConnection::timeout(Socket *)
{
TRACE("(%p): timed out", this);
// ev_unloop(loop(), EVUNLOOP_ONE);
delete this;
}
#if defined(WITH_SSL)
bool HttpConnection::isSecure() const
{
return listener_.isSecure();
}
#endif
/** start first async operation for this HttpConnection.
*
* This is done by simply registering the underlying socket to the the I/O service
* to watch for available input.
* \see stop()
* :
*/
void HttpConnection::start()
{
if (socket_->state() == Socket::HANDSHAKE)
{
//TRACE("start: handshake.");
socket_->handshake<HttpConnection, &HttpConnection::handshakeComplete>(this);
}
else
{
#if defined(TCP_DEFER_ACCEPT)
//TRACE("start: read.");
// it is ensured, that we have data pending, so directly start reading
processInput();
// destroy connection in case the above caused connection-close
// XXX this is usually done within HttpConnection::io(), but we are not.
if (isClosed())
delete this;
else
active_ = false;
#else
//TRACE("start: startRead.");
// client connected, but we do not yet know if we have data pending
startRead();
#endif
}
}
void HttpConnection::handshakeComplete(Socket *)
{
TRACE("handshakeComplete() socketState=%s", socket_->state_str());
if (socket_->state() == Socket::OPERATIONAL)
startRead();
else
{
TRACE("handshakeComplete(): handshake failed\n%s", StackTrace().c_str());
close(); //delete this;
}
}
inline bool url_decode(BufferRef& url)
{
std::size_t left = url.offset();
std::size_t right = left + url.size();
std::size_t i = left; // read pos
std::size_t d = left; // write pos
Buffer& value = url.buffer();
while (i != right)
{
if (value[i] == '%')
{
if (i + 3 <= right)
{
int ival;
if (hex2int(value.begin() + i + 1, value.begin() + i + 3, ival))
{
value[d++] = static_cast<char>(ival);
i += 3;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (value[i] == '+')
{
value[d++] = ' ';
++i;
}
else if (d != i)
{
value[d++] = value[i++];
}
else
{
++d;
++i;
}
}
url = value.ref(left, d - left);
return true;
}
void HttpConnection::messageBegin(BufferRef&& method, BufferRef&& uri, int version_major, int version_minor)
{
TRACE("messageBegin('%s', '%s', HTTP/%d.%d)", method.str().c_str(), uri.str().c_str(), version_major, version_minor);
request_ = new HttpRequest(*this);
request_->method = std::move(method);
request_->uri = std::move(uri);
url_decode(request_->uri);
std::size_t n = request_->uri.find("?");
if (n != std::string::npos)
{
request_->path = request_->uri.ref(0, n);
request_->query = request_->uri.ref(n + 1);
}
else
{
request_->path = request_->uri;
}
request_->httpVersionMajor = version_major;
request_->httpVersionMinor = version_minor;
}
void HttpConnection::messageHeader(BufferRef&& name, BufferRef&& value)
{
if (iequals(name, "Host"))
{
auto i = value.find(':');
if (i != BufferRef::npos)
request_->hostname = value.ref(0, i);
else
request_->hostname = value;
}
request_->requestHeaders.push_back(HttpRequestHeader(std::move(name), std::move(value)));
}
bool HttpConnection::messageHeaderEnd()
{
TRACE("messageHeaderEnd()");
#if X0_HTTP_STRICT
BufferRef expectHeader = request_->requestHeader("Expect");
bool content_required = request_->method == "POST" || request_->method == "PUT";
if (content_required && !request_->contentAvailable())
{
request_->status = HttpError::LengthRequired;
request_->finish();
}
else if (!content_required && request_->contentAvailable())
{
request_->status = HttpError::BadRequest; // FIXME do we have a better status code?
request_->finish();
}
else if (expectHeader)
{
request_->expectingContinue = equals(expectHeader, "100-continue");
if (!request_->expectingContinue || !request_->supportsProtocol(1, 1))
{
printf("expectHeader: failed\n");
request_->status = HttpError::ExpectationFailed;
request_->finish();
}
else
worker_.handleRequest(request_);
}
else
worker_.handleRequest(request_);
#else
worker_.handleRequest(request_);
#endif
return true;
}
bool HttpConnection::messageContent(BufferRef&& chunk)
{
TRACE("messageContent(#%ld)", chunk.size());
if (request_)
request_->onRequestContent(std::move(chunk));
return true;
}
bool HttpConnection::messageEnd()
{
TRACE("messageEnd()");
// increment the number of fully processed requests
++request_count_;
// XXX is this really required? (meant to mark the request-content EOS)
if (request_)
request_->onRequestContent(BufferRef());
// allow continueing processing possible further requests
return true;
}
/** Resumes processing the <b>next</b> HTTP request message within this connection.
*
* This method may only be invoked when the current/old request has been fully processed,
* and is though only be invoked from within the finish handler of \p HttpRequest.
*
* \see HttpRequest::finish()
*/
void HttpConnection::resume()
{
if (socket()->tcpCork())
socket()->setTcpCork(false);
delete request_;
request_ = 0;
// wait for new request message, if nothing in buffer
if (offset_ != buffer_.size())
startRead();
}
void HttpConnection::startRead()
{
int timeout = request_count_ && state() == MESSAGE_BEGIN
? worker_.server_.max_keep_alive_idle()
: worker_.server_.max_read_idle();
if (timeout > 0)
socket_->setTimeout<HttpConnection, &HttpConnection::timeout>(this, timeout);
socket_->setReadyCallback<HttpConnection, &HttpConnection::io>(this);
socket_->setMode(Socket::READ);
}
/**
* This method gets invoked when there is data in our HttpConnection ready to read.
*
* We assume, that we are in request-parsing state.
*/
void HttpConnection::processInput()
{
TRACE("(%p).processInput()", this);
ssize_t rv = socket_->read(buffer_);
if (rv < 0) // error
{
if (errno == EAGAIN || errno == EINTR)
{
startRead();
ev_unloop(loop(), EVUNLOOP_ONE);
}
else
{
TRACE("processInput(): %s", strerror(errno));
close();
}
}
else if (rv == 0) // EOF
{
TRACE("processInput(): (EOF)");
close();
}
else
{
TRACE("processInput(): read %ld bytes", rv);
//std::size_t offset = buffer_.size();
//buffer_.resize(offset + rv);
process();
TRACE("(%p).processInput(): done process()ing; mode=%s, fd=%d, request=%p",
this, socket_->mode_str(), socket_->handle(), request_);
}
}
/**
* Writes as much as it wouldn't block of the response stream into the underlying socket.
*
*/
void HttpConnection::processOutput()
{
TRACE("processOutput()");
for (;;)
{
ssize_t rv = sink_.pump(source_);
TRACE("processOutput(): pump().rv=%ld %s", rv, rv < 0 ? strerror(errno) : "");
// TODO make use of source_->eof()
if (rv > 0) // source (partially?) written
{
bytesTransferred_ += rv;
}
else if (rv == 0) // source fully written
{
//TRACE("processOutput(): source fully written");
source_.reset();
if (onWriteComplete_)
onWriteComplete_(0, bytesTransferred_);
//onWriteComplete_ = CompletionHandlerType();
break;
}
else if (errno == EAGAIN || errno == EINTR) // completing write would block
{
socket_->setReadyCallback<HttpConnection, &HttpConnection::io>(this); // XXX should be same
socket_->setMode(Socket::WRITE);
break;
}
else // an error occurred
{
TRACE("processOutput(): write error (%d): %s", errno, strerror(errno));
source_.reset();
if (onWriteComplete_)
onWriteComplete_(errno, bytesTransferred_);
//onWriteComplete_ = CompletionHandlerType();
close();
break;
}
}
}
/** closes this HttpConnection, possibly deleting this object (or propagating delayed delete).
*/
void HttpConnection::close()
{
TRACE("(%p).close() (active=%d)", this, active_);
TRACE("Stack Trace:%s\n", StackTrace().c_str());
socket_->close();
if (!active_)
delete this;
}
/** processes a (partial) request from buffer's given \p offset of \p count bytes.
*/
void HttpConnection::process()
{
TRACE("process: offset=%ld, size=%ld (before processing)", offset_, buffer_.size());
std::error_code ec = HttpMessageProcessor::process(
buffer_.ref(offset_, buffer_.size() - offset_),
offset_);
TRACE("process: offset=%ld, bs=%ld, ec=%s, state=%s (after processing)",
offset_, buffer_.size(), ec.message().c_str(), state_str());
if (state() == HttpMessageProcessor::MESSAGE_BEGIN)
{
#if 0
offset_ = 0;
buffer_.clear();
#endif
}
if (isClosed())
return;
if (ec == HttpMessageError::Partial)
startRead();
else if (ec && ec != HttpMessageError::Aborted)
{
// -> send stock response: BAD_REQUEST
request_->status = HttpError::BadRequest;
request_->finish();
}
}
std::string HttpConnection::remoteIP() const
{
return socket_->remoteIP();
}
unsigned int HttpConnection::remotePort() const
{
return socket_->remotePort();
}
std::string HttpConnection::localIP() const
{
return listener_.address();
}
unsigned int HttpConnection::localPort() const
{
return socket_->localPort();
}
} // namespace x0
<commit_msg>[http] HttpConnection: fix a 411 case as POST messages with "Content-Length: 0" are to be valid, too.<commit_after>/* <x0/HttpConnection.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpListener.h>
#include <x0/http/HttpRequest.h>
#include <x0/SocketDriver.h>
#include <x0/StackTrace.h>
#include <x0/Socket.h>
#include <x0/Types.h>
#include <x0/sysconfig.h>
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#if 0 // !defined(NDEBUG)
# define TRACE(msg...) DEBUG("HttpConnection: " msg)
#else
# define TRACE(msg...)
#endif
#define X0_HTTP_STRICT 1
namespace x0 {
/**
* \class HttpConnection
* \brief represents an HTTP connection handling incoming requests.
*
* The \p HttpConnection object is to be allocated once an HTTP client connects
* to the HTTP server and was accepted by the \p HttpListener.
* It will also own the respective request and response objects created to serve
* the requests passed through this connection.
*/
/** initializes a new connection object, created by given listener.
* \param lst the listener object that created this connection.
* \note This triggers the onConnectionOpen event.
*/
HttpConnection::HttpConnection(HttpListener& lst, HttpWorker& w, int fd) :
HttpMessageProcessor(HttpMessageProcessor::REQUEST),
secure(false),
listener_(lst),
worker_(w),
socket_(0),
active_(true), // when this is constricuted, it *must* be active right now :)
buffer_(8192),
offset_(0),
request_count_(0),
request_(0),
source_(),
sink_(NULL),
onWriteComplete_(),
bytesTransferred_(0)
#if !defined(NDEBUG)
, ctime_(ev_now(loop()))
#endif
{
socket_ = listener_.socketDriver()->create(loop(), fd, lst.addressFamily());
sink_.setSocket(socket_);
TRACE("(%p): fd=%d", this, socket_->handle());
#if defined(TCP_NODELAY)
if (worker_.server_.tcp_nodelay())
socket_->setTcpNoDelay(true);
#endif
worker_.server_.onConnectionOpen(this);
}
/** releases all connection resources and triggers the onConnectionClose event.
*/
HttpConnection::~HttpConnection()
{
delete request_;
request_ = 0;
TRACE("~(%p)", this);
//TRACE("Stack Trace:\n%s", StackTrace().c_str());
worker_.release(this);
try
{
worker_.server_.onConnectionClose(this); // we cannot pass a shared pointer here as use_count is already zero and it would just lead into an exception though
}
catch (...)
{
TRACE("~HttpConnection(%p): unexpected exception", this);
}
if (socket_)
{
delete socket_;
#if !defined(NDEBUG)
socket_ = 0;
#endif
}
}
void HttpConnection::io(Socket *)
{
TRACE("(%p).io(mode=%s)", this, socket_->mode_str());
active_ = true;
switch (socket_->mode())
{
case Socket::READ:
processInput();
break;
case Socket::WRITE:
processOutput();
break;
default:
break;
}
if (isClosed())
delete this;
else
active_ = false;
}
void HttpConnection::timeout(Socket *)
{
TRACE("(%p): timed out", this);
// ev_unloop(loop(), EVUNLOOP_ONE);
delete this;
}
#if defined(WITH_SSL)
bool HttpConnection::isSecure() const
{
return listener_.isSecure();
}
#endif
/** start first async operation for this HttpConnection.
*
* This is done by simply registering the underlying socket to the the I/O service
* to watch for available input.
* \see stop()
* :
*/
void HttpConnection::start()
{
if (socket_->state() == Socket::HANDSHAKE)
{
//TRACE("start: handshake.");
socket_->handshake<HttpConnection, &HttpConnection::handshakeComplete>(this);
}
else
{
#if defined(TCP_DEFER_ACCEPT)
//TRACE("start: read.");
// it is ensured, that we have data pending, so directly start reading
processInput();
// destroy connection in case the above caused connection-close
// XXX this is usually done within HttpConnection::io(), but we are not.
if (isClosed())
delete this;
else
active_ = false;
#else
//TRACE("start: startRead.");
// client connected, but we do not yet know if we have data pending
startRead();
#endif
}
}
void HttpConnection::handshakeComplete(Socket *)
{
TRACE("handshakeComplete() socketState=%s", socket_->state_str());
if (socket_->state() == Socket::OPERATIONAL)
startRead();
else
{
TRACE("handshakeComplete(): handshake failed\n%s", StackTrace().c_str());
close(); //delete this;
}
}
inline bool url_decode(BufferRef& url)
{
std::size_t left = url.offset();
std::size_t right = left + url.size();
std::size_t i = left; // read pos
std::size_t d = left; // write pos
Buffer& value = url.buffer();
while (i != right)
{
if (value[i] == '%')
{
if (i + 3 <= right)
{
int ival;
if (hex2int(value.begin() + i + 1, value.begin() + i + 3, ival))
{
value[d++] = static_cast<char>(ival);
i += 3;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (value[i] == '+')
{
value[d++] = ' ';
++i;
}
else if (d != i)
{
value[d++] = value[i++];
}
else
{
++d;
++i;
}
}
url = value.ref(left, d - left);
return true;
}
void HttpConnection::messageBegin(BufferRef&& method, BufferRef&& uri, int version_major, int version_minor)
{
TRACE("messageBegin('%s', '%s', HTTP/%d.%d)", method.str().c_str(), uri.str().c_str(), version_major, version_minor);
request_ = new HttpRequest(*this);
request_->method = std::move(method);
request_->uri = std::move(uri);
url_decode(request_->uri);
std::size_t n = request_->uri.find("?");
if (n != std::string::npos)
{
request_->path = request_->uri.ref(0, n);
request_->query = request_->uri.ref(n + 1);
}
else
{
request_->path = request_->uri;
}
request_->httpVersionMajor = version_major;
request_->httpVersionMinor = version_minor;
}
void HttpConnection::messageHeader(BufferRef&& name, BufferRef&& value)
{
if (iequals(name, "Host"))
{
auto i = value.find(':');
if (i != BufferRef::npos)
request_->hostname = value.ref(0, i);
else
request_->hostname = value;
}
request_->requestHeaders.push_back(HttpRequestHeader(std::move(name), std::move(value)));
}
bool HttpConnection::messageHeaderEnd()
{
TRACE("messageHeaderEnd()");
#if X0_HTTP_STRICT
BufferRef expectHeader = request_->requestHeader("Expect");
bool content_required = request_->method == "POST" || request_->method == "PUT";
if (content_required && request_->connection.contentLength() == -1)
{
request_->status = HttpError::LengthRequired;
request_->finish();
}
else if (!content_required && request_->contentAvailable())
{
request_->status = HttpError::BadRequest; // FIXME do we have a better status code?
request_->finish();
}
else if (expectHeader)
{
request_->expectingContinue = equals(expectHeader, "100-continue");
if (!request_->expectingContinue || !request_->supportsProtocol(1, 1))
{
request_->status = HttpError::ExpectationFailed;
request_->finish();
}
else
worker_.handleRequest(request_);
}
else
worker_.handleRequest(request_);
#else
worker_.handleRequest(request_);
#endif
return true;
}
bool HttpConnection::messageContent(BufferRef&& chunk)
{
TRACE("messageContent(#%ld)", chunk.size());
if (request_)
request_->onRequestContent(std::move(chunk));
return true;
}
bool HttpConnection::messageEnd()
{
TRACE("messageEnd()");
// increment the number of fully processed requests
++request_count_;
// XXX is this really required? (meant to mark the request-content EOS)
if (request_)
request_->onRequestContent(BufferRef());
// allow continueing processing possible further requests
return true;
}
/** Resumes processing the <b>next</b> HTTP request message within this connection.
*
* This method may only be invoked when the current/old request has been fully processed,
* and is though only be invoked from within the finish handler of \p HttpRequest.
*
* \see HttpRequest::finish()
*/
void HttpConnection::resume()
{
if (socket()->tcpCork())
socket()->setTcpCork(false);
delete request_;
request_ = 0;
// wait for new request message, if nothing in buffer
if (offset_ != buffer_.size())
startRead();
}
void HttpConnection::startRead()
{
int timeout = request_count_ && state() == MESSAGE_BEGIN
? worker_.server_.max_keep_alive_idle()
: worker_.server_.max_read_idle();
if (timeout > 0)
socket_->setTimeout<HttpConnection, &HttpConnection::timeout>(this, timeout);
socket_->setReadyCallback<HttpConnection, &HttpConnection::io>(this);
socket_->setMode(Socket::READ);
}
/**
* This method gets invoked when there is data in our HttpConnection ready to read.
*
* We assume, that we are in request-parsing state.
*/
void HttpConnection::processInput()
{
TRACE("(%p).processInput()", this);
ssize_t rv = socket_->read(buffer_);
if (rv < 0) // error
{
if (errno == EAGAIN || errno == EINTR)
{
startRead();
ev_unloop(loop(), EVUNLOOP_ONE);
}
else
{
TRACE("processInput(): %s", strerror(errno));
close();
}
}
else if (rv == 0) // EOF
{
TRACE("processInput(): (EOF)");
close();
}
else
{
TRACE("processInput(): read %ld bytes", rv);
//std::size_t offset = buffer_.size();
//buffer_.resize(offset + rv);
process();
TRACE("(%p).processInput(): done process()ing; mode=%s, fd=%d, request=%p",
this, socket_->mode_str(), socket_->handle(), request_);
}
}
/**
* Writes as much as it wouldn't block of the response stream into the underlying socket.
*
*/
void HttpConnection::processOutput()
{
TRACE("processOutput()");
for (;;)
{
ssize_t rv = sink_.pump(source_);
TRACE("processOutput(): pump().rv=%ld %s", rv, rv < 0 ? strerror(errno) : "");
// TODO make use of source_->eof()
if (rv > 0) // source (partially?) written
{
bytesTransferred_ += rv;
}
else if (rv == 0) // source fully written
{
//TRACE("processOutput(): source fully written");
source_.reset();
if (onWriteComplete_)
onWriteComplete_(0, bytesTransferred_);
//onWriteComplete_ = CompletionHandlerType();
break;
}
else if (errno == EAGAIN || errno == EINTR) // completing write would block
{
socket_->setReadyCallback<HttpConnection, &HttpConnection::io>(this); // XXX should be same
socket_->setMode(Socket::WRITE);
break;
}
else // an error occurred
{
TRACE("processOutput(): write error (%d): %s", errno, strerror(errno));
source_.reset();
if (onWriteComplete_)
onWriteComplete_(errno, bytesTransferred_);
//onWriteComplete_ = CompletionHandlerType();
close();
break;
}
}
}
/** closes this HttpConnection, possibly deleting this object (or propagating delayed delete).
*/
void HttpConnection::close()
{
TRACE("(%p).close() (active=%d)", this, active_);
TRACE("Stack Trace:%s\n", StackTrace().c_str());
socket_->close();
if (!active_)
delete this;
}
/** processes a (partial) request from buffer's given \p offset of \p count bytes.
*/
void HttpConnection::process()
{
TRACE("process: offset=%ld, size=%ld (before processing)", offset_, buffer_.size());
std::error_code ec = HttpMessageProcessor::process(
buffer_.ref(offset_, buffer_.size() - offset_),
offset_);
TRACE("process: offset=%ld, bs=%ld, ec=%s, state=%s (after processing)",
offset_, buffer_.size(), ec.message().c_str(), state_str());
if (state() == HttpMessageProcessor::MESSAGE_BEGIN)
{
// TODO reenable buffer reset (or reuse another for content! to be more huge-body friendly)
#if 0
offset_ = 0;
buffer_.clear();
#endif
}
if (isClosed())
return;
if (ec == HttpMessageError::Partial)
startRead();
else if (ec && ec != HttpMessageError::Aborted)
{
// -> send stock response: BAD_REQUEST
request_->status = HttpError::BadRequest;
request_->finish();
}
}
std::string HttpConnection::remoteIP() const
{
return socket_->remoteIP();
}
unsigned int HttpConnection::remotePort() const
{
return socket_->remotePort();
}
std::string HttpConnection::localIP() const
{
return listener_.address();
}
unsigned int HttpConnection::localPort() const
{
return socket_->localPort();
}
} // namespace x0
<|endoftext|>
|
<commit_before>#ifndef _FALCON_TUPLE_TUPLE_APPLY_HPP
#define _FALCON_TUPLE_TUPLE_APPLY_HPP
#include <falcon/tuple/parameter_index.hpp>
namespace falcon {
template <typename _Function, typename _T, std::size_t... _Indexes>
constexpr auto tuple_apply(const parameter_index<_Indexes...>&,
_Function __func, const _T& __t)
-> decltype(__func(std::get<_Indexes>(__t)...))
{ return __func(std::get<_Indexes>(__t)...); }
template <typename _Function, typename _T, std::size_t... _Indexes>
constexpr auto tuple_apply(const parameter_index<_Indexes...>&,
_Function __func, _T& __t)
-> decltype(__func(std::get<_Indexes>(__t)...))
{ return __func(std::get<_Indexes>(__t)...); }
template <typename _Function, typename _T,
typename _Indexes = typename build_tuple_index<_T>::type
>
constexpr auto tuple_apply(_Function __func, const _T& __t)
-> decltype(tuple_apply<_Function&>(_Indexes(), __func, __t))
{ return tuple_apply<_Function&>(_Indexes(), __func, __t); }
template <typename _Function, typename _T,
typename _Indexes = typename build_tuple_index<_T>::type
>
constexpr auto tuple_apply(_Function __func, _T& __t)
-> decltype(tuple_apply<_Function&>(_Indexes(), __func, __t))
{ return tuple_apply<_Function&>(_Indexes(), __func, __t); }
}
#endif<commit_msg>rename _T to _Tuple<commit_after>#ifndef _FALCON_TUPLE_TUPLE_APPLY_HPP
#define _FALCON_TUPLE_TUPLE_APPLY_HPP
#include <falcon/tuple/parameter_index.hpp>
namespace falcon {
template <typename _Function, typename _Tuple, std::size_t... _Indexes>
constexpr auto tuple_apply(const parameter_index<_Indexes...>&,
_Function __func, const _Tuple& __t)
-> decltype(__func(std::get<_Indexes>(__t)...))
{ return __func(std::get<_Indexes>(__t)...); }
template <typename _Function, typename _Tuple, std::size_t... _Indexes>
constexpr auto tuple_apply(const parameter_index<_Indexes...>&,
_Function __func, _Tuple& __t)
-> decltype(__func(std::get<_Indexes>(__t)...))
{ return __func(std::get<_Indexes>(__t)...); }
template <typename _Function, typename _Tuple,
typename _Indexes = typename build_tuple_index<_Tuple>::type
>
constexpr auto tuple_apply(_Function __func, const _Tuple& __t)
-> decltype(tuple_apply<_Function&>(_Indexes(), __func, __t))
{ return tuple_apply<_Function&>(_Indexes(), __func, __t); }
template <typename _Function, typename _Tuple,
typename _Indexes = typename build_tuple_index<_Tuple>::type
>
constexpr auto tuple_apply(_Function __func, _Tuple& __t)
-> decltype(tuple_apply<_Function&>(_Indexes(), __func, __t))
{ return tuple_apply<_Function&>(_Indexes(), __func, __t); }
}
#endif<|endoftext|>
|
<commit_before>/**
*
* FaZend.com, Fully Automated Zend Framework
* RQDQL.com, Requirements Definition and Query Language
*
* Redistribution and use in source and binary forms, with or
* without modification, are PROHIBITED without prior written
* permission from the author. This product may NOT be used
* anywhere and on any computer except the server platform of
* FaZend.com. located at www.fazend.com. If you received this
* code occasionally and without intent to use it, please report
* this incident to the author by email: team@rqdql.com
*
* @author Yegor Bugayenko <egor@tpc2.com>
* @copyright Copyright (c) rqdql.com, 2010
* @version $Id: rqdql.cpp 1746 2010-05-04 11:47:08Z yegor256@yahoo.com $
*/
#include <stdarg.h>
#include <unistd.h>
#include <iostream>
#include "rqdql.h"
#include "Scanner.h"
#include "Logger.h"
rqdql::LogLevel rqdql::level = L_ERROR;
/**
* Main method in the product
*/
int main(int argc, char** argv) {
using namespace std;
bool optIndicateAmbiguity = false;
bool optIndicateLinks = false;
char c;
while ((c = getopt(argc, argv, "val?")) != -1) {
switch (c) {
case 'a':
optIndicateAmbiguity = true;
break;
case 'l':
optIndicateLinks = true;
break;
case 'v':
cout << RQDQL_VERSION << endl;
return 0;
case '?':
cout <<
"usage: rqdql [-?v]" << endl <<
"Options:" << endl <<
" -?\tShows this help message" << endl <<
" -v\tReturns current version of the product" << endl <<
" -a\tAdd scope ambiguity to the report" << endl <<
" -l\tAdd links between objects into the report" << endl <<
"This program built for " << __VERSION__ << endl <<
"Report bugs to <bugs@rqdql.com>" << endl
;
return 0;
}
}
string text;
while (!cin.eof()) {
string s;
getline(cin, s);
text = text + s + "\n";
}
try {
rqdql::Scanner::getInstance().scan(text);
proxy::Proxy::getInstance().inject();
// show cross-links between lines
if (optIndicateLinks) {
rqdql::Logger::getInstance().reportLinks();
}
// show summary ambiguity
if (optIndicateAmbiguity) {
if (!rqdql::Logger::getInstance().hasErrors()) {
rqdql::Logger::getInstance().log(
0,
(boost::format("[INFO] Scope ambiguity: %0.2f") % solm::Solm::getInstance().getAmbiguity()).str()
);
} else {
rqdql::Logger::getInstance().log(
0,
(boost::format("Scope ambiguity can't be calculated since there are %d errors")
% rqdql::Logger::getInstance().countErrors()
).str()
);
}
}
} catch (char* e) {
cout << "Internal error: \"" << e << "\"" << endl;
} catch (...) {
cout << "Unknown internal error, email us your text to <team@rqdql.com>" << endl;
}
// no, we should display all errors and log messages found
cout << rqdql::Logger::getInstance().getReport() << endl;
return 0;
}
<commit_msg>even stronger message<commit_after>/**
*
* FaZend.com, Fully Automated Zend Framework
* RQDQL.com, Requirements Definition and Query Language
*
* Redistribution and use in source and binary forms, with or
* without modification, are PROHIBITED without prior written
* permission from the author. This product may NOT be used
* anywhere and on any computer except the server platform of
* FaZend.com. located at www.fazend.com. If you received this
* code occasionally and without intent to use it, please report
* this incident to the author by email: team@rqdql.com
*
* @author Yegor Bugayenko <egor@tpc2.com>
* @copyright Copyright (c) rqdql.com, 2010
* @version $Id: rqdql.cpp 1746 2010-05-04 11:47:08Z yegor256@yahoo.com $
*/
#include <stdarg.h>
#include <unistd.h>
#include <iostream>
#include "rqdql.h"
#include "Scanner.h"
#include "Logger.h"
rqdql::LogLevel rqdql::level = L_ERROR;
/**
* Main method in the product
*/
int main(int argc, char** argv) {
using namespace std;
bool optIndicateAmbiguity = false;
bool optIndicateLinks = false;
char c;
while ((c = getopt(argc, argv, "val?")) != -1) {
switch (c) {
case 'a':
optIndicateAmbiguity = true;
break;
case 'l':
optIndicateLinks = true;
break;
case 'v':
cout << RQDQL_VERSION << endl;
return 0;
case '?':
cout <<
"usage: rqdql [-?v]" << endl <<
"Options:" << endl <<
" -?\tShows this help message" << endl <<
" -v\tReturns current version of the product" << endl <<
" -a\tAdd scope ambiguity to the report" << endl <<
" -l\tAdd links between objects into the report" << endl <<
"This program built for " << __VERSION__ << endl <<
"Report bugs to <bugs@rqdql.com>" << endl
;
return 0;
}
}
string text;
while (!cin.eof()) {
string s;
getline(cin, s);
text = text + s + "\n";
}
try {
rqdql::Scanner::getInstance().scan(text);
proxy::Proxy::getInstance().inject();
// show cross-links between lines
if (optIndicateLinks) {
rqdql::Logger::getInstance().reportLinks();
}
// show summary ambiguity
if (optIndicateAmbiguity) {
if (!rqdql::Logger::getInstance().hasErrors()) {
rqdql::Logger::getInstance().log(
0,
(boost::format("[INFO] ambiguity=%0.2f") % solm::Solm::getInstance().getAmbiguity()).str()
);
} else {
rqdql::Logger::getInstance().log(
0,
(boost::format("Scope ambiguity can't be calculated since there are %d errors")
% rqdql::Logger::getInstance().countErrors()
).str()
);
}
}
} catch (char* e) {
cout << "Internal error: \"" << e << "\"" << endl;
} catch (...) {
cout << "Unknown internal error, email us your text to <team@rqdql.com>" << endl;
}
// no, we should display all errors and log messages found
cout << rqdql::Logger::getInstance().getReport() << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file Font.hpp
* @brief Font class prototype.
* @author zer0
* @date 2017-11-16
*
* @see <https://en.wikipedia.org/wiki/TrueType>
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/graphic/Image.hpp>
#include <libtbag/util/BufferInfo.hpp>
#include <libtbag/geometry/Rect.hpp>
#include <array>
#include <string>
#include <vector>
#include <memory>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace typography {
TBAG_CONSTEXPR int const ASCII_FONT_TABLE_SIZE = 8;
TBAG_CONSTEXPR char const DEFAULT_ASCII_FONT_TABLE[ASCII_FONT_TABLE_SIZE + 1/*NULL*/] = " .:ioVM@";
TBAG_API std::string getAsciiImage(unsigned char const * true_type, std::size_t size, char c,
char const * table, std::size_t table_size, int scale = 12);
TBAG_API std::string getAsciiImage(util::Buffer const & true_type, char c,
std::string const & table = std::string(DEFAULT_ASCII_FONT_TABLE), int scale = 12);
TBAG_API std::string getAsciiImage(util::Buffer const & true_type, std::string const & text,
std::string const & table = std::string(DEFAULT_ASCII_FONT_TABLE), int scale = 12);
/**
* TrueType information class prototype.
*
* @author zer0
* @date 2018-07-03
*/
class TrueType : private Noncopyable
{
public:
struct Impl;
friend struct Impl;
public:
using UniqueImpl = std::unique_ptr<Impl>;
using Buffer = libtbag::util::Buffer;
using BoundingBox = libtbag::geometry::Recti;
using Size = libtbag::geometry::Sizei;
using ImageGray = libtbag::graphic::ImageGray;
using CodePoints = std::vector<int>;
public:
/**
* Vertical metrics information.
*
* @remarks
* So you should advance the vertical position by @n
* @code{.cpp}
* ascent - descent + line_gap
* @endcode
*/
struct VerticalMetrics
{
int ascent; ///< Coordinate above the baseline the font extends.
int descent; ///< Coordinate below the baseline the font extends (i.e. it is typically negative).
int line_gap; ///< Spacing between one row's descent and the next row's ascent.
};
/**
* Horizontal metrics information.
*
* @remarks
* These are expressed in unscaled coordinates.
*/
struct HorizontalMetrics
{
int advance_width; ///< Offset from the current horizontal position to the left edge of the character.
int left_side_bearing; ///< Offset from the current horizontal position to the next horizontal position.
};
public:
TBAG_CONSTEXPR static int const DEFAULT_LINE_HEIGHT = 64;
private:
UniqueImpl _impl;
public:
TrueType();
~TrueType();
public:
Err loadFromMemory(char const * buffer, std::size_t size);
Err loadFromMemory(Buffer const & buffer);
Err loadFromFile(std::string const & file_path);
public:
void clear();
public:
BoundingBox getBoundingBox() const;
public:
Size calcSize(CodePoints const & code_points, int line_height = DEFAULT_LINE_HEIGHT) const;
public:
Err draw(CodePoints const & code_points, ImageGray & bitmap, int line_height = DEFAULT_LINE_HEIGHT) const;
Err drawAscii(std::string const & ascii, ImageGray & bitmap, int line_height = DEFAULT_LINE_HEIGHT) const;
private:
void drawAndUpdate(unsigned char * bitmap, int code_point, int ascent, float scale, int image_width, int & update_next_x) const;
};
} // namespace typography
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
<commit_msg>Fixed link error in MSVC.<commit_after>/**
* @file Font.hpp
* @brief Font class prototype.
* @author zer0
* @date 2017-11-16
*
* @see <https://en.wikipedia.org/wiki/TrueType>
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/graphic/Image.hpp>
#include <libtbag/util/BufferInfo.hpp>
#include <libtbag/geometry/Rect.hpp>
#include <array>
#include <string>
#include <vector>
#include <memory>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace typography {
TBAG_CONSTEXPR int const ASCII_FONT_TABLE_SIZE = 8;
TBAG_CONSTEXPR char const DEFAULT_ASCII_FONT_TABLE[ASCII_FONT_TABLE_SIZE + 1/*NULL*/] = " .:ioVM@";
TBAG_API std::string getAsciiImage(unsigned char const * true_type, std::size_t size, char c,
char const * table, std::size_t table_size, int scale = 12);
TBAG_API std::string getAsciiImage(util::Buffer const & true_type, char c,
std::string const & table = std::string(DEFAULT_ASCII_FONT_TABLE), int scale = 12);
TBAG_API std::string getAsciiImage(util::Buffer const & true_type, std::string const & text,
std::string const & table = std::string(DEFAULT_ASCII_FONT_TABLE), int scale = 12);
/**
* TrueType information class prototype.
*
* @author zer0
* @date 2018-07-03
*/
class TBAG_API TrueType : private Noncopyable
{
public:
struct Impl;
friend struct Impl;
public:
using UniqueImpl = std::unique_ptr<Impl>;
using Buffer = libtbag::util::Buffer;
using BoundingBox = libtbag::geometry::Recti;
using Size = libtbag::geometry::Sizei;
using ImageGray = libtbag::graphic::ImageGray;
using CodePoints = std::vector<int>;
public:
/**
* Vertical metrics information.
*
* @remarks
* So you should advance the vertical position by @n
* @code{.cpp}
* ascent - descent + line_gap
* @endcode
*/
struct VerticalMetrics
{
int ascent; ///< Coordinate above the baseline the font extends.
int descent; ///< Coordinate below the baseline the font extends (i.e. it is typically negative).
int line_gap; ///< Spacing between one row's descent and the next row's ascent.
};
/**
* Horizontal metrics information.
*
* @remarks
* These are expressed in unscaled coordinates.
*/
struct HorizontalMetrics
{
int advance_width; ///< Offset from the current horizontal position to the left edge of the character.
int left_side_bearing; ///< Offset from the current horizontal position to the next horizontal position.
};
public:
TBAG_CONSTEXPR static int const DEFAULT_LINE_HEIGHT = 64;
private:
UniqueImpl _impl;
public:
TrueType();
~TrueType();
public:
Err loadFromMemory(char const * buffer, std::size_t size);
Err loadFromMemory(Buffer const & buffer);
Err loadFromFile(std::string const & file_path);
public:
void clear();
public:
BoundingBox getBoundingBox() const;
public:
Size calcSize(CodePoints const & code_points, int line_height = DEFAULT_LINE_HEIGHT) const;
public:
Err draw(CodePoints const & code_points, ImageGray & bitmap, int line_height = DEFAULT_LINE_HEIGHT) const;
Err drawAscii(std::string const & ascii, ImageGray & bitmap, int line_height = DEFAULT_LINE_HEIGHT) const;
private:
void drawAndUpdate(unsigned char * bitmap, int code_point, int ascent, float scale, int image_width, int & update_next_x) const;
};
} // namespace typography
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_TYPOGRAPHY_FONT_HPP__
<|endoftext|>
|
<commit_before>#line 1 "C:/Program Files/Git/smart_house/exec_unit/USBdsc.c"
const unsigned int USB_VENDOR_ID = 0x1209;
const unsigned int USB_PRODUCT_ID = 0x0001;
const char USB_SELF_POWER = 0xC0;
const char USB_MAX_POWER = 50;
const char HID_INPUT_REPORT_BYTES = 64;
const char HID_OUTPUT_REPORT_BYTES = 64;
const char USB_TRANSFER_TYPE = 0x03;
const char EP_IN_INTERVAL = 1;
const char EP_OUT_INTERVAL = 1;
const char USB_INTERRUPT = 1;
const char USB_HID_EP = 1;
const char USB_HID_RPT_SIZE = 33;
const struct {
char bLength;
char bDescriptorType;
unsigned int bcdUSB;
char bDeviceClass;
char bDeviceSubClass;
char bDeviceProtocol;
char bMaxPacketSize0;
unsigned int idVendor;
unsigned int idProduct;
unsigned int bcdDevice;
char iManufacturer;
char iProduct;
char iSerialNumber;
char bNumConfigurations;
} device_dsc = {
0x12,
0x01,
0x0200,
0x00,
0x00,
0x00,
8,
USB_VENDOR_ID,
USB_PRODUCT_ID,
0x0001,
0x01,
0x02,
0x00,
0x01
};
const char configDescriptor1[]= {
0x09,
0x02,
0x29,0x00,
1,
1,
0,
USB_SELF_POWER,
USB_MAX_POWER,
0x09,
0x04,
0,
0,
2,
0x03,
0,
0,
0,
0x09,
0x21,
0x01,0x01,
0x00,
1,
0x22,
USB_HID_RPT_SIZE,0x00,
0x07,
0x05,
USB_HID_EP | 0x80,
USB_TRANSFER_TYPE,
0x40,0x00,
EP_IN_INTERVAL,
0x07,
0x05,
USB_HID_EP,
USB_TRANSFER_TYPE,
0x40,0x00,
EP_OUT_INTERVAL
};
const struct {
char report[USB_HID_RPT_SIZE];
}hid_rpt_desc =
{
{0x06, 0x00, 0xFF,
0x09, 0x01,
0xA1, 0x01,
0x19, 0x01,
0x29, 0x40,
0x15, 0x00,
0x26, 0xFF, 0x00,
0x75, 0x08,
0x95, HID_INPUT_REPORT_BYTES,
0x81, 0x02,
0x19, 0x01,
0x29, 0x40,
0x75, 0x08,
0x95, HID_OUTPUT_REPORT_BYTES,
0x91, 0x02,
0xC0}
};
const struct {
char bLength;
char bDscType;
unsigned int string[1];
} strd1 = {
4,
0x03,
{0x0409}
};
const struct{
char bLength;
char bDscType;
unsigned int string[2];
}strd2={
6,
0x03,
{'G','L'}
};
const struct{
char bLength;
char bDscType;
unsigned int string[26];
}strd3={
54,
0x03,
{'S','m','a','r','t',' ','H','o','u','s','e',' ','E','x','e','c','u','t','i','v','e',' ','U','n','i','t'}
};
const char* USB_config_dsc_ptr[1];
const char* USB_string_dsc_ptr[3];
void USB_Init_Desc(){
USB_config_dsc_ptr[0] = &configDescriptor1;
USB_string_dsc_ptr[0] = (const char*)&strd1;
USB_string_dsc_ptr[1] = (const char*)&strd2;
USB_string_dsc_ptr[2] = (const char*)&strd3;
}
<commit_msg>Delete USBdsc.cp<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
* *
* I|*j^3Cl|a "+!*% qt Nd gW *
* l]{y+l?MM* !#Wla\NNP NW MM I| *
* PW ?E| tWg Wg sC! AW ~@v~ *
* NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *
* CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *
* #M aQ? MW M3 Mg Q( HQ YR IM| *
* Dq {Ql MH iMX Mg MM QP QM Eg *
* !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D *
* *
* Website: https://github.com/zpublic/zpublic *
* *
************************************************************************/
/**
* @file
* @brief Ϣ
*/
#pragma once
#include "win_utils_header.h"
namespace zl
{
namespace WinUtils
{
/**
* @brief UIPIϢز
*/
class ZLMessage
{
inline UINT RegisterMessage(LPCTSTR lpMsgName)
{
return ::RegisterWindowMessage(lpMsgName);
}
typedef BOOL (__stdcall *ChangeWindowMessageFilterType)(UINT, DWORD);
#define MSGFLT_ADD 1 // ChangeWindowMessageFilter ĵڶϢ
#define MSGFLT_REMOVE 2 // ChangeWindowMessageFilter ĵڶƳϢ
/**
* @brief UIPIϢӻɾһϢ
* @param[in] uMsg ָӻӹɾָϢ
* @param[in] dwOper ָ
* @return ɹTRUEʧܷFALSE
* @see ChangeWindowMessageFilter
*/
static BOOL ChangeMessageFilter(UINT uMsg, DWORD dwOper = MSGFLT_ADD)
{
BOOL bRet = FALSE;
static HMODULE hModule = NULL;
static ChangeWindowMessageFilterType pChangeWindowMessageFilterType = NULL;
if (pChangeWindowMessageFilterType == NULL)
{
hModule = ::LoadLibrary(TEXT("user32.dll"));
if (hModule == NULL)
goto Exit0;
pChangeWindowMessageFilterType = (ChangeWindowMessageFilterType)::GetProcAddress(hModule, "ChangeWindowMessageFilter");
if (pChangeWindowMessageFilterType == NULL)
goto Exit0;
}
bRet = pChangeWindowMessageFilterType(uMsg, dwOper);
Exit0:
return bRet;
}
}
}
}
<commit_msg>* 类后面少了";"号<commit_after>/*************************************************************************
* *
* I|*j^3Cl|a "+!*% qt Nd gW *
* l]{y+l?MM* !#Wla\NNP NW MM I| *
* PW ?E| tWg Wg sC! AW ~@v~ *
* NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *
* CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *
* #M aQ? MW M3 Mg Q( HQ YR IM| *
* Dq {Ql MH iMX Mg MM QP QM Eg *
* !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D *
* *
* Website: https://github.com/zpublic/zpublic *
* *
************************************************************************/
/**
* @file
* @brief Ϣ
*/
#pragma once
#include "win_utils_header.h"
namespace zl
{
namespace WinUtils
{
/**
* @brief UIPIϢز
*/
class ZLMessage
{
inline UINT RegisterMessage(LPCTSTR lpMsgName)
{
return ::RegisterWindowMessage(lpMsgName);
}
typedef BOOL (__stdcall *ChangeWindowMessageFilterType)(UINT, DWORD);
#define MSGFLT_ADD 1 // ChangeWindowMessageFilter ĵڶϢ
#define MSGFLT_REMOVE 2 // ChangeWindowMessageFilter ĵڶƳϢ
/**
* @brief UIPIϢӻɾһϢ
* @param[in] uMsg ָӻӹɾָϢ
* @param[in] dwOper ָ
* @return ɹTRUEʧܷFALSE
* @see ChangeWindowMessageFilter
*/
static BOOL ChangeMessageFilter(UINT uMsg, DWORD dwOper = MSGFLT_ADD)
{
BOOL bRet = FALSE;
static HMODULE hModule = NULL;
static ChangeWindowMessageFilterType pChangeWindowMessageFilterType = NULL;
if (pChangeWindowMessageFilterType == NULL)
{
hModule = ::LoadLibrary(TEXT("user32.dll"));
if (hModule == NULL)
goto Exit0;
pChangeWindowMessageFilterType = (ChangeWindowMessageFilterType)::GetProcAddress(hModule, "ChangeWindowMessageFilter");
if (pChangeWindowMessageFilterType == NULL)
goto Exit0;
}
bRet = pChangeWindowMessageFilterType(uMsg, dwOper);
Exit0:
return bRet;
}
};
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(OS_WIN)
#include <atlbase.h>
#include <atlapp.h>
#include <atlmisc.h>
#endif
#include "chrome/browser/tab_contents/web_drag_source.h"
#include "chrome/browser/renderer_host/render_view_host.h"
namespace {
static void GetCursorPositions(gfx::NativeWindow wnd, gfx::Point* client,
gfx::Point* screen) {
#if defined(OS_WIN)
POINT cursor_pos;
GetCursorPos(&cursor_pos);
screen->SetPoint(cursor_pos.x, cursor_pos.y);
ScreenToClient(wnd, &cursor_pos);
client->SetPoint(cursor_pos.x, cursor_pos.y);
#else
// TODO(port): Get the cursor positions.
NOTIMPLEMENTED();
#endif
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// WebDragSource, public:
WebDragSource::WebDragSource(gfx::NativeWindow source_wnd,
RenderViewHost* render_view_host)
: BaseDragSource(),
source_wnd_(source_wnd),
render_view_host_(render_view_host) {
}
void WebDragSource::OnDragSourceCancel() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceEndedAt(client.x(), client.y(),
screen.x(), screen.y());
}
void WebDragSource::OnDragSourceDrop() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceEndedAt(client.x(), client.y(),
screen.x(), screen.y());
}
void WebDragSource::OnDragSourceMove() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceMovedTo(client.x(), client.y(),
screen.x(), screen.y());
}
<commit_msg>Try to track down the cause of the Drag&Drop crash seen in bug 12524.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(OS_WIN)
#include <atlbase.h>
#include <atlapp.h>
#include <atlmisc.h>
#endif
#include "chrome/browser/tab_contents/web_drag_source.h"
#include "chrome/browser/renderer_host/render_view_host.h"
namespace {
static void GetCursorPositions(gfx::NativeWindow wnd, gfx::Point* client,
gfx::Point* screen) {
#if defined(OS_WIN)
POINT cursor_pos;
GetCursorPos(&cursor_pos);
screen->SetPoint(cursor_pos.x, cursor_pos.y);
ScreenToClient(wnd, &cursor_pos);
client->SetPoint(cursor_pos.x, cursor_pos.y);
#else
// TODO(port): Get the cursor positions.
NOTIMPLEMENTED();
#endif
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// WebDragSource, public:
WebDragSource::WebDragSource(gfx::NativeWindow source_wnd,
RenderViewHost* render_view_host)
: BaseDragSource(),
source_wnd_(source_wnd),
render_view_host_(render_view_host) {
// In an effort to try to track down http://crbug.com/12524 we now CHECK
// when a NULL render_view_host is passed to us. I think this is what is
// happening but it is hard to tell since the minidump is not helpful in this
// case. At least we can then rule that out.
CHECK(render_view_host_);
}
void WebDragSource::OnDragSourceCancel() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceEndedAt(client.x(), client.y(),
screen.x(), screen.y());
}
void WebDragSource::OnDragSourceDrop() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceEndedAt(client.x(), client.y(),
screen.x(), screen.y());
}
void WebDragSource::OnDragSourceMove() {
gfx::Point client;
gfx::Point screen;
GetCursorPositions(source_wnd_, &client, &screen);
render_view_host_->DragSourceMovedTo(client.x(), client.y(),
screen.x(), screen.y());
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <modules/plottinggl/processors/colorscalelegend.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ColorScaleLegend::processorInfo_{
"org.inviwo.ColorScaleLegend", // Class identifier
"Color Scale Legend", // Display name
"Drawing", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }
ColorScaleLegend::ColorScaleLegend()
: Processor()
, inport_("inport")
, outport_("outport")
, volumeInport_("volumeInport")
, positioning_("positioning", "Positioning")
, style_("style", "Style")
, isotfComposite_("isotfComposite", "TF & Isovalues")
, legendPlacement_("legendPlacement", "Legend Placement",
{{"top", "Top", 0},
{"right", "Right", 1},
{"bottom", "Bottom", 2},
{"left", "Left", 3},
{"custom", "Custom", 4}},
1)
, rotation_("legendRotation", "Legend Rotation",
{{"degree0", "0 degrees", 0},
{"degree90", "90 degrees", 1},
{"degree180", "180 degrees", 2},
{"degree270", "270 degrees", 3}},
1)
, lastLegendOrientation_(1)
, position_("position", "Position", vec2(0.5f), vec2(0.0f), vec2(1.0f))
, margin_("margin", "Margin (in pixels)", 25, 0, 100)
, legendSize_("legendSize", "Legend Size", vec2(25, 200), vec2(10, 10), vec2(400, 400))
, borderWidth_("borderWidth", "Border Width", 2, 0, 10)
, borderColor_("borderColor", "Border Color", vec4(1, 1, 1, 1))
, title_("title", "Legend Title", "Legend Title")
, fontSize_("fontSize", "Font Size", 14, 8, 36)
, backgroundStyle_("backgroundStyle", "Background",
{{"noBackground", "No background", BackgroundStyle::NoBackground},
{"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}},
0)
, checkerBoardSize_("checkerBoardSize", "Checker Board Size", 5, 1, 20)
, shader_("img_texturequad.vert", "legend.frag")
, axis_("axis", "Scale Axis")
, axisRenderer_(axis_) {
shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
inport_.setOptional(true);
volumeInport_.setOptional(true);
addPort(inport_);
addPort(outport_);
addPort(volumeInport_);
addProperty(isotfComposite_);
// legend position
positioning_.addProperty(legendPlacement_);
positioning_.addProperty(rotation_);
rotation_.setVisible(false);
positioning_.addProperty(position_);
position_.setVisible(false);
positioning_.addProperty(margin_);
margin_.setVisible(false);
addProperty(positioning_);
// legend style
style_.addProperty(legendSize_);
style_.addProperty(borderWidth_);
style_.addProperty(borderColor_);
borderColor_.setSemantics(PropertySemantics::Color);
style_.addProperty(title_);
style_.addProperty(fontSize_);
// legend background
style_.addProperty(backgroundStyle_);
style_.addProperty(checkerBoardSize_);
addProperty(style_);
addProperty(axis_);
rotation_.onChange([&]() { setLegendRotation(); });
title_.onChange([&]() { axis_.caption_.title_.set(title_.get()); });
fontSize_.onChange([&]() {
// the caption should be bigger than labels
axis_.caption_.font_.fontSize_.set(fontSize_.get() + 2);
axis_.labels_.font_.fontSize_.set(fontSize_.get());
});
borderColor_.onChange([&]() {
axis_.color_.set(borderColor_.get());
axis_.caption_.color_.set(borderColor_.get());
axis_.labels_.color_.set(borderColor_.get());
axis_.ticks_.majorTicks_.color_.set(borderColor_.get());
axis_.ticks_.minorTicks_.color_.set(borderColor_.get());
});
legendPlacement_.onChange([&]() {
if (legendPlacement_.get() == 4) {
rotation_.setVisible(true);
position_.setVisible(true);
margin_.setVisible(true);
} else {
rotation_.setVisible(false);
position_.setVisible(false);
margin_.setVisible(false);
}
});
backgroundStyle_.onChange([&]() {
switch (backgroundStyle_.get()) {
default:
case BackgroundStyle::NoBackground:
checkerBoardSize_.setVisible(false);
break;
case BackgroundStyle::CheckerBoard:
checkerBoardSize_.setVisible(true);
break;
}
});
}
void ColorScaleLegend::initializeResources() {
// set initial axis parameters
axis_.width_ = 0;
axis_.caption_.title_.set(title_.get());
axis_.caption_.setChecked(true);
axis_.labels_.font_.fontFace_.set(axis_.caption_.font_.fontFace_.get());
fontSize_.propertyModified();
shader_.build();
}
// this function handles the legend rotation and updates the axis thereafter
void ColorScaleLegend::setAxisPosition() {
NetworkLock lock(this); // is this necessary?
switch (rotation_.get()) {
default:
case 0:
axisStart_ = bottomLeft_;
axisEnd_ = bottomRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 1:
axisStart_ = bottomLeft_;
axisEnd_ = topLeft_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 2:
axisStart_ = topLeft_;
axisEnd_ = topRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
case 3:
axisStart_ = bottomRight_;
axisEnd_ = topRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
}
// change the caption offset to get be occluded by the border
axis_.caption_.offset_.set(borderWidth_.get() + 4);
}
// set the boundaries of the position so that the legend is always inside the output canvas
void ColorScaleLegend::updatePositionBoundaries() {
auto legendSize = legendSize_.get();
auto dim = outport_.getDimensions();
vec2 normalizedMin(((float)legendSize.x / 2) / dim.x, ((float)legendSize.y / 2) / dim.y);
vec2 normalizedMax(1.0 - normalizedMin.x, 1.0 - normalizedMin.y);
vec2 normalizedMargin((float)margin_.get() / dim.x, (float)margin_.get() / dim.y);
position_.setMinValue(
vec2(normalizedMin.x + normalizedMargin.x, normalizedMin.y + normalizedMargin.y));
position_.setMaxValue(
vec2(normalizedMax.x - normalizedMargin.x, normalizedMax.y - normalizedMargin.y));
}
void ColorScaleLegend::setLegendPosition() {
switch (legendPlacement_.get()) {
default:
break;
case 0:
position_.set(vec2(0.5, 1));
break;
case 1:
position_.set(vec2(1, 0.5));
break;
case 2:
position_.set(vec2(0.5, 0));
break;
case 3:
position_.set(vec2(0, 0.5));
break;
}
}
void ColorScaleLegend::setLegendRotation() {
if (legendPlacement_.get() != 4) rotation_.set(legendPlacement_.get());
// flip the legend size
vec2 oldSize = legendSize_.get();
if (rotation_.get() % 2 != lastLegendOrientation_ % 2) {
legendSize_.set(vec2(oldSize.y, oldSize.x));
}
lastLegendOrientation_ = rotation_.get();
}
void ColorScaleLegend::process() {
// draw cached overlay on top of the input image
if (inport_.isReady()) {
utilgl::activateTargetAndCopySource(outport_, inport_);
} else {
utilgl::activateAndClearTarget(outport_);
}
setLegendRotation();
updatePositionBoundaries();
setLegendPosition();
utilgl::DepthFuncState depthFunc(GL_ALWAYS);
utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
vec2 dimensions = outport_.getDimensions();
vec2 position = position_.get();
vec2 legendSize = legendSize_.get();
float borderWidth = borderWidth_.get();
// define the legend corners
bottomLeft_ = vec2(position.x * dimensions.x - (legendSize.x / 2.0),
position.y * dimensions.y - (legendSize.y / 2.0));
bottomRight_ = vec2(bottomLeft_.x + legendSize.x, bottomLeft_.y);
topLeft_ = vec2(bottomLeft_.x, bottomLeft_.y + legendSize.y);
topRight_ = vec2(bottomRight_.x, topLeft_.y);
legendSize_.setMaxValue(dimensions - vec2(margin_.get() * 2));
// update the legend range if a volume is connected to inport
if (volumeInport_.isChanged() && volumeInport_.isConnected()) {
axis_.setRange(volumeInport_.getData()->dataMap_.dataRange);
} else if (!volumeInport_.isConnected()) {
axis_.setRange(vec2(0, 1));
}
setAxisPosition();
axisRenderer_.render(dimensions, axisStart_, axisEnd_);
TextureUnit colorUnit;
shader_.activate();
shader_.setUniform("color_", colorUnit.getUnitNumber());
shader_.setUniform("dimensions_", dimensions);
shader_.setUniform("position_", position);
shader_.setUniform("legendSize_", legendSize);
shader_.setUniform("borderColor_", borderColor_.get());
shader_.setUniform("backgroundAlpha_", (int)backgroundStyle_.get());
shader_.setUniform("checkerBoardSize_", (int)checkerBoardSize_.get());
shader_.setUniform("rotationTF_", rotation_.get());
utilgl::bindTexture(isotfComposite_.tf_, colorUnit);
utilgl::ViewportState viewport(bottomLeft_.x - borderWidth, bottomLeft_.y - borderWidth,
legendSize.x + (borderWidth * 2),
legendSize.y + (borderWidth * 2));
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
TextureUnit::setZeroUnit();
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<commit_msg>PlottingGL: colorscalelegend: forgot to change back to the default border color before pushing.<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <modules/plottinggl/processors/colorscalelegend.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo ColorScaleLegend::processorInfo_{
"org.inviwo.ColorScaleLegend", // Class identifier
"Color Scale Legend", // Display name
"Drawing", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo ColorScaleLegend::getProcessorInfo() const { return processorInfo_; }
ColorScaleLegend::ColorScaleLegend()
: Processor()
, inport_("inport")
, outport_("outport")
, volumeInport_("volumeInport")
, positioning_("positioning", "Positioning")
, style_("style", "Style")
, isotfComposite_("isotfComposite", "TF & Isovalues")
, legendPlacement_("legendPlacement", "Legend Placement",
{{"top", "Top", 0},
{"right", "Right", 1},
{"bottom", "Bottom", 2},
{"left", "Left", 3},
{"custom", "Custom", 4}},
1)
, rotation_("legendRotation", "Legend Rotation",
{{"degree0", "0 degrees", 0},
{"degree90", "90 degrees", 1},
{"degree180", "180 degrees", 2},
{"degree270", "270 degrees", 3}},
1)
, lastLegendOrientation_(1)
, position_("position", "Position", vec2(0.5f), vec2(0.0f), vec2(1.0f))
, margin_("margin", "Margin (in pixels)", 25, 0, 100)
, legendSize_("legendSize", "Legend Size", vec2(25, 200), vec2(10, 10), vec2(400, 400))
, borderWidth_("borderWidth", "Border Width", 2, 0, 10)
, borderColor_("borderColor", "Border Color", vec4(0, 0, 0, 1))
, title_("title", "Legend Title", "Legend Title")
, fontSize_("fontSize", "Font Size", 14, 8, 36)
, backgroundStyle_("backgroundStyle", "Background",
{{"noBackground", "No background", BackgroundStyle::NoBackground},
{"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}},
0)
, checkerBoardSize_("checkerBoardSize", "Checker Board Size", 5, 1, 20)
, shader_("img_texturequad.vert", "legend.frag")
, axis_("axis", "Scale Axis")
, axisRenderer_(axis_) {
shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
inport_.setOptional(true);
volumeInport_.setOptional(true);
addPort(inport_);
addPort(outport_);
addPort(volumeInport_);
addProperty(isotfComposite_);
// legend position
positioning_.addProperty(legendPlacement_);
positioning_.addProperty(rotation_);
rotation_.setVisible(false);
positioning_.addProperty(position_);
position_.setVisible(false);
positioning_.addProperty(margin_);
margin_.setVisible(false);
addProperty(positioning_);
// legend style
style_.addProperty(legendSize_);
style_.addProperty(borderWidth_);
style_.addProperty(borderColor_);
borderColor_.setSemantics(PropertySemantics::Color);
style_.addProperty(title_);
style_.addProperty(fontSize_);
// legend background
style_.addProperty(backgroundStyle_);
style_.addProperty(checkerBoardSize_);
addProperty(style_);
addProperty(axis_);
rotation_.onChange([&]() { setLegendRotation(); });
title_.onChange([&]() { axis_.caption_.title_.set(title_.get()); });
fontSize_.onChange([&]() {
// the caption should be bigger than labels
axis_.caption_.font_.fontSize_.set(fontSize_.get() + 2);
axis_.labels_.font_.fontSize_.set(fontSize_.get());
});
borderColor_.onChange([&]() {
axis_.color_.set(borderColor_.get());
axis_.caption_.color_.set(borderColor_.get());
axis_.labels_.color_.set(borderColor_.get());
axis_.ticks_.majorTicks_.color_.set(borderColor_.get());
axis_.ticks_.minorTicks_.color_.set(borderColor_.get());
});
legendPlacement_.onChange([&]() {
if (legendPlacement_.get() == 4) {
rotation_.setVisible(true);
position_.setVisible(true);
margin_.setVisible(true);
} else {
rotation_.setVisible(false);
position_.setVisible(false);
margin_.setVisible(false);
}
});
backgroundStyle_.onChange([&]() {
switch (backgroundStyle_.get()) {
default:
case BackgroundStyle::NoBackground:
checkerBoardSize_.setVisible(false);
break;
case BackgroundStyle::CheckerBoard:
checkerBoardSize_.setVisible(true);
break;
}
});
}
void ColorScaleLegend::initializeResources() {
// set initial axis parameters
axis_.width_ = 0;
axis_.caption_.title_.set(title_.get());
axis_.caption_.setChecked(true);
axis_.labels_.font_.fontFace_.set(axis_.caption_.font_.fontFace_.get());
fontSize_.propertyModified();
shader_.build();
}
// this function handles the legend rotation and updates the axis thereafter
void ColorScaleLegend::setAxisPosition() {
NetworkLock lock(this); // is this necessary?
switch (rotation_.get()) {
default:
case 0:
axisStart_ = bottomLeft_;
axisEnd_ = bottomRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 1:
axisStart_ = bottomLeft_;
axisEnd_ = topLeft_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Outside);
break;
case 2:
axisStart_ = topLeft_;
axisEnd_ = topRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Horizontal);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
case 3:
axisStart_ = bottomRight_;
axisEnd_ = topRight_;
axis_.orientation_.set(plot::AxisProperty::Orientation::Vertical);
axis_.placement_.set(plot::AxisProperty::Placement::Inside);
break;
}
// change the caption offset to get be occluded by the border
axis_.caption_.offset_.set(borderWidth_.get() + 4);
}
// set the boundaries of the position so that the legend is always inside the output canvas
void ColorScaleLegend::updatePositionBoundaries() {
auto legendSize = legendSize_.get();
auto dim = outport_.getDimensions();
vec2 normalizedMin(((float)legendSize.x / 2) / dim.x, ((float)legendSize.y / 2) / dim.y);
vec2 normalizedMax(1.0 - normalizedMin.x, 1.0 - normalizedMin.y);
vec2 normalizedMargin((float)margin_.get() / dim.x, (float)margin_.get() / dim.y);
position_.setMinValue(
vec2(normalizedMin.x + normalizedMargin.x, normalizedMin.y + normalizedMargin.y));
position_.setMaxValue(
vec2(normalizedMax.x - normalizedMargin.x, normalizedMax.y - normalizedMargin.y));
}
void ColorScaleLegend::setLegendPosition() {
switch (legendPlacement_.get()) {
default:
break;
case 0:
position_.set(vec2(0.5, 1));
break;
case 1:
position_.set(vec2(1, 0.5));
break;
case 2:
position_.set(vec2(0.5, 0));
break;
case 3:
position_.set(vec2(0, 0.5));
break;
}
}
void ColorScaleLegend::setLegendRotation() {
if (legendPlacement_.get() != 4) rotation_.set(legendPlacement_.get());
// flip the legend size
vec2 oldSize = legendSize_.get();
if (rotation_.get() % 2 != lastLegendOrientation_ % 2) {
legendSize_.set(vec2(oldSize.y, oldSize.x));
}
lastLegendOrientation_ = rotation_.get();
}
void ColorScaleLegend::process() {
// draw cached overlay on top of the input image
if (inport_.isReady()) {
utilgl::activateTargetAndCopySource(outport_, inport_);
} else {
utilgl::activateAndClearTarget(outport_);
}
setLegendRotation();
updatePositionBoundaries();
setLegendPosition();
utilgl::DepthFuncState depthFunc(GL_ALWAYS);
utilgl::BlendModeState blending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
vec2 dimensions = outport_.getDimensions();
vec2 position = position_.get();
vec2 legendSize = legendSize_.get();
float borderWidth = borderWidth_.get();
// define the legend corners
bottomLeft_ = vec2(position.x * dimensions.x - (legendSize.x / 2.0),
position.y * dimensions.y - (legendSize.y / 2.0));
bottomRight_ = vec2(bottomLeft_.x + legendSize.x, bottomLeft_.y);
topLeft_ = vec2(bottomLeft_.x, bottomLeft_.y + legendSize.y);
topRight_ = vec2(bottomRight_.x, topLeft_.y);
legendSize_.setMaxValue(dimensions - vec2(margin_.get() * 2));
// update the legend range if a volume is connected to inport
if (volumeInport_.isChanged() && volumeInport_.isConnected()) {
axis_.setRange(volumeInport_.getData()->dataMap_.dataRange);
} else if (!volumeInport_.isConnected()) {
axis_.setRange(vec2(0, 1));
}
setAxisPosition();
axisRenderer_.render(dimensions, axisStart_, axisEnd_);
TextureUnit colorUnit;
shader_.activate();
shader_.setUniform("color_", colorUnit.getUnitNumber());
shader_.setUniform("dimensions_", dimensions);
shader_.setUniform("position_", position);
shader_.setUniform("legendSize_", legendSize);
shader_.setUniform("borderColor_", borderColor_.get());
shader_.setUniform("backgroundAlpha_", (int)backgroundStyle_.get());
shader_.setUniform("checkerBoardSize_", (int)checkerBoardSize_.get());
shader_.setUniform("rotationTF_", rotation_.get());
utilgl::bindTexture(isotfComposite_.tf_, colorUnit);
utilgl::ViewportState viewport(bottomLeft_.x - borderWidth, bottomLeft_.y - borderWidth,
legendSize.x + (borderWidth * 2),
legendSize.y + (borderWidth * 2));
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
TextureUnit::setZeroUnit();
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
<|endoftext|>
|
<commit_before>// (c) 2015, dividiti
// BSD license
#ifndef CL_LAUNCHER_HPP
#define CL_LAUNCHER_HPP
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>
#include <CL/cl.h>
#include <xopenme.h>
namespace gemmbench
{
class arguments
{
public:
std::string file;
cl_uint platform_idx;
cl_uint device_idx;
arguments() : file(""),
platform_idx(0),
device_idx(0)
{}
void parse(int argc, char* argv[])
{
for (int i = 1; i < argc-1; ++i)
{
std::string this_arg(argv[i]);
std::string next_arg(argv[++i]);
if ("-f" == this_arg)
{
file = next_arg;
}
else if ("-p" == this_arg)
{
std::istringstream ss(next_arg); ss >> platform_idx;
}
else if ("-d" == this_arg)
{
std::istringstream ss(next_arg); ss >> device_idx;
}
else
{
std::cerr << "Unhandled argument: " << this_arg << std::endl;
--i; // skip only one argument
}
} // END OF for each argument
} // END OF parse()
}; // END OF class arguments
class state
{
private:
static const int xopenme_max_str_len = 1024;
static const int xopenme_max_tmr_count = 1;
static const int xopenme_max_var_count = 24;
char xopenme_str[xopenme_max_str_len];
int xopenme_var_count;
arguments args;
public:
cl_platform_id platform;
cl_device_id device;
state() :
xopenme_var_count(0),
platform(NULL),
device(NULL)
{
xopenme_init(xopenme_max_tmr_count, xopenme_max_var_count);
}
~state()
{
xopenme_dump_state();
}
void parse_arguments(int argc, char* argv[])
{
args.parse(argc, argv);
}
void get_platform()
{
cl_uint err = CL_SUCCESS;
cl_uint platform_idx = args.platform_idx;
cl_uint num_entries = platform_idx+1;
cl_platform_id * platforms = new cl_platform_id[num_entries];
cl_uint num_platforms;
err = clGetPlatformIDs(num_entries, platforms, &num_platforms);
assert(CL_SUCCESS == err && "clGetPlatformIDs() failed.");
assert(platform_idx < num_platforms && "No platform.");
this->platform = platforms[platform_idx];
delete [] platforms;
#if (1 == XOPENME)
err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_NAME\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetPlatformInfo(platform, CL_PLATFORM_VENDOR, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_VENDOR\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_VERSION\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
#endif
} // END OF get_platform()
void get_device()
{
cl_uint err = CL_SUCCESS;
cl_uint device_idx = args.device_idx;
cl_uint num_entries = device_idx+1;
cl_device_id * devices = new cl_device_id[num_entries];
cl_uint num_devices;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_entries, devices, &num_devices);
assert(CL_SUCCESS == err && "clGetDeviceIDs() failed.");
assert(device_idx < num_devices && "No device.");
this->device = devices[device_idx];
delete [] devices;
#if (1 == XOPENME)
err = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_NAME\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_VENDOR\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetDeviceInfo(device, CL_DEVICE_VERSION, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_VERSION\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
#endif
} // END OF get_device()
};
} // END OF namespace gemmbench
#endif // CL_LAUNCHER_HPP
<commit_msg>Query driver version.<commit_after>// (c) 2015, dividiti
// BSD license
#ifndef CL_LAUNCHER_HPP
#define CL_LAUNCHER_HPP
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>
#include <CL/cl.h>
#include <xopenme.h>
namespace gemmbench
{
class arguments
{
public:
std::string file;
cl_uint platform_idx;
cl_uint device_idx;
arguments() : file(""),
platform_idx(0),
device_idx(0)
{}
void parse(int argc, char* argv[])
{
for (int i = 1; i < argc-1; ++i)
{
std::string this_arg(argv[i]);
std::string next_arg(argv[++i]);
if ("-f" == this_arg)
{
file = next_arg;
}
else if ("-p" == this_arg)
{
std::istringstream ss(next_arg); ss >> platform_idx;
}
else if ("-d" == this_arg)
{
std::istringstream ss(next_arg); ss >> device_idx;
}
else
{
std::cerr << "Unhandled argument: " << this_arg << std::endl;
--i; // skip only one argument
}
} // END OF for each argument
} // END OF parse()
}; // END OF class arguments
class state
{
private:
static const int xopenme_max_str_len = 1024;
static const int xopenme_max_tmr_count = 1;
static const int xopenme_max_var_count = 24;
char xopenme_str[xopenme_max_str_len];
int xopenme_var_count;
arguments args;
public:
cl_platform_id platform;
cl_device_id device;
state() :
xopenme_var_count(0),
platform(NULL),
device(NULL)
{
xopenme_init(xopenme_max_tmr_count, xopenme_max_var_count);
}
~state()
{
xopenme_dump_state();
}
void parse_arguments(int argc, char* argv[])
{
args.parse(argc, argv);
}
void get_platform()
{
cl_uint err = CL_SUCCESS;
cl_uint platform_idx = args.platform_idx;
cl_uint num_entries = platform_idx+1;
cl_platform_id * platforms = new cl_platform_id[num_entries];
cl_uint num_platforms;
err = clGetPlatformIDs(num_entries, platforms, &num_platforms);
assert(CL_SUCCESS == err && "clGetPlatformIDs() failed.");
assert(platform_idx < num_platforms && "No platform.");
this->platform = platforms[platform_idx];
delete [] platforms;
#if (1 == XOPENME)
err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_NAME\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetPlatformInfo(platform, CL_PLATFORM_VENDOR, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_VENDOR\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetPlatformInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_PLATFORM_VERSION\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
#endif
} // END OF get_platform()
void get_device()
{
cl_uint err = CL_SUCCESS;
cl_uint device_idx = args.device_idx;
cl_uint num_entries = device_idx+1;
cl_device_id * devices = new cl_device_id[num_entries];
cl_uint num_devices;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, num_entries, devices, &num_devices);
assert(CL_SUCCESS == err && "clGetDeviceIDs() failed.");
assert(device_idx < num_devices && "No device.");
this->device = devices[device_idx];
delete [] devices;
#if (1 == XOPENME)
err = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_NAME\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_VENDOR\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetDeviceInfo(device, CL_DEVICE_VERSION, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DEVICE_VERSION\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
err = clGetDeviceInfo(device, CL_DRIVER_VERSION, sizeof(xopenme_str), &xopenme_str, NULL);
assert(CL_SUCCESS == err && "clGetDeviceInfo() failed.");
xopenme_add_var_s(xopenme_var_count++, (char*) " \"CL_DRIVER_VERSION\":\"%s\"", xopenme_str);
assert(xopenme_var_count < xopenme_max_var_count && "xOpenME max var count reached.");
#endif
} // END OF get_device()
};
} // END OF namespace gemmbench
#endif // CL_LAUNCHER_HPP
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2000-2005 Kern Sibbald
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.
This file is patterned after the VNC Win32 code by ATT
*/
#ifndef HAVE_WIN32
#define HAVE_CYGWIN 1
#endif
#include <unistd.h>
#include <lmcons.h>
#include <ctype.h>
#include "winbacula.h"
#include "wintray.h"
#include "winservice.h"
#include <signal.h>
#include <pthread.h>
#include "../../lib/winapi.h"
extern int BaculaMain(int argc, char *argv[]);
extern void terminate_filed(int sig);
extern DWORD g_error;
extern BOOL ReportStatus(DWORD state, DWORD exitcode, DWORD waithint);
extern void d_msg(const char *, int, int, const char *, ...);
/* Globals */
HINSTANCE hAppInstance;
const char *szAppName = "Bacula";
DWORD mainthreadId;
/* Imported variables */
extern DWORD g_servicethread;
#define MAX_COMMAND_ARGS 100
static char *command_args[MAX_COMMAND_ARGS] = {"bacula-fd", NULL};
static int num_command_args = 1;
static pid_t main_pid;
static pthread_t main_tid;
/*
* WinMain parses the command line and either calls the main App
* routine or, under NT, the main service routine.
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR CmdLine, int iCmdShow)
{
char *szCmdLine = CmdLine;
char *wordPtr, *tempPtr;
int i, quote;
/* Save the application instance and main thread id */
hAppInstance = hInstance;
mainthreadId = GetCurrentThreadId();
main_pid = getpid();
main_tid = pthread_self();
/*
* Funny things happen with the command line if the
* execution comes from c:/Program Files/bacula/bacula.exe
* We get a command line like: Files/bacula/bacula.exe" options
* I.e. someone stops scanning command line on a space, not
* realizing that the filename is quoted!!!!!!!!!!
* So if first character is not a double quote and
* the last character before first space is a double
* quote, we throw away the junk.
*/
wordPtr = szCmdLine;
while (*wordPtr && *wordPtr != ' ')
wordPtr++;
if (wordPtr > szCmdLine) /* backup to char before space */
wordPtr--;
/* if first character is not a quote and last is, junk it */
if (*szCmdLine != '"' && *wordPtr == '"') {
szCmdLine = wordPtr + 1;
}
// MessageBox(NULL, szCmdLine, "Cmdline", MB_OK);
/* Build Unix style argc *argv[] */
/* Don't NULL command_args[0] !!! */
for (i=1;i<MAX_COMMAND_ARGS;i++)
command_args[i] = NULL;
wordPtr = szCmdLine;
quote = 0;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
if (*wordPtr == '\"') {
quote = 1;
wordPtr++;
} else if (*wordPtr == '/') {
/* Skip Windows options */
while (*wordPtr && (*wordPtr != ' ' && *wordPtr != '\t'))
wordPtr++;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
}
if (*wordPtr) {
while (*wordPtr && num_command_args < MAX_COMMAND_ARGS) {
tempPtr = wordPtr;
if (quote) {
while (*tempPtr && *tempPtr != '\"')
tempPtr++;
quote = 0;
} else {
while (*tempPtr && *tempPtr != ' ')
tempPtr++;
}
if (*tempPtr)
*(tempPtr++) = '\0';
command_args[num_command_args++] = wordPtr;
wordPtr = tempPtr;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
if (*wordPtr == '\"') {
quote = 1;
wordPtr++;
}
}
}
/*
* Now process Windows command line options
* as defined by ATT
*
* Make the command-line lowercase and parse it
*/
for (i = 0; i < (int)strlen(szCmdLine); i++) {
szCmdLine[i] = tolower(szCmdLine[i]);
}
bool argfound = false;
for (i = 0; i < (int)strlen(szCmdLine); i++) {
if (szCmdLine[i] <= ' ') {
continue;
}
if (szCmdLine[i] == '-') {
while (szCmdLine[i] && szCmdLine[i] != ' ') {
i++;
}
continue;
}
argfound = true;
/* Now check for command-line arguments */
/* /service start service */
if (strncmp(&szCmdLine[i], BaculaRunService, strlen(BaculaRunService)) == 0) {
/* Run Bacula as a service */
return bacService::BaculaServiceMain();
}
/* /run (this is the default if no command line arguments) */
if (strncmp(&szCmdLine[i], BaculaRunAsUserApp, strlen(BaculaRunAsUserApp)) == 0) {
/* Bacula is being run as a user-level program */
return BaculaAppMain();
}
/* /install */
if (strncmp(&szCmdLine[i], BaculaInstallService, strlen(BaculaInstallService)) == 0) {
/* Install Bacula as a service */
bacService::InstallService();
i += strlen(BaculaInstallService);
continue;
}
/* /remove */
if (strncmp(&szCmdLine[i], BaculaRemoveService, strlen(BaculaRemoveService)) == 0) {
/* Remove the Bacula service */
bacService::RemoveService();
i += strlen(BaculaRemoveService);
continue;
}
/* /about */
if (strncmp(&szCmdLine[i], BaculaShowAbout, strlen(BaculaShowAbout)) == 0) {
/* Show Bacula's about box */
bacService::ShowAboutBox();
i += strlen(BaculaShowAbout);
continue;
}
/* /status */
if (strncmp(&szCmdLine[i], BaculaShowStatus, strlen(BaculaShowStatus)) == 0) {
/* Show Bacula's status box */
bacService::ShowStatus();
i += strlen(BaculaShowStatus);
continue;
}
/* /kill */
if (strncmp(&szCmdLine[i], BaculaKillRunningCopy, strlen(BaculaKillRunningCopy)) == 0) {
/* Kill running copy of Bacula */
bacService::KillRunningCopy();
i += strlen(BaculaKillRunningCopy);
continue;
}
/* /help */
if (strncmp(&szCmdLine[i], BaculaShowHelp, strlen(BaculaShowHelp)) == 0) {
MessageBox(NULL, BaculaUsageText, "Bacula Usage", MB_OK|MB_ICONINFORMATION);
i += strlen(BaculaShowHelp);
continue;
}
MessageBox(NULL, szCmdLine, "Bad Command Line Options", MB_OK);
/* Show the usage dialog */
MessageBox(NULL, BaculaUsageText, "Bacula Usage", MB_OK | MB_ICONINFORMATION);
break;
}
/* If no arguments were given then just run */
if (!argfound) {
BaculaAppMain();
}
return 0;
}
/*
* Called as a thread from BaculaAppMain()
* Here we handle the Windows messages
*/
//DWORD WINAPI Main_Msg_Loop(LPVOID lpwThreadParam)
void *Main_Msg_Loop(LPVOID lpwThreadParam)
{
DWORD old_servicethread = g_servicethread;
pthread_detach(pthread_self());
/* Since we are the only thread with a message loop
* mark ourselves as the service thread so that
* we can receive all the window events.
*/
g_servicethread = GetCurrentThreadId();
/* Create tray icon & menu if we're running as an app */
bacMenu *menu = new bacMenu();
if (menu == NULL) {
// log_error_message("Could not create sys tray menu");
PostQuitMessage(0);
}
/* Now enter the Windows message handling loop until told to quit! */
MSG msg;
while (GetMessage(&msg, NULL, 0,0) ) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (menu != NULL) {
delete menu;
}
if (old_servicethread != 0) { /* started as NT service */
/* Mark that we're no longer running */
g_servicethread = 0;
/* Tell the service manager that we've stopped. */
ReportStatus(SERVICE_STOPPED, g_error, 0);
}
/* Tell main program to go away */
terminate_filed(0);
/* Should not get here */
pthread_kill(main_tid, SIGTERM); /* ask main thread to terminate */
sleep(1);
kill(main_pid, SIGTERM); /* ask main thread to terminate */
_exit(0);
}
/*
* This is the main routine for Bacula when running as an application
* (under Windows 95 or Windows NT)
* Under NT, Bacula can also run as a service. The BaculaServerMain routine,
* defined in the bacService header, is used instead when running as a service.
*/
int BaculaAppMain()
{
/* DWORD dwThreadID; */
pthread_t tid;
InitWinAPIWrapper();
WSA_Init();
/* Set this process to be the last application to be shut down. */
if (p_SetProcessShutdownParameters) {
p_SetProcessShutdownParameters(0x100, 0);
}
HWND hservwnd = FindWindow(MENU_CLASS_NAME, NULL);
if (hservwnd != NULL) {
/* We don't allow multiple instances! */
MessageBox(NULL, "Another instance of Bacula is already running", szAppName, MB_OK);
_exit(0);
}
/* Create a thread to handle the Windows messages */
// (void)CreateThread(NULL, 0, Main_Msg_Loop, NULL, 0, &dwThreadID);
pthread_create(&tid, NULL, Main_Msg_Loop, (void *)0);
/* Call the "real" Bacula */
BaculaMain(num_command_args, command_args);
PostQuitMessage(0);
WSACleanup();
_exit(0);
}
<commit_msg>- hotfix for bug #312 (we don't need /servicehelper on nt) at least I don't know why.<commit_after>/*
Copyright (C) 2000-2005 Kern Sibbald
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.
This file is patterned after the VNC Win32 code by ATT
*/
#ifndef HAVE_WIN32
#define HAVE_CYGWIN 1
#endif
#include <unistd.h>
#include <lmcons.h>
#include <ctype.h>
#include "winbacula.h"
#include "wintray.h"
#include "winservice.h"
#include <signal.h>
#include <pthread.h>
#include "../../lib/winapi.h"
extern int BaculaMain(int argc, char *argv[]);
extern void terminate_filed(int sig);
extern DWORD g_error;
extern BOOL ReportStatus(DWORD state, DWORD exitcode, DWORD waithint);
extern void d_msg(const char *, int, int, const char *, ...);
/* Globals */
HINSTANCE hAppInstance;
const char *szAppName = "Bacula";
DWORD mainthreadId;
/* Imported variables */
extern DWORD g_servicethread;
extern DWORD g_platform_id;
#define MAX_COMMAND_ARGS 100
static char *command_args[MAX_COMMAND_ARGS] = {"bacula-fd", NULL};
static int num_command_args = 1;
static pid_t main_pid;
static pthread_t main_tid;
/*
* WinMain parses the command line and either calls the main App
* routine or, under NT, the main service routine.
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR CmdLine, int iCmdShow)
{
char *szCmdLine = CmdLine;
char *wordPtr, *tempPtr;
int i, quote;
/* Save the application instance and main thread id */
hAppInstance = hInstance;
mainthreadId = GetCurrentThreadId();
main_pid = getpid();
main_tid = pthread_self();
/*
* Funny things happen with the command line if the
* execution comes from c:/Program Files/bacula/bacula.exe
* We get a command line like: Files/bacula/bacula.exe" options
* I.e. someone stops scanning command line on a space, not
* realizing that the filename is quoted!!!!!!!!!!
* So if first character is not a double quote and
* the last character before first space is a double
* quote, we throw away the junk.
*/
wordPtr = szCmdLine;
while (*wordPtr && *wordPtr != ' ')
wordPtr++;
if (wordPtr > szCmdLine) /* backup to char before space */
wordPtr--;
/* if first character is not a quote and last is, junk it */
if (*szCmdLine != '"' && *wordPtr == '"') {
szCmdLine = wordPtr + 1;
}
// MessageBox(NULL, szCmdLine, "Cmdline", MB_OK);
/* Build Unix style argc *argv[] */
/* Don't NULL command_args[0] !!! */
for (i=1;i<MAX_COMMAND_ARGS;i++)
command_args[i] = NULL;
wordPtr = szCmdLine;
quote = 0;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
if (*wordPtr == '\"') {
quote = 1;
wordPtr++;
} else if (*wordPtr == '/') {
/* Skip Windows options */
while (*wordPtr && (*wordPtr != ' ' && *wordPtr != '\t'))
wordPtr++;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
}
if (*wordPtr) {
while (*wordPtr && num_command_args < MAX_COMMAND_ARGS) {
tempPtr = wordPtr;
if (quote) {
while (*tempPtr && *tempPtr != '\"')
tempPtr++;
quote = 0;
} else {
while (*tempPtr && *tempPtr != ' ')
tempPtr++;
}
if (*tempPtr)
*(tempPtr++) = '\0';
command_args[num_command_args++] = wordPtr;
wordPtr = tempPtr;
while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
wordPtr++;
if (*wordPtr == '\"') {
quote = 1;
wordPtr++;
}
}
}
/*
* Now process Windows command line options
* as defined by ATT
*
* Make the command-line lowercase and parse it
*/
for (i = 0; i < (int)strlen(szCmdLine); i++) {
szCmdLine[i] = tolower(szCmdLine[i]);
}
bool argfound = false;
for (i = 0; i < (int)strlen(szCmdLine); i++) {
if (szCmdLine[i] <= ' ') {
continue;
}
if (szCmdLine[i] == '-') {
while (szCmdLine[i] && szCmdLine[i] != ' ') {
i++;
}
continue;
}
argfound = true;
/* Now check for command-line arguments */
/* /service helper - probably only needed on win9x */
if (strncmp(&szCmdLine[i], BaculaRunServiceHelper, strlen(BaculaRunServiceHelper)) == 0
&& g_platform_id == VER_PLATFORM_WIN32_NT) {
/* exit with result "okay" */
return 0;
}
/* /service start service */
if (strncmp(&szCmdLine[i], BaculaRunService, strlen(BaculaRunService)) == 0) {
/* Run Bacula as a service */
return bacService::BaculaServiceMain();
}
/* /run (this is the default if no command line arguments) */
if (strncmp(&szCmdLine[i], BaculaRunAsUserApp, strlen(BaculaRunAsUserApp)) == 0) {
/* Bacula is being run as a user-level program */
return BaculaAppMain();
}
/* /install */
if (strncmp(&szCmdLine[i], BaculaInstallService, strlen(BaculaInstallService)) == 0) {
/* Install Bacula as a service */
bacService::InstallService();
i += strlen(BaculaInstallService);
continue;
}
/* /remove */
if (strncmp(&szCmdLine[i], BaculaRemoveService, strlen(BaculaRemoveService)) == 0) {
/* Remove the Bacula service */
bacService::RemoveService();
i += strlen(BaculaRemoveService);
continue;
}
/* /about */
if (strncmp(&szCmdLine[i], BaculaShowAbout, strlen(BaculaShowAbout)) == 0) {
/* Show Bacula's about box */
bacService::ShowAboutBox();
i += strlen(BaculaShowAbout);
continue;
}
/* /status */
if (strncmp(&szCmdLine[i], BaculaShowStatus, strlen(BaculaShowStatus)) == 0) {
/* Show Bacula's status box */
bacService::ShowStatus();
i += strlen(BaculaShowStatus);
continue;
}
/* /kill */
if (strncmp(&szCmdLine[i], BaculaKillRunningCopy, strlen(BaculaKillRunningCopy)) == 0) {
/* Kill running copy of Bacula */
bacService::KillRunningCopy();
i += strlen(BaculaKillRunningCopy);
continue;
}
/* /help */
if (strncmp(&szCmdLine[i], BaculaShowHelp, strlen(BaculaShowHelp)) == 0) {
MessageBox(NULL, BaculaUsageText, "Bacula Usage", MB_OK|MB_ICONINFORMATION);
i += strlen(BaculaShowHelp);
continue;
}
MessageBox(NULL, szCmdLine, "Bad Command Line Options", MB_OK);
/* Show the usage dialog */
MessageBox(NULL, BaculaUsageText, "Bacula Usage", MB_OK | MB_ICONINFORMATION);
break;
}
/* If no arguments were given then just run */
if (!argfound) {
BaculaAppMain();
}
return 0;
}
/*
* Called as a thread from BaculaAppMain()
* Here we handle the Windows messages
*/
//DWORD WINAPI Main_Msg_Loop(LPVOID lpwThreadParam)
void *Main_Msg_Loop(LPVOID lpwThreadParam)
{
DWORD old_servicethread = g_servicethread;
pthread_detach(pthread_self());
/* Since we are the only thread with a message loop
* mark ourselves as the service thread so that
* we can receive all the window events.
*/
g_servicethread = GetCurrentThreadId();
/* Create tray icon & menu if we're running as an app */
bacMenu *menu = new bacMenu();
if (menu == NULL) {
// log_error_message("Could not create sys tray menu");
PostQuitMessage(0);
}
/* Now enter the Windows message handling loop until told to quit! */
MSG msg;
while (GetMessage(&msg, NULL, 0,0) ) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (menu != NULL) {
delete menu;
}
if (old_servicethread != 0) { /* started as NT service */
/* Mark that we're no longer running */
g_servicethread = 0;
/* Tell the service manager that we've stopped. */
ReportStatus(SERVICE_STOPPED, g_error, 0);
}
/* Tell main program to go away */
terminate_filed(0);
/* Should not get here */
pthread_kill(main_tid, SIGTERM); /* ask main thread to terminate */
sleep(1);
kill(main_pid, SIGTERM); /* ask main thread to terminate */
_exit(0);
}
/*
* This is the main routine for Bacula when running as an application
* (under Windows 95 or Windows NT)
* Under NT, Bacula can also run as a service. The BaculaServerMain routine,
* defined in the bacService header, is used instead when running as a service.
*/
int BaculaAppMain()
{
/* DWORD dwThreadID; */
pthread_t tid;
InitWinAPIWrapper();
WSA_Init();
/* Set this process to be the last application to be shut down. */
if (p_SetProcessShutdownParameters) {
p_SetProcessShutdownParameters(0x100, 0);
}
HWND hservwnd = FindWindow(MENU_CLASS_NAME, NULL);
if (hservwnd != NULL) {
/* We don't allow multiple instances! */
MessageBox(NULL, "Another instance of Bacula is already running", szAppName, MB_OK);
_exit(0);
}
/* Create a thread to handle the Windows messages */
// (void)CreateThread(NULL, 0, Main_Msg_Loop, NULL, 0, &dwThreadID);
pthread_create(&tid, NULL, Main_Msg_Loop, (void *)0);
/* Call the "real" Bacula */
BaculaMain(num_command_args, command_args);
PostQuitMessage(0);
WSACleanup();
_exit(0);
}
<|endoftext|>
|
<commit_before><commit_msg>Test WNT instead of the vague UNX<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ide_pch.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:28:13 $
*
* 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_basctl.hxx"
#include <ide_pch.hxx>
<commit_msg>INTEGRATION: CWS changefileheader (1.3.148); FILE MERGED 2008/03/28 16:04:44 rt 1.3.148.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: ide_pch.cxx,v $
* $Revision: 1.4 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basctl.hxx"
#include <ide_pch.hxx>
<|endoftext|>
|
<commit_before>#include "gns/test_util/random_number.h"
namespace gns {
namespace test_util {
RandomNumber::RandomNumber(const size_t seed)
: engine_(), distribution_()
{
}
double RandomNumber::operator()()
{
return distribution_(engine_);
}
double RandomNumber::operator()(const double min, const double max)
{
const int diff = max - min;
return (*this)() * diff + min;
}
} // namespace test_util
} // namespace gns
<commit_msg>Fix error in Travic CI<commit_after>#include "gns/test_util/random_number.h"
namespace gns {
namespace test_util {
RandomNumber::RandomNumber(const size_t seed)
: engine_(), distribution_()
{
engine_.seed(seed);
}
double RandomNumber::operator()()
{
return distribution_(engine_);
}
double RandomNumber::operator()(const double min, const double max)
{
const int diff = max - min;
return (*this)() * diff + min;
}
} // namespace test_util
} // namespace gns
<|endoftext|>
|
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE parse JSON
#include <boost/test/unit_test.hpp>
#include "../parse.h"
static const char correct_json[] = "{\"id\": 7384,\"method\": \"add\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
static const char wrong_json[] = "{\"id\": 7384,\"method\": add\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
BOOST_AUTO_TEST_CASE(parse_correct_json)
{
int ret = parse_message(correct_json, strlen(correct_json));
BOOST_CHECK(ret == 0);
}
BOOST_AUTO_TEST_CASE(lenth_too_long)
{
int ret = parse_message(correct_json, strlen(correct_json) + 1);
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(lenth_too_short)
{
int ret = parse_message(correct_json, strlen(correct_json) -1);
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(parse_wrong_json)
{
int ret = parse_message(wrong_json, strlen(wrong_json));
BOOST_CHECK(ret == -1);
}
<commit_msg>Add more unit tests.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE parse JSON
#include <boost/test/unit_test.hpp>
#include "../parse.h"
static const char correct_json[] = "{\"id\": 7384,\"method\": \"add\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
static const char wrong_json[] = "{\"id\": 7384,\"method\": add\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
static const char json_no_method[] = "{\"id\": 7384,\"meth\": \"add\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
static const char json_no_string_method[] = "{\"id\": 7384,\"method\": 123,\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
static const char json_unsupported_method[] = "{\"id\": 7384,\"method\": \"horst\",\"params\":{\"path\": \"foo/bar/state\",\"value\": 123}}";
BOOST_AUTO_TEST_CASE(parse_correct_json)
{
int ret = parse_message(correct_json, strlen(correct_json));
BOOST_CHECK(ret == 0);
}
BOOST_AUTO_TEST_CASE(lenth_too_long)
{
int ret = parse_message(correct_json, strlen(correct_json) + 1);
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(lenth_too_short)
{
int ret = parse_message(correct_json, strlen(correct_json) -1);
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(parse_wrong_json)
{
int ret = parse_message(wrong_json, strlen(wrong_json));
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(no_method)
{
int ret = parse_message(json_no_method, strlen(json_no_method));
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(no_string_method)
{
int ret = parse_message(json_no_string_method, strlen(json_no_string_method));
BOOST_CHECK(ret == -1);
}
BOOST_AUTO_TEST_CASE(unsupported_method)
{
int ret = parse_message(json_unsupported_method, strlen(json_unsupported_method));
BOOST_CHECK(ret == -1);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <memory>
#include <sdbusplus/message.hpp>
#include "utils.hpp"
namespace phosphor
{
namespace inventory
{
namespace manager
{
class Manager;
namespace details
{
using FilterBase = holder::CallableBase <
bool, sdbusplus::message::message&, Manager& >;
using FilterBasePtr = std::shared_ptr<FilterBase>;
template <typename T>
using Filter = holder::CallableHolder <
T, bool, sdbusplus::message::message&, Manager& >;
/** @struct Event
* @brief Event object interface.
*/
struct Event
{
enum class Type
{
DBUS_SIGNAL,
};
virtual ~Event() = default;
Event(const Event&) = default;
Event& operator=(const Event&) = default;
Event(Event&&) = default;
Event& operator=(Event&&) = default;
explicit Event(Type t) : type(t) {}
Type type;
};
using EventBasePtr = std::shared_ptr<Event>;
/** @struct DbusSignal
* @brief DBus signal event.
*
* DBus signal events are an association of a match signature
* and filtering function object.
*/
struct DbusSignal final :
public Event,
public std::tuple<const char*, std::vector<FilterBasePtr>>
{
virtual ~DbusSignal() = default;
DbusSignal(const DbusSignal&) = default;
DbusSignal& operator=(const DbusSignal&) = delete;
DbusSignal(DbusSignal&&) = default;
DbusSignal& operator=(DbusSignal&&) = default;
/** @brief Import from signature and filter constructor.
*
* @param[in] sig - The DBus match signature.
* @param[in] filter - A DBus signal match callback filtering function.
*/
DbusSignal(const char* sig, const std::vector<FilterBasePtr>& filters) :
Event(Type::DBUS_SIGNAL),
std::tuple<const char*, std::vector<FilterBasePtr>>(
sig, std::move(filters)) {}
};
/** @brief make_filter
*
* Adapt a filter function object.
*
* @param[in] filter - The filter being adapted.
* @returns - The adapted filter.
*
* @tparam T - The type of the filter being adapted.
*/
template <typename T>
auto make_filter(T&& filter)
{
return Filter<T>::template make_shared<Filter<T>>(
std::forward<T>(filter));
}
} // namespace details
namespace filters
{
namespace details
{
namespace property_condition
{
/** @struct PropertyCondition
* @brief Match filter functor that tests a property value.
*
* @tparam T - The type of the property being tested.
* @tparam U - The type of the condition checking functor.
*/
template <typename T, typename U>
struct PropertyCondition
{
PropertyCondition() = delete;
~PropertyCondition() = default;
PropertyCondition(const PropertyCondition&) = default;
PropertyCondition& operator=(const PropertyCondition&) = delete;
PropertyCondition(PropertyCondition&&) = default;
PropertyCondition& operator=(PropertyCondition&&) = default;
PropertyCondition(const char* iface, const char* property, U&& condition) :
_iface(iface),
_property(property),
_condition(std::forward<U>(condition)) { }
/** @brief Test a property value.
*
* Extract the property from the PropertiesChanged
* message and run the condition test.
*/
bool operator()(sdbusplus::message::message& msg, Manager&) const
{
std::map <
std::string,
sdbusplus::message::variant<T >> properties;
const char* iface = nullptr;
msg.read(iface);
if (!iface || strcmp(iface, _iface))
{
return false;
}
msg.read(properties);
auto it = properties.find(_property);
if (it == properties.cend())
{
return false;
}
return _condition(
std::forward<T>(it->second.template get<T>()));
}
private:
const char* _iface;
const char* _property;
U _condition;
};
} // namespace property_condition
} // namespace details
/** @brief Implicit type deduction for constructing PropertyCondition. */
template <typename T>
auto propertyChangedTo(
const char* iface,
const char* property,
T&& val)
{
auto condition = [val = std::move(val)](T && arg)
{
return arg == val;
};
using U = decltype(condition);
return details::property_condition::PropertyCondition<T, U>(
iface, property, std::move(condition));
}
} // namespace filters
} // namespace manager
} // namespace inventory
} // namespace phosphor
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<commit_msg>Rename PropertyCondition<commit_after>#pragma once
#include <utility>
#include <memory>
#include <sdbusplus/message.hpp>
#include "utils.hpp"
namespace phosphor
{
namespace inventory
{
namespace manager
{
class Manager;
namespace details
{
using FilterBase = holder::CallableBase <
bool, sdbusplus::message::message&, Manager& >;
using FilterBasePtr = std::shared_ptr<FilterBase>;
template <typename T>
using Filter = holder::CallableHolder <
T, bool, sdbusplus::message::message&, Manager& >;
/** @struct Event
* @brief Event object interface.
*/
struct Event
{
enum class Type
{
DBUS_SIGNAL,
};
virtual ~Event() = default;
Event(const Event&) = default;
Event& operator=(const Event&) = default;
Event(Event&&) = default;
Event& operator=(Event&&) = default;
explicit Event(Type t) : type(t) {}
Type type;
};
using EventBasePtr = std::shared_ptr<Event>;
/** @struct DbusSignal
* @brief DBus signal event.
*
* DBus signal events are an association of a match signature
* and filtering function object.
*/
struct DbusSignal final :
public Event,
public std::tuple<const char*, std::vector<FilterBasePtr>>
{
virtual ~DbusSignal() = default;
DbusSignal(const DbusSignal&) = default;
DbusSignal& operator=(const DbusSignal&) = delete;
DbusSignal(DbusSignal&&) = default;
DbusSignal& operator=(DbusSignal&&) = default;
/** @brief Import from signature and filter constructor.
*
* @param[in] sig - The DBus match signature.
* @param[in] filter - A DBus signal match callback filtering function.
*/
DbusSignal(const char* sig, const std::vector<FilterBasePtr>& filters) :
Event(Type::DBUS_SIGNAL),
std::tuple<const char*, std::vector<FilterBasePtr>>(
sig, std::move(filters)) {}
};
/** @brief make_filter
*
* Adapt a filter function object.
*
* @param[in] filter - The filter being adapted.
* @returns - The adapted filter.
*
* @tparam T - The type of the filter being adapted.
*/
template <typename T>
auto make_filter(T&& filter)
{
return Filter<T>::template make_shared<Filter<T>>(
std::forward<T>(filter));
}
} // namespace details
namespace filters
{
namespace details
{
namespace property_condition
{
/** @struct PropertyChangedCondition
* @brief Match filter functor that tests a property value.
*
* @tparam T - The type of the property being tested.
* @tparam U - The type of the condition checking functor.
*/
template <typename T, typename U>
struct PropertyChangedCondition
{
PropertyChangedCondition() = delete;
~PropertyChangedCondition() = default;
PropertyChangedCondition(const PropertyChangedCondition&) = default;
PropertyChangedCondition& operator=(const PropertyChangedCondition&) = delete;
PropertyChangedCondition(PropertyChangedCondition&&) = default;
PropertyChangedCondition& operator=(PropertyChangedCondition&&) = default;
PropertyChangedCondition(const char* iface, const char* property,
U&& condition) :
_iface(iface),
_property(property),
_condition(std::forward<U>(condition)) { }
/** @brief Test a property value.
*
* Extract the property from the PropertiesChanged
* message and run the condition test.
*/
bool operator()(sdbusplus::message::message& msg, Manager&) const
{
std::map <
std::string,
sdbusplus::message::variant<T >> properties;
const char* iface = nullptr;
msg.read(iface);
if (!iface || strcmp(iface, _iface))
{
return false;
}
msg.read(properties);
auto it = properties.find(_property);
if (it == properties.cend())
{
return false;
}
return _condition(
std::forward<T>(it->second.template get<T>()));
}
private:
const char* _iface;
const char* _property;
U _condition;
};
} // namespace property_condition
} // namespace details
/** @brief Implicit type deduction for constructing PropertyChangedCondition. */
template <typename T>
auto propertyChangedTo(
const char* iface,
const char* property,
T&& val)
{
auto condition = [val = std::move(val)](T && arg)
{
return arg == val;
};
using U = decltype(condition);
return details::property_condition::PropertyChangedCondition<T, U>(
iface, property, std::move(condition));
}
} // namespace filters
} // namespace manager
} // namespace inventory
} // namespace phosphor
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkUserInputSimulation.h"
#include <itkMersenneTwisterRandomVariateGenerator.h>
#include <qevent.h>
#include <qapplication.h>
#include <math.h>
#include <iostream>
#include <stdlib.h>
void QmitkUserInputSimulation::MouseDown( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseDown( widget, widget->width()/2, widget->height()/2, button, state );
}
void QmitkUserInputSimulation::MouseDown( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonPress, QPoint( x, y ), button, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseMove( QWidget* widget, int x, int y, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseMove, QPoint( x, y ), widget->mapToGlobal(QPoint( x, y )), Qt::NoButton, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int button)
{
if (!widget) return;
MouseRelease( widget, widget->width()/2, widget->height()/2, button );
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseRelease( widget, widget->width()/2, widget->height()/2, button, state );
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int x, int y, int button )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonRelease, QPoint( x, y ), button, button );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonRelease, QPoint( x, y ), button, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseClick( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseDown ( widget, button, state );
MouseRelease( widget, button, state );
}
void QmitkUserInputSimulation::MouseClick( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
MouseDown ( widget, x, y, button, state );
MouseRelease( widget, x, y, button, state );
}
void QmitkUserInputSimulation::MouseMoveScrollWheel( QWidget* widget, int delta )
{
MouseMoveScrollWheel( widget, widget->width()/2, widget->height()/2, delta );
}
void QmitkUserInputSimulation::MouseMoveScrollWheel( QWidget* widget, int x, int y, int delta )
{
if (!widget) return;
QWheelEvent* we = new QWheelEvent( QPoint( x, y ), delta, 0 );
QApplication::postEvent( widget, we );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseDrawRandom( QWidget* widget, int button, unsigned int points )
{
if (!widget) return;
static itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomgen= itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
static bool done = false;
if (!done)
{
//time_t randomInit = std::time(0);
randomgen->SetSeed( 0 );
done = true;
}
float w = (float)widget->width();
float h = (float)widget->height();
for (unsigned int i = 0; i <= points; ++i )
{
double r;
//r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
r = randomgen->GetVariate();
float x = r * w;
//r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
r = randomgen->GetVariate();
float y = r * h;
if (i == 0 )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == points )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
// TODO generate points first and write to file (reproducibility)
}
void QmitkUserInputSimulation::MouseDrawCircle( QWidget* widget, int button, float relativePositionX, float relativePositionY, float relativeRadius )
{
if (!widget) return;
int firstDegree = -180;
int lastDegree = 180;
int degreeStep = 10;
int secondLastDegree = lastDegree - degreeStep;
float w = (float)widget->width() * relativeRadius;
float h = (float)widget->height() * relativeRadius;
float x0 = relativePositionX * (float)widget->width();
float y0 = relativePositionY * (float)widget->height();
for (int i = firstDegree; i < lastDegree; i += degreeStep )
{
float rad = (float)i * 3.1415926535 / 180.0;
float x = cos( rad ) * w + x0;
float y = sin( rad ) * h + y0;
if (i == firstDegree )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == secondLastDegree )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
}
void QmitkUserInputSimulation::MouseDrawLine( QWidget* widget, int button, Qt::Orientation orientation )
{
if (!widget) return;
float relativeradius = 0.4f;
float w = (float)widget->width() * relativeradius;
float h = (float)widget->height() * relativeradius;
float x0 = (float)widget->width() / 2.0;
float y0 = (float)widget->height() / 2.0;
for (int i = -100; i < 100; i += 5 )
{
float x,y;
if (orientation == Qt::Horizontal)
{
x = ((float)i/100.0) * w + x0;
y = y0;
}
else
{
x = x0;
y = ((float)i/100.0) * h + y0;
}
if (i == -100 )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == 99 )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
}
void QmitkUserInputSimulation::SimulateKeyboardTyping( QWidget* widget, const QString& text )
{
for ( unsigned int i = 0; i < text.length(); ++i )
{
KeyboardTypeKey(widget, (char)text.at(i) );
}
}
void QmitkUserInputSimulation::KeyboardTypeKey( QWidget* widget, char c, int state )
{
KeyboardKeyDown( widget, c, state );
KeyboardKeyRelease( widget, c, state );
}
void QmitkUserInputSimulation::KeyboardKeyDown( QWidget* widget, char c, int state )
{
// TODO replace parameter 2 (Qt::Key_unknown) with something sensible
QKeyEvent* ke = new QKeyEvent( QEvent::KeyPress, Qt::Key_unknown, QChar(c).latin1(), state, QChar(c) );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardKeyRelease( QWidget* widget, char c, int state )
{
// TODO replace parameter 2 (Qt::Key_unknown) with something sensible
QKeyEvent* ke = new QKeyEvent( QEvent::KeyRelease, Qt::Key_unknown, QChar(c).latin1(), state, QChar(c) );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardTypeKey( QWidget* widget, int key, int state )
{
KeyboardKeyDown( widget, key, state );
KeyboardKeyRelease( widget, key, state );
}
void QmitkUserInputSimulation::KeyboardKeyDown( QWidget* widget, int key, int state )
{
QKeyEvent* ke = new QKeyEvent( QEvent::KeyPress, key, 0, state );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardKeyRelease( QWidget* widget, int key, int state )
{
QKeyEvent* ke = new QKeyEvent( QEvent::KeyRelease, key, 0, state );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
<commit_msg>COMP explicit type<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile: mitkPropertyManager.cpp,v $
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkUserInputSimulation.h"
#include <itkMersenneTwisterRandomVariateGenerator.h>
#include <qevent.h>
#include <qapplication.h>
#include <math.h>
#include <iostream>
#include <stdlib.h>
void QmitkUserInputSimulation::MouseDown( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseDown( widget, widget->width()/2, widget->height()/2, button, state );
}
void QmitkUserInputSimulation::MouseDown( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonPress, QPoint( x, y ), button, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseMove( QWidget* widget, int x, int y, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseMove, QPoint( x, y ), widget->mapToGlobal(QPoint( x, y )), Qt::NoButton, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int button)
{
if (!widget) return;
MouseRelease( widget, widget->width()/2, widget->height()/2, button );
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseRelease( widget, widget->width()/2, widget->height()/2, button, state );
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int x, int y, int button )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonRelease, QPoint( x, y ), button, button );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseRelease( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
QMouseEvent* me = new QMouseEvent( QEvent::MouseButtonRelease, QPoint( x, y ), button, state );
QApplication::postEvent( widget, me );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseClick( QWidget* widget, int button, int state )
{
if (!widget) return;
MouseDown ( widget, button, state );
MouseRelease( widget, button, state );
}
void QmitkUserInputSimulation::MouseClick( QWidget* widget, int x, int y, int button, int state )
{
if (!widget) return;
MouseDown ( widget, x, y, button, state );
MouseRelease( widget, x, y, button, state );
}
void QmitkUserInputSimulation::MouseMoveScrollWheel( QWidget* widget, int delta )
{
MouseMoveScrollWheel( widget, widget->width()/2, widget->height()/2, delta );
}
void QmitkUserInputSimulation::MouseMoveScrollWheel( QWidget* widget, int x, int y, int delta )
{
if (!widget) return;
QWheelEvent* we = new QWheelEvent( QPoint( x, y ), delta, 0 );
QApplication::postEvent( widget, we );
qApp->processEvents();
}
void QmitkUserInputSimulation::MouseDrawRandom( QWidget* widget, int button, unsigned int points )
{
if (!widget) return;
static itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomgen= itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
static bool done = false;
if (!done)
{
//time_t randomInit = std::time(0);
randomgen->SetSeed( (unsigned int) 0 );
done = true;
}
float w = (float)widget->width();
float h = (float)widget->height();
for (unsigned int i = 0; i <= points; ++i )
{
double r;
//r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
r = randomgen->GetVariate();
float x = r * w;
//r = ( (double)rand() / ((double)(RAND_MAX)+(double)(1)) );
r = randomgen->GetVariate();
float y = r * h;
if (i == 0 )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == points )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
// TODO generate points first and write to file (reproducibility)
}
void QmitkUserInputSimulation::MouseDrawCircle( QWidget* widget, int button, float relativePositionX, float relativePositionY, float relativeRadius )
{
if (!widget) return;
int firstDegree = -180;
int lastDegree = 180;
int degreeStep = 10;
int secondLastDegree = lastDegree - degreeStep;
float w = (float)widget->width() * relativeRadius;
float h = (float)widget->height() * relativeRadius;
float x0 = relativePositionX * (float)widget->width();
float y0 = relativePositionY * (float)widget->height();
for (int i = firstDegree; i < lastDegree; i += degreeStep )
{
float rad = (float)i * 3.1415926535 / 180.0;
float x = cos( rad ) * w + x0;
float y = sin( rad ) * h + y0;
if (i == firstDegree )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == secondLastDegree )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
}
void QmitkUserInputSimulation::MouseDrawLine( QWidget* widget, int button, Qt::Orientation orientation )
{
if (!widget) return;
float relativeradius = 0.4f;
float w = (float)widget->width() * relativeradius;
float h = (float)widget->height() * relativeradius;
float x0 = (float)widget->width() / 2.0;
float y0 = (float)widget->height() / 2.0;
for (int i = -100; i < 100; i += 5 )
{
float x,y;
if (orientation == Qt::Horizontal)
{
x = ((float)i/100.0) * w + x0;
y = y0;
}
else
{
x = x0;
y = ((float)i/100.0) * h + y0;
}
if (i == -100 )
{
MouseDown( widget, (int)x, (int)y, button ); // mouse down
}
MouseMove( widget, (int)x, (int)y, button ); // mouse move
//std::cout << "(" << x << "," << y << ") " << std::flush;
if (i == 99 )
{
MouseRelease( widget, (int)x, (int)y, button ); // mouse release
}
}
}
void QmitkUserInputSimulation::SimulateKeyboardTyping( QWidget* widget, const QString& text )
{
for ( unsigned int i = 0; i < text.length(); ++i )
{
KeyboardTypeKey(widget, (char)text.at(i) );
}
}
void QmitkUserInputSimulation::KeyboardTypeKey( QWidget* widget, char c, int state )
{
KeyboardKeyDown( widget, c, state );
KeyboardKeyRelease( widget, c, state );
}
void QmitkUserInputSimulation::KeyboardKeyDown( QWidget* widget, char c, int state )
{
// TODO replace parameter 2 (Qt::Key_unknown) with something sensible
QKeyEvent* ke = new QKeyEvent( QEvent::KeyPress, Qt::Key_unknown, QChar(c).latin1(), state, QChar(c) );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardKeyRelease( QWidget* widget, char c, int state )
{
// TODO replace parameter 2 (Qt::Key_unknown) with something sensible
QKeyEvent* ke = new QKeyEvent( QEvent::KeyRelease, Qt::Key_unknown, QChar(c).latin1(), state, QChar(c) );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardTypeKey( QWidget* widget, int key, int state )
{
KeyboardKeyDown( widget, key, state );
KeyboardKeyRelease( widget, key, state );
}
void QmitkUserInputSimulation::KeyboardKeyDown( QWidget* widget, int key, int state )
{
QKeyEvent* ke = new QKeyEvent( QEvent::KeyPress, key, 0, state );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
void QmitkUserInputSimulation::KeyboardKeyRelease( QWidget* widget, int key, int state )
{
QKeyEvent* ke = new QKeyEvent( QEvent::KeyRelease, key, 0, state );
QApplication::postEvent( widget, ke );
qApp->processEvents();
}
<|endoftext|>
|
<commit_before>#include "System.h"
System::System()
{
this->m_inputHandler = NULL;
this->m_window = NULL;
}
System::~System()
{
}
int System::Shutdown()
{
int result = 0;
this->m_inputHandler->Shutdown();
delete this->m_inputHandler;
//Destroy the display window
SDL_DestroyWindow(m_window);
//Quit SDL subsystems
SDL_Quit();
this->m_graphicsHandler->Shutdown();
delete this->m_graphicsHandler;
return result;
}
int System::Initialize()
{
int result = 1;
this->m_fullscreen = false;
this->m_running = true;
this->m_window = NULL;
//Get the instance if this application
this->m_hinstance = GetModuleHandle(NULL);
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
}
else
{
printf("SDL succeeded in initializing the window!\n");
}
m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (m_window == NULL)
{
printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
}
else
{
printf("Window creation succeeded!\n");
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(m_window, &wmInfo);
m_hwnd = wmInfo.info.win.window;
}
this->m_graphicsHandler = new GraphicsHandler();
if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
{
printf("GraphicsHandler did not work. RIP!\n");
}
this->m_camera = new Camera();
this->m_camera->Initialize();
this->m_graphicsHandler->SetCamera(this->m_camera);
//Initialize the InputHandler
this->m_inputHandler = new InputHandler();
this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);
return result;
}
int System::Run()
{
int result = 0;
LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
QueryPerformanceFrequency(&frequency);
//QueryPerformanceCounter(&prevTime);
float totalTime = 0.0f;
QueryPerformanceCounter(&currTime);
while (this->m_running)
{
prevTime = currTime;
QueryPerformanceCounter(&currTime);
elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
elapsedTime.QuadPart *= 1000000;
elapsedTime.QuadPart /= frequency.QuadPart;
//Prepare the InputHandler
this->m_inputHandler->Update();
//Handle events and update inputhandler through said events
result = this->HandleEvents();
SDL_PumpEvents();
//Update game
if (!this->Update((float)elapsedTime.QuadPart))
{
this->m_running = false;
}
totalTime += elapsedTime.QuadPart / 1000000.0f;
std::cout << int(totalTime) << "\n";
//Render
this->m_graphicsHandler->Render();
//printf("%i", elapsedTime.QuadPart / 1000000);
}
return result;
}
int System::Update(float deltaTime)
{
int result = 1;
if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
{
}
return result;
}
int System::HandleEvents()
{
SDL_Event m_event;
while (SDL_PollEvent(&m_event))
{
switch (m_event.type)
{
#pragma region
case SDL_WINDOWEVENT:
{
switch (m_event.window.event)
{
case SDL_WINDOWEVENT_ENTER:
{
//OnMouseFocus();
break;
}
case SDL_WINDOWEVENT_LEAVE:
{
//OnMouseBlur();
break;
}
case SDL_WINDOWEVENT_FOCUS_GAINED:
{
//OnInputFocus();
break;
}
case SDL_WINDOWEVENT_FOCUS_LOST:
{
//OnInputBlur();
break;
}
case SDL_WINDOWEVENT_SHOWN:
{
break;
}
case SDL_WINDOWEVENT_HIDDEN:
{
break;
}
case SDL_WINDOWEVENT_EXPOSED:
{
break;
}
case SDL_WINDOWEVENT_MOVED:
{
break;
}
case SDL_WINDOWEVENT_RESIZED:
{
break;
}
case SDL_WINDOWEVENT_SIZE_CHANGED:
{
break;
}
case SDL_WINDOWEVENT_MINIMIZED:
{
break;
}
case SDL_WINDOWEVENT_MAXIMIZED:
{
break;
}
case SDL_WINDOWEVENT_RESTORED:
{
break;
}
case SDL_WINDOWEVENT_CLOSE:
{
break;
}
}
break;
}
#pragma endregion window events
case SDL_MOUSEMOTION:
{
break;
}
case SDL_QUIT:
{
//The big X in the corner
this->m_running = false;
break;
}
#pragma region
case SDL_KEYDOWN:
{
//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
break;
}
case SDL_KEYUP:
{
//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
break;
}
case SDL_MOUSEBUTTONDOWN:
{
break;
}
case SDL_MOUSEBUTTONUP:
{
break;
}
#pragma endregion Key / Button events
case SDL_MOUSEWHEEL:
{
this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
break;
}
}
}
return 1;
}
int System::FullscreenToggle()
{
int result = 0;
bool IsFullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
SDL_SetWindowFullscreen(this->m_window, IsFullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
SDL_ShowCursor(IsFullscreen);
return result;
}
<commit_msg>UPDATE System camera deletion on cleanup<commit_after>#include "System.h"
System::System()
{
this->m_inputHandler = NULL;
this->m_window = NULL;
}
System::~System()
{
}
int System::Shutdown()
{
int result = 0;
this->m_inputHandler->Shutdown();
delete this->m_inputHandler;
//Destroy the display window
SDL_DestroyWindow(m_window);
//Quit SDL subsystems
SDL_Quit();
this->m_graphicsHandler->Shutdown();
delete this->m_graphicsHandler;
delete this->m_camera;
return result;
}
int System::Initialize()
{
int result = 1;
this->m_fullscreen = false;
this->m_running = true;
this->m_window = NULL;
//Get the instance if this application
this->m_hinstance = GetModuleHandle(NULL);
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError());
}
else
{
printf("SDL succeeded in initializing the window!\n");
}
m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (m_window == NULL)
{
printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError());
}
else
{
printf("Window creation succeeded!\n");
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(m_window, &wmInfo);
m_hwnd = wmInfo.info.win.window;
}
this->m_graphicsHandler = new GraphicsHandler();
if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT)))
{
printf("GraphicsHandler did not work. RIP!\n");
}
this->m_camera = new Camera();
this->m_camera->Initialize();
this->m_graphicsHandler->SetCamera(this->m_camera);
//Initialize the InputHandler
this->m_inputHandler = new InputHandler();
this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT);
return result;
}
int System::Run()
{
int result = 0;
LARGE_INTEGER frequency, currTime, prevTime, elapsedTime;
QueryPerformanceFrequency(&frequency);
//QueryPerformanceCounter(&prevTime);
float totalTime = 0.0f;
QueryPerformanceCounter(&currTime);
while (this->m_running)
{
prevTime = currTime;
QueryPerformanceCounter(&currTime);
elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart;
elapsedTime.QuadPart *= 1000000;
elapsedTime.QuadPart /= frequency.QuadPart;
//Prepare the InputHandler
this->m_inputHandler->Update();
//Handle events and update inputhandler through said events
result = this->HandleEvents();
SDL_PumpEvents();
//Update game
if (!this->Update((float)elapsedTime.QuadPart))
{
this->m_running = false;
}
totalTime += elapsedTime.QuadPart / 1000000.0f;
std::cout << int(totalTime) << "\n";
//Render
this->m_graphicsHandler->Render();
//printf("%i", elapsedTime.QuadPart / 1000000);
}
return result;
}
int System::Update(float deltaTime)
{
int result = 1;
if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S))
{
}
return result;
}
int System::HandleEvents()
{
SDL_Event m_event;
while (SDL_PollEvent(&m_event))
{
switch (m_event.type)
{
#pragma region
case SDL_WINDOWEVENT:
{
switch (m_event.window.event)
{
case SDL_WINDOWEVENT_ENTER:
{
//OnMouseFocus();
break;
}
case SDL_WINDOWEVENT_LEAVE:
{
//OnMouseBlur();
break;
}
case SDL_WINDOWEVENT_FOCUS_GAINED:
{
//OnInputFocus();
break;
}
case SDL_WINDOWEVENT_FOCUS_LOST:
{
//OnInputBlur();
break;
}
case SDL_WINDOWEVENT_SHOWN:
{
break;
}
case SDL_WINDOWEVENT_HIDDEN:
{
break;
}
case SDL_WINDOWEVENT_EXPOSED:
{
break;
}
case SDL_WINDOWEVENT_MOVED:
{
break;
}
case SDL_WINDOWEVENT_RESIZED:
{
break;
}
case SDL_WINDOWEVENT_SIZE_CHANGED:
{
break;
}
case SDL_WINDOWEVENT_MINIMIZED:
{
break;
}
case SDL_WINDOWEVENT_MAXIMIZED:
{
break;
}
case SDL_WINDOWEVENT_RESTORED:
{
break;
}
case SDL_WINDOWEVENT_CLOSE:
{
break;
}
}
break;
}
#pragma endregion window events
case SDL_MOUSEMOTION:
{
break;
}
case SDL_QUIT:
{
//The big X in the corner
this->m_running = false;
break;
}
#pragma region
case SDL_KEYDOWN:
{
//OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true);
break;
}
case SDL_KEYUP:
{
//OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode);
this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false);
break;
}
case SDL_MOUSEBUTTONDOWN:
{
break;
}
case SDL_MOUSEBUTTONUP:
{
break;
}
#pragma endregion Key / Button events
case SDL_MOUSEWHEEL:
{
this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y);
break;
}
}
}
return 1;
}
int System::FullscreenToggle()
{
int result = 0;
bool IsFullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN;
SDL_SetWindowFullscreen(this->m_window, IsFullscreen ? 0 : SDL_WINDOW_FULLSCREEN);
SDL_ShowCursor(IsFullscreen);
return result;
}
<|endoftext|>
|
<commit_before>#include "ControlledSimulator.h"
//Set these values to 0 to get all warnings
//const static double gTorqueLimitWarningThreshold = 0;
const static double gTorqueLimitWarningThreshold = Inf;
//const static double gJointLimitWarningThreshold = 0;
const static double gJointLimitWarningThreshold = Inf;
ControlledRobotSimulator::ControlledRobotSimulator()
:robot(NULL),oderobot(NULL),controller(NULL)
{
controlTimeStep = 0.01;
}
void ControlledRobotSimulator::Init(Robot* _robot,ODERobot* _oderobot,RobotController* _controller)
{
robot=_robot;
oderobot=_oderobot;
controller=_controller;
oderobot->SetConfig(robot->q);
oderobot->SetVelocities(robot->dq);
command.actuators.resize(robot->drivers.size());
if(controller) {
controller->Reset();
}
curTime = 0;
nextControlTime = 0;
}
void ControlledRobotSimulator::SimulateSensors()
{
if(!controller) return;
for(size_t i=0;i<sensors.sensors.size();i++) {
sensors.sensors[i]->Simulate(this);
sensors.sensors[i]->Advance(controlTimeStep);
}
}
void ControlledRobotSimulator::GetCommandedConfig(Config& q)
{
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
if(command.actuators[i].mode == ActuatorCommand::PID)
robot->SetDriverValue(i,command.actuators[i].qdes);
else
FatalError("Can't get commanded config for non-config drivers");
}
q = robot->q;
}
void ControlledRobotSimulator::GetCommandedVelocity(Config& dq)
{
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
if(command.actuators[i].mode == ActuatorCommand::PID)
robot->SetDriverValue(i,command.actuators[i].dqdes);
else
FatalError("Can't get commanded config for non-config drivers");
}
dq = robot->dq;
}
void ControlledRobotSimulator::GetSensedConfig(Config& q)
{
JointPositionSensor* s = sensors.GetTypedSensor<JointPositionSensor>();
if(s==NULL)
fprintf(stderr,"Warning, robot has no joint position sensor\n");
else
q = s->q;
}
void ControlledRobotSimulator::GetSensedVelocity(Config& dq)
{
JointVelocitySensor* s=sensors.GetTypedSensor<JointVelocitySensor>();
if(s==NULL)
fprintf(stderr,"Warning, robot has no joint velocity sensor\n");
else
dq = s->dq;
}
void ControlledRobotSimulator::GetSimulatedConfig(Config& q)
{
oderobot->GetConfig(q);
}
void ControlledRobotSimulator::GetSimulatedVelocity(Config& dq)
{
oderobot->GetVelocities(dq);
}
void ControlledRobotSimulator::GetActuatorTorques(Vector& t) const
{
Assert(command.actuators.size() == robot->drivers.size());
t.resize(command.actuators.size());
for(size_t i=0;i<command.actuators.size();i++) {
const RobotJointDriver& d=robot->drivers[i];
Real q=oderobot->GetDriverValue(i);
Real dq=oderobot->GetDriverVelocity(i);
int link = d.linkIndices[0];
if(q < robot->qMin(link)) {
if(q + TwoPi >= robot->qMin(link) && q + TwoPi <= robot->qMax(link))
q += TwoPi;
}
else if(q > robot->qMax(link)) {
if(q - TwoPi <= robot->qMax(link) && q - TwoPi >= robot->qMin(link))
q -= TwoPi;
}
if(q < robot->qMin(link)-gJointLimitWarningThreshold || q > robot->qMax(link)+gJointLimitWarningThreshold) {
printf("Warning: joint angle %s out of bounds\n",robot->linkNames[link].c_str());
printf("q=%g, qmin=%g, qmax=%g (deg)\n",RtoD(q),RtoD(robot->qMin(link)),RtoD(robot->qMax(link)));
//getchar();
}
const ActuatorCommand& cmd=command.actuators[i];
switch(cmd.mode) {
case ActuatorCommand::OFF:
printf("Warning: actuator off?\n");
t(i) = 0;
break;
case ActuatorCommand::TORQUE:
//printf("Warning: direct torque?\n");
if(cmd.torque < d.tmin-gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g < %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmd.torque,d.tmin);
else if(cmd.torque > d.tmax+gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g > %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmd.torque,d.tmax);
t(i) = Clamp(cmd.torque,d.tmin,d.tmax);
break;
case ActuatorCommand::PID:
{
//TODO: simulate low level errors in the PID loop
Real cmdtorque = cmd.GetPIDTorque(q,dq);
if(cmdtorque < d.tmin-gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g < %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmdtorque,d.tmin);
else if(cmdtorque > d.tmax+gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g > %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmdtorque,d.tmax);
Real td=Clamp(cmdtorque,d.tmin,d.tmax);
//printf("%d: Current %g,%g, desired %g,%g, torque desired %g, clamped %g\n",i,q,dq,cmd.qdes,cmd.dqdes,cmd.GetPIDTorque(q,dq),td);
t(i) = td;
break;
}
case ActuatorCommand::LOCKED_VELOCITY:
t(i) = 0;
break;
}
}
}
void ControlledRobotSimulator::Step(Real dt)
{
Real endOfTimeStep = curTime + dt;
if(controller) {
//the controller update happens less often than the PID update loop
if(nextControlTime < endOfTimeStep) {
//simulate sensors
SimulateSensors();
//update controller
controller->sensors = &sensors;
controller->command = &command;
controller->Update(controlTimeStep);
nextControlTime += controlTimeStep;
}
//get torques
Vector t;
GetActuatorTorques(t);
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
ActuatorCommand& cmd=command.actuators[i];
if(cmd.mode == ActuatorCommand::LOCKED_VELOCITY) {
//TODO: clamp to braking velocitiy?
oderobot->SetDriverFixedVelocity(i,cmd.desiredVelocity,cmd.torque);
}
else {
if(d.type == RobotJointDriver::Normal || d.type == RobotJointDriver::Translation || d.type == RobotJointDriver::Rotation) {
oderobot->AddDriverTorque(i,t(i));
}
else if(d.type == RobotJointDriver::Affine) {
Real q=cmd.qdes;
Real dq=cmd.dqdes;
Vector tjoints(d.linkIndices.size());
Vector driverBasis(d.linkIndices.size());
robot->SetDriverValue(i,q);
robot->SetDriverVelocity(i,dq);
//TODO: don't hard-code these! But how to encode arbitrary drive
//trains?
Real mechStiffness = 20;
Real mechDamping = 0.2;
Real mechMaxTorque = 2;
for(size_t j=0;j<d.linkIndices.size();j++) {
int link = d.linkIndices[j];
driverBasis[j] = d.affScaling[j]; //todo: should be a transmission parameter in the joint driver
tjoints[j] = mechStiffness*(robot->q(link)-oderobot->GetLinkAngle(link)) + mechDamping*(robot->dq(link)-oderobot->GetLinkVelocity(link));
}
tjoints.madd(driverBasis,-tjoints.dot(driverBasis)/driverBasis.normSquared());
if(tjoints.norm() > mechMaxTorque)
tjoints *= mechMaxTorque/tjoints.norm();
//cout<<"Stabilizing torques: "<<tjoints<<endl;
tjoints.madd(driverBasis,t[i]);
//cout<<"Torques: "<<tjoints<<endl;
for(size_t j=0;j<d.linkIndices.size();j++)
oderobot->AddLinkTorque(d.linkIndices[j],tjoints[j]);
}
else {
FatalError("Unknown driver type");
}
}
if(cmd.mode == ActuatorCommand::PID) {
//advance PID controller
Real q=oderobot->GetDriverValue(i);
cmd.IntegratePID(q,dt);
if(cmd.kI*cmd.iterm > d.tmax) { cmd.iterm = d.tmax/cmd.kI; }
else if(cmd.kI*cmd.iterm < d.tmin) { cmd.iterm = d.tmin/cmd.kI; }
}
}
}
curTime = endOfTimeStep;
}
void ControlledRobotSimulator::UpdateRobot()
{
oderobot->GetConfig(robot->q);
oderobot->GetVelocities(robot->dq);
robot->UpdateFrames();
}
bool ControlledRobotSimulator::ReadState(File& f)
{
if(!ReadFile(f,curTime)) return false;
if(!ReadFile(f,nextControlTime)) return false;
if(!ReadFile(f,command)) return false;
if(!sensors.ReadState(f)) return false;
if(controller) {
if(!controller->ReadState(f)) return false;
}
return true;
}
bool ControlledRobotSimulator::WriteState(File& f) const
{
if(!WriteFile(f,curTime)) return false;
if(!WriteFile(f,nextControlTime)) return false;
if(!WriteFile(f,command)) return false;
if(!sensors.WriteState(f)) return false;
if(controller) {
if(!controller->WriteState(f)) return false;
}
return true;
}
<commit_msg>Small fix to GetCommandedVelocity<commit_after>#include "ControlledSimulator.h"
//Set these values to 0 to get all warnings
//const static double gTorqueLimitWarningThreshold = 0;
const static double gTorqueLimitWarningThreshold = Inf;
//const static double gJointLimitWarningThreshold = 0;
const static double gJointLimitWarningThreshold = Inf;
ControlledRobotSimulator::ControlledRobotSimulator()
:robot(NULL),oderobot(NULL),controller(NULL)
{
controlTimeStep = 0.01;
}
void ControlledRobotSimulator::Init(Robot* _robot,ODERobot* _oderobot,RobotController* _controller)
{
robot=_robot;
oderobot=_oderobot;
controller=_controller;
oderobot->SetConfig(robot->q);
oderobot->SetVelocities(robot->dq);
command.actuators.resize(robot->drivers.size());
if(controller) {
controller->Reset();
}
curTime = 0;
nextControlTime = 0;
}
void ControlledRobotSimulator::SimulateSensors()
{
if(!controller) return;
for(size_t i=0;i<sensors.sensors.size();i++) {
sensors.sensors[i]->Simulate(this);
sensors.sensors[i]->Advance(controlTimeStep);
}
}
void ControlledRobotSimulator::GetCommandedConfig(Config& q)
{
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
if(command.actuators[i].mode == ActuatorCommand::PID)
robot->SetDriverValue(i,command.actuators[i].qdes);
else
FatalError("Can't get commanded config for non-config drivers");
}
q = robot->q;
}
void ControlledRobotSimulator::GetCommandedVelocity(Config& dq)
{
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
if(command.actuators[i].mode == ActuatorCommand::PID)
robot->SetDriverVelocity(i,command.actuators[i].dqdes);
else
FatalError("Can't get commanded config for non-config drivers");
}
dq = robot->dq;
}
void ControlledRobotSimulator::GetSensedConfig(Config& q)
{
JointPositionSensor* s = sensors.GetTypedSensor<JointPositionSensor>();
if(s==NULL)
fprintf(stderr,"Warning, robot has no joint position sensor\n");
else
q = s->q;
}
void ControlledRobotSimulator::GetSensedVelocity(Config& dq)
{
JointVelocitySensor* s=sensors.GetTypedSensor<JointVelocitySensor>();
if(s==NULL)
fprintf(stderr,"Warning, robot has no joint velocity sensor\n");
else
dq = s->dq;
}
void ControlledRobotSimulator::GetSimulatedConfig(Config& q)
{
oderobot->GetConfig(q);
}
void ControlledRobotSimulator::GetSimulatedVelocity(Config& dq)
{
oderobot->GetVelocities(dq);
}
void ControlledRobotSimulator::GetActuatorTorques(Vector& t) const
{
Assert(command.actuators.size() == robot->drivers.size());
t.resize(command.actuators.size());
for(size_t i=0;i<command.actuators.size();i++) {
const RobotJointDriver& d=robot->drivers[i];
Real q=oderobot->GetDriverValue(i);
Real dq=oderobot->GetDriverVelocity(i);
int link = d.linkIndices[0];
if(q < robot->qMin(link)) {
if(q + TwoPi >= robot->qMin(link) && q + TwoPi <= robot->qMax(link))
q += TwoPi;
}
else if(q > robot->qMax(link)) {
if(q - TwoPi <= robot->qMax(link) && q - TwoPi >= robot->qMin(link))
q -= TwoPi;
}
if(q < robot->qMin(link)-gJointLimitWarningThreshold || q > robot->qMax(link)+gJointLimitWarningThreshold) {
printf("Warning: joint angle %s out of bounds\n",robot->linkNames[link].c_str());
printf("q=%g, qmin=%g, qmax=%g (deg)\n",RtoD(q),RtoD(robot->qMin(link)),RtoD(robot->qMax(link)));
//getchar();
}
const ActuatorCommand& cmd=command.actuators[i];
switch(cmd.mode) {
case ActuatorCommand::OFF:
printf("Warning: actuator off?\n");
t(i) = 0;
break;
case ActuatorCommand::TORQUE:
//printf("Warning: direct torque?\n");
if(cmd.torque < d.tmin-gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g < %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmd.torque,d.tmin);
else if(cmd.torque > d.tmax+gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g > %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmd.torque,d.tmax);
t(i) = Clamp(cmd.torque,d.tmin,d.tmax);
break;
case ActuatorCommand::PID:
{
//TODO: simulate low level errors in the PID loop
Real cmdtorque = cmd.GetPIDTorque(q,dq);
if(cmdtorque < d.tmin-gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g < %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmdtorque,d.tmin);
else if(cmdtorque > d.tmax+gTorqueLimitWarningThreshold)
printf("Actuator %s limit exceeded: %g > %g\n",robot->LinkName(robot->drivers[i].linkIndices[0]).c_str(),cmdtorque,d.tmax);
Real td=Clamp(cmdtorque,d.tmin,d.tmax);
//printf("%d: Current %g,%g, desired %g,%g, torque desired %g, clamped %g\n",i,q,dq,cmd.qdes,cmd.dqdes,cmd.GetPIDTorque(q,dq),td);
t(i) = td;
break;
}
case ActuatorCommand::LOCKED_VELOCITY:
t(i) = 0;
break;
}
}
}
void ControlledRobotSimulator::Step(Real dt)
{
Real endOfTimeStep = curTime + dt;
if(controller) {
//the controller update happens less often than the PID update loop
if(nextControlTime < endOfTimeStep) {
//simulate sensors
SimulateSensors();
//update controller
controller->sensors = &sensors;
controller->command = &command;
controller->Update(controlTimeStep);
nextControlTime += controlTimeStep;
}
//get torques
Vector t;
GetActuatorTorques(t);
Assert(command.actuators.size() == robot->drivers.size());
for(size_t i=0;i<command.actuators.size();i++) {
RobotJointDriver& d=robot->drivers[i];
ActuatorCommand& cmd=command.actuators[i];
if(cmd.mode == ActuatorCommand::LOCKED_VELOCITY) {
//TODO: clamp to braking velocitiy?
oderobot->SetDriverFixedVelocity(i,cmd.desiredVelocity,cmd.torque);
}
else {
if(d.type == RobotJointDriver::Normal || d.type == RobotJointDriver::Translation || d.type == RobotJointDriver::Rotation) {
oderobot->AddDriverTorque(i,t(i));
}
else if(d.type == RobotJointDriver::Affine) {
Real q=cmd.qdes;
Real dq=cmd.dqdes;
Vector tjoints(d.linkIndices.size());
Vector driverBasis(d.linkIndices.size());
robot->SetDriverValue(i,q);
robot->SetDriverVelocity(i,dq);
//TODO: don't hard-code these! But how to encode arbitrary drive
//trains?
Real mechStiffness = 20;
Real mechDamping = 0.2;
Real mechMaxTorque = 2;
for(size_t j=0;j<d.linkIndices.size();j++) {
int link = d.linkIndices[j];
driverBasis[j] = d.affScaling[j]; //todo: should be a transmission parameter in the joint driver
tjoints[j] = mechStiffness*(robot->q(link)-oderobot->GetLinkAngle(link)) + mechDamping*(robot->dq(link)-oderobot->GetLinkVelocity(link));
}
tjoints.madd(driverBasis,-tjoints.dot(driverBasis)/driverBasis.normSquared());
if(tjoints.norm() > mechMaxTorque)
tjoints *= mechMaxTorque/tjoints.norm();
//cout<<"Stabilizing torques: "<<tjoints<<endl;
tjoints.madd(driverBasis,t[i]);
//cout<<"Torques: "<<tjoints<<endl;
for(size_t j=0;j<d.linkIndices.size();j++)
oderobot->AddLinkTorque(d.linkIndices[j],tjoints[j]);
}
else {
FatalError("Unknown driver type");
}
}
if(cmd.mode == ActuatorCommand::PID) {
//advance PID controller
Real q=oderobot->GetDriverValue(i);
cmd.IntegratePID(q,dt);
if(cmd.kI*cmd.iterm > d.tmax) { cmd.iterm = d.tmax/cmd.kI; }
else if(cmd.kI*cmd.iterm < d.tmin) { cmd.iterm = d.tmin/cmd.kI; }
}
}
}
curTime = endOfTimeStep;
}
void ControlledRobotSimulator::UpdateRobot()
{
oderobot->GetConfig(robot->q);
oderobot->GetVelocities(robot->dq);
robot->UpdateFrames();
}
bool ControlledRobotSimulator::ReadState(File& f)
{
if(!ReadFile(f,curTime)) return false;
if(!ReadFile(f,nextControlTime)) return false;
if(!ReadFile(f,command)) return false;
if(!sensors.ReadState(f)) return false;
if(controller) {
if(!controller->ReadState(f)) return false;
}
return true;
}
bool ControlledRobotSimulator::WriteState(File& f) const
{
if(!WriteFile(f,curTime)) return false;
if(!WriteFile(f,nextControlTime)) return false;
if(!WriteFile(f,command)) return false;
if(!sensors.WriteState(f)) return false;
if(controller) {
if(!controller->WriteState(f)) return false;
}
return true;
}
<|endoftext|>
|
<commit_before><commit_msg>patch accessing_xhr.response_as_arraybuffer_from_node_context<commit_after><|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
begins = 0;
if (ends == std::string::npos)
ends = Str.size();
return Str.substr(begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Properly handle the case where ReadToEndOfBuffer() is called with the raw lexer already pointing at the end of the buffer.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 1);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
begins = 0;
if (ends == std::string::npos)
ends = Str.size();
return Str.substr(begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success = m_Interp.loadFile(LexPath(RawLexer));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(LexPath(RawLexer));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.is(tok::eof))
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
llvm::sys::Path path(LexPath(RawLexer));
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return Tok.getLiteralData();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
std::string MetaProcessor::LexPath(Lexer& RawLexer) {
Token Tok;
std::string Result("");
do {
RawLexer.LexFromRawLexer(Tok);
Result += GetRawTokenName(Tok);
}
while (Tok.isNot(tok::eof));
return Result;
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Take the string with the length of the token not the entire memory buffer.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success = m_Interp.loadFile(LexPath(RawLexer));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(LexPath(RawLexer));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.is(tok::eof))
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
llvm::sys::Path path(LexPath(RawLexer));
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
std::string MetaProcessor::LexPath(Lexer& RawLexer) {
Token Tok;
std::string Result("");
do {
RawLexer.LexFromRawLexer(Tok);
Result += GetRawTokenName(Tok);
}
while (Tok.isNot(tok::eof));
return Result;
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the list with the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|>
|
<commit_before>//===--- MisplacedWideningCastCheck.cpp - clang-tidy-----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MisplacedWideningCastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/ADT/DenseMap.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace misc {
MisplacedWideningCastCheck::MisplacedWideningCastCheck(
StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
CheckImplicitCasts(Options.get("CheckImplicitCasts", true)) {}
void MisplacedWideningCastCheck::storeOptions(
ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "CheckImplicitCasts", CheckImplicitCasts);
}
void MisplacedWideningCastCheck::registerMatchers(MatchFinder *Finder) {
auto Calc = expr(anyOf(binaryOperator(anyOf(
hasOperatorName("+"), hasOperatorName("-"),
hasOperatorName("*"), hasOperatorName("<<"))),
unaryOperator(hasOperatorName("~"))),
hasType(isInteger()))
.bind("Calc");
auto ExplicitCast =
explicitCastExpr(hasDestinationType(isInteger()), has(Calc));
auto ImplicitCast =
implicitCastExpr(hasImplicitDestinationType(isInteger()), has(Calc));
auto Cast = expr(anyOf(ExplicitCast, ImplicitCast)).bind("Cast");
Finder->addMatcher(varDecl(hasInitializer(Cast)), this);
Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this);
Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this);
Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this);
Finder->addMatcher(
binaryOperator(anyOf(hasOperatorName("=="), hasOperatorName("!="),
hasOperatorName("<"), hasOperatorName("<="),
hasOperatorName(">"), hasOperatorName(">=")),
anyOf(hasLHS(Cast), hasRHS(Cast))),
this);
}
static unsigned getMaxCalculationWidth(ASTContext &Context, const Expr *E) {
E = E->IgnoreParenImpCasts();
if (const auto *Bop = dyn_cast<BinaryOperator>(E)) {
unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS());
unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS());
if (Bop->getOpcode() == BO_Mul)
return LHSWidth + RHSWidth;
if (Bop->getOpcode() == BO_Add)
return std::max(LHSWidth, RHSWidth) + 1;
if (Bop->getOpcode() == BO_Rem) {
llvm::APSInt Val;
if (Bop->getRHS()->EvaluateAsInt(Val, Context))
return Val.getActiveBits();
} else if (Bop->getOpcode() == BO_Shl) {
llvm::APSInt Bits;
if (Bop->getRHS()->EvaluateAsInt(Bits, Context)) {
// We don't handle negative values and large values well. It is assumed
// that compiler warnings are written for such values so the user will
// fix that.
return LHSWidth + Bits.getExtValue();
}
// Unknown bitcount, assume there is truncation.
return 1024U;
}
} else if (const auto *Uop = dyn_cast<UnaryOperator>(E)) {
// There is truncation when ~ is used.
if (Uop->getOpcode() == UO_Not)
return 1024U;
QualType T = Uop->getType();
return T->isIntegerType() ? Context.getIntWidth(T) : 1024U;
} else if (const auto *I = dyn_cast<IntegerLiteral>(E)) {
return I->getValue().getActiveBits();
}
return Context.getIntWidth(E->getType());
}
static llvm::SmallDenseMap<int, int> createRelativeIntSizesMap() {
llvm::SmallDenseMap<int, int> Result;
Result[BuiltinType::UChar] = 1;
Result[BuiltinType::SChar] = 1;
Result[BuiltinType::Char_U] = 1;
Result[BuiltinType::Char_S] = 1;
Result[BuiltinType::UShort] = 2;
Result[BuiltinType::Short] = 2;
Result[BuiltinType::UInt] = 3;
Result[BuiltinType::Int] = 3;
Result[BuiltinType::ULong] = 4;
Result[BuiltinType::Long] = 4;
Result[BuiltinType::ULongLong] = 5;
Result[BuiltinType::LongLong] = 5;
Result[BuiltinType::UInt128] = 6;
Result[BuiltinType::Int128] = 6;
return Result;
}
static llvm::SmallDenseMap<int, int> createRelativeCharSizesMap() {
llvm::SmallDenseMap<int, int> Result;
Result[BuiltinType::UChar] = 1;
Result[BuiltinType::SChar] = 1;
Result[BuiltinType::Char_U] = 1;
Result[BuiltinType::Char_S] = 1;
Result[BuiltinType::Char16] = 2;
Result[BuiltinType::Char32] = 3;
return Result;
}
static llvm::SmallDenseMap<int, int> createRelativeCharSizesWMap() {
llvm::SmallDenseMap<int, int> Result;
Result[BuiltinType::UChar] = 1;
Result[BuiltinType::SChar] = 1;
Result[BuiltinType::Char_U] = 1;
Result[BuiltinType::Char_S] = 1;
Result[BuiltinType::WChar_U] = 2;
Result[BuiltinType::WChar_S] = 2;
return Result;
}
static bool isFirstWider(BuiltinType::Kind First, BuiltinType::Kind Second) {
static const llvm::SmallDenseMap<int, int> RelativeIntSizes(
createRelativeIntSizesMap());
static const llvm::SmallDenseMap<int, int> RelativeCharSizes(
createRelativeCharSizesMap());
static const llvm::SmallDenseMap<int, int> RelativeCharSizesW(
createRelativeCharSizesWMap());
int FirstSize, SecondSize;
if ((FirstSize = RelativeIntSizes.lookup(First)) &&
(SecondSize = RelativeIntSizes.lookup(Second)))
return FirstSize > SecondSize;
if ((FirstSize = RelativeCharSizes.lookup(First)) &&
(SecondSize = RelativeCharSizes.lookup(Second)))
return FirstSize > SecondSize;
if ((FirstSize = RelativeCharSizesW.lookup(First)) &&
(SecondSize = RelativeCharSizesW.lookup(Second)))
return FirstSize > SecondSize;
return false;
}
void MisplacedWideningCastCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>("Cast");
if (!CheckImplicitCasts && isa<ImplicitCastExpr>(Cast))
return;
if (Cast->getLocStart().isMacroID())
return;
const auto *Calc = Result.Nodes.getNodeAs<Expr>("Calc");
if (Calc->getLocStart().isMacroID())
return;
ASTContext &Context = *Result.Context;
QualType CastType = Cast->getType();
QualType CalcType = Calc->getType();
// Explicit truncation using cast.
if (Context.getIntWidth(CastType) < Context.getIntWidth(CalcType))
return;
// If CalcType and CastType have same size then there is no real danger, but
// there can be a portability problem.
if (Context.getIntWidth(CastType) == Context.getIntWidth(CalcType)) {
const auto *CastBuiltinType =
dyn_cast<BuiltinType>(CastType->getUnqualifiedDesugaredType());
const auto *CalcBuiltinType =
dyn_cast<BuiltinType>(CalcType->getUnqualifiedDesugaredType());
if (CastBuiltinType && CalcBuiltinType &&
!isFirstWider(CastBuiltinType->getKind(), CalcBuiltinType->getKind()))
return;
}
// Don't write a warning if we can easily see that the result is not
// truncated.
if (Context.getIntWidth(CalcType) >= getMaxCalculationWidth(Context, Calc))
return;
diag(Cast->getLocStart(), "either cast from %0 to %1 is ineffective, or "
"there is loss of precision before the conversion")
<< CalcType << CastType;
}
} // namespace misc
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Fix infinite loop in MisplacedWideningCastCheck.<commit_after>//===--- MisplacedWideningCastCheck.cpp - clang-tidy-----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MisplacedWideningCastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace misc {
MisplacedWideningCastCheck::MisplacedWideningCastCheck(
StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
CheckImplicitCasts(Options.get("CheckImplicitCasts", true)) {}
void MisplacedWideningCastCheck::storeOptions(
ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "CheckImplicitCasts", CheckImplicitCasts);
}
void MisplacedWideningCastCheck::registerMatchers(MatchFinder *Finder) {
const auto Calc =
expr(anyOf(binaryOperator(
anyOf(hasOperatorName("+"), hasOperatorName("-"),
hasOperatorName("*"), hasOperatorName("<<"))),
unaryOperator(hasOperatorName("~"))),
hasType(isInteger()))
.bind("Calc");
const auto ExplicitCast =
explicitCastExpr(hasDestinationType(isInteger()), has(Calc));
const auto ImplicitCast =
implicitCastExpr(hasImplicitDestinationType(isInteger()), has(Calc));
const auto Cast = expr(anyOf(ExplicitCast, ImplicitCast)).bind("Cast");
Finder->addMatcher(varDecl(hasInitializer(Cast)), this);
Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this);
Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this);
Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this);
Finder->addMatcher(
binaryOperator(anyOf(hasOperatorName("=="), hasOperatorName("!="),
hasOperatorName("<"), hasOperatorName("<="),
hasOperatorName(">"), hasOperatorName(">=")),
hasEitherOperand(Cast)),
this);
}
static unsigned getMaxCalculationWidth(const ASTContext &Context,
const Expr *E) {
E = E->IgnoreParenImpCasts();
if (const auto *Bop = dyn_cast<BinaryOperator>(E)) {
unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS());
unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS());
if (Bop->getOpcode() == BO_Mul)
return LHSWidth + RHSWidth;
if (Bop->getOpcode() == BO_Add)
return std::max(LHSWidth, RHSWidth) + 1;
if (Bop->getOpcode() == BO_Rem) {
llvm::APSInt Val;
if (Bop->getRHS()->EvaluateAsInt(Val, Context))
return Val.getActiveBits();
} else if (Bop->getOpcode() == BO_Shl) {
llvm::APSInt Bits;
if (Bop->getRHS()->EvaluateAsInt(Bits, Context)) {
// We don't handle negative values and large values well. It is assumed
// that compiler warnings are written for such values so the user will
// fix that.
return LHSWidth + Bits.getExtValue();
}
// Unknown bitcount, assume there is truncation.
return 1024U;
}
} else if (const auto *Uop = dyn_cast<UnaryOperator>(E)) {
// There is truncation when ~ is used.
if (Uop->getOpcode() == UO_Not)
return 1024U;
QualType T = Uop->getType();
return T->isIntegerType() ? Context.getIntWidth(T) : 1024U;
} else if (const auto *I = dyn_cast<IntegerLiteral>(E)) {
return I->getValue().getActiveBits();
}
return Context.getIntWidth(E->getType());
}
static int relativeIntSizes(BuiltinType::Kind Kind) {
switch (Kind) {
case BuiltinType::UChar:
return 1;
case BuiltinType::SChar:
return 1;
case BuiltinType::Char_U:
return 1;
case BuiltinType::Char_S:
return 1;
case BuiltinType::UShort:
return 2;
case BuiltinType::Short:
return 2;
case BuiltinType::UInt:
return 3;
case BuiltinType::Int:
return 3;
case BuiltinType::ULong:
return 4;
case BuiltinType::Long:
return 4;
case BuiltinType::ULongLong:
return 5;
case BuiltinType::LongLong:
return 5;
case BuiltinType::UInt128:
return 6;
case BuiltinType::Int128:
return 6;
default:
return 0;
}
}
static int relativeCharSizes(BuiltinType::Kind Kind) {
switch (Kind) {
case BuiltinType::UChar:
return 1;
case BuiltinType::SChar:
return 1;
case BuiltinType::Char_U:
return 1;
case BuiltinType::Char_S:
return 1;
case BuiltinType::Char16:
return 2;
case BuiltinType::Char32:
return 3;
default:
return 0;
}
}
static int relativeCharSizesW(BuiltinType::Kind Kind) {
switch (Kind) {
case BuiltinType::UChar:
return 1;
case BuiltinType::SChar:
return 1;
case BuiltinType::Char_U:
return 1;
case BuiltinType::Char_S:
return 1;
case BuiltinType::WChar_U:
return 2;
case BuiltinType::WChar_S:
return 2;
default:
return 0;
}
}
static bool isFirstWider(BuiltinType::Kind First, BuiltinType::Kind Second) {
int FirstSize, SecondSize;
if ((FirstSize = relativeIntSizes(First)) != 0 &&
(SecondSize = relativeIntSizes(Second)) != 0)
return FirstSize > SecondSize;
if ((FirstSize = relativeCharSizes(First)) != 0 &&
(SecondSize = relativeCharSizes(Second)) != 0)
return FirstSize > SecondSize;
if ((FirstSize = relativeCharSizesW(First)) != 0 &&
(SecondSize = relativeCharSizesW(Second)) != 0)
return FirstSize > SecondSize;
return false;
}
void MisplacedWideningCastCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>("Cast");
if (!CheckImplicitCasts && isa<ImplicitCastExpr>(Cast))
return;
if (Cast->getLocStart().isMacroID())
return;
const auto *Calc = Result.Nodes.getNodeAs<Expr>("Calc");
if (Calc->getLocStart().isMacroID())
return;
ASTContext &Context = *Result.Context;
QualType CastType = Cast->getType();
QualType CalcType = Calc->getType();
// Explicit truncation using cast.
if (Context.getIntWidth(CastType) < Context.getIntWidth(CalcType))
return;
// If CalcType and CastType have same size then there is no real danger, but
// there can be a portability problem.
if (Context.getIntWidth(CastType) == Context.getIntWidth(CalcType)) {
const auto *CastBuiltinType =
dyn_cast<BuiltinType>(CastType->getUnqualifiedDesugaredType());
const auto *CalcBuiltinType =
dyn_cast<BuiltinType>(CalcType->getUnqualifiedDesugaredType());
if (CastBuiltinType && CalcBuiltinType &&
!isFirstWider(CastBuiltinType->getKind(), CalcBuiltinType->getKind()))
return;
}
// Don't write a warning if we can easily see that the result is not
// truncated.
if (Context.getIntWidth(CalcType) >= getMaxCalculationWidth(Context, Calc))
return;
diag(Cast->getLocStart(), "either cast from %0 to %1 is ineffective, or "
"there is loss of precision before the conversion")
<< CalcType << CastType;
}
} // namespace misc
} // namespace tidy
} // namespace clang
<|endoftext|>
|
<commit_before>#include <sys/socket.h>
#include <cassert>
#include "server.hh"
#include "../runtime/fiber.hh"
namespace mimosa
{
namespace net
{
Server::Server()
: handler_(0),
fd_(-1),
stop_(false),
accept_loop_(0)
{
}
Server::~Server()
{
stop();
}
bool
Server::listenInet4(uint16_t port, const struct ::in_addr * interface)
{
stop();
fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd_ < 0)
return false;
// enable reuse of the port after the close
static const int enable = 1;
::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
struct sockaddr_in addr;
addr.sin_addr.s_addr = interface ? interface->s_addr : INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = ::htons(port);
if (::bind(fd_, (struct sockaddr *)&addr, sizeof (addr)))
goto failure;
if (::listen(fd_, 10))
goto failure;
try {
this->accept_loop_ = new runtime::Fiber(std::bind(&Server::acceptLoop, Server::Ptr(this)));
} catch (...) {
goto failure;
}
return true;
failure:
::close(fd_);
fd_ = -1;
this->accept_loop_ = 0;
return false;
}
void
Server::acceptLoop(Server::Ptr server)
{
while (!server->stop_)
{
int fd = ::melon_accept(server->fd_, 0, 0, 0);
if (fd < 0)
continue;
try {
runtime::Fiber::start([server, fd]() { (*server->handler_)(fd); });
} catch (...) {
::close(fd);
}
}
}
void
Server::stop()
{
if (fd_ >= 0)
{
assert(accept_loop_);
stop_ = true;
::melon_close(fd_);
accept_loop_->join();
delete accept_loop_;
accept_loop_ = 0;
fd_ = -1;
}
else
assert(!accept_loop_);
}
}
}
<commit_msg>Better Server::close()<commit_after>#include <sys/socket.h>
#include <cassert>
#include "server.hh"
#include "../runtime/fiber.hh"
namespace mimosa
{
namespace net
{
Server::Server()
: handler_(0),
fd_(-1),
stop_(false),
accept_loop_(0)
{
}
Server::~Server()
{
stop();
}
bool
Server::listenInet4(uint16_t port, const struct ::in_addr * interface)
{
stop();
fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd_ < 0)
return false;
// enable reuse of the port after the close
static const int enable = 1;
::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
struct sockaddr_in addr;
addr.sin_addr.s_addr = interface ? interface->s_addr : INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = ::htons(port);
if (::bind(fd_, (struct sockaddr *)&addr, sizeof (addr)))
goto failure;
if (::listen(fd_, 10))
goto failure;
try {
this->accept_loop_ = new runtime::Fiber(std::bind(&Server::acceptLoop, Server::Ptr(this)));
} catch (...) {
goto failure;
}
return true;
failure:
::close(fd_);
fd_ = -1;
this->accept_loop_ = 0;
return false;
}
void
Server::acceptLoop(Server::Ptr server)
{
while (!server->stop_)
{
int fd = ::melon_accept(server->fd_, 0, 0, 0);
if (fd < 0)
continue;
try {
runtime::Fiber::start([server, fd]() { (*server->handler_)(fd); });
} catch (...) {
::close(fd);
}
}
}
void
Server::stop()
{
if (fd_ >= 0)
{
assert(accept_loop_);
stop_ = true;
do {
puts("canceling io...");
::melon_cancelio(fd_);
} while (!accept_loop_->timedJoin(runtime::time() + runtime::milliseconds(1)));
delete accept_loop_;
::melon_close(fd_);
accept_loop_ = 0;
fd_ = -1;
}
else
assert(!accept_loop_);
}
}
}
<|endoftext|>
|
<commit_before>//
// Custom Casts
//
namespace {
$(when measurements $(foreach measurements
$(if active and ( custom_cast or label_map ) then
OUT=[[
template<typename FilterType>
struct ${name}CustomCast
{
template <typename T>
]]
if custom_cast then
OUT=OUT..[[
static ${type} Helper( const T & value ) { return ${custom_cast}; }
]]
else
OUT=OUT..[[
static const ${type} &Helper( const T & value ) { return value; }
]]
end
OUT=OUT..[[
static ${type} CustomCast( const FilterType *f]]
if parameters then
for inum=1,#parameters do
OUT=OUT..', '..parameters[inum].type..' '..parameters[inum].name
end
end
OUT=OUT..[[ )
{
return ${name}CustomCast::Helper(f]]
if label_map then
OUT=OUT..[[->GetOutput()->GetLabelObject(label)->Get${name}()]]
else
OUT=OUT..[[->Get${name}(label)]]
end
OUT=OUT..');'..[[
}
};
]]
end)))
}
<commit_msg>BUG: fix return by reference of temporary for active custom casts<commit_after>//
// Custom Casts
//
namespace {
$(when measurements $(foreach measurements
$(if active and ( custom_cast or label_map ) then
OUT=[[
template<typename FilterType>
struct ${name}CustomCast
{
template <typename T>
]]
if custom_cast then
OUT=OUT..[[
static ${type} Helper( const T & value ) { return ${custom_cast}; }
]]
else
OUT=OUT..[[
static const ${type} Helper( const T & value ) { return value; }
]]
end
OUT=OUT..[[
static ${type} CustomCast( const FilterType *f]]
if parameters then
for inum=1,#parameters do
OUT=OUT..', '..parameters[inum].type..' '..parameters[inum].name
end
end
OUT=OUT..[[ )
{
return ${name}CustomCast::Helper(f]]
if label_map then
OUT=OUT..[[->GetOutput()->GetLabelObject(label)->Get${name}()]]
else
OUT=OUT..[[->Get${name}(label)]]
end
OUT=OUT..');'..[[
}
};
]]
end)))
}
<|endoftext|>
|
<commit_before>#include "rec/util/STL.h"
#include "echomesh/color/FColorList.h"
#include "echomesh/color/RGB.h"
#include "echomesh/component/InstrumentGrid.h"
namespace echomesh {
static const int TOP_TWEAK = 5;
static const int LEFT_TWEAK = 5;
InstrumentGrid::InstrumentGrid()
: isUnclipped_(false),
labelStartsAtZero_(false),
showLabel_(false),
background_(Colours::white),
layout_(32, 32),
size_(12, 12),
padding_(4, 4),
instrumentPadding_(2, 2),
labelPadding_(2, 2) {
setSize(64, 64);
MessageManagerLock l;
layout();
}
InstrumentGrid::~InstrumentGrid() {}
void InstrumentGrid::setLayout(
const Point& lay, const Point& size, const Point& padding,
const Point& instrumentPadding, const Point& labelPadding) {
MessageManagerLock l;
padding_ = padding;
size_ = size;
layout_ = lay;
instrumentPadding_ = instrumentPadding;
labelPadding_ = labelPadding;
layout();
}
void InstrumentGrid::setShape(bool isRect) {
MessageManagerLock l;
for (auto& i: instruments_)
i->setShape(isRect);
}
void InstrumentGrid::layout() {
auto left = padding_.first;
auto top = padding_.second;
auto columns = layout_.first;
auto rows = layout_.second;
auto w = size_.first + instrumentPadding_.first;
auto h = size_.second + instrumentPadding_.second;
auto i = 0;
for (auto y = 0; y < rows and i < instruments_.size(); ++y) {
for (auto x = 0; x < columns and i < instruments_.size(); ++x) {
auto& instr = instruments_[i++];
instr->setLabelPadding(labelPadding_.first, labelPadding_.second);
instr->setBounds(left + x * w, top + y * h, size_.first, size_.second);
instr->setShowLabel(showLabel_);
}
}
auto screenWidth = left + w * columns + padding_.first,
screenHeight = top + h * rows + padding_.second;
setSize(screenWidth, screenHeight);
}
void InstrumentGrid::paint(Graphics& g) {
g.fillAll(background_);
}
void InstrumentGrid::setPaintingIsUnclipped(bool isUnclipped) {
MessageManagerLock l;
if (isUnclipped != isUnclipped_) {
isUnclipped_ = isUnclipped;
for (auto& i: instruments_)
i->setPaintingIsUnclipped(isUnclipped);
}
}
void InstrumentGrid::setLabelStartsAtZero(bool startsAtZero) {
MessageManagerLock l;
if (startsAtZero != labelStartsAtZero_) {
labelStartsAtZero_ = startsAtZero;
auto delta = labelStartsAtZero_ ? 0 : 1;
for (auto i = 0; i < instruments_.size(); ++i)
instruments_[i]->setLabel(String(i + delta));
}
}
void InstrumentGrid::setLightCount(int count) {
MessageManagerLock l;
auto oldCount = instruments_.size();
if (count == oldCount)
return;
cache_.resize(3 * count);
auto delta = labelStartsAtZero_ ? 0 : 1;
instruments_.resize(count);
for (auto i = oldCount; i < count; ++i) {
auto inst = make_unique<InstrumentComponent>();
inst->setPaintingIsUnclipped(isUnclipped_);
inst->setLabelPadding(labelPadding_.first, labelPadding_.second);
inst->setLabel(String(uint32(i + delta)));
addAndMakeVisible(inst.get());
instruments_[i] = std::move(inst);
}
layout();
}
void InstrumentGrid::setBackground(const Colour& c) {
MessageManagerLock l;
background_ = c;
}
void InstrumentGrid::setShowLabel(bool showLabel) {
MessageManagerLock l;
if (showLabel != showLabel_) {
showLabel_ = showLabel;
for (auto& i: instruments_)
i->setShowLabel(showLabel);
}
}
int InstrumentGrid::getLightCount() const {
MessageManagerLock l;
return instruments_.size();
}
void InstrumentGrid::setLights(const color::FColorList& colors) {
MessageManagerLock l;
auto size = jmin(colors.size(), instruments_.size());
for (auto i = 0; i < size; ++i)
instruments_[i]->setColor(colors.at(i).toColour());
auto maxSize = jmax(colors.size(), instruments_.size());
for (auto i = size; i < maxSize; ++i)
instruments_[i]->setColor(Colours::black);
pythonRepaint();
}
void InstrumentGrid::pythonRepaint() {
JUCE_AUTORELEASEPOOL {
repaint();
}
}
} // namespace echomesh
<commit_msg>Set default background for visualizer to black.<commit_after>#include "rec/util/STL.h"
#include "echomesh/color/FColorList.h"
#include "echomesh/color/RGB.h"
#include "echomesh/component/InstrumentGrid.h"
namespace echomesh {
static const int TOP_TWEAK = 5;
static const int LEFT_TWEAK = 5;
InstrumentGrid::InstrumentGrid()
: isUnclipped_(false),
labelStartsAtZero_(false),
showLabel_(false),
background_(Colours::black),
layout_(32, 32),
size_(12, 12),
padding_(4, 4),
instrumentPadding_(2, 2),
labelPadding_(2, 2) {
setSize(64, 64);
MessageManagerLock l;
layout();
}
InstrumentGrid::~InstrumentGrid() {}
void InstrumentGrid::setLayout(
const Point& lay, const Point& size, const Point& padding,
const Point& instrumentPadding, const Point& labelPadding) {
MessageManagerLock l;
padding_ = padding;
size_ = size;
layout_ = lay;
instrumentPadding_ = instrumentPadding;
labelPadding_ = labelPadding;
layout();
}
void InstrumentGrid::setShape(bool isRect) {
MessageManagerLock l;
for (auto& i: instruments_)
i->setShape(isRect);
}
void InstrumentGrid::layout() {
auto left = padding_.first;
auto top = padding_.second;
auto columns = layout_.first;
auto rows = layout_.second;
auto w = size_.first + instrumentPadding_.first;
auto h = size_.second + instrumentPadding_.second;
auto i = 0;
for (auto y = 0; y < rows and i < instruments_.size(); ++y) {
for (auto x = 0; x < columns and i < instruments_.size(); ++x) {
auto& instr = instruments_[i++];
instr->setLabelPadding(labelPadding_.first, labelPadding_.second);
instr->setBounds(left + x * w, top + y * h, size_.first, size_.second);
instr->setShowLabel(showLabel_);
}
}
auto screenWidth = left + w * columns + padding_.first,
screenHeight = top + h * rows + padding_.second;
setSize(screenWidth, screenHeight);
}
void InstrumentGrid::paint(Graphics& g) {
g.fillAll(background_);
}
void InstrumentGrid::setPaintingIsUnclipped(bool isUnclipped) {
MessageManagerLock l;
if (isUnclipped != isUnclipped_) {
isUnclipped_ = isUnclipped;
for (auto& i: instruments_)
i->setPaintingIsUnclipped(isUnclipped);
}
}
void InstrumentGrid::setLabelStartsAtZero(bool startsAtZero) {
MessageManagerLock l;
if (startsAtZero != labelStartsAtZero_) {
labelStartsAtZero_ = startsAtZero;
auto delta = labelStartsAtZero_ ? 0 : 1;
for (auto i = 0; i < instruments_.size(); ++i)
instruments_[i]->setLabel(String(i + delta));
}
}
void InstrumentGrid::setLightCount(int count) {
MessageManagerLock l;
auto oldCount = instruments_.size();
if (count == oldCount)
return;
cache_.resize(3 * count);
auto delta = labelStartsAtZero_ ? 0 : 1;
instruments_.resize(count);
for (auto i = oldCount; i < count; ++i) {
auto inst = make_unique<InstrumentComponent>();
inst->setPaintingIsUnclipped(isUnclipped_);
inst->setLabelPadding(labelPadding_.first, labelPadding_.second);
inst->setLabel(String(uint32(i + delta)));
addAndMakeVisible(inst.get());
instruments_[i] = std::move(inst);
}
layout();
}
void InstrumentGrid::setBackground(const Colour& c) {
MessageManagerLock l;
background_ = c;
}
void InstrumentGrid::setShowLabel(bool showLabel) {
MessageManagerLock l;
if (showLabel != showLabel_) {
showLabel_ = showLabel;
for (auto& i: instruments_)
i->setShowLabel(showLabel);
}
}
int InstrumentGrid::getLightCount() const {
MessageManagerLock l;
return instruments_.size();
}
void InstrumentGrid::setLights(const color::FColorList& colors) {
MessageManagerLock l;
auto size = jmin(colors.size(), instruments_.size());
for (auto i = 0; i < size; ++i)
instruments_[i]->setColor(colors.at(i).toColour());
auto maxSize = jmax(colors.size(), instruments_.size());
for (auto i = size; i < maxSize; ++i)
instruments_[i]->setColor(Colours::black);
pythonRepaint();
}
void InstrumentGrid::pythonRepaint() {
JUCE_AUTORELEASEPOOL {
repaint();
}
}
} // namespace echomesh
<|endoftext|>
|
<commit_before>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <thread>
#include <future>
#include <fibre/protocol.hpp>
#define TCP_RX_BUF_LEN 512
class TCPBytesSender : public StreamSink {
public:
TCPBytesSender(int socket_fd) :
_socket_fd(socket_fd)
{}
int process_bytes(const uint8_t* buffer, size_t length, size_t& processed_bytes) {
int bytes_sent = send(_socket_fd, buffer, length, 0);
processed_bytes = (bytes_sent == -1) ? 0 : bytes_sent;
return (bytes_sent == -1) ? -1 : 0;
}
size_t get_free_space() { return SIZE_MAX; }
private:
int _socket_fd;
};
int serve_client(const Endpoint endpoints[], size_t n_endpoints, int sock_fd) {
uint8_t buf[TCP_RX_BUF_LEN];
// printf("initializing output stack\n");
// initialize output stack for this client
TCPBytesSender tcp_packet_output(sock_fd);
StreamBasedPacketSink packet2stream(tcp_packet_output);
BidirectionalPacketBasedChannel channel(endpoints, n_endpoints, packet2stream);
StreamToPacketSegmenter stream2packet(channel);
// now listen for it
for (;;) {
memset(buf, 0, sizeof(buf));
// returns as soon as there is some data
ssize_t n_received = recv(sock_fd, buf, sizeof(buf), 0);
printf("recvd something: %d\n", n_received);
if (n_received == -1 || n_received == 0) {// -1 indicates error and 0 means that the client gracefully terminated
close(sock_fd);
return n_received;
}
// printf("Received packet from %s:%d\n\n",
// inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
// input processing stack
size_t processed = 0;
stream2packet.process_bytes(buf, n_received, processed);
}
}
// function to check if a worker thread handling a single client is done
template<typename T>
bool future_is_ready(std::future<T>& t){
return t.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
int serve_on_tcp(const Endpoint endpoints[], size_t n_endpoints, unsigned int port) {
struct sockaddr_in si_me, si_other;
int s;
if ((s=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, reinterpret_cast<struct sockaddr *>(&si_me), sizeof(si_me)) == -1)
return -1;
listen(s, 128); // make this socket a passive socket
std::vector<std::future<int>> serv_pool;
for (;;) {
memset(&si_other, 0, sizeof(si_other));
socklen_t silen = sizeof(si_other);
printf("enter blocking accept\n");
int client_portal_fd = accept(s, reinterpret_cast<sockaddr *>(&si_other), &silen); // blocking call
printf("accepted client\n");
serv_pool.push_back(std::async(std::launch::async, serve_client, endpoints, n_endpoints, client_portal_fd));
// do a little clean up on the pool
for (std::vector<std::future<int>>::iterator it = serv_pool.end()-1; it >= serv_pool.begin(); --it) {
if (future_is_ready(*it)) {
printf("erasing thread\n");
// we can erase this thread
serv_pool.erase(it);
}
}
}
close(s);
}
<commit_msg>target comments by @samuelsadok<commit_after>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <thread>
#include <future>
#include <vector>
#include <fibre/protocol.hpp>
#define TCP_RX_BUF_LEN 512
class TCPStreamSink : public StreamSink {
public:
TCPStreamSink(int socket_fd) :
socket_fd_(socket_fd)
{}
int process_bytes(const uint8_t* buffer, size_t length, size_t& processed_bytes) {
int bytes_sent = send(socket_fd_, buffer, length, 0);
processed_bytes = (bytes_sent == -1) ? 0 : bytes_sent;
return (bytes_sent == -1) ? -1 : 0;
}
size_t get_free_space() { return SIZE_MAX; }
private:
int socket_fd_;
};
int serve_client(const Endpoint endpoints[], size_t n_endpoints, int sock_fd) {
uint8_t buf[TCP_RX_BUF_LEN];
// initialize output stack for this client
TCPStreamSink tcp_packet_output(sock_fd);
StreamBasedPacketSink packet2stream(tcp_packet_output);
BidirectionalPacketBasedChannel channel(endpoints, n_endpoints, packet2stream);
StreamToPacketSegmenter stream2packet(channel);
// now listen for it
for (;;) {
memset(buf, 0, sizeof(buf));
// returns as soon as there is some data
ssize_t n_received = recv(sock_fd, buf, sizeof(buf), 0);
// -1 indicates error and 0 means that the client gracefully terminated
if (n_received == -1 || n_received == 0) {
close(sock_fd);
return n_received;
}
// input processing stack
size_t processed = 0;
stream2packet.process_bytes(buf, n_received, processed);
}
}
// function to check if a worker thread handling a single client is done
template<typename T>
bool future_is_ready(std::future<T>& t){
return t.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
int serve_on_tcp(const Endpoint endpoints[], size_t n_endpoints, unsigned int port) {
struct sockaddr_in6 si_me, si_other;
int s;
if ((s=socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP)) == -1) {
return -1;
}
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin6_family = AF_INET6;
si_me.sin6_port = htons(port);
si_me.sin6_flowinfo = 0;
si_me.sin6_addr = in6addr_any;
if (bind(s, reinterpret_cast<struct sockaddr *>(&si_me), sizeof(si_me)) == -1) {
return -1;
}
listen(s, 128); // make this socket a passive socket
std::vector<std::future<int>> serv_pool;
for (;;) {
memset(&si_other, 0, sizeof(si_other));
socklen_t silen = sizeof(si_other);
// TODO: Add a limit on accepting connections
int client_portal_fd = accept(s, reinterpret_cast<sockaddr *>(&si_other), &silen); // blocking call
serv_pool.push_back(std::async(std::launch::async, serve_client, endpoints, n_endpoints, client_portal_fd));
// do a little clean up on the pool
for (std::vector<std::future<int>>::iterator it = serv_pool.end()-1; it >= serv_pool.begin(); --it) {
if (future_is_ready(*it)) {
// we can erase this thread
serv_pool.erase(it);
}
}
}
close(s);
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPTION_HPP
#define CPPA_OPTION_HPP
#include <new>
#include <utility>
#include "cppa/none.hpp"
#include "cppa/unit.hpp"
#include "cppa/config.hpp"
namespace cppa {
/**
* @brief Represents an optional value of @p T.
*/
template<typename T>
class optional {
public:
/**
* @brief Typdef for @p T.
*/
typedef T type;
/* *
* @brief Default constructor.
* @post <tt>valid() == false</tt>
*/
//optional() : m_valid(false) { }
/**
* @post <tt>valid() == false</tt>
*/
optional(const none_t& = none) : m_valid(false) { }
/**
* @brief Creates an @p option from @p value.
* @post <tt>valid() == true</tt>
*/
optional(T value) : m_valid(false) { cr(std::move(value)); }
optional(const optional& other) : m_valid(false) {
if (other.m_valid) cr(other.m_value);
}
optional(optional&& other) : m_valid(false) {
if (other.m_valid) cr(std::move(other.m_value));
}
~optional() { destroy(); }
optional& operator=(const optional& other) {
if (m_valid) {
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid) {
cr(other.m_value);
}
return *this;
}
optional& operator=(optional&& other) {
if (m_valid) {
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid) {
cr(std::move(other.m_value));
}
return *this;
}
/**
* @brief Returns @p true if this @p option has a valid value;
* otherwise @p false.
*/
inline bool valid() const { return m_valid; }
/**
* @brief Returns <tt>!valid()</tt>.
*/
inline bool empty() const { return !m_valid; }
/**
* @copydoc valid()
*/
inline explicit operator bool() const { return valid(); }
/**
* @brief Returns <tt>!valid()</tt>.
*/
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
/**
* @brief Returns the value.
*/
inline T& operator*() {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline const T& operator*() const {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline T& get() {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline const T& get() const {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value. The value is set to @p default_value
* if <tt>valid() == false</tt>.
* @post <tt>valid() == true</tt>
*/
inline const T& get_or_else(const T& default_value) const {
if (valid()) return get();
return default_value;
}
private:
bool m_valid;
union { T m_value; };
void destroy() {
if (m_valid) {
m_value.~T();
m_valid = false;
}
}
template<typename V>
void cr(V&& value) {
CPPA_REQUIRE(!valid());
m_valid = true;
new (&m_value) T (std::forward<V>(value));
}
};
template<typename T>
class optional<T&> {
public:
typedef T type;
optional() : m_value(nullptr) { }
optional(T& value) : m_value(&value) { }
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
inline bool valid() const { return m_value != nullptr; }
inline bool empty() const { return !valid(); }
inline explicit operator bool() const { return valid(); }
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
inline T& operator*() {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& operator*() const {
CPPA_REQUIRE(valid());
return *m_value;
}
inline T& get() {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& get() const {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& get_or_else(const T& default_value) const {
if (valid()) return get();
return default_value;
}
private:
T* m_value;
};
template<>
class optional<void> {
public:
optional(const unit_t&) : m_valid(true) { }
optional(const none_t&) : m_valid(false) { }
inline bool valid() const { return m_valid; }
inline bool empty() const { return !m_valid; }
inline explicit operator bool() const { return valid(); }
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
inline const unit_t& operator*() const { return unit; }
private:
bool m_valid;
};
/** @relates option */
template<typename T>
struct is_optional { static constexpr bool value = false; };
template<typename T>
struct is_optional<optional<T>> { static constexpr bool value = true; };
/** @relates option */
template<typename T, typename U>
bool operator==(const optional<T>& lhs, const optional<U>& rhs) {
if ((lhs) && (rhs)) return *lhs == *rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(const optional<T>& lhs, const U& rhs) {
if (lhs) return *lhs == rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(const T& lhs, const optional<U>& rhs) {
return rhs == lhs;
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const optional<T>& lhs, const optional<U>& rhs) {
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const optional<T>& lhs, const U& rhs) {
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const T& lhs, const optional<U>& rhs) {
return !(lhs == rhs);
}
} // namespace cppa
#endif // CPPA_OPTION_HPP
<commit_msg>Provide operator-> for optional<T>.<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPTION_HPP
#define CPPA_OPTION_HPP
#include <new>
#include <utility>
#include "cppa/none.hpp"
#include "cppa/unit.hpp"
#include "cppa/config.hpp"
namespace cppa {
/**
* @brief Represents an optional value of @p T.
*/
template<typename T>
class optional {
public:
/**
* @brief Typdef for @p T.
*/
typedef T type;
/* *
* @brief Default constructor.
* @post <tt>valid() == false</tt>
*/
//optional() : m_valid(false) { }
/**
* @post <tt>valid() == false</tt>
*/
optional(const none_t& = none) : m_valid(false) { }
/**
* @brief Creates an @p option from @p value.
* @post <tt>valid() == true</tt>
*/
optional(T value) : m_valid(false) { cr(std::move(value)); }
optional(const optional& other) : m_valid(false) {
if (other.m_valid) cr(other.m_value);
}
optional(optional&& other) : m_valid(false) {
if (other.m_valid) cr(std::move(other.m_value));
}
~optional() { destroy(); }
optional& operator=(const optional& other) {
if (m_valid) {
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid) {
cr(other.m_value);
}
return *this;
}
optional& operator=(optional&& other) {
if (m_valid) {
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid) {
cr(std::move(other.m_value));
}
return *this;
}
/**
* @brief Returns @p true if this @p option has a valid value;
* otherwise @p false.
*/
inline bool valid() const { return m_valid; }
/**
* @brief Returns <tt>!valid()</tt>.
*/
inline bool empty() const { return !m_valid; }
/**
* @copydoc valid()
*/
inline explicit operator bool() const { return valid(); }
/**
* @brief Returns <tt>!valid()</tt>.
*/
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
/**
* @brief Returns the value.
*/
inline T& operator*() {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline const T& operator*() const {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline const T* operator->() const {
CPPA_REQUIRE(valid());
return &m_value;
}
/**
* @brief Returns the value.
*/
inline T* operator->() {
CPPA_REQUIRE(valid());
return &m_value;
}
/**
* @brief Returns the value.
*/
inline T& get() {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value.
*/
inline const T& get() const {
CPPA_REQUIRE(valid());
return m_value;
}
/**
* @brief Returns the value. The value is set to @p default_value
* if <tt>valid() == false</tt>.
* @post <tt>valid() == true</tt>
*/
inline const T& get_or_else(const T& default_value) const {
if (valid()) return get();
return default_value;
}
private:
bool m_valid;
union { T m_value; };
void destroy() {
if (m_valid) {
m_value.~T();
m_valid = false;
}
}
template<typename V>
void cr(V&& value) {
CPPA_REQUIRE(!valid());
m_valid = true;
new (&m_value) T (std::forward<V>(value));
}
};
template<typename T>
class optional<T&> {
public:
typedef T type;
optional() : m_value(nullptr) { }
optional(T& value) : m_value(&value) { }
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
inline bool valid() const { return m_value != nullptr; }
inline bool empty() const { return !valid(); }
inline explicit operator bool() const { return valid(); }
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
inline T& operator*() {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& operator*() const {
CPPA_REQUIRE(valid());
return *m_value;
}
inline T& get() {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& get() const {
CPPA_REQUIRE(valid());
return *m_value;
}
inline const T& get_or_else(const T& default_value) const {
if (valid()) return get();
return default_value;
}
private:
T* m_value;
};
template<>
class optional<void> {
public:
optional(const unit_t&) : m_valid(true) { }
optional(const none_t&) : m_valid(false) { }
inline bool valid() const { return m_valid; }
inline bool empty() const { return !m_valid; }
inline explicit operator bool() const { return valid(); }
inline bool operator!() const { return empty(); }
inline bool operator==(const none_t&) { return empty(); }
inline const unit_t& operator*() const { return unit; }
private:
bool m_valid;
};
/** @relates option */
template<typename T>
struct is_optional { static constexpr bool value = false; };
template<typename T>
struct is_optional<optional<T>> { static constexpr bool value = true; };
/** @relates option */
template<typename T, typename U>
bool operator==(const optional<T>& lhs, const optional<U>& rhs) {
if ((lhs) && (rhs)) return *lhs == *rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(const optional<T>& lhs, const U& rhs) {
if (lhs) return *lhs == rhs;
return false;
}
/** @relates option */
template<typename T, typename U>
bool operator==(const T& lhs, const optional<U>& rhs) {
return rhs == lhs;
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const optional<T>& lhs, const optional<U>& rhs) {
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const optional<T>& lhs, const U& rhs) {
return !(lhs == rhs);
}
/** @relates option */
template<typename T, typename U>
bool operator!=(const T& lhs, const optional<U>& rhs) {
return !(lhs == rhs);
}
} // namespace cppa
#endif // CPPA_OPTION_HPP
<|endoftext|>
|
<commit_before>#include <ContentForgeTool.h>
#include <Utils.h>
#include <fbxsdk.h>
//#include <CLI11.hpp>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/scenes
class CFBXTool : public CContentForgeTool
{
protected:
FbxManager* pFbxManager = nullptr;
public:
CFBXTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual bool SupportsMultithreading() const override
{
// FBX SDK as of 2020.0 is not guaranteed to be multithreaded
return false;
}
virtual int Init() override
{
pFbxManager = FbxManager::Create();
if (!pFbxManager) return 1;
FbxIOSettings* pIOSettings = FbxIOSettings::Create(pFbxManager, IOSROOT);
pFbxManager->SetIOSettings(pIOSettings);
return 0;
}
virtual int Term() override
{
pFbxManager->Destroy();
pFbxManager = nullptr;
return 0;
}
//virtual void ProcessCommandLine(CLI::App& CLIApp) override
//{
// CContentForgeTool::ProcessCommandLine(CLIApp);
//}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
// TODO: check whether the metafile can be processed by this tool
const std::string MeshOutput = GetParam<std::string>(Task.Params, "MeshOutput", std::string{});
const std::string TaskID(Task.TaskID.CStr());
auto DestPath = fs::path(MeshOutput) / (TaskID + ".msh");
if (!_RootDir.empty() && DestPath.is_relative())
DestPath = fs::path(_RootDir) / DestPath;
// Import FBX scene from the source file
FbxImporter* pImporter = FbxImporter::Create(pFbxManager, "");
const auto SrcPath = Task.SrcFilePath.string();
// Use the first argument as the filename for the importer.
if (!pImporter->Initialize(SrcPath.c_str(), -1, pFbxManager->GetIOSettings()))
{
Task.Log.LogError("Failed to create FbxImporter for " + SrcPath + ": " + pImporter->GetStatus().GetErrorString());
return false;
}
if (pImporter->IsFBX())
{
int Major, Minor, Revision;
pImporter->GetFileVersion(Major, Minor, Revision);
Task.Log.LogDebug("Source format: FBX v" + std::to_string(Major) + '.' + std::to_string(Minor) + '.' + std::to_string(Revision));
}
FbxScene* pScene = FbxScene::Create(pFbxManager, "SourceScene");
if (!pImporter->Import(pScene))
{
Task.Log.LogError("Failed to import " + SrcPath + ": " + pImporter->GetStatus().GetErrorString());
pImporter->Destroy();
return false;
}
pImporter->Destroy();
//!!!DBG TMP!
if (FbxNode* pRootNode = pScene->GetRootNode())
{
for (int i = 0; i < pRootNode->GetChildCount(); ++i)
PrintNode(pRootNode->GetChild(i), 0);
}
return true;
}
//======================
std::string GetAttributeTypeName(FbxNodeAttribute::EType type)
{
switch(type)
{
case FbxNodeAttribute::eUnknown: return "unidentified";
case FbxNodeAttribute::eNull: return "null";
case FbxNodeAttribute::eMarker: return "marker";
case FbxNodeAttribute::eSkeleton: return "skeleton";
case FbxNodeAttribute::eMesh: return "mesh";
case FbxNodeAttribute::eNurbs: return "nurbs";
case FbxNodeAttribute::ePatch: return "patch";
case FbxNodeAttribute::eCamera: return "camera";
case FbxNodeAttribute::eCameraStereo: return "stereo";
case FbxNodeAttribute::eCameraSwitcher: return "camera switcher";
case FbxNodeAttribute::eLight: return "light";
case FbxNodeAttribute::eOpticalReference: return "optical reference";
case FbxNodeAttribute::eOpticalMarker: return "marker";
case FbxNodeAttribute::eNurbsCurve: return "nurbs curve";
case FbxNodeAttribute::eTrimNurbsSurface: return "trim nurbs surface";
case FbxNodeAttribute::eBoundary: return "boundary";
case FbxNodeAttribute::eNurbsSurface: return "nurbs surface";
case FbxNodeAttribute::eShape: return "shape";
case FbxNodeAttribute::eLODGroup: return "lodgroup";
case FbxNodeAttribute::eSubDiv: return "subdiv";
default: return "unknown";
}
}
void PrintAttribute(FbxNodeAttribute* pAttribute, int depth)
{
if (!pAttribute) return;
auto typeName = GetAttributeTypeName(pAttribute->GetAttributeType());
for(int i = 0; i < depth; i++)
printf(" ");
printf("<attribute type='%s' name='%s'/>\n", typeName.c_str(), pAttribute->GetName());
}
void PrintNode(FbxNode* pNode, int depth)
{
for(int i = 0; i < depth; i++)
printf(" ");
const char* nodeName = pNode->GetName();
FbxDouble3 translation = pNode->LclTranslation.Get();
FbxDouble3 rotation = pNode->LclRotation.Get();
FbxDouble3 scaling = pNode->LclScaling.Get();
// Print the contents of the node.
printf("<node name='%s' translation='(%f, %f, %f)' rotation='(%f, %f, %f)' scaling='(%f, %f, %f)'>\n",
nodeName,
translation[0], translation[1], translation[2],
rotation[0], rotation[1], rotation[2],
scaling[0], scaling[1], scaling[2]
);
// Print the node's attributes.
for(int i = 0; i < pNode->GetNodeAttributeCount(); i++)
PrintAttribute(pNode->GetNodeAttributeByIndex(i), depth + 1);
// Recursively print the children.
for(int j = 0; j < pNode->GetChildCount(); j++)
PrintNode(pNode->GetChild(j), depth + 1);
for(int i = 0; i < depth; i++)
printf(" ");
printf("</node>\n");
}
//=======================
};
int main(int argc, const char** argv)
{
CFBXTool Tool("cf-fbx", "FBX to DeusExMachina resource converter", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
<commit_msg>cf-fbx skeleton<commit_after>#include <ContentForgeTool.h>
#include <Utils.h>
#include <fbxsdk.h>
//#include <CLI11.hpp>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/scenes
static void ConvertTransformsToSRTRecursive(FbxNode* pNode)
{
FbxVector4 lZero(0, 0, 0);
// Activate pivot converting
pNode->SetPivotState(FbxNode::eSourcePivot, FbxNode::ePivotActive);
pNode->SetPivotState(FbxNode::eDestinationPivot, FbxNode::ePivotActive);
// We want to set all these to 0 and bake them into the transforms.
pNode->SetPostRotation(FbxNode::eDestinationPivot, lZero);
pNode->SetPreRotation(FbxNode::eDestinationPivot, lZero);
pNode->SetRotationOffset(FbxNode::eDestinationPivot, lZero);
pNode->SetScalingOffset(FbxNode::eDestinationPivot, lZero);
pNode->SetRotationPivot(FbxNode::eDestinationPivot, lZero);
pNode->SetScalingPivot(FbxNode::eDestinationPivot, lZero);
// Bake rotation order
pNode->SetRotationOrder(FbxNode::eDestinationPivot, FbxEuler::eOrderXYZ);
// Bake geometric transforms to avoid creating DEM nodes for them
pNode->SetGeometricTranslation(FbxNode::eDestinationPivot, lZero);
pNode->SetGeometricRotation(FbxNode::eDestinationPivot, lZero);
pNode->SetGeometricScaling(FbxNode::eDestinationPivot, lZero);
// DEM is capable of slerp
pNode->SetQuaternionInterpolation(FbxNode::eDestinationPivot, EFbxQuatInterpMode::eQuatInterpSlerp);
for (int i = 0; i < pNode->GetChildCount(); ++i)
ConvertTransformsToSRTRecursive(pNode->GetChild(i));
}
class CFBXTool : public CContentForgeTool
{
protected:
struct CContext
{
CThreadSafeLog& Log;
};
FbxManager* pFBXManager = nullptr;
public:
CFBXTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual bool SupportsMultithreading() const override
{
// FBX SDK as of 2020.0 is not guaranteed to be multithreaded
return false;
}
virtual int Init() override
{
pFBXManager = FbxManager::Create();
if (!pFBXManager) return 1;
FbxIOSettings* pIOSettings = FbxIOSettings::Create(pFBXManager, IOSROOT);
pFBXManager->SetIOSettings(pIOSettings);
return 0;
}
virtual int Term() override
{
pFBXManager->Destroy();
pFBXManager = nullptr;
return 0;
}
//virtual void ProcessCommandLine(CLI::App& CLIApp) override
//{
// CContentForgeTool::ProcessCommandLine(CLIApp);
//}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
// TODO: check whether the metafile can be processed by this tool
const std::string MeshOutput = GetParam<std::string>(Task.Params, "MeshOutput", std::string{});
const std::string TaskID(Task.TaskID.CStr());
auto DestPath = fs::path(MeshOutput) / (TaskID + ".msh");
if (!_RootDir.empty() && DestPath.is_relative())
DestPath = fs::path(_RootDir) / DestPath;
const double animSamplingRate = 30.0;
// Import FBX scene from the source file
FbxImporter* pImporter = FbxImporter::Create(pFBXManager, "");
const auto SrcPath = Task.SrcFilePath.string();
// Use the first argument as the filename for the importer.
if (!pImporter->Initialize(SrcPath.c_str(), -1, pFBXManager->GetIOSettings()))
{
Task.Log.LogError("Failed to create FbxImporter for " + SrcPath + ": " + pImporter->GetStatus().GetErrorString());
return false;
}
if (pImporter->IsFBX())
{
int Major, Minor, Revision;
pImporter->GetFileVersion(Major, Minor, Revision);
Task.Log.LogDebug("Source format: FBX v" + std::to_string(Major) + '.' + std::to_string(Minor) + '.' + std::to_string(Revision));
}
FbxScene* pScene = FbxScene::Create(pFBXManager, "SourceScene");
if (!pImporter->Import(pScene))
{
Task.Log.LogError("Failed to import " + SrcPath + ": " + pImporter->GetStatus().GetErrorString());
pImporter->Destroy();
return false;
}
pImporter->Destroy();
// Preprocess scene transforms and geometry to a more suitable format
// TODO: save results back to FBX?
ConvertTransformsToSRTRecursive(pScene->GetRootNode());
pScene->GetRootNode()->ConvertPivotAnimationRecursive(nullptr, FbxNode::eDestinationPivot, animSamplingRate);
{
FbxGeometryConverter GeometryConverter(pFBXManager);
if (!GeometryConverter.Triangulate(pScene, true))
Task.Log.LogWarning("Couldn't triangulate some geometry");
GeometryConverter.RemoveBadPolygonsFromMeshes(pScene);
if (!GeometryConverter.SplitMeshesPerMaterial(pScene, true))
Task.Log.LogWarning("Couldn't split some meshes per material");
}
// Export node hierarchy to DEM format
CContext Ctx{ Task.Log };
return ExportNode(pScene->GetRootNode(), Ctx);
}
bool ExportNode(FbxNode* pNode, CContext& Ctx)
{
if (!pNode)
{
Ctx.Log.LogWarning("Empty FBX node encountered");
return true;
}
// Process node info
const char* pName = pNode->GetName();
FbxDouble3 Translation = pNode->LclTranslation.Get();
FbxDouble3 Scaling = pNode->LclScaling.Get();
FbxQuaternion Rotation;
Rotation.ComposeSphericalXYZ(pNode->LclRotation.Get());
// Process attributes
for (int i = 0; i < pNode->GetNodeAttributeCount(); ++i)
{
auto pAttribute = pNode->GetNodeAttributeByIndex(i);
switch (pAttribute->GetAttributeType())
{
case FbxNodeAttribute::eMesh:
{
ExportModel(static_cast<FbxMesh*>(pAttribute), Ctx);
break;
}
case FbxNodeAttribute::eLight:
{
ExportLight(static_cast<FbxLight*>(pAttribute), Ctx);
break;
}
case FbxNodeAttribute::eCamera:
{
ExportCamera(static_cast<FbxCamera*>(pAttribute), Ctx);
break;
}
case FbxNodeAttribute::eLODGroup:
{
ExportLODGroup(static_cast<FbxLODGroup*>(pAttribute), Ctx);
break;
}
/*
eSkeleton,
eShape,
eCachedEffect,
eLine
*/
default:
{
Ctx.Log.LogInfo("Skipped unsupported attribute of type " + std::to_string(pAttribute->GetAttributeType()));
break;
}
}
}
// Process children
for (int i = 0; i < pNode->GetChildCount(); ++i)
if (!ExportNode(pNode->GetChild(i), Ctx)) return false;
return true;
}
void ExportModel(FbxMesh* pMesh, CContext& Ctx)
{
// mesh
// material
// skin
}
void ExportLight(FbxLight* pLight, CContext& Ctx)
{
}
void ExportCamera(FbxCamera* pCamera, CContext& Ctx)
{
}
void ExportLODGroup(FbxLODGroup* pLODGroup, CContext& Ctx)
{
}
};
int main(int argc, const char** argv)
{
CFBXTool Tool("cf-fbx", "FBX to DeusExMachina resource converter", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
<|endoftext|>
|
<commit_before>#include "HelloWorld2.h"
#include "NFComm\NFCore\NFCObject.h"
bool HelloWorld2::Init()
{
//ʼ
std::cout << "Hello, world2, Init" << std::endl;
return true;
}
int HelloWorld2::OnPropertyCallBackEvent( const NFIDENTID& self, const std::string& strProperty, const NFIValueList& oldVarList, const NFIValueList& newVarList, const NFIValueList& argVarList )
{
//Իص¼ֻҪֵб仯ͻᱻص
std::cout << "OnPropertyCallBackEvent Property: " << strProperty << " OldValue: " << oldVarList.IntVal(0) << " NewValue: " << newVarList.IntVal(0) << std::endl;
return 0;
}
bool HelloWorld2::AfterInit()
{
//ʼ
std::cout << "Hello, world2, AfterInit" << std::endl;
NFIObject* pObject = new NFCObject(1);
pObject->GetPropertyManager()->AddProperty(pObject->Self(), "Hello", VTYPE_STRING, true, true, true, 0, "");
pObject->GetPropertyManager()->AddProperty(pObject->Self(), "World", VTYPE_INT, true, true, true, 0, "");
pObject->SetPropertyInt("World", 1111);
const int nProperty1 = pObject->QueryPropertyInt("World");
std::cout << "Property World:" << nProperty1 << std::endl;
//¼
pObject->AddPropertyCallBack("World", this, &HelloWorld2::OnPropertyCallBackEvent);
pObject->SetPropertyInt("World", 2222);
const int nProperty2 = pObject->QueryPropertyInt("World");
std::cout << "Property World:" << nProperty2 << std::endl;
return true;
}
bool HelloWorld2::Execute( const float fLasFrametime, const float fStartedTime )
{
//ÿִ֡
//std::cout << "Hello, world2, Execute" << std::endl;
return true;
}
bool HelloWorld2::BeforeShut()
{
//ʼ֮ǰ
std::cout << "Hello, world2, BeforeShut" << std::endl;
return true;
}
bool HelloWorld2::Shut()
{
//ʼ
std::cout << "Hello, world2, Shut" << std::endl;
return true;
}
<commit_msg>fix tutorial2 bug<commit_after>#include "HelloWorld2.h"
#include "NFComm\NFCore\NFCObject.h"
bool HelloWorld2::Init()
{
//ʼ
std::cout << "Hello, world2, Init" << std::endl;
return true;
}
int HelloWorld2::OnPropertyCallBackEvent( const NFIDENTID& self, const std::string& strProperty, const NFIValueList& oldVarList, const NFIValueList& newVarList, const NFIValueList& argVarList )
{
//Իص¼ֻҪֵб仯ͻᱻص
std::cout << "OnPropertyCallBackEvent Property: " << strProperty << " OldValue: " << oldVarList.IntVal(0) << " NewValue: " << newVarList.IntVal(0) << std::endl;
return 0;
}
bool HelloWorld2::AfterInit()
{
//ʼ
std::cout << "Hello, world2, AfterInit" << std::endl;
NFIObject* pObject = new NFCObject(1, pPluginManager);
pObject->GetPropertyManager()->AddProperty(pObject->Self(), "Hello", VTYPE_STRING, true, true, true, 0, "");
pObject->GetPropertyManager()->AddProperty(pObject->Self(), "World", VTYPE_INT, true, true, true, 0, "");
pObject->SetPropertyInt("World", 1111);
const int nProperty1 = pObject->QueryPropertyInt("World");
std::cout << "Property World:" << nProperty1 << std::endl;
//¼
pObject->AddPropertyCallBack("World", this, &HelloWorld2::OnPropertyCallBackEvent);
pObject->SetPropertyInt("World", 2222);
const int nProperty2 = pObject->QueryPropertyInt("World");
std::cout << "Property World:" << nProperty2 << std::endl;
return true;
}
bool HelloWorld2::Execute( const float fLasFrametime, const float fStartedTime )
{
//ÿִ֡
//std::cout << "Hello, world2, Execute" << std::endl;
return true;
}
bool HelloWorld2::BeforeShut()
{
//ʼ֮ǰ
std::cout << "Hello, world2, BeforeShut" << std::endl;
return true;
}
bool HelloWorld2::Shut()
{
//ʼ
std::cout << "Hello, world2, Shut" << std::endl;
return true;
}
<|endoftext|>
|
<commit_before>/* -*-C-*-
###############################################################################
#
# File: list.c
# Description: List processing procedures.
# Author: Mark Seaman, Software Productivity
# Created: Thu Jul 23 13:24:09 1987
# Modified: Thu Dec 22 10:59:52 1988 (Mark Seaman) marks@hpgrlt
# Language: C
# Package: N/A
# Status: Reusable Software Component
#
# (c) Copyright 1987, Hewlett-Packard Company.
** 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.
#
################################################################################
* Revision 1.13 90/03/06 15:37:54 15:37:54 marks (Mark Seaman)
* Look for correct file of <malloc.h> or <stdlib.h>
*
* Revision 1.12 90/02/26 17:37:36 17:37:36 marks (Mark Seaman)
* Added pop_off and join_on
*
This file contains a set of general purpose list manipulation routines.
These routines can be used in a wide variety of ways to provide several
different popular data structures. A new list can be created by declaring
a variable of type 'LIST', and can be initialized with the value 'NIL_LIST'.
All of these routines check for the NIL_LIST condition before dereferencing
pointers. NOTE: There is a users' manual available in printed form from
Mark Seaman at (303) 350-4492 at Greeley Hard Copy.
To implement a STACK use:
push to add to the Stack l = push (l, (LIST) "jim");
pop to remove items from the Stack l = pop (l);
first_node to access the head name = (char *) first_node (l);
To implement a QUEUE use:
push_last to add to the Queue l = push_last (l, (LIST) "jim");
pop remove items from the Queue l = pop (l);
first_node to access the head name = (char *) first_node (l);
To implement LISP like functions use:
first_node CAR x = (int) first_node (l);
rest CDR l = list_rest (l);
push CONS l = push (l, (LIST) this);
last LAST x = last (l);
concat APPEND l = concat (r, s);
count LENGTH x = count (l);
search MEMBER if (search (l, x, NULL))
To implement SETS use:
adjoin l = adjoin (l, x);
set_union l = set_union (r, s);
intersection l = intersection (r, s);
set_difference l = set_difference (r, s);
delete l = delete (s, x, NULL);
search if (search (l, x, NULL))
To Implement Associated LISTS use:
lpush l = lpush (l, p);
assoc s = assoc (l, x);
adelete l = adelete (l, x);
The following rules of closure exist for the functions provided.
a = first_node (push (a, b))
b = list_rest (push (a, b))
a = push (pop (a), a)) For all a <> NIL_LIST
a = reverse (reverse (a))
******************************************************************************/
#include "oldlist.h"
#include "structures.h"
#include <stdio.h>
#if MAC_OR_DOS
#include <stdlib.h>
#else
#include "freelist.h"
#endif
/*----------------------------------------------------------------------
M a c r o s
----------------------------------------------------------------------*/
#define add_on(l,x) l = push (l,first_node (x))
#define next_one(l) l = list_rest (l)
/*----------------------------------------------------------------------
F u n c t i o n s
----------------------------------------------------------------------*/
/**********************************************************************
* c o u n t
*
* Recursively count the elements in a list. Return the count.
**********************************************************************/
int count(LIST var_list) {
int temp = 0;
iterate (var_list) temp += 1;
return (temp);
}
/**********************************************************************
* d e l e t e d
*
* Delete all the elements out of the current list that match the key.
* This operation destroys the original list. The caller will supply a
* routine that will compare each node to the
* key, and return a non-zero value when they match. If the value
* NULL is supplied for is_equal, the is_key routine will be used.
**********************************************************************/
LIST delete_d(LIST list, void *key, int_compare is_equal) {
LIST result = NIL_LIST;
LIST last_one = NIL_LIST;
if (is_equal == NULL)
is_equal = is_same;
while (list != NIL_LIST) {
if (!(*is_equal) (first_node (list), key)) {
if (last_one == NIL_LIST) {
last_one = list;
list = list_rest (list);
result = last_one;
set_rest(last_one, NIL_LIST);
}
else {
set_rest(last_one, list);
last_one = list;
list = list_rest (list);
set_rest(last_one, NIL_LIST);
}
}
else {
list = pop (list);
}
}
return (result);
}
LIST delete_d(LIST list, void *key,
TessResultCallback2<int, void*, void*>* is_equal) {
LIST result = NIL_LIST;
LIST last_one = NIL_LIST;
while (list != NIL_LIST) {
if (!(*is_equal).Run (first_node (list), key)) {
if (last_one == NIL_LIST) {
last_one = list;
list = list_rest (list);
result = last_one;
set_rest(last_one, NIL_LIST);
}
else {
set_rest(last_one, list);
last_one = list;
list = list_rest (list);
set_rest(last_one, NIL_LIST);
}
}
else {
list = pop (list);
}
}
return (result);
}
/**********************************************************************
* d e s t r o y
*
* Return the space taken by a list to the heap.
**********************************************************************/
LIST destroy(LIST list) {
LIST next;
while (list != NIL_LIST) {
next = list_rest (list);
free_cell(list);
list = next;
}
return (NIL_LIST);
}
/**********************************************************************
* d e s t r o y n o d e s
*
* Return the space taken by the LISTs of a list to the heap.
**********************************************************************/
void destroy_nodes(LIST list, void_dest destructor) {
if (destructor == NULL)
destructor = memfree;
while (list != NIL_LIST) {
if (first_node(list) != NULL) (*destructor)(first_node(list));
list = pop(list);
}
}
/**********************************************************************
* i n s e r t
*
* Create a list element and rearange the pointers so that the first
* element in the list is the second aurgment.
**********************************************************************/
void insert(LIST list, void *node) {
LIST element;
if (list != NIL_LIST) {
element = push (NIL_LIST, node);
set_rest (element, list_rest (list));
set_rest(list, element);
node = first_node (list);
list->node = first_node (list_rest (list));
list->next->node = (LIST) node;
}
}
/**********************************************************************
* i s s a m e n o d e
*
* Compare the list node with the key value return TRUE (non-zero)
* if they are equivalent strings. (Return FALSE if not)
**********************************************************************/
int is_same_node(void *item1, void *item2) {
return (item1 == item2);
}
/**********************************************************************
* i s s a m e
*
* Compare the list node with the key value return TRUE (non-zero)
* if they are equivalent strings. (Return FALSE if not)
**********************************************************************/
int is_same(void *item1, void *item2) {
return (!strcmp ((char *) item1, (char *) item2));
}
/**********************************************************************
* j o i n
*
* Join the two lists together. This function is similar to concat
* except that concat creates a new list. This function returns the
* first list updated.
**********************************************************************/
LIST join(LIST list1, LIST list2) {
if (list1 == NIL_LIST)
return (list2);
set_rest (last (list1), list2);
return (list1);
}
/**********************************************************************
* l a s t
*
* Return the last list item (this is list type).
**********************************************************************/
LIST last(LIST var_list) {
while (list_rest (var_list) != NIL_LIST)
var_list = list_rest (var_list);
return (var_list);
}
/**********************************************************************
* n t h c e l l
*
* Return nth list cell in the list.
**********************************************************************/
void *nth_cell(LIST var_list, int item_num) {
int x = 0;
iterate(var_list) {
if (x++ == item_num)
return (var_list);
}
return (var_list);
}
/**********************************************************************
* p o p
*
* Return the list with the first element removed. Destroy the space
* that it occupied in the list.
**********************************************************************/
LIST pop(LIST list) {
LIST temp;
temp = list_rest (list);
if (list != NIL_LIST) {
free_cell(list);
}
return (temp);
}
/**********************************************************************
* p u s h
*
* Create a list element. Push the second parameter (the node) onto
* the first parameter (the list). Return the new list to the caller.
**********************************************************************/
LIST push(LIST list, void *element) {
LIST t;
t = new_cell ();
t->node = (LIST) element;
set_rest(t, list);
return (t);
}
/**********************************************************************
* p u s h l a s t
*
* Create a list element. Add the element onto the end of the list.
**********************************************************************/
LIST push_last(LIST list, void *item) {
LIST t;
if (list != NIL_LIST) {
t = last (list);
t->next = push (NIL_LIST, item);
return (list);
}
else
return (push (NIL_LIST, item));
}
/**********************************************************************
* r e v e r s e
*
* Create a new list with the elements reversed. The old list is not
* destroyed.
**********************************************************************/
LIST reverse(LIST list) {
LIST newlist = NIL_LIST;
iterate (list) copy_first (list, newlist);
return (newlist);
}
/**********************************************************************
* r e v e r s e d
*
* Create a new list with the elements reversed. The old list is
* destroyed.
**********************************************************************/
LIST reverse_d(LIST list) {
LIST result = reverse (list);
destroy(list);
return (result);
}
/**********************************************************************
* s a d j o i n
*
* Adjoin an element to an assorted list. The original list is
* modified. Returns the modified list.
**********************************************************************/
LIST s_adjoin(LIST var_list, void *variable, int_compare compare) {
LIST l;
int result;
if (compare == NULL)
compare = (int_compare) strcmp;
l = var_list;
iterate(l) {
result = (*compare) (variable, first_node (l));
if (result == 0)
return (var_list);
else if (result < 0) {
insert(l, variable);
return (var_list);
}
}
return (push_last (var_list, variable));
}
/**********************************************************************
* s e a r c h
*
* Search list, return NIL_LIST if not found. Return the list starting from
* the item if found. The compare routine "is_equal" is passed in as
* the third parameter to this routine. If the value NULL is supplied
* for is_equal, the is_key routine will be used.
**********************************************************************/
LIST search(LIST list, void *key, int_compare is_equal) {
if (is_equal == NULL)
is_equal = is_same;
iterate (list) if ((*is_equal) (first_node (list), key))
return (list);
return (NIL_LIST);
}
LIST search(LIST list, void *key, TessResultCallback2<int, void*, void*>* is_equal) {
iterate (list) if ((*is_equal).Run(first_node (list), key))
return (list);
return (NIL_LIST);
}
<commit_msg>cutil: Remove unused code using memfree<commit_after>/* -*-C-*-
###############################################################################
#
# File: list.c
# Description: List processing procedures.
# Author: Mark Seaman, Software Productivity
# Created: Thu Jul 23 13:24:09 1987
# Modified: Thu Dec 22 10:59:52 1988 (Mark Seaman) marks@hpgrlt
# Language: C
# Package: N/A
# Status: Reusable Software Component
#
# (c) Copyright 1987, Hewlett-Packard Company.
** 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.
#
################################################################################
* Revision 1.13 90/03/06 15:37:54 15:37:54 marks (Mark Seaman)
* Look for correct file of <malloc.h> or <stdlib.h>
*
* Revision 1.12 90/02/26 17:37:36 17:37:36 marks (Mark Seaman)
* Added pop_off and join_on
*
This file contains a set of general purpose list manipulation routines.
These routines can be used in a wide variety of ways to provide several
different popular data structures. A new list can be created by declaring
a variable of type 'LIST', and can be initialized with the value 'NIL_LIST'.
All of these routines check for the NIL_LIST condition before dereferencing
pointers. NOTE: There is a users' manual available in printed form from
Mark Seaman at (303) 350-4492 at Greeley Hard Copy.
To implement a STACK use:
push to add to the Stack l = push (l, (LIST) "jim");
pop to remove items from the Stack l = pop (l);
first_node to access the head name = (char *) first_node (l);
To implement a QUEUE use:
push_last to add to the Queue l = push_last (l, (LIST) "jim");
pop remove items from the Queue l = pop (l);
first_node to access the head name = (char *) first_node (l);
To implement LISP like functions use:
first_node CAR x = (int) first_node (l);
rest CDR l = list_rest (l);
push CONS l = push (l, (LIST) this);
last LAST x = last (l);
concat APPEND l = concat (r, s);
count LENGTH x = count (l);
search MEMBER if (search (l, x, NULL))
To implement SETS use:
adjoin l = adjoin (l, x);
set_union l = set_union (r, s);
intersection l = intersection (r, s);
set_difference l = set_difference (r, s);
delete l = delete (s, x, NULL);
search if (search (l, x, NULL))
To Implement Associated LISTS use:
lpush l = lpush (l, p);
assoc s = assoc (l, x);
adelete l = adelete (l, x);
The following rules of closure exist for the functions provided.
a = first_node (push (a, b))
b = list_rest (push (a, b))
a = push (pop (a), a)) For all a <> NIL_LIST
a = reverse (reverse (a))
******************************************************************************/
#include "oldlist.h"
#include "structures.h"
#include <stdio.h>
#if MAC_OR_DOS
#include <stdlib.h>
#endif
/*----------------------------------------------------------------------
M a c r o s
----------------------------------------------------------------------*/
#define add_on(l,x) l = push (l,first_node (x))
#define next_one(l) l = list_rest (l)
/*----------------------------------------------------------------------
F u n c t i o n s
----------------------------------------------------------------------*/
/**********************************************************************
* c o u n t
*
* Recursively count the elements in a list. Return the count.
**********************************************************************/
int count(LIST var_list) {
int temp = 0;
iterate (var_list) temp += 1;
return (temp);
}
/**********************************************************************
* d e l e t e d
*
* Delete all the elements out of the current list that match the key.
* This operation destroys the original list. The caller will supply a
* routine that will compare each node to the
* key, and return a non-zero value when they match. If the value
* NULL is supplied for is_equal, the is_key routine will be used.
**********************************************************************/
LIST delete_d(LIST list, void *key, int_compare is_equal) {
LIST result = NIL_LIST;
LIST last_one = NIL_LIST;
if (is_equal == NULL)
is_equal = is_same;
while (list != NIL_LIST) {
if (!(*is_equal) (first_node (list), key)) {
if (last_one == NIL_LIST) {
last_one = list;
list = list_rest (list);
result = last_one;
set_rest(last_one, NIL_LIST);
}
else {
set_rest(last_one, list);
last_one = list;
list = list_rest (list);
set_rest(last_one, NIL_LIST);
}
}
else {
list = pop (list);
}
}
return (result);
}
LIST delete_d(LIST list, void *key,
TessResultCallback2<int, void*, void*>* is_equal) {
LIST result = NIL_LIST;
LIST last_one = NIL_LIST;
while (list != NIL_LIST) {
if (!(*is_equal).Run (first_node (list), key)) {
if (last_one == NIL_LIST) {
last_one = list;
list = list_rest (list);
result = last_one;
set_rest(last_one, NIL_LIST);
}
else {
set_rest(last_one, list);
last_one = list;
list = list_rest (list);
set_rest(last_one, NIL_LIST);
}
}
else {
list = pop (list);
}
}
return (result);
}
/**********************************************************************
* d e s t r o y
*
* Return the space taken by a list to the heap.
**********************************************************************/
LIST destroy(LIST list) {
LIST next;
while (list != NIL_LIST) {
next = list_rest (list);
free_cell(list);
list = next;
}
return (NIL_LIST);
}
/**********************************************************************
* d e s t r o y n o d e s
*
* Return the space taken by the LISTs of a list to the heap.
**********************************************************************/
void destroy_nodes(LIST list, void_dest destructor) {
ASSERT_HOST(destructor != NULL);
while (list != NIL_LIST) {
if (first_node(list) != NULL) (*destructor)(first_node(list));
list = pop(list);
}
}
/**********************************************************************
* i n s e r t
*
* Create a list element and rearange the pointers so that the first
* element in the list is the second aurgment.
**********************************************************************/
void insert(LIST list, void *node) {
LIST element;
if (list != NIL_LIST) {
element = push (NIL_LIST, node);
set_rest (element, list_rest (list));
set_rest(list, element);
node = first_node (list);
list->node = first_node (list_rest (list));
list->next->node = (LIST) node;
}
}
/**********************************************************************
* i s s a m e n o d e
*
* Compare the list node with the key value return TRUE (non-zero)
* if they are equivalent strings. (Return FALSE if not)
**********************************************************************/
int is_same_node(void *item1, void *item2) {
return (item1 == item2);
}
/**********************************************************************
* i s s a m e
*
* Compare the list node with the key value return TRUE (non-zero)
* if they are equivalent strings. (Return FALSE if not)
**********************************************************************/
int is_same(void *item1, void *item2) {
return (!strcmp ((char *) item1, (char *) item2));
}
/**********************************************************************
* j o i n
*
* Join the two lists together. This function is similar to concat
* except that concat creates a new list. This function returns the
* first list updated.
**********************************************************************/
LIST join(LIST list1, LIST list2) {
if (list1 == NIL_LIST)
return (list2);
set_rest (last (list1), list2);
return (list1);
}
/**********************************************************************
* l a s t
*
* Return the last list item (this is list type).
**********************************************************************/
LIST last(LIST var_list) {
while (list_rest (var_list) != NIL_LIST)
var_list = list_rest (var_list);
return (var_list);
}
/**********************************************************************
* n t h c e l l
*
* Return nth list cell in the list.
**********************************************************************/
void *nth_cell(LIST var_list, int item_num) {
int x = 0;
iterate(var_list) {
if (x++ == item_num)
return (var_list);
}
return (var_list);
}
/**********************************************************************
* p o p
*
* Return the list with the first element removed. Destroy the space
* that it occupied in the list.
**********************************************************************/
LIST pop(LIST list) {
LIST temp;
temp = list_rest (list);
if (list != NIL_LIST) {
free_cell(list);
}
return (temp);
}
/**********************************************************************
* p u s h
*
* Create a list element. Push the second parameter (the node) onto
* the first parameter (the list). Return the new list to the caller.
**********************************************************************/
LIST push(LIST list, void *element) {
LIST t;
t = new_cell ();
t->node = (LIST) element;
set_rest(t, list);
return (t);
}
/**********************************************************************
* p u s h l a s t
*
* Create a list element. Add the element onto the end of the list.
**********************************************************************/
LIST push_last(LIST list, void *item) {
LIST t;
if (list != NIL_LIST) {
t = last (list);
t->next = push (NIL_LIST, item);
return (list);
}
else
return (push (NIL_LIST, item));
}
/**********************************************************************
* r e v e r s e
*
* Create a new list with the elements reversed. The old list is not
* destroyed.
**********************************************************************/
LIST reverse(LIST list) {
LIST newlist = NIL_LIST;
iterate (list) copy_first (list, newlist);
return (newlist);
}
/**********************************************************************
* r e v e r s e d
*
* Create a new list with the elements reversed. The old list is
* destroyed.
**********************************************************************/
LIST reverse_d(LIST list) {
LIST result = reverse (list);
destroy(list);
return (result);
}
/**********************************************************************
* s a d j o i n
*
* Adjoin an element to an assorted list. The original list is
* modified. Returns the modified list.
**********************************************************************/
LIST s_adjoin(LIST var_list, void *variable, int_compare compare) {
LIST l;
int result;
if (compare == NULL)
compare = (int_compare) strcmp;
l = var_list;
iterate(l) {
result = (*compare) (variable, first_node (l));
if (result == 0)
return (var_list);
else if (result < 0) {
insert(l, variable);
return (var_list);
}
}
return (push_last (var_list, variable));
}
/**********************************************************************
* s e a r c h
*
* Search list, return NIL_LIST if not found. Return the list starting from
* the item if found. The compare routine "is_equal" is passed in as
* the third parameter to this routine. If the value NULL is supplied
* for is_equal, the is_key routine will be used.
**********************************************************************/
LIST search(LIST list, void *key, int_compare is_equal) {
if (is_equal == NULL)
is_equal = is_same;
iterate (list) if ((*is_equal) (first_node (list), key))
return (list);
return (NIL_LIST);
}
LIST search(LIST list, void *key, TessResultCallback2<int, void*, void*>* is_equal) {
iterate (list) if ((*is_equal).Run(first_node (list), key))
return (list);
return (NIL_LIST);
}
<|endoftext|>
|
<commit_before>#include "LibraryPanel.h"
#include "LibraryPage.h"
#include "StagePanel.h"
#include "dataset/Layer.h"
#include <ee/panel_msg.h>
#include <ee/FileHelper.h>
#include <ee/LibraryList.h>
#include <ee/SymbolMgr.h>
#include <ee/Exception.h>
#include <ee/FetchAllVisitor.h>
#include <ee/PasteSymbolOP.h>
#include <ee/SelectShapesOP.h>
#include <ee/SpriteSelection.h>
#include <ee/ShapeSelection.h>
#include <ee/ViewlistPanel.h>
#include <ee/GroupTreePanel.h>
#include <easyshape.h>
namespace lr
{
BEGIN_EVENT_TABLE(LibraryPanel, wxPanel)
EVT_CHAR_HOOK(LibraryPanel::CharHook)
END_EVENT_TABLE()
LibraryPanel::LibraryPanel(wxWindow* parent)
: ee::LibraryPanel(parent)
, m_viewlist(NULL)
, m_grouptree(NULL)
, m_stage(NULL)
{
m_terrain_page = m_unit_page = m_path_page = m_level_page = NULL;
}
void LibraryPanel::OnPageChanged(wxBookCtrlEvent& event)
{
ee::LibraryPanel::OnPageChanged(event);
Layer* curr = static_cast<LibraryPage*>(GetCurrPage())->GetLayer();
ee::ChangeLayerMgrSJ::Instance()->Change(curr->GetLayerMgr());
curr->SetEditable(true);
static_cast<LibraryPage*>(m_pages[event.GetSelection()])->UpdateStatusFromLayer();
Refresh();
}
void LibraryPanel::OnPageChanging(wxBookCtrlEvent& event)
{
ee::LibraryPanel::OnPageChanging(event);
Layer* curr = static_cast<LibraryPage*>(GetCurrPage())->GetLayer();
curr->SetEditable(false);
static_cast<LibraryPage*>(m_pages[event.GetSelection()])->UpdateStatusFromLayer();
}
void LibraryPanel::LoadFromFile(const Json::Value& value, const std::string& dir)
{
for (int i = 0, n = value.size(); i < n; ++i)
{
Json::Value layer_val = value[i];
if (layer_val.isNull()) {
continue;
}
ee::LibraryList* list = m_pages[i]->GetList();
int item_idx = 0;
Json::Value item_val = layer_val[item_idx++];
while (!item_val.isNull()) {
std::string item_path = item_val.asString();
std::string filepath = ee::FileHelper::GetAbsolutePath(dir, item_path);
try {
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
sym->RefreshThumbnail(sym->GetFilepath());
list->Insert(sym);
sym->RemoveReference();
} catch (ee::Exception& e) {
throw ee::Exception("Create symbol %s fail!", item_path.c_str());
}
item_val = layer_val[item_idx++];
}
}
}
void LibraryPanel::StoreToFile(Json::Value& value, const std::string& dir) const
{
for (int i = 0, n = m_pages.size(); i < n; ++i)
{
ee::LibraryList* list = m_pages[i]->GetList();
int j = 0;
ee::Symbol* sym = static_cast<ee::Symbol*>(list->GetItem(j++));
while (sym) {
value[i][j-1] = ee::FileHelper::GetRelativePath(dir, sym->GetFilepath());
sym = static_cast<ee::Symbol*>(list->GetItem(j++));
}
}
}
void LibraryPanel::InitFromLayers(const std::vector<Layer*>& layers)
{
assert(layers.size() <= m_pages.size());
for (int i = 0, n = layers.size(); i < n; ++i)
{
Layer* layer = layers[i];
ee::LibraryPage* page = m_pages[i];
static_cast<LibraryPage*>(page)->SetLayer(layer);
layer->SetName(page->GetPageName());
static_cast<LibraryPage*>(page)->UpdateStatusFromLayer();
}
}
void LibraryPanel::LoadSymbolFromLayer()
{
for (int i = 0, n = m_pages.size(); i < n; ++i)
{
LibraryPage* page = static_cast<LibraryPage*>(m_pages[i]);
std::vector<ee::Sprite*> sprs;
page->GetLayer()->TraverseSprite(ee::FetchAllVisitor<ee::Sprite>(sprs), true);
std::set<ee::Symbol*> symbol_set;
for (int i = 0, n = sprs.size(); i < n; ++i) {
ee::Symbol* sym = dynamic_cast<ee::Symbol*>(sprs[i]->GetSymbol());
symbol_set.insert(sym);
}
std::set<ee::Symbol*>::iterator itr = symbol_set.begin();
for ( ; itr != symbol_set.end(); ++itr) {
ee::Symbol* sym = *itr;
sym->RefreshThumbnail(sym->GetFilepath());
page->GetList()->Insert(sym);
}
}
}
void LibraryPanel::InitPages(StagePanel* stage, ee::PropertySettingPanel* property)
{
ee::EditOP* paste_op = new ee::PasteSymbolOP(stage, stage->GetStageImpl(), this);
ee::OneFloatValue* capture_val = new ee::OneFloatValueStatic(10);
ee::EditOP* draw_line_op = new eshape::EditPolylineOP<eshape::DrawPenLineOP, ee::SelectShapesOP>(stage, stage->GetStageImpl(), stage, property, capture_val, NULL);
ee::EditOP* draw_poly_op = new eshape::EditPolylineOP<eshape::DrawPolygonOP, ee::SelectShapesOP>(stage, stage->GetStageImpl(), stage, property, capture_val, NULL);
int id = 0;
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_terrain_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "װ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_AUTO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "λ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_AUTO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_unit_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "·", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_line_op);
AddPage(page);
m_path_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "", LT_SHAPE, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_poly_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "ײ", LT_SHAPE, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_poly_op);
page->AddEditOP(draw_line_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "ؿ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_level_page = page;
}
paste_op->RemoveReference();
draw_line_op->RemoveReference();
draw_poly_op->RemoveReference();
std::vector<Layer*> layers;
for (int i = 0, n = m_pages.size(); i < n; ++i) {
Layer* layer = static_cast<LibraryPage*>(m_pages[i])->GetLayer();
layer->AddReference();
layers.push_back(layer);
}
stage->SetLayers(layers);
}
void LibraryPanel::Refresh()
{
Layer* layer = static_cast<LibraryPage*>(m_selected)->GetLayer();
std::vector<ee::Sprite*> sprs;
layer->TraverseSprite(ee::FetchAllVisitor<ee::Sprite>(sprs), true);
// stage
m_stage->GetSpriteSelection()->Clear();
m_stage->GetShapeSelection()->Clear();
// view list
m_viewlist->Clear();
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_viewlist->Insert(sprs[i]);
}
// group tree
m_grouptree->EnableExpand(false);
m_grouptree->Clear();
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_grouptree->Insert(sprs[i]);
}
m_grouptree->EnableExpand(true);
}
Layer* LibraryPanel::GetTerrainLayer()
{
return m_terrain_page->GetLayer();
}
LayerType LibraryPanel::GetLayerType(int idx) const
{
if (idx < 0 || idx >= m_pages.size()) {
return LT_DEFAULT;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayerType();
}
}
s2::CameraMode LibraryPanel::GetLayerCameraMode(int idx) const
{
if (idx < 0 || idx >= m_pages.size()) {
return s2::CM_ORTHO;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayerCameraMode();
}
}
Layer* LibraryPanel::GetLayer(int idx)
{
if (idx < 0 || idx >= m_pages.size()) {
return NULL;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayer();
}
}
bool LibraryPanel::IsCurrUnitLayer()
{
return m_unit_page == static_cast<LibraryPage*>(GetCurrPage());
}
bool LibraryPanel::IsCurrLevelLayer()
{
return m_level_page == static_cast<LibraryPage*>(GetCurrPage());
}
void LibraryPanel::GetAllPathName(std::vector<std::string>& names) const
{
Layer* layer = static_cast<LibraryPage*>(m_path_page)->GetLayer();
std::vector<ee::Shape*> shapes;
layer->TraverseShape(ee::FetchAllVisitor<ee::Shape>(shapes));
for (int i = 0, n = shapes.size(); i < n; ++i) {
names.push_back(shapes[i]->GetName());
}
}
void LibraryPanel::CharHook(wxKeyEvent& event)
{
int key_code = event.GetKeyCode();
if (key_code >= '1' && key_code <= '9') {
int idx = key_code - '1';
SetCurrPage(idx);
return;
} else {
event.Skip();
}
}
}<commit_msg>[FIXED] catch FetchSymbol<commit_after>#include "LibraryPanel.h"
#include "LibraryPage.h"
#include "StagePanel.h"
#include "dataset/Layer.h"
#include <ee/panel_msg.h>
#include <ee/FileHelper.h>
#include <ee/LibraryList.h>
#include <ee/SymbolMgr.h>
#include <ee/Exception.h>
#include <ee/FetchAllVisitor.h>
#include <ee/PasteSymbolOP.h>
#include <ee/SelectShapesOP.h>
#include <ee/SpriteSelection.h>
#include <ee/ShapeSelection.h>
#include <ee/ViewlistPanel.h>
#include <ee/GroupTreePanel.h>
#include <easyshape.h>
namespace lr
{
BEGIN_EVENT_TABLE(LibraryPanel, wxPanel)
EVT_CHAR_HOOK(LibraryPanel::CharHook)
END_EVENT_TABLE()
LibraryPanel::LibraryPanel(wxWindow* parent)
: ee::LibraryPanel(parent)
, m_viewlist(NULL)
, m_grouptree(NULL)
, m_stage(NULL)
{
m_terrain_page = m_unit_page = m_path_page = m_level_page = NULL;
}
void LibraryPanel::OnPageChanged(wxBookCtrlEvent& event)
{
ee::LibraryPanel::OnPageChanged(event);
Layer* curr = static_cast<LibraryPage*>(GetCurrPage())->GetLayer();
ee::ChangeLayerMgrSJ::Instance()->Change(curr->GetLayerMgr());
curr->SetEditable(true);
static_cast<LibraryPage*>(m_pages[event.GetSelection()])->UpdateStatusFromLayer();
Refresh();
}
void LibraryPanel::OnPageChanging(wxBookCtrlEvent& event)
{
ee::LibraryPanel::OnPageChanging(event);
Layer* curr = static_cast<LibraryPage*>(GetCurrPage())->GetLayer();
curr->SetEditable(false);
static_cast<LibraryPage*>(m_pages[event.GetSelection()])->UpdateStatusFromLayer();
}
void LibraryPanel::LoadFromFile(const Json::Value& value, const std::string& dir)
{
for (int i = 0, n = value.size(); i < n; ++i)
{
Json::Value layer_val = value[i];
if (layer_val.isNull()) {
continue;
}
ee::LibraryList* list = m_pages[i]->GetList();
int item_idx = 0;
Json::Value item_val = layer_val[item_idx++];
while (!item_val.isNull()) {
std::string item_path = item_val.asString();
std::string filepath = ee::FileHelper::GetAbsolutePath(dir, item_path);
try {
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
if (!sym) {
throw ee::Exception("Create symbol %s fail!", item_path.c_str());
}
sym->RefreshThumbnail(sym->GetFilepath());
list->Insert(sym);
sym->RemoveReference();
} catch (ee::Exception& e) {
throw ee::Exception("Create symbol %s fail!", item_path.c_str());
}
item_val = layer_val[item_idx++];
}
}
}
void LibraryPanel::StoreToFile(Json::Value& value, const std::string& dir) const
{
for (int i = 0, n = m_pages.size(); i < n; ++i)
{
ee::LibraryList* list = m_pages[i]->GetList();
int j = 0;
ee::Symbol* sym = static_cast<ee::Symbol*>(list->GetItem(j++));
while (sym) {
value[i][j-1] = ee::FileHelper::GetRelativePath(dir, sym->GetFilepath());
sym = static_cast<ee::Symbol*>(list->GetItem(j++));
}
}
}
void LibraryPanel::InitFromLayers(const std::vector<Layer*>& layers)
{
assert(layers.size() <= m_pages.size());
for (int i = 0, n = layers.size(); i < n; ++i)
{
Layer* layer = layers[i];
ee::LibraryPage* page = m_pages[i];
static_cast<LibraryPage*>(page)->SetLayer(layer);
layer->SetName(page->GetPageName());
static_cast<LibraryPage*>(page)->UpdateStatusFromLayer();
}
}
void LibraryPanel::LoadSymbolFromLayer()
{
for (int i = 0, n = m_pages.size(); i < n; ++i)
{
LibraryPage* page = static_cast<LibraryPage*>(m_pages[i]);
std::vector<ee::Sprite*> sprs;
page->GetLayer()->TraverseSprite(ee::FetchAllVisitor<ee::Sprite>(sprs), true);
std::set<ee::Symbol*> symbol_set;
for (int i = 0, n = sprs.size(); i < n; ++i) {
ee::Symbol* sym = dynamic_cast<ee::Symbol*>(sprs[i]->GetSymbol());
symbol_set.insert(sym);
}
std::set<ee::Symbol*>::iterator itr = symbol_set.begin();
for ( ; itr != symbol_set.end(); ++itr) {
ee::Symbol* sym = *itr;
sym->RefreshThumbnail(sym->GetFilepath());
page->GetList()->Insert(sym);
}
}
}
void LibraryPanel::InitPages(StagePanel* stage, ee::PropertySettingPanel* property)
{
ee::EditOP* paste_op = new ee::PasteSymbolOP(stage, stage->GetStageImpl(), this);
ee::OneFloatValue* capture_val = new ee::OneFloatValueStatic(10);
ee::EditOP* draw_line_op = new eshape::EditPolylineOP<eshape::DrawPenLineOP, ee::SelectShapesOP>(stage, stage->GetStageImpl(), stage, property, capture_val, NULL);
ee::EditOP* draw_poly_op = new eshape::EditPolylineOP<eshape::DrawPolygonOP, ee::SelectShapesOP>(stage, stage->GetStageImpl(), stage, property, capture_val, NULL);
int id = 0;
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_terrain_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "װ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_AUTO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "λ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_AUTO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_unit_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "·", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_line_op);
AddPage(page);
m_path_page = page;
}
{
LibraryPage* page = new LibraryPage(this, "", LT_SHAPE, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_poly_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "ײ", LT_SHAPE, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(draw_poly_op);
page->AddEditOP(draw_line_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
}
{
LibraryPage* page = new LibraryPage(this, "ؿ", LT_DEFAULT, id++, s2::CM_PERSPECTIVE_NO_HEIGHT);
Layer* layer = page->GetLayer();
page->AddEditOP(m_stage->GetBaseOP());
page->AddEditOP(paste_op);
AddPage(page);
m_level_page = page;
}
paste_op->RemoveReference();
draw_line_op->RemoveReference();
draw_poly_op->RemoveReference();
std::vector<Layer*> layers;
for (int i = 0, n = m_pages.size(); i < n; ++i) {
Layer* layer = static_cast<LibraryPage*>(m_pages[i])->GetLayer();
layer->AddReference();
layers.push_back(layer);
}
stage->SetLayers(layers);
}
void LibraryPanel::Refresh()
{
Layer* layer = static_cast<LibraryPage*>(m_selected)->GetLayer();
std::vector<ee::Sprite*> sprs;
layer->TraverseSprite(ee::FetchAllVisitor<ee::Sprite>(sprs), true);
// stage
m_stage->GetSpriteSelection()->Clear();
m_stage->GetShapeSelection()->Clear();
// view list
m_viewlist->Clear();
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_viewlist->Insert(sprs[i]);
}
// group tree
m_grouptree->EnableExpand(false);
m_grouptree->Clear();
for (int i = 0, n = sprs.size(); i < n; ++i) {
m_grouptree->Insert(sprs[i]);
}
m_grouptree->EnableExpand(true);
}
Layer* LibraryPanel::GetTerrainLayer()
{
return m_terrain_page->GetLayer();
}
LayerType LibraryPanel::GetLayerType(int idx) const
{
if (idx < 0 || idx >= m_pages.size()) {
return LT_DEFAULT;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayerType();
}
}
s2::CameraMode LibraryPanel::GetLayerCameraMode(int idx) const
{
if (idx < 0 || idx >= m_pages.size()) {
return s2::CM_ORTHO;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayerCameraMode();
}
}
Layer* LibraryPanel::GetLayer(int idx)
{
if (idx < 0 || idx >= m_pages.size()) {
return NULL;
} else {
return static_cast<LibraryPage*>(m_pages[idx])->GetLayer();
}
}
bool LibraryPanel::IsCurrUnitLayer()
{
return m_unit_page == static_cast<LibraryPage*>(GetCurrPage());
}
bool LibraryPanel::IsCurrLevelLayer()
{
return m_level_page == static_cast<LibraryPage*>(GetCurrPage());
}
void LibraryPanel::GetAllPathName(std::vector<std::string>& names) const
{
Layer* layer = static_cast<LibraryPage*>(m_path_page)->GetLayer();
std::vector<ee::Shape*> shapes;
layer->TraverseShape(ee::FetchAllVisitor<ee::Shape>(shapes));
for (int i = 0, n = shapes.size(); i < n; ++i) {
names.push_back(shapes[i]->GetName());
}
}
void LibraryPanel::CharHook(wxKeyEvent& event)
{
int key_code = event.GetKeyCode();
if (key_code >= '1' && key_code <= '9') {
int idx = key_code - '1';
SetCurrPage(idx);
return;
} else {
event.Skip();
}
}
}<|endoftext|>
|
<commit_before>#include "StateSpace.h"
StateSpace::StateSpace(const int _x_size, const int _y_size):
x_size(_x_size),
y_size(_y_size),
space(x_size, std::vector< PriorityQueue<Experience*,double> > (y_size, PriorityQueue<Experience*,double> (HeapType::MAX)))
{}
StateSpace::~StateSpace()
{
//ridiculously extensive clean-up
for(unsigned int i=0 ; i<x_size ; ++i)
{
for(unsigned int j=0 ; j<x_size ; ++j)
{
PriorityQueue<Experience*,double>& queue=space[i][j];
for(auto iter=queue.begin(),queue=list.end() ; iter!=end ; ++iter)
{
delete *iter;
}
}
}
}
SateSpace::SubscriptProxy SateSpace::operator[](const unsigned int action)
{
if(action>1)throw std::domain_error("action index exceeded");
//return proxy object to accept second [] operator
return SubscriptProxy( action ? space1 : space2 );
}
<commit_msg>updated to use action objects<commit_after>#include "StateSpace.h"
StateSpace::StateSpace(const int _x_size, const int _y_size):
x_size(_x_size),
y_size(_y_size),
space(x_size, std::vector< PriorityQueue<Action*,double> > (y_size, PriorityQueue<Action*,double> (HeapType::MAX)))
{}
StateSpace::~StateSpace()
{
//ridiculously extensive clean-up
for(unsigned int i=0 ; i<x_size ; ++i)
{
for(unsigned int j=0 ; j<x_size ; ++j)
{
PriorityQueue<Action*,double>& queue=space[i][j];
for(auto iter=queue.begin(),queue=list.end() ; iter!=end ; ++iter)
{
delete *iter;
}
}
}
}
SateSpace::SubscriptProxy SateSpace::operator[](const unsigned int action)
{
if(action>1)throw std::domain_error("action index exceeded");
//return proxy object to accept second [] operator
return SubscriptProxy( action ? space1 : space2 );
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/mail/SmtpClient.h"
#include "db/net/InternetAddress.h"
using namespace std;
using namespace db::io;
using namespace db::mail;
using namespace db::net;
using namespace db::rt;
SmtpClient::SmtpClient()
{
mSslContext = NULL;
}
SmtpClient::~SmtpClient()
{
if(mSslContext != NULL)
{
delete mSslContext;
}
}
void SmtpClient::activateSsl(Connection* c)
{
mSslContext = new SslContext(NULL, true);
// switch underlying socket with an SSL socket
Socket* s = new SslSocket(
mSslContext, (TcpSocket*)c->getSocket(), true, c->mustCleanupSocket());
c->setSocket(s, true);
c->setSecure(true);
}
int SmtpClient::getResponseCode(Connection* c)
{
int rval = -1;
// get response line
string line;
if(c->getInputStream()->readCrlf(line))
{
// parse code from line
rval = strtoul(line.c_str(), NULL, 10);
}
return rval;
}
bool SmtpClient::sendCrlf(Connection* c)
{
return c->getOutputStream()->write("\r\n", 2);
}
bool SmtpClient::helo(Connection* c, const char* domain)
{
// send "HELO" verb, space, and domain
return
c->getOutputStream()->write("HELO", 4) &&
c->getOutputStream()->write(" ", 1) &&
c->getOutputStream()->write(domain, strlen(domain)) &&
sendCrlf(c);
}
bool SmtpClient::mailFrom(Connection* c, const char* address)
{
// send "MAIL FROM:" verb and SMTP-encoded address
return
c->getOutputStream()->write("MAIL FROM:", 10) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::rcptTo(Connection* c, const char* address)
{
// send "RCPT TO:" verb and SMTP-encoded address
return
c->getOutputStream()->write("RCPT TO:", 8) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::startData(Connection* c)
{
// send "DATA" verb
return
c->getOutputStream()->write("DATA", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMessage(Connection* c, Message msg)
{
bool rval = true;
// send headers
DynamicObjectIterator i = msg["headers"].getIterator();
while(rval && i->hasNext())
{
// iterate over each header
DynamicObjectIterator hi = i->next().getIterator();
bool comma = false;
while(rval && hi->hasNext())
{
DynamicObject header = hi->next();
if(rval && !comma)
{
// send header name and colon
rval =
c->getOutputStream()->write(
i->getName(), strlen(i->getName())) &&
c->getOutputStream()->write(": ", 2);
}
if(rval && comma)
{
// send comma
rval = c->getOutputStream()->write(", ", 2);
}
else
{
comma = true;
}
if(rval)
{
// send smtp-encoded header value
string value = header->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
}
// send CRLF
if(rval)
{
rval = sendCrlf(c);
}
}
if(rval)
{
// send smtp-encoded body
string value = msg["body"]->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
return rval;
}
bool SmtpClient::endData(Connection* c)
{
// end with .CRLF
return c->getOutputStream()->write("\r\n.\r\n", 5);
}
bool SmtpClient::quit(Connection* c)
{
// send "QUIT" verb
return
c->getOutputStream()->write("QUIT", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMail(Connection* c, Mail* mail)
{
bool rval = true;
// FIXME: this is the simplest implementation to get this thing to
// send mail to our server, it will have to be filled out later if
// we so desire
// for storing server response codes
int code;
// receive response from server
rval = ((code = getResponseCode(c)) == 220);
// say helo from sender's domain
if(rval && (rval = helo(c, mail->getSender()["domain"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// send sender's address
if(rval && (rval = mailFrom(
c, mail->getSender()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// do rcpt to
AddressIterator i = mail->getRecipients().getIterator();
while(rval && i->hasNext())
{
// send recipient's address
if((rval = rcptTo(c, i->next()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
}
// start data
if(rval && (rval = startData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 354);
}
// send data
if(rval && (rval = sendMessage(c, mail->getMessage())));
// end data
if(rval && (rval = endData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// quit
if(rval && (rval = quit(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 221);
}
if(!rval)
{
if(code != -1)
{
// code was not the expected one
char temp[120];
sprintf(temp, "Unexpected SMTP server response code!,code=%i", code);
ExceptionRef e = new IOException(temp, "db.mail.UnexpectedSmtpCode");
Exception::setLast(e, false);
}
}
return rval;
}
bool SmtpClient::sendMail(Url* url, Mail* mail)
{
bool rval = false;
// connect, use 30 second timeouts
TcpSocket s;
s.setReceiveTimeout(30000);
InternetAddress address(url->getHost().c_str(), url->getPort());
if(s.connect(&address, 30))
{
// create smtp connection
Connection c(&s, false);
// send mail
rval = sendMail(&c, mail);
// disconnect
c.close();
}
return rval;
}
<commit_msg>Add error handling.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/mail/SmtpClient.h"
#include "db/net/InternetAddress.h"
using namespace std;
using namespace db::io;
using namespace db::mail;
using namespace db::net;
using namespace db::rt;
SmtpClient::SmtpClient()
{
mSslContext = NULL;
}
SmtpClient::~SmtpClient()
{
if(mSslContext != NULL)
{
delete mSslContext;
}
}
void SmtpClient::activateSsl(Connection* c)
{
mSslContext = new SslContext(NULL, true);
// switch underlying socket with an SSL socket
Socket* s = new SslSocket(
mSslContext, (TcpSocket*)c->getSocket(), true, c->mustCleanupSocket());
c->setSocket(s, true);
c->setSecure(true);
}
int SmtpClient::getResponseCode(Connection* c)
{
int rval = -1;
// get response line
string line;
if(c->getInputStream()->readCrlf(line))
{
// parse code from line
rval = strtoul(line.c_str(), NULL, 10);
}
return rval;
}
bool SmtpClient::sendCrlf(Connection* c)
{
return c->getOutputStream()->write("\r\n", 2);
}
bool SmtpClient::helo(Connection* c, const char* domain)
{
// send "HELO" verb, space, and domain
return
c->getOutputStream()->write("HELO", 4) &&
c->getOutputStream()->write(" ", 1) &&
c->getOutputStream()->write(domain, strlen(domain)) &&
sendCrlf(c);
}
bool SmtpClient::mailFrom(Connection* c, const char* address)
{
// send "MAIL FROM:" verb and SMTP-encoded address
return
c->getOutputStream()->write("MAIL FROM:", 10) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::rcptTo(Connection* c, const char* address)
{
// send "RCPT TO:" verb and SMTP-encoded address
return
c->getOutputStream()->write("RCPT TO:", 8) &&
c->getOutputStream()->write(address, strlen(address)) &&
sendCrlf(c);
}
bool SmtpClient::startData(Connection* c)
{
// send "DATA" verb
return
c->getOutputStream()->write("DATA", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMessage(Connection* c, Message msg)
{
bool rval = true;
// send headers
DynamicObjectIterator i = msg["headers"].getIterator();
while(rval && i->hasNext())
{
// iterate over each header
DynamicObjectIterator hi = i->next().getIterator();
bool comma = false;
while(rval && hi->hasNext())
{
DynamicObject header = hi->next();
if(rval && !comma)
{
// send header name and colon
rval =
c->getOutputStream()->write(
i->getName(), strlen(i->getName())) &&
c->getOutputStream()->write(": ", 2);
}
if(rval && comma)
{
// send comma
rval = c->getOutputStream()->write(", ", 2);
}
else
{
comma = true;
}
if(rval)
{
// send smtp-encoded header value
string value = header->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
}
// send CRLF
if(rval)
{
rval = sendCrlf(c);
}
}
if(rval)
{
// send smtp-encoded body
string value = msg["body"]->getString();
Mail::smtpMessageEncode(value);
rval = c->getOutputStream()->write(value.c_str(), value.length());
}
return rval;
}
bool SmtpClient::endData(Connection* c)
{
// end with .CRLF
return c->getOutputStream()->write("\r\n.\r\n", 5);
}
bool SmtpClient::quit(Connection* c)
{
// send "QUIT" verb
return
c->getOutputStream()->write("QUIT", 4) &&
sendCrlf(c);
}
bool SmtpClient::sendMail(Connection* c, Mail* mail)
{
bool rval = true;
// FIXME: this is the simplest implementation to get this thing to
// send mail to our server, it will have to be filled out later if
// we so desire
// for storing server response codes
int code;
// receive response from server
rval = ((code = getResponseCode(c)) == 220);
// say helo from sender's domain
if(rval && (rval = helo(c, mail->getSender()["domain"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// send sender's address
if(rval && (rval = mailFrom(
c, mail->getSender()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// do rcpt to
AddressIterator i = mail->getRecipients().getIterator();
while(rval && i->hasNext())
{
// send recipient's address
if((rval = rcptTo(c, i->next()["smtpEncoding"]->getString())))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
}
// start data
if(rval && (rval = startData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 354);
}
// send data
if(rval && (rval = sendMessage(c, mail->getMessage())));
// end data
if(rval && (rval = endData(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 250);
}
// quit
if(rval && (rval = quit(c)))
{
// receive response
rval = ((code = getResponseCode(c)) == 221);
}
if(!rval)
{
if(code != -1)
{
// code was not the expected one
char temp[120];
sprintf(temp, "Unexpected SMTP server response code!,code=%i", code);
ExceptionRef e = new IOException(temp, "db.mail.UnexpectedSmtpCode");
Exception::setLast(e, false);
}
}
return rval;
}
bool SmtpClient::sendMail(Url* url, Mail* mail)
{
bool rval = false;
// connect, use 30 second timeouts
TcpSocket s;
s.setReceiveTimeout(30000);
Exception::clearLast();
InternetAddress address(url->getHost().c_str(), url->getPort());
if(Exception::hasLast())
{
ExceptionRef e = new Exception(
"Failed to setup SMTP host address.",
"db.mail.SmtpAddressLookupFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
else if(s.connect(&address, 30))
{
// create smtp connection
Connection c(&s, false);
// send mail
rval = sendMail(&c, mail);
// disconnect
c.close();
}
else
{
ExceptionRef e = new Exception(
"Failed to connect to SMTP host.",
"db.mail.SmtpConnectionFailure");
e->getDetails()["host"] = url->getHost().c_str();
e->getDetails()["port"] = url->getPort();
Exception::setLast(e, true);
rval = false;
}
return rval;
}
<|endoftext|>
|
<commit_before>// @(#)root/mathcore:$Id$
// Author: L. Moneta Thu Sep 21 16:21:29 2006
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class FitConfig
#include "Fit/FitConfig.h"
#include "Math/IParamFunction.h"
#include "Math/Util.h"
#include "Math/Minimizer.h"
#include "Math/Factory.h"
#include <cmath>
#include <string>
#include <sstream>
#include "Math/Error.h"
//#define DEBUG
#ifdef DEBUG
#endif
#include <iostream>
namespace ROOT {
namespace Fit {
FitConfig::FitConfig(unsigned int npar) :
fNormErrors(false),
fParabErrors(false), // ensure that in any case correct parabolic errors are estimated
fMinosErrors(false), // do full Minos error analysis for all parameters
fSettings(std::vector<ParameterSettings>(npar) )
{
// constructor implementation
}
FitConfig::~FitConfig()
{
// destructor implementation. No Op
}
FitConfig::FitConfig(const FitConfig &rhs) {
// Implementation of copy constructor
(*this) = rhs;
}
FitConfig & FitConfig::operator = (const FitConfig &rhs) {
// Implementation of assignment operator.
if (this == &rhs) return *this; // time saving self-test
fNormErrors = rhs.fNormErrors;
fParabErrors = rhs.fParabErrors;
fMinosErrors = rhs.fMinosErrors;
fSettings = rhs.fSettings;
fMinosParams = rhs.fMinosParams;
fMinimizerOpts = rhs.fMinimizerOpts;
return *this;
}
void FitConfig::SetParamsSettings(unsigned int npar, const double *params, const double * vstep ) {
// initialize fit config from parameter values
if (params == 0) {
fSettings = std::vector<ParameterSettings>(npar);
return;
}
// if a vector of parameters is given and parameters are not existing or are of different size
bool createNew = false;
if (npar != fSettings.size() ) {
fSettings.clear();
fSettings.reserve(npar);
createNew = true;
}
unsigned int i = 0;
const double * end = params+npar;
for (const double * ipar = params; ipar != end; ++ipar) {
double val = *ipar;
double step = 0;
if (vstep == 0) {
step = 0.3*std::fabs(val); // step size is 30% of par value
//double step = 2.0*std::fabs(val); // step size is 30% of par value
if (val == 0) step = 0.3;
}
else
step = vstep[i];
if (createNew)
fSettings.push_back( ParameterSettings("Par_" + ROOT::Math::Util::ToString(i), val, step ) );
else {
fSettings[i].SetValue(val);
fSettings[i].SetStepSize(step);
}
i++;
}
}
void FitConfig::CreateParamsSettings(const ROOT::Math::IParamMultiFunction & func) {
// initialize from model function
// set the parameters values from the function
unsigned int npar = func.NPar();
const double * begin = func.Parameters();
if (begin == 0) {
fSettings = std::vector<ParameterSettings>(npar);
return;
}
fSettings.clear();
fSettings.reserve(npar);
const double * end = begin+npar;
unsigned int i = 0;
for (const double * ipar = begin; ipar != end; ++ipar) {
double val = *ipar;
double step = 0.3*std::fabs(val); // step size is 30% of par value
//double step = 2.0*std::fabs(val); // step size is 30% of par value
if (val == 0) step = 0.3;
fSettings.push_back( ParameterSettings(func.ParameterName(i), val, step ) );
#ifdef DEBUG
std::cout << "FitConfig: add parameter " << func.ParameterName(i) << " val = " << val << std::endl;
#endif
i++;
}
}
ROOT::Math::Minimizer * FitConfig::CreateMinimizer() {
// create minimizer according to the chosen configuration using the
// plug-in manager
const std::string & minimType = fMinimizerOpts.MinimizerType();
const std::string & algoType = fMinimizerOpts.MinimizerAlgorithm();
std::string defaultMinim = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
ROOT::Math::Minimizer * min = ROOT::Math::Factory::CreateMinimizer(minimType, algoType);
// check if a different minimizer is used (in case a default value is passed, then set correctly in FitConfig)
const std::string & minim_newDefault = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
if (defaultMinim != minim_newDefault ) fMinimizerOpts.SetMinimizerType(minim_newDefault.c_str());
if (min == 0) {
// if creation of minimizer failed force the use by default of Minuit
std::string minim2 = "Minuit";
if (minimType == "Minuit") minim2 = "Minuit2";
if (minimType != minim2 ) {
std::string msg = "Could not create the " + minimType + " minimizer. Try using the minimizer " + minim2;
MATH_WARN_MSG("FitConfig::CreateMinimizer",msg.c_str());
min = ROOT::Math::Factory::CreateMinimizer(minim2,"Migrad");
if (min == 0) {
MATH_ERROR_MSG("FitConfig::CreateMinimizer","Could not create the Minuit2 minimizer");
return 0;
}
SetMinimizer( minim2.c_str(),"Migrad");
}
else {
std::string msg = "Could not create the Minimizer " + minimType;
MATH_ERROR_MSG("FitConfig::CreateMinimizer",msg.c_str());
return 0;
}
}
// set default max of function calls according to the number of parameters
// formula from Minuit2 (adapted)
if (fMinimizerOpts.MaxFunctionCalls() == 0) {
unsigned int npar = fSettings.size();
int maxfcn = 1000 + 100*npar + 5*npar*npar;
fMinimizerOpts.SetMaxFunctionCalls(maxfcn);
}
// set default minimizer control parameters
min->SetPrintLevel( fMinimizerOpts.PrintLevel() );
min->SetMaxFunctionCalls( fMinimizerOpts.MaxFunctionCalls() );
min->SetMaxIterations( fMinimizerOpts.MaxIterations() );
min->SetTolerance( fMinimizerOpts.Tolerance() );
min->SetPrecision( fMinimizerOpts.Precision() );
min->SetValidError( fParabErrors );
min->SetStrategy( fMinimizerOpts.Strategy() );
min->SetErrorDef( fMinimizerOpts.ErrorDef() );
return min;
}
void FitConfig::SetDefaultMinimizer(const char * type, const char *algo ) {
// set the default minimizer type and algorithms
ROOT::Math::MinimizerOptions::SetDefaultMinimizer(type, algo);
}
void FitConfig::SetMinimizerOptions(const ROOT::Math::MinimizerOptions & minopt) {
// set all the minimizer options
fMinimizerOpts = minopt;
}
} // end namespace Fit
} // end namespace ROOT
<commit_msg>update comment<commit_after>// @(#)root/mathcore:$Id$
// Author: L. Moneta Thu Sep 21 16:21:29 2006
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class FitConfig
#include "Fit/FitConfig.h"
#include "Math/IParamFunction.h"
#include "Math/Util.h"
#include "Math/Minimizer.h"
#include "Math/Factory.h"
#include <cmath>
#include <string>
#include <sstream>
#include "Math/Error.h"
//#define DEBUG
#ifdef DEBUG
#endif
#include <iostream>
namespace ROOT {
namespace Fit {
FitConfig::FitConfig(unsigned int npar) :
fNormErrors(false),
fParabErrors(false), // ensure that in any case correct parabolic errors are estimated
fMinosErrors(false), // do full Minos error analysis for all parameters
fSettings(std::vector<ParameterSettings>(npar) )
{
// constructor implementation
}
FitConfig::~FitConfig()
{
// destructor implementation. No Operations
}
FitConfig::FitConfig(const FitConfig &rhs) {
// Implementation of copy constructor
(*this) = rhs;
}
FitConfig & FitConfig::operator = (const FitConfig &rhs) {
// Implementation of assignment operator.
if (this == &rhs) return *this; // time saving self-test
fNormErrors = rhs.fNormErrors;
fParabErrors = rhs.fParabErrors;
fMinosErrors = rhs.fMinosErrors;
fSettings = rhs.fSettings;
fMinosParams = rhs.fMinosParams;
fMinimizerOpts = rhs.fMinimizerOpts;
return *this;
}
void FitConfig::SetParamsSettings(unsigned int npar, const double *params, const double * vstep ) {
// initialize FitConfig from given parameter values and step sizes
// if npar different than existing one - clear old one and create new ones
if (params == 0) {
fSettings = std::vector<ParameterSettings>(npar);
return;
}
// if a vector of parameters is given and parameters are not existing or are of different size
bool createNew = false;
if (npar != fSettings.size() ) {
fSettings.clear();
fSettings.reserve(npar);
createNew = true;
}
unsigned int i = 0;
const double * end = params+npar;
for (const double * ipar = params; ipar != end; ++ipar) {
double val = *ipar;
double step = 0;
if (vstep == 0) {
step = 0.3*std::fabs(val); // step size is 30% of par value
//double step = 2.0*std::fabs(val); // step size is 30% of par value
if (val == 0) step = 0.3;
}
else
step = vstep[i];
if (createNew)
fSettings.push_back( ParameterSettings("Par_" + ROOT::Math::Util::ToString(i), val, step ) );
else {
fSettings[i].SetValue(val);
fSettings[i].SetStepSize(step);
}
i++;
}
}
void FitConfig::CreateParamsSettings(const ROOT::Math::IParamMultiFunction & func) {
// initialize from model function
// set the parameters values from the function
unsigned int npar = func.NPar();
const double * begin = func.Parameters();
if (begin == 0) {
fSettings = std::vector<ParameterSettings>(npar);
return;
}
fSettings.clear();
fSettings.reserve(npar);
const double * end = begin+npar;
unsigned int i = 0;
for (const double * ipar = begin; ipar != end; ++ipar) {
double val = *ipar;
double step = 0.3*std::fabs(val); // step size is 30% of par value
//double step = 2.0*std::fabs(val); // step size is 30% of par value
if (val == 0) step = 0.3;
fSettings.push_back( ParameterSettings(func.ParameterName(i), val, step ) );
#ifdef DEBUG
std::cout << "FitConfig: add parameter " << func.ParameterName(i) << " val = " << val << std::endl;
#endif
i++;
}
}
ROOT::Math::Minimizer * FitConfig::CreateMinimizer() {
// create minimizer according to the chosen configuration using the
// plug-in manager
const std::string & minimType = fMinimizerOpts.MinimizerType();
const std::string & algoType = fMinimizerOpts.MinimizerAlgorithm();
std::string defaultMinim = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
ROOT::Math::Minimizer * min = ROOT::Math::Factory::CreateMinimizer(minimType, algoType);
// check if a different minimizer is used (in case a default value is passed, then set correctly in FitConfig)
const std::string & minim_newDefault = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
if (defaultMinim != minim_newDefault ) fMinimizerOpts.SetMinimizerType(minim_newDefault.c_str());
if (min == 0) {
// if creation of minimizer failed force the use by default of Minuit
std::string minim2 = "Minuit";
if (minimType == "Minuit") minim2 = "Minuit2";
if (minimType != minim2 ) {
std::string msg = "Could not create the " + minimType + " minimizer. Try using the minimizer " + minim2;
MATH_WARN_MSG("FitConfig::CreateMinimizer",msg.c_str());
min = ROOT::Math::Factory::CreateMinimizer(minim2,"Migrad");
if (min == 0) {
MATH_ERROR_MSG("FitConfig::CreateMinimizer","Could not create the Minuit2 minimizer");
return 0;
}
SetMinimizer( minim2.c_str(),"Migrad");
}
else {
std::string msg = "Could not create the Minimizer " + minimType;
MATH_ERROR_MSG("FitConfig::CreateMinimizer",msg.c_str());
return 0;
}
}
// set default max of function calls according to the number of parameters
// formula from Minuit2 (adapted)
if (fMinimizerOpts.MaxFunctionCalls() == 0) {
unsigned int npar = fSettings.size();
int maxfcn = 1000 + 100*npar + 5*npar*npar;
fMinimizerOpts.SetMaxFunctionCalls(maxfcn);
}
// set default minimizer control parameters
min->SetPrintLevel( fMinimizerOpts.PrintLevel() );
min->SetMaxFunctionCalls( fMinimizerOpts.MaxFunctionCalls() );
min->SetMaxIterations( fMinimizerOpts.MaxIterations() );
min->SetTolerance( fMinimizerOpts.Tolerance() );
min->SetPrecision( fMinimizerOpts.Precision() );
min->SetValidError( fParabErrors );
min->SetStrategy( fMinimizerOpts.Strategy() );
min->SetErrorDef( fMinimizerOpts.ErrorDef() );
return min;
}
void FitConfig::SetDefaultMinimizer(const char * type, const char *algo ) {
// set the default minimizer type and algorithms
ROOT::Math::MinimizerOptions::SetDefaultMinimizer(type, algo);
}
void FitConfig::SetMinimizerOptions(const ROOT::Math::MinimizerOptions & minopt) {
// set all the minimizer options
fMinimizerOpts = minopt;
}
} // end namespace Fit
} // end namespace ROOT
<|endoftext|>
|
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/dbmcsa_max_clique.hh>
#include <max_clique/colourise.hh>
#include <max_clique/print_incumbent.hh>
#include <threads/atomic_incumbent.hh>
#include <threads/queue.hh>
#include <graph/degree_sort.hh>
#include <graph/min_width_sort.hh>
#include <algorithm>
#include <list>
#include <functional>
#include <vector>
#include <thread>
using namespace parasols;
namespace
{
template <unsigned size_>
struct QueueItem
{
FixedBitSet<size_> c;
FixedBitSet<size_> p;
unsigned cn;
std::vector<int> position;
};
template <unsigned size_>
struct StealPoint
{
std::mutex mutex;
std::condition_variable cv;
bool ready = false;
FixedBitSet<size_> c;
FixedBitSet<size_> p;
std::vector<int> position;
int skip = 0;
bool was_stolen = false;
void not_ready()
{
std::unique_lock<std::mutex> guard(mutex);
ready = false;
was_stolen = false;
skip = 0;
}
void finished()
{
std::unique_lock<std::mutex> guard(mutex);
ready = true;
was_stolen = false;
skip = 0;
p = FixedBitSet<size_>();
cv.notify_all();
}
};
template <unsigned size_>
auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,
const FixedBitSet<size_> & c, int c_popcount,
const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,
const std::vector<int> & position) -> void
{
if (best_anywhere.update(c_popcount)) {
result.size = c_popcount;
result.members.clear();
for (int i = 0 ; i < graph.size() ; ++i)
if (c.test(i))
result.members.insert(o[i]);
print_incumbent(params, result.size, position);
}
}
auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool
{
unsigned best_anywhere_value = best_anywhere.get();
return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);
}
template <MaxCliqueOrder order_, unsigned size_>
auto expand(
const FixedBitGraph<size_> & graph,
const std::vector<int> & o, // vertex ordering
Queue<QueueItem<size_> > * const maybe_queue, // not null if we're populating: enqueue here
bool blocking_enqueue,
StealPoint<size_> * const steal_point,
StealPoint<size_> * const next_steal_point,
FixedBitSet<size_> & c, // current candidate clique
FixedBitSet<size_> & p, // potential additions
int skip,
MaxCliqueResult & result,
const MaxCliqueParams & params,
AtomicIncumbent & best_anywhere,
std::vector<int> & position) -> void
{
++result.nodes;
auto c_popcount = c.popcount();
// get our coloured vertices
std::array<unsigned, size_ * bits_per_word> p_order, colours;
colourise<size_>(graph, p, p_order, colours);
// for each v in p... (v comes later)
for (int n = p.popcount() - 1 ; n >= 0 ; --n) {
++position.back();
// bound, timeout or early exit?
if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())
return;
auto v = p_order[n];
// consider taking v
c.set(v);
++c_popcount;
if (skip > 0) {
--skip;
}
else {
// export stealable?
if (steal_point) {
std::unique_lock<std::mutex> guard(steal_point->mutex);
if (steal_point->was_stolen)
return;
if (! steal_point->ready) {
steal_point->c = c;
steal_point->p = p;
steal_point->position = position;
steal_point->skip = 0;
steal_point->was_stolen = false;
steal_point->ready = true;
steal_point->cv.notify_all();
}
++steal_point->skip;
}
// filter p to contain vertices adjacent to v
FixedBitSet<size_> new_p = p;
new_p = p;
graph.intersect_with_row(v, new_p);
if (new_p.empty())
found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);
else
{
if (maybe_queue) {
auto new_position = position;
new_position.push_back(0);
if (blocking_enqueue)
maybe_queue->enqueue_blocking(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) }, params.n_threads);
else
maybe_queue->enqueue(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) });
}
else {
position.push_back(0);
if (next_steal_point)
next_steal_point->not_ready();
expand<order_, size_>(graph, o, maybe_queue, false,
next_steal_point, nullptr,
c, new_p, 0, result, params, best_anywhere, position);
if (next_steal_point)
next_steal_point->not_ready();
position.pop_back();
}
}
}
// now consider not taking v
c.unset(v);
p.unset(v);
--c_popcount;
}
}
template <MaxCliqueOrder order_, unsigned size_>
auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult
{
Queue<QueueItem<size_> > queue{ params.n_threads, false, false }; // work queue
Queue<QueueItem<size_> > queue_2{ params.n_threads, false, false }; // work queue, depth 2
Queue<QueueItem<size_> > queue_3{ params.n_threads, false, false }; // work queue, depth 3
MaxCliqueResult result; // global result
std::mutex result_mutex;
AtomicIncumbent best_anywhere; // global incumbent
best_anywhere.update(params.initial_bound);
std::list<std::thread> threads; // populating thread, and workers
/* populate */
threads.push_back(std::thread([&] {
MaxCliqueResult tr; // local result
FixedBitSet<size_> tc; // local candidate clique
tc.resize(graph.size());
FixedBitSet<size_> tp; // local potential additions
tp.resize(graph.size());
tp.set_all();
std::vector<int> position;
position.reserve(graph.size());
position.push_back(0);
// populate!
expand<order_, size_>(graph, o, &queue, true, nullptr, nullptr,
tc, tp, 0, result, params, best_anywhere, position);
// merge results
queue.initial_producer_done();
std::unique_lock<std::mutex> guard(result_mutex);
result.merge(tr);
}));
/* steal points */
std::vector<StealPoint<size_> > steal_points_1((params.n_threads));
std::vector<StealPoint<size_> > steal_points_2((params.n_threads));
/* workers */
for (unsigned i = 0 ; i < params.n_threads ; ++i) {
threads.push_back(std::thread([&, i] {
auto start_time = std::chrono::steady_clock::now(); // local start time
MaxCliqueResult tr; // local result
auto * current_queue = &queue, next_queue = &queue_2, next_next_queue = &queue_3;
auto * current_steal_points = &steal_points_1, next_steal_points = &steal_points_2;
while (true) {
while (true) {
// get some work to do
QueueItem<size_> args;
if (! current_queue->dequeue_blocking(args))
break;
// re-evaluate the bound against our new best
if (args.cn <= best_anywhere.get())
continue;
if (current_steal_points)
(*current_steal_points)[i].not_ready();
if (next_steal_points)
(*next_steal_points)[i].not_ready();
// do some work
expand<order_, size_>(graph, o, nullptr, false,
current_steal_points ? &(*current_steal_points)[i] : nullptr,
next_steal_points ? &(*next_steal_points)[i] : nullptr,
args.c, args.p, 0, tr, params, best_anywhere, args.position);
if (current_steal_points)
(*current_steal_points)[i].not_ready();
if (next_steal_points)
(*next_steal_points)[i].not_ready();
}
if (current_steal_points)
(*current_steal_points)[i].finished();
if (next_steal_points)
(*next_steal_points)[i].finished();
if (! next_queue)
break;
if (next_queue->want_producer()) {
for (auto & s : *current_steal_points) {
std::unique_lock<std::mutex> guard(s.mutex);
while (! s.ready)
s.cv.wait(guard);
s.was_stolen = true;
auto c = s.c;
auto p = s.p;
auto skip = s.skip;
auto position = s.position;
guard.unlock();
expand<order_, size_>(graph, o, next_queue, false,
nullptr, nullptr,
c, p, skip, tr, params, best_anywhere, position);
}
next_queue->initial_producer_done();
}
current_queue = next_queue;
next_queue = next_next_queue;
next_next_queue = nullptr;
current_steal_points = next_steal_points;
next_steal_points = nullptr;
}
auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);
// merge results
{
std::unique_lock<std::mutex> guard(result_mutex);
result.merge(tr);
result.times.push_back(overall_time);
}
}));
}
// wait until they're done, and clean up threads
for (auto & t : threads)
t.join();
return result;
}
template <MaxCliqueOrder order_, unsigned size_>
auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
std::vector<int> o(graph.size()); // vertex ordering
std::iota(o.begin(), o.end(), 0);
switch (order_) {
case MaxCliqueOrder::Degree:
degree_sort(graph, o, false);
break;
case MaxCliqueOrder::MinWidth:
min_width_sort(graph, o, false);
break;
case MaxCliqueOrder::ExDegree:
exdegree_sort(graph, o, false);
break;
case MaxCliqueOrder::DynExDegree:
dynexdegree_sort(graph, o, false);
break;
}
// re-encode graph as a bit graph
FixedBitGraph<size_> bit_graph;
bit_graph.resize(graph.size());
for (int i = 0 ; i < graph.size() ; ++i)
for (int j = 0 ; j < graph.size() ; ++j)
if (graph.adjacent(o[i], o[j]))
bit_graph.add_edge(i, j);
// go!
return max_clique<order_>(bit_graph, o, params);
}
}
template <MaxCliqueOrder order_>
auto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
/* This is pretty horrible: in order to avoid dynamic allocation, select
* the appropriate specialisation for our graph's size. */
static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed.");
if (graph.size() < bits_per_word)
return dbmcsa<order_, 1>(graph, params);
else if (graph.size() < 2 * bits_per_word)
return dbmcsa<order_, 2>(graph, params);
else if (graph.size() < 4 * bits_per_word)
return dbmcsa<order_, 4>(graph, params);
else if (graph.size() < 8 * bits_per_word)
return dbmcsa<order_, 8>(graph, params);
else if (graph.size() < 16 * bits_per_word)
return dbmcsa<order_, 16>(graph, params);
else if (graph.size() < 32 * bits_per_word)
return dbmcsa<order_, 32>(graph, params);
else if (graph.size() < 64 * bits_per_word)
return dbmcsa<order_, 64>(graph, params);
else if (graph.size() < 128 * bits_per_word)
return dbmcsa<order_, 128>(graph, params);
else if (graph.size() < 256 * bits_per_word)
return dbmcsa<order_, 256>(graph, params);
else if (graph.size() < 512 * bits_per_word)
return dbmcsa<order_, 512>(graph, params);
else if (graph.size() < 1024 * bits_per_word)
return dbmcsa<order_, 1024>(graph, params);
else
throw GraphTooBig();
}
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<commit_msg>Avoid possible overlap between c and p<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_clique/dbmcsa_max_clique.hh>
#include <max_clique/colourise.hh>
#include <max_clique/print_incumbent.hh>
#include <threads/atomic_incumbent.hh>
#include <threads/queue.hh>
#include <graph/degree_sort.hh>
#include <graph/min_width_sort.hh>
#include <algorithm>
#include <list>
#include <functional>
#include <vector>
#include <thread>
using namespace parasols;
namespace
{
template <unsigned size_>
struct QueueItem
{
FixedBitSet<size_> c;
FixedBitSet<size_> p;
unsigned cn;
std::vector<int> position;
};
template <unsigned size_>
struct StealPoint
{
std::mutex mutex;
std::condition_variable cv;
bool ready = false;
FixedBitSet<size_> c;
FixedBitSet<size_> p;
std::vector<int> position;
int skip = 0;
bool was_stolen = false;
void not_ready()
{
std::unique_lock<std::mutex> guard(mutex);
ready = false;
was_stolen = false;
skip = 0;
}
void finished()
{
std::unique_lock<std::mutex> guard(mutex);
ready = true;
was_stolen = false;
skip = 0;
p = FixedBitSet<size_>();
cv.notify_all();
}
};
template <unsigned size_>
auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,
const FixedBitSet<size_> & c, int c_popcount,
const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,
const std::vector<int> & position) -> void
{
if (best_anywhere.update(c_popcount)) {
result.size = c_popcount;
result.members.clear();
for (int i = 0 ; i < graph.size() ; ++i)
if (c.test(i))
result.members.insert(o[i]);
print_incumbent(params, result.size, position);
}
}
auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool
{
unsigned best_anywhere_value = best_anywhere.get();
return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);
}
template <MaxCliqueOrder order_, unsigned size_>
auto expand(
const FixedBitGraph<size_> & graph,
const std::vector<int> & o, // vertex ordering
Queue<QueueItem<size_> > * const maybe_queue, // not null if we're populating: enqueue here
bool blocking_enqueue,
StealPoint<size_> * const steal_point,
StealPoint<size_> * const next_steal_point,
FixedBitSet<size_> & c, // current candidate clique
FixedBitSet<size_> & p, // potential additions
int skip,
MaxCliqueResult & result,
const MaxCliqueParams & params,
AtomicIncumbent & best_anywhere,
std::vector<int> & position) -> void
{
++result.nodes;
auto c_popcount = c.popcount();
// get our coloured vertices
std::array<unsigned, size_ * bits_per_word> p_order, colours;
colourise<size_>(graph, p, p_order, colours);
// for each v in p... (v comes later)
for (int n_start = p.popcount() - 1, n = n_start ; n >= 0 ; --n) {
++position.back();
// bound, timeout or early exit?
if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())
return;
auto v = p_order[n];
// consider taking v
if (skip > 0) {
--skip;
// just go straight to considering not taking v
p.unset(v);
}
else {
// export stealable?
if (steal_point) {
std::unique_lock<std::mutex> guard(steal_point->mutex);
if (steal_point->was_stolen)
return;
if (! steal_point->ready) {
steal_point->c = c;
steal_point->p = p;
steal_point->position = position;
steal_point->skip = 0;
steal_point->was_stolen = false;
steal_point->ready = true;
steal_point->cv.notify_all();
}
++steal_point->skip;
}
// consider taking v
c.set(v);
++c_popcount;
// filter p to contain vertices adjacent to v
FixedBitSet<size_> new_p = p;
new_p = p;
graph.intersect_with_row(v, new_p);
if (new_p.empty())
found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);
else
{
if (maybe_queue) {
auto new_position = position;
new_position.push_back(0);
if (blocking_enqueue)
maybe_queue->enqueue_blocking(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) }, params.n_threads);
else
maybe_queue->enqueue(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) });
}
else {
position.push_back(0);
if (next_steal_point)
next_steal_point->not_ready();
expand<order_, size_>(graph, o, maybe_queue, false,
next_steal_point, nullptr,
c, new_p, 0, result, params, best_anywhere, position);
if (next_steal_point)
next_steal_point->not_ready();
position.pop_back();
}
}
// now consider not taking v
c.unset(v);
p.unset(v);
--c_popcount;
}
}
}
template <MaxCliqueOrder order_, unsigned size_>
auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult
{
Queue<QueueItem<size_> > queue{ params.n_threads, false, false }; // work queue
Queue<QueueItem<size_> > queue_2{ params.n_threads, false, false }; // work queue, depth 2
Queue<QueueItem<size_> > queue_3{ params.n_threads, false, false }; // work queue, depth 3
MaxCliqueResult result; // global result
std::mutex result_mutex;
AtomicIncumbent best_anywhere; // global incumbent
best_anywhere.update(params.initial_bound);
std::list<std::thread> threads; // populating thread, and workers
/* populate */
threads.push_back(std::thread([&] {
MaxCliqueResult tr; // local result
FixedBitSet<size_> tc; // local candidate clique
tc.resize(graph.size());
FixedBitSet<size_> tp; // local potential additions
tp.resize(graph.size());
tp.set_all();
std::vector<int> position;
position.reserve(graph.size());
position.push_back(0);
// populate!
expand<order_, size_>(graph, o, &queue, true, nullptr, nullptr,
tc, tp, 0, result, params, best_anywhere, position);
// merge results
queue.initial_producer_done();
std::unique_lock<std::mutex> guard(result_mutex);
result.merge(tr);
}));
/* steal points */
std::vector<StealPoint<size_> > steal_points_1((params.n_threads));
std::vector<StealPoint<size_> > steal_points_2((params.n_threads));
/* workers */
for (unsigned i = 0 ; i < params.n_threads ; ++i) {
threads.push_back(std::thread([&, i] {
auto start_time = std::chrono::steady_clock::now(); // local start time
MaxCliqueResult tr; // local result
auto * current_queue = &queue, next_queue = &queue_2, next_next_queue = &queue_3;
auto * current_steal_points = &steal_points_1, next_steal_points = &steal_points_2;
while (true) {
while (true) {
// get some work to do
QueueItem<size_> args;
if (! current_queue->dequeue_blocking(args))
break;
// re-evaluate the bound against our new best
if (args.cn <= best_anywhere.get())
continue;
if (current_steal_points)
(*current_steal_points)[i].not_ready();
if (next_steal_points)
(*next_steal_points)[i].not_ready();
// do some work
expand<order_, size_>(graph, o, nullptr, false,
current_steal_points ? &(*current_steal_points)[i] : nullptr,
next_steal_points ? &(*next_steal_points)[i] : nullptr,
args.c, args.p, 0, tr, params, best_anywhere, args.position);
if (current_steal_points)
(*current_steal_points)[i].not_ready();
if (next_steal_points)
(*next_steal_points)[i].not_ready();
}
if (current_steal_points)
(*current_steal_points)[i].finished();
if (next_steal_points)
(*next_steal_points)[i].finished();
if (! next_queue)
break;
if (next_queue->want_producer()) {
for (auto & s : *current_steal_points) {
std::unique_lock<std::mutex> guard(s.mutex);
while (! s.ready)
s.cv.wait(guard);
s.was_stolen = true;
auto c = s.c;
auto p = s.p;
auto skip = s.skip;
auto position = s.position;
guard.unlock();
expand<order_, size_>(graph, o, next_queue, false,
nullptr, nullptr,
c, p, skip, tr, params, best_anywhere, position);
}
next_queue->initial_producer_done();
}
current_queue = next_queue;
next_queue = next_next_queue;
next_next_queue = nullptr;
current_steal_points = next_steal_points;
next_steal_points = nullptr;
}
auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);
// merge results
{
std::unique_lock<std::mutex> guard(result_mutex);
result.merge(tr);
result.times.push_back(overall_time);
}
}));
}
// wait until they're done, and clean up threads
for (auto & t : threads)
t.join();
return result;
}
template <MaxCliqueOrder order_, unsigned size_>
auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
std::vector<int> o(graph.size()); // vertex ordering
std::iota(o.begin(), o.end(), 0);
switch (order_) {
case MaxCliqueOrder::Degree:
degree_sort(graph, o, false);
break;
case MaxCliqueOrder::MinWidth:
min_width_sort(graph, o, false);
break;
case MaxCliqueOrder::ExDegree:
exdegree_sort(graph, o, false);
break;
case MaxCliqueOrder::DynExDegree:
dynexdegree_sort(graph, o, false);
break;
}
// re-encode graph as a bit graph
FixedBitGraph<size_> bit_graph;
bit_graph.resize(graph.size());
for (int i = 0 ; i < graph.size() ; ++i)
for (int j = 0 ; j < graph.size() ; ++j)
if (graph.adjacent(o[i], o[j]))
bit_graph.add_edge(i, j);
// go!
return max_clique<order_>(bit_graph, o, params);
}
}
template <MaxCliqueOrder order_>
auto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult
{
/* This is pretty horrible: in order to avoid dynamic allocation, select
* the appropriate specialisation for our graph's size. */
static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed.");
if (graph.size() < bits_per_word)
return dbmcsa<order_, 1>(graph, params);
else if (graph.size() < 2 * bits_per_word)
return dbmcsa<order_, 2>(graph, params);
else if (graph.size() < 4 * bits_per_word)
return dbmcsa<order_, 4>(graph, params);
else if (graph.size() < 8 * bits_per_word)
return dbmcsa<order_, 8>(graph, params);
else if (graph.size() < 16 * bits_per_word)
return dbmcsa<order_, 16>(graph, params);
else if (graph.size() < 32 * bits_per_word)
return dbmcsa<order_, 32>(graph, params);
else if (graph.size() < 64 * bits_per_word)
return dbmcsa<order_, 64>(graph, params);
else if (graph.size() < 128 * bits_per_word)
return dbmcsa<order_, 128>(graph, params);
else if (graph.size() < 256 * bits_per_word)
return dbmcsa<order_, 256>(graph, params);
else if (graph.size() < 512 * bits_per_word)
return dbmcsa<order_, 512>(graph, params);
else if (graph.size() < 1024 * bits_per_word)
return dbmcsa<order_, 1024>(graph, params);
else
throw GraphTooBig();
}
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;
<|endoftext|>
|
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBlendModePriv.h"
#include "SkRasterPipeline.h"
#include "../jumper/SkJumper.h"
bool SkBlendMode_SupportsCoverageAsAlpha(SkBlendMode mode) {
switch (mode) {
case SkBlendMode::kDst:
case SkBlendMode::kSrcOver:
case SkBlendMode::kDstOver:
case SkBlendMode::kDstOut:
case SkBlendMode::kSrcATop:
case SkBlendMode::kXor:
case SkBlendMode::kPlus:
return true;
default:
break;
}
return false;
}
struct CoeffRec {
SkBlendModeCoeff fSrc;
SkBlendModeCoeff fDst;
};
const CoeffRec gCoeffs[] = {
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kDA, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kSA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kDA, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kSA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kSC },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kISC }, // screen
};
bool SkBlendMode_AsCoeff(SkBlendMode mode, SkBlendModeCoeff* src, SkBlendModeCoeff* dst) {
if (mode > SkBlendMode::kScreen) {
return false;
}
if (src) {
*src = gCoeffs[static_cast<int>(mode)].fSrc;
}
if (dst) {
*dst = gCoeffs[static_cast<int>(mode)].fDst;
}
return true;
}
bool SkBlendMode_ShouldPreScaleCoverage(SkBlendMode mode, bool rgb_coverage) {
// The most important things we do here are:
// - always use pre-scaling for plus mode;
// - never use pre-scaling for srcover with 565 coverage.
return mode == SkBlendMode::kPlus ||
(mode == SkBlendMode::kSrcOver && !rgb_coverage);
}
void SkBlendMode_AppendStages(SkBlendMode mode, SkRasterPipeline* p) {
auto stage = SkRasterPipeline::srcover;
switch (mode) {
case SkBlendMode::kClear: stage = SkRasterPipeline::clear; break;
case SkBlendMode::kSrc: return; // This stage is a no-op.
case SkBlendMode::kDst: stage = SkRasterPipeline::move_dst_src; break;
case SkBlendMode::kSrcOver: stage = SkRasterPipeline::srcover; break;
case SkBlendMode::kDstOver: stage = SkRasterPipeline::dstover; break;
case SkBlendMode::kSrcIn: stage = SkRasterPipeline::srcin; break;
case SkBlendMode::kDstIn: stage = SkRasterPipeline::dstin; break;
case SkBlendMode::kSrcOut: stage = SkRasterPipeline::srcout; break;
case SkBlendMode::kDstOut: stage = SkRasterPipeline::dstout; break;
case SkBlendMode::kSrcATop: stage = SkRasterPipeline::srcatop; break;
case SkBlendMode::kDstATop: stage = SkRasterPipeline::dstatop; break;
case SkBlendMode::kXor: stage = SkRasterPipeline::xor_; break;
case SkBlendMode::kPlus: stage = SkRasterPipeline::plus_; break;
case SkBlendMode::kModulate: stage = SkRasterPipeline::modulate; break;
case SkBlendMode::kScreen: stage = SkRasterPipeline::screen; break;
case SkBlendMode::kOverlay: stage = SkRasterPipeline::overlay; break;
case SkBlendMode::kDarken: stage = SkRasterPipeline::darken; break;
case SkBlendMode::kLighten: stage = SkRasterPipeline::lighten; break;
case SkBlendMode::kColorDodge: stage = SkRasterPipeline::colordodge; break;
case SkBlendMode::kColorBurn: stage = SkRasterPipeline::colorburn; break;
case SkBlendMode::kHardLight: stage = SkRasterPipeline::hardlight; break;
case SkBlendMode::kSoftLight: stage = SkRasterPipeline::softlight; break;
case SkBlendMode::kDifference: stage = SkRasterPipeline::difference; break;
case SkBlendMode::kExclusion: stage = SkRasterPipeline::exclusion; break;
case SkBlendMode::kMultiply: stage = SkRasterPipeline::multiply; break;
case SkBlendMode::kHue: stage = SkRasterPipeline::hue; break;
case SkBlendMode::kSaturation: stage = SkRasterPipeline::saturation; break;
case SkBlendMode::kColor: stage = SkRasterPipeline::color; break;
case SkBlendMode::kLuminosity: stage = SkRasterPipeline::luminosity; break;
}
p->append(stage);
}
SkPM4f SkBlendMode_Apply(SkBlendMode mode, const SkPM4f& src, const SkPM4f& dst) {
// special-case simple/common modes...
switch (mode) {
case SkBlendMode::kClear: return {{ 0, 0, 0, 0 }};
case SkBlendMode::kSrc: return src;
case SkBlendMode::kDst: return dst;
case SkBlendMode::kSrcOver:
return SkPM4f::From4f(src.to4f() + dst.to4f() * Sk4f(1 - src.a()));
default:
break;
}
SkRasterPipeline_<256> p;
SkPM4f src_storage = src,
dst_storage = dst,
res_storage;
SkJumper_MemoryCtx src_ctx = { &src_storage, 0 },
dst_ctx = { &dst_storage, 0 },
res_ctx = { &res_storage, 0 };
p.append(SkRasterPipeline::load_f32, &dst_ctx);
p.append(SkRasterPipeline::move_src_dst);
p.append(SkRasterPipeline::load_f32, &src_ctx);
SkBlendMode_AppendStages(mode, &p);
p.append(SkRasterPipeline::store_f32, &res_ctx);
p.run(0,0, 1,1);
return res_storage;
}
<commit_msg>Post-lerp -> pre-scale if blend mode supports it.<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBlendModePriv.h"
#include "SkRasterPipeline.h"
#include "../jumper/SkJumper.h"
bool SkBlendMode_ShouldPreScaleCoverage(SkBlendMode mode, bool rgb_coverage) {
// The most important things we do here are:
// 1) never pre-scale with rgb coverage if the blend mode involves a source-alpha term;
// 2) always pre-scale Plus.
//
// When we pre-scale with rgb coverage, we scale each of source r,g,b, with a distinct value,
// and source alpha with one of those three values. This process destructively updates the
// source-alpha term, so we can't evaluate blend modes that need its original value.
//
// Plus always requires pre-scaling as a specific quirk of its implementation in
// SkRasterPipeline. This lets us put the clamp inside the blend mode itself rather
// than as a separate stage that'd come after the lerp.
//
// This function is a finer-grained breakdown of SkBlendMode_SupportsCoverageAsAlpha().
switch (mode) {
case SkBlendMode::kDst: // d --> no sa term, ok!
case SkBlendMode::kDstOver: // d + s*inv(da) --> no sa term, ok!
case SkBlendMode::kPlus: // clamp(s+d) --> no sa term, ok!
return true;
case SkBlendMode::kDstOut: // d * inv(sa)
case SkBlendMode::kSrcATop: // s*da + d*inv(sa)
case SkBlendMode::kSrcOver: // s + d*inv(sa)
case SkBlendMode::kXor: // s*inv(da) + d*inv(sa)
return !rgb_coverage;
default: break;
}
return false;
}
// Users of this function may want to switch to the rgb-coverage aware version above.
bool SkBlendMode_SupportsCoverageAsAlpha(SkBlendMode mode) {
return SkBlendMode_ShouldPreScaleCoverage(mode, false);
}
struct CoeffRec {
SkBlendModeCoeff fSrc;
SkBlendModeCoeff fDst;
};
const CoeffRec gCoeffs[] = {
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kDA, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kSA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kZero },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kDA, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kSA },
{ SkBlendModeCoeff::kIDA, SkBlendModeCoeff::kISA },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kOne },
{ SkBlendModeCoeff::kZero, SkBlendModeCoeff::kSC },
{ SkBlendModeCoeff::kOne, SkBlendModeCoeff::kISC }, // screen
};
bool SkBlendMode_AsCoeff(SkBlendMode mode, SkBlendModeCoeff* src, SkBlendModeCoeff* dst) {
if (mode > SkBlendMode::kScreen) {
return false;
}
if (src) {
*src = gCoeffs[static_cast<int>(mode)].fSrc;
}
if (dst) {
*dst = gCoeffs[static_cast<int>(mode)].fDst;
}
return true;
}
void SkBlendMode_AppendStages(SkBlendMode mode, SkRasterPipeline* p) {
auto stage = SkRasterPipeline::srcover;
switch (mode) {
case SkBlendMode::kClear: stage = SkRasterPipeline::clear; break;
case SkBlendMode::kSrc: return; // This stage is a no-op.
case SkBlendMode::kDst: stage = SkRasterPipeline::move_dst_src; break;
case SkBlendMode::kSrcOver: stage = SkRasterPipeline::srcover; break;
case SkBlendMode::kDstOver: stage = SkRasterPipeline::dstover; break;
case SkBlendMode::kSrcIn: stage = SkRasterPipeline::srcin; break;
case SkBlendMode::kDstIn: stage = SkRasterPipeline::dstin; break;
case SkBlendMode::kSrcOut: stage = SkRasterPipeline::srcout; break;
case SkBlendMode::kDstOut: stage = SkRasterPipeline::dstout; break;
case SkBlendMode::kSrcATop: stage = SkRasterPipeline::srcatop; break;
case SkBlendMode::kDstATop: stage = SkRasterPipeline::dstatop; break;
case SkBlendMode::kXor: stage = SkRasterPipeline::xor_; break;
case SkBlendMode::kPlus: stage = SkRasterPipeline::plus_; break;
case SkBlendMode::kModulate: stage = SkRasterPipeline::modulate; break;
case SkBlendMode::kScreen: stage = SkRasterPipeline::screen; break;
case SkBlendMode::kOverlay: stage = SkRasterPipeline::overlay; break;
case SkBlendMode::kDarken: stage = SkRasterPipeline::darken; break;
case SkBlendMode::kLighten: stage = SkRasterPipeline::lighten; break;
case SkBlendMode::kColorDodge: stage = SkRasterPipeline::colordodge; break;
case SkBlendMode::kColorBurn: stage = SkRasterPipeline::colorburn; break;
case SkBlendMode::kHardLight: stage = SkRasterPipeline::hardlight; break;
case SkBlendMode::kSoftLight: stage = SkRasterPipeline::softlight; break;
case SkBlendMode::kDifference: stage = SkRasterPipeline::difference; break;
case SkBlendMode::kExclusion: stage = SkRasterPipeline::exclusion; break;
case SkBlendMode::kMultiply: stage = SkRasterPipeline::multiply; break;
case SkBlendMode::kHue: stage = SkRasterPipeline::hue; break;
case SkBlendMode::kSaturation: stage = SkRasterPipeline::saturation; break;
case SkBlendMode::kColor: stage = SkRasterPipeline::color; break;
case SkBlendMode::kLuminosity: stage = SkRasterPipeline::luminosity; break;
}
p->append(stage);
}
SkPM4f SkBlendMode_Apply(SkBlendMode mode, const SkPM4f& src, const SkPM4f& dst) {
// special-case simple/common modes...
switch (mode) {
case SkBlendMode::kClear: return {{ 0, 0, 0, 0 }};
case SkBlendMode::kSrc: return src;
case SkBlendMode::kDst: return dst;
case SkBlendMode::kSrcOver:
return SkPM4f::From4f(src.to4f() + dst.to4f() * Sk4f(1 - src.a()));
default:
break;
}
SkRasterPipeline_<256> p;
SkPM4f src_storage = src,
dst_storage = dst,
res_storage;
SkJumper_MemoryCtx src_ctx = { &src_storage, 0 },
dst_ctx = { &dst_storage, 0 },
res_ctx = { &res_storage, 0 };
p.append(SkRasterPipeline::load_f32, &dst_ctx);
p.append(SkRasterPipeline::move_src_dst);
p.append(SkRasterPipeline::load_f32, &src_ctx);
SkBlendMode_AppendStages(mode, &p);
p.append(SkRasterPipeline::store_f32, &res_ctx);
p.run(0,0, 1,1);
return res_storage;
}
<|endoftext|>
|
<commit_before>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener listener) :
Scope(listener), angles() {}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener(Move<arg1type,arg2type,restype>(MoveType::movetype, arg1, arg2, res)); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b))
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, Point, &b, Point, res, Line);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);
}
return res;
}
#undef _make_move
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
const Line &l1 (l); // ensure containment for line segments
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr);
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = pair.first == o1 ? pair.second : pair.first;
assert(o2 != nullptr);
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(c1 != nullptr);
assert(c2 != nullptr);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.first != nullptr);
assert(pair.second != nullptr);
assert(*pair.first != *pair.second); // c1 and c2 are different
return join_line(*pair.first, *pair.second);
// the deletion of all these items are to be handled by ~Scope()
}
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
assert(diff != nullptr);
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
res = new LineSegment(start, *end);
Scope::add(res);
return res;
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr || c1 == c2)
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second);
}
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
const Line *Constructor::bisect(const Angle &a)
{
if (a.l1 == a.l2)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1);
auto _meet = meet(a.l2, *c);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;
return join_line(*p1, *p2);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
// TODO
// - Translate l to the vertex of a, call the new segment l1
// - Draw circle with center l1.start and touching l1.end
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
// - Find perpendicular bisector to l1.end and p2
// - Reflect p1 around the bisector
// - Connect l1.start with p1 and translate the new line segment back to l.start
return nullptr;
}
<commit_msg>Added reflect functions<commit_after>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener listener) :
Scope(listener), angles() {}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener(Move<arg1type,arg2type,restype>(MoveType::movetype, arg1, arg2, res)); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b))
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, Point, &b, Point, res, Line);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);
}
return res;
}
#undef _make_move
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
const Line &l1 (l); // ensure containment for line segments
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr);
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = pair.first == o1 ? pair.second : pair.first;
assert(o2 != nullptr);
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(c1 != nullptr);
assert(c2 != nullptr);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.first != nullptr);
assert(pair.second != nullptr);
assert(*pair.first != *pair.second); // c1 and c2 are different
return join_line(*pair.first, *pair.second);
// the deletion of all these items are to be handled by ~Scope()
}
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
assert(diff != nullptr);
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
res = new LineSegment(start, *end);
Scope::add(res);
return res;
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr || c1 == c2)
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second);
}
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
const Line *Constructor::bisect(const Angle &a)
{
if (a.l1 == a.l2)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1);
auto _meet = meet(a.l2, *c);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;
return join_line(*p1, *p2);
}
const Point *Constructor::reflect(const Point &a, const Point &pivot)
{
const Line *l = join_line(a, pivot);
const Circle *c = join_circle(pivot, a);
auto _meet = meet(*l, *c);
if (_meet.first == nullptr || _meet.second == nullptr)
return nullptr;
return *_meet.first == a ? _meet.second : _meet.first;
}
const Point *Constructor::reflect(const Point &a, const Line &pivot)
{
const Line &p (pivot), // override within_boundary
*l = perpendicular(p, a);
if (l == nullptr)
return nullptr;
const Point *c = meet(p, *l);
if (c == nullptr)
return nullptr;
return reflect(a, *c);
}
const Line *Constructor::reflect(const Line &a, const Point &pivot)
{
const Line &l (a),
*p = perpendicular(l, pivot);
if (p == nullptr)
return nullptr;
const Point *b = reflect(*meet(l, *p), pivot);
if (b == nullptr)
return nullptr;
return perpendicular(*p, *b);
}
const Line *Constructor::reflect(const Line &a, const Line &pivot)
{
// different cases for a and pivot being parallel or not
const Point *vertex = meet(a, pivot), *p1 = nullptr;
if (vertex == nullptr) { // parallel
// find point on pivot
for (auto *p : points)
if (pivot.contains(*p)) { p1 = p; break; }
assert(p1 != nullptr);
// reflect a by p1
return reflect(a, *p1);
}
// not parallel
// find point on a
for (auto *p : points)
if (a.contains(*p) && *p != *vertex) { p1 = p; break; }
assert(p1 != nullptr);
// reflect p1 around pivot
const Point *p = reflect(*p1, pivot);
if (p == nullptr)
return nullptr;
return join_line(*vertex, *p);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
// TODO
// - Translate l to the vertex of a, call the new segment l1
// - Draw circle with center l1.start and touching l1.end
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
// - Find perpendicular bisector to l1.end and p2
// - Reflect p1 around the bisector
// - Connect l1.start with p1 and translate the new line segment back to l.start
return nullptr;
}
<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* 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 <cstring>
#include "qhttpsocket.h"
#include "qhttpsocket_p.h"
QHttpSocketPrivate::QHttpSocketPrivate(QHttpSocket *httpSocket, QTcpSocket *tcpSocket)
: QObject(httpSocket),
q(httpSocket),
socket(tcpSocket),
readState(ReadHeaders),
requestDataRead(0),
writeState(WriteNone),
responseStatusCode("200 OK")
{
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(onBytesWritten(qint64)));
connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
// Process anything already received by the socket
onReadyRead();
}
void QHttpSocketPrivate::onReadyRead()
{
// Append all of the new data to the read buffer
readBuffer.append(socket->readAll());
if(readState == ReadHeaders) {
if(!readHeaders()) {
return;
}
}
if(readState == ReadData) {
readData();
}
if(readState == ReadFinished) {
readBuffer.clear();
}
}
void QHttpSocketPrivate::onBytesWritten(qint64 bytes)
{
// Check to see if all of the response header was written
if(writeState == WriteHeaders) {
if(responseHeaderRemaining - bytes > 0) {
responseHeaderRemaining -= bytes;
} else {
writeState = WriteData;
bytes -= responseHeaderRemaining;
}
}
if(writeState == WriteData) {
Q_EMIT q->bytesWritten(bytes);
}
}
void QHttpSocketPrivate::onDisconnected()
{
// The socket should not be disconnected until both the reading and
// writing have completed - if so, an error has occurred
if(readState != ReadFinished || writeState != WriteFinished) {
Q_EMIT q->error();
q->setOpenMode(QIODevice::NotOpen);
}
Q_EMIT q->disconnected();
}
bool QHttpSocketPrivate::readHeaders()
{
// Check for the double CRLF that signals the end of the headers and
// if it is not found, wait until the next time readyRead is emitted
int index = readBuffer.indexOf("\r\n\r\n");
if(index == -1) {
return false;
}
// Attempt to parse the headers and if a problem is encountered, abort
// the connection (so that no more data is read or written) and return
if(!QHttpParser::parseRequestHeaders(readBuffer.left(index), requestMethod, requestPath, requestHeaders)) {
socket->abort();
return false;
}
// Check for the content-length header - if it is present, then
// prepare to read the specified amount of data, otherwise, no data
// should be read from the socket and the read channel is finished
if(requestHeaders.contains("Content-Length")) {
readState = ReadData;
requestDataTotal = requestHeaders.value("Content-Length").toLongLong();
} else {
readState = ReadFinished;
Q_EMIT q->readChannelFinished();
}
// Indicate that the headers have been parsed
Q_EMIT q->headersParsed();
return true;
}
void QHttpSocketPrivate::readData()
{
Q_EMIT q->readyRead();
// Check to see if the specified amount of data has been read from the
// socket, if so, emit the readChannelFinished() signal
if(requestDataRead + readBuffer.size() >= requestDataTotal) {
readState = ReadFinished;
Q_EMIT q->readChannelFinished();
}
}
QHttpSocket::QHttpSocket(QTcpSocket *socket, QObject *parent)
: QIODevice(parent),
d(new QHttpSocketPrivate(this, socket))
{
// The device is initially open for both reading and writing
setOpenMode(QIODevice::ReadWrite);
}
qint64 QHttpSocket::bytesAvailable() const
{
return d->readBuffer.size() + QIODevice::bytesAvailable();
}
bool QHttpSocket::isSequential() const
{
return true;
}
void QHttpSocket::close()
{
// Invoke the parent method
QIODevice::close();
d->readState = QHttpSocketPrivate::ReadFinished;
d->writeState = QHttpSocketPrivate::WriteFinished;
d->socket->close();
}
QByteArray QHttpSocket::method() const
{
return d->requestMethod;
}
QByteArray QHttpSocket::path() const
{
return d->requestPath;
}
QHttpHeaderMap &QHttpSocket::headers() const
{
return d->requestHeaders;
}
void QHttpSocket::setStatusCode(const QByteArray &statusCode)
{
d->responseStatusCode = statusCode;
}
void QHttpSocket::setHeader(const QByteArray &name, const QByteArray &value)
{
d->responseHeaders.insert(name, value);
}
void QHttpSocket::setHeaders(const QHttpHeaderMap &headers)
{
d->responseHeaders = headers;
}
void QHttpSocket::writeHeaders()
{
// Use a QByteArray for building the header so that we can later determine
// exactly how many bytes were written
QByteArray header;
// Append the status line
header.append("HTTP/1.0 ");
header.append(d->responseStatusCode);
header.append("\r\n");
// Append each of the headers followed by a CRLF
for(QHttpHeaderMap::const_iterator i = d->responseHeaders.constBegin(); i != d->responseHeaders.constEnd(); ++i) {
header.append(i.key());
header.append(": ");
header.append(i.value());
header.append("\r\n");
}
// Append an extra CRLF
header.append("\r\n");
d->writeState = QHttpSocketPrivate::WriteHeaders;
d->responseHeaderRemaining = header.length();
// Write the header
d->socket->write(header);
}
qint64 QHttpSocket::readData(char *data, qint64 maxlen)
{
// Ensure the connection is in the correct state for reading data
if(d->readState != QHttpSocketPrivate::ReadData) {
return 0;
}
// Ensure that no more than the requested amount or the size of the buffer is read
qint64 size = qMin(static_cast<qint64>(d->readBuffer.size()), maxlen);
memcpy(data, d->readBuffer.constData(), size);
// Remove the amount that was read from the buffer
d->readBuffer.remove(0, size);
d->requestDataRead += size;
return size;
}
qint64 QHttpSocket::writeData(const char *data, qint64 len)
{
// If the response headers have not yet been written, they must
// immediately be written before the data can be
if(d->writeState == QHttpSocketPrivate::WriteNone) {
writeHeaders();
}
return d->socket->write(data, len);
}
<commit_msg>Fixed issue with headers being read as data in QHttpSocket class.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* 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 <cstring>
#include "qhttpsocket.h"
#include "qhttpsocket_p.h"
QHttpSocketPrivate::QHttpSocketPrivate(QHttpSocket *httpSocket, QTcpSocket *tcpSocket)
: QObject(httpSocket),
q(httpSocket),
socket(tcpSocket),
readState(ReadHeaders),
requestDataRead(0),
writeState(WriteNone),
responseStatusCode("200 OK")
{
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(onBytesWritten(qint64)));
connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
// Process anything already received by the socket
onReadyRead();
}
void QHttpSocketPrivate::onReadyRead()
{
// Append all of the new data to the read buffer
readBuffer.append(socket->readAll());
if(readState == ReadHeaders) {
if(!readHeaders()) {
return;
}
}
if(readState == ReadData) {
readData();
}
if(readState == ReadFinished) {
readBuffer.clear();
}
}
void QHttpSocketPrivate::onBytesWritten(qint64 bytes)
{
// Check to see if all of the response header was written
if(writeState == WriteHeaders) {
if(responseHeaderRemaining - bytes > 0) {
responseHeaderRemaining -= bytes;
} else {
writeState = WriteData;
bytes -= responseHeaderRemaining;
}
}
if(writeState == WriteData) {
Q_EMIT q->bytesWritten(bytes);
}
}
void QHttpSocketPrivate::onDisconnected()
{
// The socket should not be disconnected until both the reading and
// writing have completed - if so, an error has occurred
if(readState != ReadFinished || writeState != WriteFinished) {
Q_EMIT q->error();
q->setOpenMode(QIODevice::NotOpen);
}
Q_EMIT q->disconnected();
}
bool QHttpSocketPrivate::readHeaders()
{
// Check for the double CRLF that signals the end of the headers and
// if it is not found, wait until the next time readyRead is emitted
int index = readBuffer.indexOf("\r\n\r\n");
if(index == -1) {
return false;
}
// Attempt to parse the headers and if a problem is encountered, abort
// the connection (so that no more data is read or written) and return
if(!QHttpParser::parseRequestHeaders(readBuffer.left(index), requestMethod, requestPath, requestHeaders)) {
socket->abort();
return false;
}
// Remove the headers from the buffer
readBuffer.remove(0, index + 4);
// Check for the content-length header - if it is present, then
// prepare to read the specified amount of data, otherwise, no data
// should be read from the socket and the read channel is finished
if(requestHeaders.contains("Content-Length")) {
readState = ReadData;
requestDataTotal = requestHeaders.value("Content-Length").toLongLong();
} else {
readState = ReadFinished;
Q_EMIT q->readChannelFinished();
}
// Indicate that the headers have been parsed
Q_EMIT q->headersParsed();
return true;
}
void QHttpSocketPrivate::readData()
{
Q_EMIT q->readyRead();
// Check to see if the specified amount of data has been read from the
// socket, if so, emit the readChannelFinished() signal
if(requestDataRead + readBuffer.size() >= requestDataTotal) {
readState = ReadFinished;
Q_EMIT q->readChannelFinished();
}
}
QHttpSocket::QHttpSocket(QTcpSocket *socket, QObject *parent)
: QIODevice(parent),
d(new QHttpSocketPrivate(this, socket))
{
// The device is initially open for both reading and writing
setOpenMode(QIODevice::ReadWrite);
}
qint64 QHttpSocket::bytesAvailable() const
{
return d->readBuffer.size() + QIODevice::bytesAvailable();
}
bool QHttpSocket::isSequential() const
{
return true;
}
void QHttpSocket::close()
{
// Invoke the parent method
QIODevice::close();
d->readState = QHttpSocketPrivate::ReadFinished;
d->writeState = QHttpSocketPrivate::WriteFinished;
d->socket->close();
}
QByteArray QHttpSocket::method() const
{
return d->requestMethod;
}
QByteArray QHttpSocket::path() const
{
return d->requestPath;
}
QHttpHeaderMap &QHttpSocket::headers() const
{
return d->requestHeaders;
}
void QHttpSocket::setStatusCode(const QByteArray &statusCode)
{
d->responseStatusCode = statusCode;
}
void QHttpSocket::setHeader(const QByteArray &name, const QByteArray &value)
{
d->responseHeaders.insert(name, value);
}
void QHttpSocket::setHeaders(const QHttpHeaderMap &headers)
{
d->responseHeaders = headers;
}
void QHttpSocket::writeHeaders()
{
// Use a QByteArray for building the header so that we can later determine
// exactly how many bytes were written
QByteArray header;
// Append the status line
header.append("HTTP/1.0 ");
header.append(d->responseStatusCode);
header.append("\r\n");
// Append each of the headers followed by a CRLF
for(QHttpHeaderMap::const_iterator i = d->responseHeaders.constBegin(); i != d->responseHeaders.constEnd(); ++i) {
header.append(i.key());
header.append(": ");
header.append(i.value());
header.append("\r\n");
}
// Append an extra CRLF
header.append("\r\n");
d->writeState = QHttpSocketPrivate::WriteHeaders;
d->responseHeaderRemaining = header.length();
// Write the header
d->socket->write(header);
}
qint64 QHttpSocket::readData(char *data, qint64 maxlen)
{
// Ensure the connection is in the correct state for reading data
if(d->readState != QHttpSocketPrivate::ReadData) {
return 0;
}
// Ensure that no more than the requested amount or the size of the buffer is read
qint64 size = qMin(static_cast<qint64>(d->readBuffer.size()), maxlen);
memcpy(data, d->readBuffer.constData(), size);
// Remove the amount that was read from the buffer
d->readBuffer.remove(0, size);
d->requestDataRead += size;
return size;
}
qint64 QHttpSocket::writeData(const char *data, qint64 len)
{
// If the response headers have not yet been written, they must
// immediately be written before the data can be
if(d->writeState == QHttpSocketPrivate::WriteNone) {
writeHeaders();
}
return d->socket->write(data, len);
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <inviwo/core/util/canvas.h>
#include <inviwo/core/util/rendercontext.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/processors/canvasprocessorwidget.h>
#include <inviwo/core/network/processornetworkevaluator.h>
#include <inviwo/core/io/datawriterfactory.h>
#include <inviwo/core/interaction/events/eventpropagator.h>
namespace inviwo {
EventHandler* eventHandler_();
Mesh* Canvas::screenAlignedRect_ = nullptr;
DataWriterType<Layer>* Canvas::generalLayerWriter_ = nullptr;
Canvas::Canvas(uvec2 dimensions)
: initialized_(false)
, shared_(true)
, screenDimensions_(dimensions)
, propagator_(nullptr)
, pickingContainer_(new PickingContainer())
, ownerWidget_(nullptr) {
if (!screenAlignedRect_) {
shared_ = false;
Position2dBuffer* verticesBuffer = new Position2dBuffer();
Position2dBufferRAM* verticesBufferRAM =
verticesBuffer->getEditableRepresentation<Position2dBufferRAM>();
verticesBufferRAM->add(vec2(-1.0f, -1.0f));
verticesBufferRAM->add(vec2(1.0f, -1.0f));
verticesBufferRAM->add(vec2(-1.0f, 1.0f));
verticesBufferRAM->add(vec2(1.0f, 1.0f));
TexCoord2dBuffer* texCoordsBuffer = new TexCoord2dBuffer();
TexCoord2dBufferRAM* texCoordsBufferRAM =
texCoordsBuffer->getEditableRepresentation<TexCoord2dBufferRAM>();
texCoordsBufferRAM->add(vec2(0.0f, 0.0f));
texCoordsBufferRAM->add(vec2(1.0f, 0.0f));
texCoordsBufferRAM->add(vec2(0.0f, 1.0f));
texCoordsBufferRAM->add(vec2(1.0f, 1.0f));
IndexBuffer* indices_ = new IndexBuffer();
IndexBufferRAM* indexBufferRAM = indices_->getEditableRepresentation<IndexBufferRAM>();
indexBufferRAM->add(0);
indexBufferRAM->add(1);
indexBufferRAM->add(2);
indexBufferRAM->add(3);
Mesh* screenAlignedRectMesh = new Mesh();
screenAlignedRectMesh->addAttribute(verticesBuffer);
screenAlignedRectMesh->addAttribute(texCoordsBuffer);
screenAlignedRectMesh->addIndicies(Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP), indices_);
screenAlignedRect_ = screenAlignedRectMesh;
}
if(!generalLayerWriter_){
generalLayerWriter_ = DataWriterFactory::getPtr()->getWriterForTypeAndExtension<Layer>("png");
}
}
Canvas::~Canvas() {
if (!shared_) {
delete screenAlignedRect_;
screenAlignedRect_ = nullptr;
delete generalLayerWriter_;
generalLayerWriter_ = nullptr;
}
delete pickingContainer_;
if (this == RenderContext::getPtr()->getDefaultRenderContext()) {
RenderContext::getPtr()->setDefaultRenderContext(nullptr);
}
}
void Canvas::initialize() {
if (!pickingContainer_)
pickingContainer_ = new PickingContainer();
initialized_ = true;
propagator_ = nullptr;
}
void Canvas::deinitialize() { propagator_ = nullptr; }
void Canvas::render(const Image* im, LayerType layerType, size_t idx) {}
void Canvas::activate() {}
void Canvas::resize(uvec2 canvasSize) {
uvec2 previousScreenDimensions_ = screenDimensions_;
screenDimensions_ = canvasSize;
if (propagator_) {
RenderContext::getPtr()->activateDefaultRenderContext();
ResizeEvent* resizeEvent = new ResizeEvent(screenDimensions_);
resizeEvent->setPreviousSize(previousScreenDimensions_);
propagator_->propagateResizeEvent(resizeEvent, nullptr);
delete resizeEvent;
}
}
uvec2 Canvas::getScreenDimensions() const {
return screenDimensions_;
}
void Canvas::update() {}
bool Canvas::isInitialized(){
return initialized_;
}
void Canvas::activateDefaultRenderContext(){
RenderContext::getPtr()->activateDefaultRenderContext();
}
void Canvas::interactionEvent(Event* event) {
if (propagator_){
NetworkLock lock;
propagator_->propagateEvent(event);
}
}
void Canvas::mousePressEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseReleaseEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseMoveEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseButtonEvent(MouseEvent* e){
NetworkLock lock;
bool picked = pickingContainer_->performMousePick(e);
if (!picked)
interactionEvent(e);
}
void Canvas::mouseWheelEvent(MouseEvent* e) {
interactionEvent(e);
}
void Canvas::keyPressEvent(KeyboardEvent* e) {
interactionEvent(e);
}
void Canvas::keyReleaseEvent(KeyboardEvent* e) {
interactionEvent(e);
}
void Canvas::gestureEvent(GestureEvent* e) {
interactionEvent(e);
}
void Canvas::touchEvent(TouchEvent* e){
NetworkLock lock;
bool picked = pickingContainer_->performTouchPick(e);
if (!picked){
interactionEvent(e);
}
else if (e->hasTouchPoints()){
// As one touch point is handle as mouse event
// Send out a mouse event if only one touch point remains
const std::vector<TouchPoint>& touchPoints = e->getTouchPoints();
if (touchPoints.size() == 1){
MouseEvent mouseEvent(touchPoints[0].getPos(),
MouseEvent::MOUSE_BUTTON_LEFT, MouseEvent::MOUSE_STATE_MOVE,
InteractionEvent::MODIFIER_NONE, e->canvasSize(),
touchPoints[0].getDepth());
interactionEvent(&mouseEvent);
}
else{
interactionEvent(e);
}
}
}
void Canvas::setEventPropagator(EventPropagator* propagator) {
propagator_ = propagator;
}
ProcessorWidget* Canvas::getProcessorWidgetOwner() const {
return ownerWidget_;
}
void Canvas::setProcessorWidgetOwner(ProcessorWidget* ownerWidget) {
ownerWidget_ = ownerWidget;
}
} // namespace
<commit_msg>Canvas: Added NetworkLock to resizeevent to make sure all everything is complete before evaluation.<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <inviwo/core/util/canvas.h>
#include <inviwo/core/util/rendercontext.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/processors/canvasprocessorwidget.h>
#include <inviwo/core/network/processornetworkevaluator.h>
#include <inviwo/core/io/datawriterfactory.h>
#include <inviwo/core/interaction/events/eventpropagator.h>
namespace inviwo {
EventHandler* eventHandler_();
Mesh* Canvas::screenAlignedRect_ = nullptr;
DataWriterType<Layer>* Canvas::generalLayerWriter_ = nullptr;
Canvas::Canvas(uvec2 dimensions)
: initialized_(false)
, shared_(true)
, screenDimensions_(dimensions)
, propagator_(nullptr)
, pickingContainer_(new PickingContainer())
, ownerWidget_(nullptr) {
if (!screenAlignedRect_) {
shared_ = false;
Position2dBuffer* verticesBuffer = new Position2dBuffer();
Position2dBufferRAM* verticesBufferRAM =
verticesBuffer->getEditableRepresentation<Position2dBufferRAM>();
verticesBufferRAM->add(vec2(-1.0f, -1.0f));
verticesBufferRAM->add(vec2(1.0f, -1.0f));
verticesBufferRAM->add(vec2(-1.0f, 1.0f));
verticesBufferRAM->add(vec2(1.0f, 1.0f));
TexCoord2dBuffer* texCoordsBuffer = new TexCoord2dBuffer();
TexCoord2dBufferRAM* texCoordsBufferRAM =
texCoordsBuffer->getEditableRepresentation<TexCoord2dBufferRAM>();
texCoordsBufferRAM->add(vec2(0.0f, 0.0f));
texCoordsBufferRAM->add(vec2(1.0f, 0.0f));
texCoordsBufferRAM->add(vec2(0.0f, 1.0f));
texCoordsBufferRAM->add(vec2(1.0f, 1.0f));
IndexBuffer* indices_ = new IndexBuffer();
IndexBufferRAM* indexBufferRAM = indices_->getEditableRepresentation<IndexBufferRAM>();
indexBufferRAM->add(0);
indexBufferRAM->add(1);
indexBufferRAM->add(2);
indexBufferRAM->add(3);
Mesh* screenAlignedRectMesh = new Mesh();
screenAlignedRectMesh->addAttribute(verticesBuffer);
screenAlignedRectMesh->addAttribute(texCoordsBuffer);
screenAlignedRectMesh->addIndicies(Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP), indices_);
screenAlignedRect_ = screenAlignedRectMesh;
}
if(!generalLayerWriter_){
generalLayerWriter_ = DataWriterFactory::getPtr()->getWriterForTypeAndExtension<Layer>("png");
}
}
Canvas::~Canvas() {
if (!shared_) {
delete screenAlignedRect_;
screenAlignedRect_ = nullptr;
delete generalLayerWriter_;
generalLayerWriter_ = nullptr;
}
delete pickingContainer_;
if (this == RenderContext::getPtr()->getDefaultRenderContext()) {
RenderContext::getPtr()->setDefaultRenderContext(nullptr);
}
}
void Canvas::initialize() {
if (!pickingContainer_)
pickingContainer_ = new PickingContainer();
initialized_ = true;
propagator_ = nullptr;
}
void Canvas::deinitialize() { propagator_ = nullptr; }
void Canvas::render(const Image* im, LayerType layerType, size_t idx) {}
void Canvas::activate() {}
void Canvas::resize(uvec2 canvasSize) {
uvec2 previousScreenDimensions_ = screenDimensions_;
screenDimensions_ = canvasSize;
if (propagator_) {
NetworkLock lock;
RenderContext::getPtr()->activateDefaultRenderContext();
ResizeEvent* resizeEvent = new ResizeEvent(screenDimensions_);
resizeEvent->setPreviousSize(previousScreenDimensions_);
propagator_->propagateResizeEvent(resizeEvent, nullptr);
delete resizeEvent;
}
}
uvec2 Canvas::getScreenDimensions() const {
return screenDimensions_;
}
void Canvas::update() {}
bool Canvas::isInitialized(){
return initialized_;
}
void Canvas::activateDefaultRenderContext(){
RenderContext::getPtr()->activateDefaultRenderContext();
}
void Canvas::interactionEvent(Event* event) {
if (propagator_){
NetworkLock lock;
propagator_->propagateEvent(event);
}
}
void Canvas::mousePressEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseReleaseEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseMoveEvent(MouseEvent* e) {
mouseButtonEvent(e);
}
void Canvas::mouseButtonEvent(MouseEvent* e){
NetworkLock lock;
bool picked = pickingContainer_->performMousePick(e);
if (!picked)
interactionEvent(e);
}
void Canvas::mouseWheelEvent(MouseEvent* e) {
interactionEvent(e);
}
void Canvas::keyPressEvent(KeyboardEvent* e) {
interactionEvent(e);
}
void Canvas::keyReleaseEvent(KeyboardEvent* e) {
interactionEvent(e);
}
void Canvas::gestureEvent(GestureEvent* e) {
interactionEvent(e);
}
void Canvas::touchEvent(TouchEvent* e){
NetworkLock lock;
bool picked = pickingContainer_->performTouchPick(e);
if (!picked){
interactionEvent(e);
}
else if (e->hasTouchPoints()){
// As one touch point is handle as mouse event
// Send out a mouse event if only one touch point remains
const std::vector<TouchPoint>& touchPoints = e->getTouchPoints();
if (touchPoints.size() == 1){
MouseEvent mouseEvent(touchPoints[0].getPos(),
MouseEvent::MOUSE_BUTTON_LEFT, MouseEvent::MOUSE_STATE_MOVE,
InteractionEvent::MODIFIER_NONE, e->canvasSize(),
touchPoints[0].getDepth());
interactionEvent(&mouseEvent);
}
else{
interactionEvent(e);
}
}
}
void Canvas::setEventPropagator(EventPropagator* propagator) {
propagator_ = propagator;
}
ProcessorWidget* Canvas::getProcessorWidgetOwner() const {
return ownerWidget_;
}
void Canvas::setProcessorWidgetOwner(ProcessorWidget* ownerWidget) {
ownerWidget_ = ownerWidget;
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 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: Andreas Sandberg
*/
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <syscall.h>
#include <unistd.h>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstring>
#include "base/logging.hh"
#include "perfevent.hh"
PerfKvmCounterConfig::PerfKvmCounterConfig(uint32_t type, uint64_t config)
{
memset(&attr, 0, sizeof(attr));
attr.size = PERF_ATTR_SIZE_VER0;
attr.type = type;
attr.config = config;
}
PerfKvmCounterConfig::~PerfKvmCounterConfig()
{
}
PerfKvmCounter::PerfKvmCounter(PerfKvmCounterConfig &config, pid_t tid)
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
attach(config, tid, -1);
}
PerfKvmCounter::PerfKvmCounter(PerfKvmCounterConfig &config,
pid_t tid, const PerfKvmCounter &parent)
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
attach(config, tid, parent);
}
PerfKvmCounter::PerfKvmCounter()
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
}
PerfKvmCounter::~PerfKvmCounter()
{
if (attached())
detach();
}
void
PerfKvmCounter::detach()
{
assert(attached());
if (munmap(ringBuffer, ringNumPages * pageSize) == -1)
warn("PerfKvmCounter: Failed to unmap ring buffer (%i)\n",
errno);
close(fd);
fd = -1;
ringBuffer = NULL;
}
void
PerfKvmCounter::start()
{
if (ioctl(PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) == -1)
panic("KVM: Failed to enable performance counters (%i)\n", errno);
}
void
PerfKvmCounter::stop()
{
if (ioctl(PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) == -1)
panic("KVM: Failed to disable performance counters (%i)\n", errno);
}
void
PerfKvmCounter::period(uint64_t period)
{
if (ioctl(PERF_EVENT_IOC_PERIOD, &period) == -1)
panic("KVM: Failed to set period of performance counter (%i)\n", errno);
}
void
PerfKvmCounter::refresh(int refresh)
{
if (ioctl(PERF_EVENT_IOC_REFRESH, refresh) == -1)
panic("KVM: Failed to refresh performance counter (%i)\n", errno);
}
uint64_t
PerfKvmCounter::read() const
{
uint64_t value;
read(&value, sizeof(uint64_t));
return value;
}
void
PerfKvmCounter::enableSignals(pid_t tid, int signal)
{
struct f_owner_ex sigowner;
sigowner.type = F_OWNER_TID;
sigowner.pid = tid;
if (fcntl(F_SETOWN_EX, &sigowner) == -1 ||
fcntl(F_SETSIG, signal) == -1 ||
fcntl(F_SETFL, O_ASYNC) == -1)
panic("PerfKvmCounter: Failed to enable signals for counter (%i)\n",
errno);
}
void
PerfKvmCounter::attach(PerfKvmCounterConfig &config,
pid_t tid, int group_fd)
{
assert(!attached());
fd = syscall(__NR_perf_event_open,
&config.attr, tid,
-1, // CPU (-1 => Any CPU that the task happens to run on)
group_fd,
0); // Flags
if (fd == -1)
panic("PerfKvmCounter::open failed (%i)\n", errno);
mmapPerf(1);
}
pid_t
PerfKvmCounter::gettid()
{
return syscall(__NR_gettid);
}
void
PerfKvmCounter::mmapPerf(int pages)
{
assert(attached());
assert(ringBuffer == NULL);
if (pageSize == -1) {
pageSize = sysconf(_SC_PAGE_SIZE);
if (pageSize == -1)
panic("PerfKvmCounter: Failed to determine page size (%i)\n",
errno);
}
ringNumPages = pages + 1;
ringBuffer = (struct perf_event_mmap_page *)mmap(
NULL, ringNumPages * 4096,
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
if (ringBuffer == MAP_FAILED)
panic("PerfKvmCounter: MMAP failed (%i)\n",
errno);
}
int
PerfKvmCounter::fcntl(int cmd, long p1)
{
assert(attached());
return ::fcntl(fd, cmd, p1);
}
int
PerfKvmCounter::ioctl(int request, long p1)
{
assert(attached());
return ::ioctl(fd, request, p1);
}
void
PerfKvmCounter::read(void *buf, size_t size) const
{
char *_buf = (char *)buf;
size_t _size = size;
assert(attached());
do {
ssize_t ret;
ret = ::read(fd, _buf, _size);
switch (ret) {
case -1:
if (errno != EAGAIN)
panic("PerfKvmCounter::read failed (%i)\n", errno);
break;
case 0:
panic("PerfKvmCounter::read unexpected EOF.\n");
default:
_size -= ret;
_buf += ret;
break;
}
} while (_size);
}
<commit_msg>cpu-kvm: Added informative error message<commit_after>/*
* Copyright (c) 2012 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: Andreas Sandberg
*/
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <syscall.h>
#include <unistd.h>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstring>
#include "base/logging.hh"
#include "perfevent.hh"
PerfKvmCounterConfig::PerfKvmCounterConfig(uint32_t type, uint64_t config)
{
memset(&attr, 0, sizeof(attr));
attr.size = PERF_ATTR_SIZE_VER0;
attr.type = type;
attr.config = config;
}
PerfKvmCounterConfig::~PerfKvmCounterConfig()
{
}
PerfKvmCounter::PerfKvmCounter(PerfKvmCounterConfig &config, pid_t tid)
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
attach(config, tid, -1);
}
PerfKvmCounter::PerfKvmCounter(PerfKvmCounterConfig &config,
pid_t tid, const PerfKvmCounter &parent)
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
attach(config, tid, parent);
}
PerfKvmCounter::PerfKvmCounter()
: fd(-1), ringBuffer(NULL), pageSize(-1)
{
}
PerfKvmCounter::~PerfKvmCounter()
{
if (attached())
detach();
}
void
PerfKvmCounter::detach()
{
assert(attached());
if (munmap(ringBuffer, ringNumPages * pageSize) == -1)
warn("PerfKvmCounter: Failed to unmap ring buffer (%i)\n",
errno);
close(fd);
fd = -1;
ringBuffer = NULL;
}
void
PerfKvmCounter::start()
{
if (ioctl(PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) == -1)
panic("KVM: Failed to enable performance counters (%i)\n", errno);
}
void
PerfKvmCounter::stop()
{
if (ioctl(PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) == -1)
panic("KVM: Failed to disable performance counters (%i)\n", errno);
}
void
PerfKvmCounter::period(uint64_t period)
{
if (ioctl(PERF_EVENT_IOC_PERIOD, &period) == -1)
panic("KVM: Failed to set period of performance counter (%i)\n", errno);
}
void
PerfKvmCounter::refresh(int refresh)
{
if (ioctl(PERF_EVENT_IOC_REFRESH, refresh) == -1)
panic("KVM: Failed to refresh performance counter (%i)\n", errno);
}
uint64_t
PerfKvmCounter::read() const
{
uint64_t value;
read(&value, sizeof(uint64_t));
return value;
}
void
PerfKvmCounter::enableSignals(pid_t tid, int signal)
{
struct f_owner_ex sigowner;
sigowner.type = F_OWNER_TID;
sigowner.pid = tid;
if (fcntl(F_SETOWN_EX, &sigowner) == -1 ||
fcntl(F_SETSIG, signal) == -1 ||
fcntl(F_SETFL, O_ASYNC) == -1)
panic("PerfKvmCounter: Failed to enable signals for counter (%i)\n",
errno);
}
void
PerfKvmCounter::attach(PerfKvmCounterConfig &config,
pid_t tid, int group_fd)
{
assert(!attached());
fd = syscall(__NR_perf_event_open,
&config.attr, tid,
-1, // CPU (-1 => Any CPU that the task happens to run on)
group_fd,
0); // Flags
if (fd == -1)
{
if (errno == EACCES)
{
panic("PerfKvmCounter::attach recieved error EACCESS\n"
" This error may be caused by a too restrictive setting\n"
" in the file '/proc/sys/kernel/perf_event_paranoid'\n"
" The default value was changed to 2 in kernel 4.6\n"
" A value greater than 1 prevents gem5 from making\n"
" the syscall to perf_event_open");
}
panic("PerfKvmCounter::attach failed (%i)\n", errno);
}
mmapPerf(1);
}
pid_t
PerfKvmCounter::gettid()
{
return syscall(__NR_gettid);
}
void
PerfKvmCounter::mmapPerf(int pages)
{
assert(attached());
assert(ringBuffer == NULL);
if (pageSize == -1) {
pageSize = sysconf(_SC_PAGE_SIZE);
if (pageSize == -1)
panic("PerfKvmCounter: Failed to determine page size (%i)\n",
errno);
}
ringNumPages = pages + 1;
ringBuffer = (struct perf_event_mmap_page *)mmap(
NULL, ringNumPages * 4096,
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
if (ringBuffer == MAP_FAILED)
panic("PerfKvmCounter: MMAP failed (%i)\n",
errno);
}
int
PerfKvmCounter::fcntl(int cmd, long p1)
{
assert(attached());
return ::fcntl(fd, cmd, p1);
}
int
PerfKvmCounter::ioctl(int request, long p1)
{
assert(attached());
return ::ioctl(fd, request, p1);
}
void
PerfKvmCounter::read(void *buf, size_t size) const
{
char *_buf = (char *)buf;
size_t _size = size;
assert(attached());
do {
ssize_t ret;
ret = ::read(fd, _buf, _size);
switch (ret) {
case -1:
if (errno != EAGAIN)
panic("PerfKvmCounter::read failed (%i)\n", errno);
break;
case 0:
panic("PerfKvmCounter::read unexpected EOF.\n");
default:
_size -= ret;
_buf += ret;
break;
}
} while (_size);
}
<|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2016-2017 Mark Allender
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 <array>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include "apple2emu.h"
#include "apple2emu_defs.h"
#include "debugger_console.h"
#include "imgui.h"
debugger_console::debugger_console()
{
clear_log();
memset(m_input_buf, 0, sizeof(m_input_buf));
m_history_pos = -1;
m_commands["help"] = { "Show help ",
[this](char *) {
for (auto const &cmd : m_commands) {
add_log("%s - %s", cmd.first.c_str(), cmd.second.m_help.c_str());
}
} };
m_reset_window = false;
}
debugger_console::~debugger_console()
{
clear_log();
for (size_t i = 0; i < m_history.size(); i++) {
free(m_history[i]);
}
}
void debugger_console::add_command(const char *name, const char *help, std::function<void(char *)> func)
{
console_command cmd;
cmd.m_help = help;
cmd.m_func = func;
m_commands[name] = cmd;
}
void debugger_console::clear_log()
{
for (size_t i = 0; i < m_items.size(); i++) {
free(m_items[i]);
}
m_items.clear();
m_scroll_to_bottom = true;
}
void debugger_console::add_log(const char* fmt, ...)
{
char buf[max_line_size];
va_list args;
va_start(args, fmt);
vsnprintf(buf, max_line_size, fmt, args);
buf[max_line_size - 1] = 0;
va_end(args);
m_items.push_back(strdup(buf));
m_scroll_to_bottom = true;
}
void debugger_console::draw(const char* title, bool* p_open)
{
ImGuiCond condition = ImGuiCond_FirstUseEver;
if (m_reset_window == true) {
condition = ImGuiCond_Always;
m_reset_window = false;
}
ImGui::SetNextWindowSize(ImVec2(562,180), condition);
ImGui::SetNextWindowPos(ImVec2(2, 582), condition);
if (!ImGui::Begin(title, p_open, 0)) {
ImGui::End();
return;
}
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginPopupContextWindow()) {
if (ImGui::Selectable("Clear")) {
clear_log();
}
ImGui::EndPopup();
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
for (size_t i = 0; i < m_items.size(); i++) {
const char* item = m_items[i];
ImVec4 col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
if (strstr(item, "[error]")) col = ImColor(1.0f, 0.4f, 0.4f, 1.0f);
else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f, 0.78f, 0.58f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_Text, col);
ImGui::TextUnformatted(item);
ImGui::PopStyleColor();
}
if (m_scroll_to_bottom) {
ImGui::SetScrollHere();
}
m_scroll_to_bottom = false;
ImGui::PopStyleVar();
ImGui::EndChild();
ImGui::Separator();
// Command-line
if (ImGui::InputText("Input", m_input_buf, max_line_size,
ImGuiInputTextFlags_EnterReturnsTrue |
ImGuiInputTextFlags_CallbackCompletion |
ImGuiInputTextFlags_CallbackHistory,
[](ImGuiTextEditCallbackData *data) {
debugger_console* console = (debugger_console *)data->UserData;
return console->text_edit_callback(data);
}, (void*)this)) {
char* input_end = m_input_buf + strlen(m_input_buf);
while (input_end > m_input_buf && input_end[-1] == ' ') {
input_end--;
*input_end = 0;
}
if (m_input_buf[0]) {
execute_command();
}
strcpy(m_input_buf, "");
}
// Demonstrate keeping auto focus on the input box
if (ImGui::IsItemHovered() || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) {
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
}
ImGui::End();
}
void debugger_console::execute_command(const char *command)
{
m_history_pos = -1;
// don't insert duplicate items into history. Acts like
// ignoredupes in bash.
if (command == nullptr && (m_history.size() == 0 || stricmp(m_history[m_history.size()-1], m_input_buf))) {
m_history.push_back(strdup(m_input_buf));
}
// parse the debugger commands
const char *token = nullptr;
if (command != nullptr) {
strcpy(m_input_buf, command);
}
token = strtok(m_input_buf, " ");
if (m_commands.find(token) != m_commands.end()) {
m_commands[token].m_func(m_input_buf);
}
if (command != nullptr) {
m_input_buf[0] = '\0';
}
}
int debugger_console::text_edit_callback(ImGuiTextEditCallbackData* data) {
switch (data->EventFlag) {
case ImGuiInputTextFlags_CallbackCompletion:
{
// Example of TEXT COMPLETION
// Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf) {
const char c = word_start[-1];
if (c == ' ' || c == '\t' || c == ',' || c == ';') {
break;
}
word_start--;
}
// Build a list of candidates
std::vector<const char*> candidates;
for (auto cmd : m_commands) {
if (strnicmp(cmd.first.c_str(), word_start, (int)(word_end - word_start)) == 0) {
candidates.push_back(cmd.first.c_str());
}
}
if (candidates.size() == 0) {
// No match
add_log("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
} else if (candidates.size() == 1) {
// Single match. Delete the beginning of the word
// and replace it entirely so we've got nice casing
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
} else {
// Multiple matches. Complete as much as we can, so
// inputing "C" will complete to "CL" and display
// "CLEAR" and "CLASSIFY"
int match_len = (int)(word_end - word_start);
for (;;) {
int c = 0;
bool all_candidates_matches = true;
for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) {
if (i == 0) {
c = toupper(candidates[i][match_len]);
}
else if (c != toupper(candidates[i][match_len])) {
all_candidates_matches = false;
}
}
if (!all_candidates_matches) {
break;
}
match_len++;
}
if (match_len > 0) {
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
// List matches
add_log("Possible matches:\n");
for (size_t i = 0; i < candidates.size(); i++)
add_log("- %s\n", candidates[i]);
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
// Example of HISTORY
const int32_t prev_history_pos = m_history_pos;
if (data->EventKey == ImGuiKey_UpArrow) {
if (m_history_pos == -1) {
m_history_pos = m_history.size() - 1;
}
else if (m_history_pos > 0) {
m_history_pos--;
}
}
else if (data->EventKey == ImGuiKey_DownArrow) {
if (m_history_pos != -1) {
if (++m_history_pos >= (int)m_history.size()) {
m_history_pos = -1;
}
}
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos != m_history_pos) {
data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (m_history_pos >= 0) ? m_history[m_history_pos] : "");
data->BufDirty = true;
}
}
}
return 0;
}
<commit_msg>Fix compiler warning with size_t and console history<commit_after>/*
MIT License
Copyright (c) 2016-2017 Mark Allender
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 <array>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include "apple2emu.h"
#include "apple2emu_defs.h"
#include "debugger_console.h"
#include "imgui.h"
debugger_console::debugger_console()
{
clear_log();
memset(m_input_buf, 0, sizeof(m_input_buf));
m_history_pos = -1;
m_commands["help"] = { "Show help ",
[this](char *) {
for (auto const &cmd : m_commands) {
add_log("%s - %s", cmd.first.c_str(), cmd.second.m_help.c_str());
}
} };
m_reset_window = false;
}
debugger_console::~debugger_console()
{
clear_log();
for (size_t i = 0; i < m_history.size(); i++) {
free(m_history[i]);
}
}
void debugger_console::add_command(const char *name, const char *help, std::function<void(char *)> func)
{
console_command cmd;
cmd.m_help = help;
cmd.m_func = func;
m_commands[name] = cmd;
}
void debugger_console::clear_log()
{
for (size_t i = 0; i < m_items.size(); i++) {
free(m_items[i]);
}
m_items.clear();
m_scroll_to_bottom = true;
}
void debugger_console::add_log(const char* fmt, ...)
{
char buf[max_line_size];
va_list args;
va_start(args, fmt);
vsnprintf(buf, max_line_size, fmt, args);
buf[max_line_size - 1] = 0;
va_end(args);
m_items.push_back(strdup(buf));
m_scroll_to_bottom = true;
}
void debugger_console::draw(const char* title, bool* p_open)
{
ImGuiCond condition = ImGuiCond_FirstUseEver;
if (m_reset_window == true) {
condition = ImGuiCond_Always;
m_reset_window = false;
}
ImGui::SetNextWindowSize(ImVec2(562,180), condition);
ImGui::SetNextWindowPos(ImVec2(2, 582), condition);
if (!ImGui::Begin(title, p_open, 0)) {
ImGui::End();
return;
}
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginPopupContextWindow()) {
if (ImGui::Selectable("Clear")) {
clear_log();
}
ImGui::EndPopup();
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
for (size_t i = 0; i < m_items.size(); i++) {
const char* item = m_items[i];
ImVec4 col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
if (strstr(item, "[error]")) col = ImColor(1.0f, 0.4f, 0.4f, 1.0f);
else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f, 0.78f, 0.58f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_Text, col);
ImGui::TextUnformatted(item);
ImGui::PopStyleColor();
}
if (m_scroll_to_bottom) {
ImGui::SetScrollHere();
}
m_scroll_to_bottom = false;
ImGui::PopStyleVar();
ImGui::EndChild();
ImGui::Separator();
// Command-line
if (ImGui::InputText("Input", m_input_buf, max_line_size,
ImGuiInputTextFlags_EnterReturnsTrue |
ImGuiInputTextFlags_CallbackCompletion |
ImGuiInputTextFlags_CallbackHistory,
[](ImGuiTextEditCallbackData *data) {
debugger_console* console = (debugger_console *)data->UserData;
return console->text_edit_callback(data);
}, (void*)this)) {
char* input_end = m_input_buf + strlen(m_input_buf);
while (input_end > m_input_buf && input_end[-1] == ' ') {
input_end--;
*input_end = 0;
}
if (m_input_buf[0]) {
execute_command();
}
strcpy(m_input_buf, "");
}
// Demonstrate keeping auto focus on the input box
if (ImGui::IsItemHovered() || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) {
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
}
ImGui::End();
}
void debugger_console::execute_command(const char *command)
{
m_history_pos = -1;
// don't insert duplicate items into history. Acts like
// ignoredupes in bash.
if (command == nullptr && (m_history.size() == 0 || stricmp(m_history[m_history.size()-1], m_input_buf))) {
m_history.push_back(strdup(m_input_buf));
}
// parse the debugger commands
const char *token = nullptr;
if (command != nullptr) {
strcpy(m_input_buf, command);
}
token = strtok(m_input_buf, " ");
if (m_commands.find(token) != m_commands.end()) {
m_commands[token].m_func(m_input_buf);
}
if (command != nullptr) {
m_input_buf[0] = '\0';
}
}
int debugger_console::text_edit_callback(ImGuiTextEditCallbackData* data) {
switch (data->EventFlag) {
case ImGuiInputTextFlags_CallbackCompletion:
{
// Example of TEXT COMPLETION
// Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf) {
const char c = word_start[-1];
if (c == ' ' || c == '\t' || c == ',' || c == ';') {
break;
}
word_start--;
}
// Build a list of candidates
std::vector<const char*> candidates;
for (auto cmd : m_commands) {
if (strnicmp(cmd.first.c_str(), word_start, (int)(word_end - word_start)) == 0) {
candidates.push_back(cmd.first.c_str());
}
}
if (candidates.size() == 0) {
// No match
add_log("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
} else if (candidates.size() == 1) {
// Single match. Delete the beginning of the word
// and replace it entirely so we've got nice casing
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
} else {
// Multiple matches. Complete as much as we can, so
// inputing "C" will complete to "CL" and display
// "CLEAR" and "CLASSIFY"
int match_len = (int)(word_end - word_start);
for (;;) {
int c = 0;
bool all_candidates_matches = true;
for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) {
if (i == 0) {
c = toupper(candidates[i][match_len]);
}
else if (c != toupper(candidates[i][match_len])) {
all_candidates_matches = false;
}
}
if (!all_candidates_matches) {
break;
}
match_len++;
}
if (match_len > 0) {
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
// List matches
add_log("Possible matches:\n");
for (size_t i = 0; i < candidates.size(); i++)
add_log("- %s\n", candidates[i]);
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
// Example of HISTORY
const int32_t prev_history_pos = m_history_pos;
if (data->EventKey == ImGuiKey_UpArrow) {
if (m_history_pos == -1) {
m_history_pos = (int32_t)(m_history.size() - 1);
}
else if (m_history_pos > 0) {
m_history_pos--;
}
}
else if (data->EventKey == ImGuiKey_DownArrow) {
if (m_history_pos != -1) {
if (++m_history_pos >= (int)m_history.size()) {
m_history_pos = -1;
}
}
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos != m_history_pos) {
data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (m_history_pos >= 0) ? m_history[m_history_pos] : "");
data->BufDirty = true;
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPoolDevice thread_pool_device(4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPoolDevice thread_pool_device(12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPoolDevice thread_pool_device(num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int i = 0; i < size; i++) {
VERIFY_IS_EQUAL(t1(i), result[i]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPoolDevice device(2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<commit_msg>Fix clang compilation<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using std::isnan;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPoolDevice thread_pool_device(4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPoolDevice thread_pool_device(12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPoolDevice thread_pool_device(num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int i = 0; i < size; i++) {
VERIFY_IS_EQUAL(t1(i), result[i]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPoolDevice device(2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<|endoftext|>
|
<commit_before>//
// PROJECT: Aspia Remote Desktop
// FILE: crypto/encryptor.cc
// LICENSE: See top-level directory
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "crypto/encryptor.h"
#include "base/logging.h"
namespace aspia {
Encryptor::Encryptor(Mode mode, SecureBuffer public_key, SecureBuffer secret_key) :
local_public_key_(std::move(public_key)),
local_secret_key_(std::move(secret_key)),
decrypt_key_(crypto_kx_SESSIONKEYBYTES),
encrypt_key_(crypto_kx_SESSIONKEYBYTES),
nonce_(crypto_secretbox_NONCEBYTES),
mode_(mode)
{
// Generate nonce.
randombytes_buf(nonce_.data(), nonce_.size());
}
Encryptor::~Encryptor()
{
// Nothing
}
// static
std::unique_ptr<Encryptor> Encryptor::Create(Mode mode)
{
if (sodium_init() == -1)
{
LOG(ERROR) << "sodium_init() failed";
return nullptr;
}
SecureBuffer public_key(crypto_kx_PUBLICKEYBYTES);
SecureBuffer secret_key(crypto_kx_SECRETKEYBYTES);
if (crypto_kx_keypair(public_key.data(), secret_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_keypair() failed";
return nullptr;
}
return std::unique_ptr<Encryptor>(new Encryptor(mode,
std::move(public_key),
std::move(secret_key)));
}
bool Encryptor::SetRemotePublicKey(const IOBuffer& public_key)
{
if (public_key.IsEmpty())
{
LOG(ERROR) << "Empty public key";
return false;
}
if (public_key.size() != crypto_kx_PUBLICKEYBYTES)
{
LOG(ERROR) << "Wrong public key size";
return false;
}
if (mode_ == Mode::SERVER)
{
if (crypto_kx_server_session_keys(decrypt_key_.data(),
encrypt_key_.data(),
local_public_key_.data(),
local_secret_key_.data(),
public_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_server_session_keys() failed";
return false;
}
}
else
{
DCHECK(mode_ == Mode::CLIENT);
if (crypto_kx_client_session_keys(decrypt_key_.data(),
encrypt_key_.data(),
local_public_key_.data(),
local_secret_key_.data(),
public_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_client_session_keys() failed";
return false;
}
}
sodium_memzero(public_key.data(), public_key.size());
return true;
}
IOBuffer Encryptor::GetLocalPublicKey()
{
if (local_public_key_.IsEmpty())
return IOBuffer();
IOBuffer public_key(local_public_key_.size());
memcpy(public_key.data(), local_public_key_.data(), public_key.size());
return public_key;
}
IOBuffer Encryptor::Encrypt(const IOBuffer& source_buffer)
{
DCHECK_EQ(nonce_.size(), crypto_secretbox_NONCEBYTES);
sodium_increment(nonce_.data(), crypto_secretbox_NONCEBYTES);
IOBuffer encrypted_buffer(source_buffer.size() +
crypto_secretbox_NONCEBYTES +
crypto_secretbox_MACBYTES);
memcpy(encrypted_buffer.data(), nonce_.data(), crypto_secretbox_NONCEBYTES);
// Encrypt message.
if (crypto_secretbox_easy(encrypted_buffer.data() + crypto_secretbox_NONCEBYTES,
source_buffer.data(),
source_buffer.size(),
nonce_.data(),
encrypt_key_.data()) != 0)
{
LOG(ERROR) << "crypto_secretbox_easy() failed";
return IOBuffer();
}
return encrypted_buffer;
}
IOBuffer Encryptor::Decrypt(const IOBuffer& source_buffer)
{
IOBuffer decrypted_buffer(source_buffer.size() -
crypto_secretbox_NONCEBYTES -
crypto_secretbox_MACBYTES);
// Decrypt message.
if (crypto_secretbox_open_easy(decrypted_buffer.data(),
source_buffer.data() + crypto_secretbox_NONCEBYTES,
source_buffer.size() - crypto_secretbox_NONCEBYTES,
source_buffer.data(),
decrypt_key_.data()) != 0)
{
LOG(ERROR) << "crypto_secretbox_open_easy() failed";
return IOBuffer();
}
return decrypted_buffer;
}
} // namespace aspia
<commit_msg>- Add missed checks<commit_after>//
// PROJECT: Aspia Remote Desktop
// FILE: crypto/encryptor.cc
// LICENSE: See top-level directory
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "crypto/encryptor.h"
#include "base/logging.h"
namespace aspia {
Encryptor::Encryptor(Mode mode, SecureBuffer public_key, SecureBuffer secret_key) :
local_public_key_(std::move(public_key)),
local_secret_key_(std::move(secret_key)),
decrypt_key_(crypto_kx_SESSIONKEYBYTES),
encrypt_key_(crypto_kx_SESSIONKEYBYTES),
nonce_(crypto_secretbox_NONCEBYTES),
mode_(mode)
{
// Generate nonce.
randombytes_buf(nonce_.data(), nonce_.size());
}
Encryptor::~Encryptor()
{
// Nothing
}
// static
std::unique_ptr<Encryptor> Encryptor::Create(Mode mode)
{
if (sodium_init() == -1)
{
LOG(ERROR) << "sodium_init() failed";
return nullptr;
}
SecureBuffer public_key(crypto_kx_PUBLICKEYBYTES);
SecureBuffer secret_key(crypto_kx_SECRETKEYBYTES);
if (crypto_kx_keypair(public_key.data(), secret_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_keypair() failed";
return nullptr;
}
return std::unique_ptr<Encryptor>(new Encryptor(mode,
std::move(public_key),
std::move(secret_key)));
}
bool Encryptor::SetRemotePublicKey(const IOBuffer& public_key)
{
if (public_key.IsEmpty())
{
LOG(ERROR) << "Empty public key";
return false;
}
if (public_key.size() != crypto_kx_PUBLICKEYBYTES)
{
LOG(ERROR) << "Wrong public key size";
return false;
}
if (mode_ == Mode::SERVER)
{
if (crypto_kx_server_session_keys(decrypt_key_.data(),
encrypt_key_.data(),
local_public_key_.data(),
local_secret_key_.data(),
public_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_server_session_keys() failed";
return false;
}
}
else
{
DCHECK(mode_ == Mode::CLIENT);
if (crypto_kx_client_session_keys(decrypt_key_.data(),
encrypt_key_.data(),
local_public_key_.data(),
local_secret_key_.data(),
public_key.data()) != 0)
{
LOG(ERROR) << "crypto_kx_client_session_keys() failed";
return false;
}
}
sodium_memzero(public_key.data(), public_key.size());
return true;
}
IOBuffer Encryptor::GetLocalPublicKey()
{
if (local_public_key_.IsEmpty())
return IOBuffer();
IOBuffer public_key(local_public_key_.size());
memcpy(public_key.data(), local_public_key_.data(), public_key.size());
return public_key;
}
IOBuffer Encryptor::Encrypt(const IOBuffer& source_buffer)
{
DCHECK_EQ(nonce_.size(), crypto_secretbox_NONCEBYTES);
if (source_buffer.IsEmpty())
return IOBuffer();
sodium_increment(nonce_.data(), crypto_secretbox_NONCEBYTES);
IOBuffer encrypted_buffer(source_buffer.size() +
crypto_secretbox_NONCEBYTES +
crypto_secretbox_MACBYTES);
memcpy(encrypted_buffer.data(), nonce_.data(), crypto_secretbox_NONCEBYTES);
// Encrypt message.
if (crypto_secretbox_easy(encrypted_buffer.data() + crypto_secretbox_NONCEBYTES,
source_buffer.data(),
source_buffer.size(),
nonce_.data(),
encrypt_key_.data()) != 0)
{
LOG(ERROR) << "crypto_secretbox_easy() failed";
return IOBuffer();
}
return encrypted_buffer;
}
IOBuffer Encryptor::Decrypt(const IOBuffer& source_buffer)
{
if (source_buffer.IsEmpty())
return IOBuffer();
IOBuffer decrypted_buffer(source_buffer.size() -
crypto_secretbox_NONCEBYTES -
crypto_secretbox_MACBYTES);
// Decrypt message.
if (crypto_secretbox_open_easy(decrypted_buffer.data(),
source_buffer.data() + crypto_secretbox_NONCEBYTES,
source_buffer.size() - crypto_secretbox_NONCEBYTES,
source_buffer.data(),
decrypt_key_.data()) != 0)
{
LOG(ERROR) << "crypto_secretbox_open_easy() failed";
return IOBuffer();
}
return decrypted_buffer;
}
} // namespace aspia
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <vector>
#include <deque>
#include <string>
#include <algorithm>
#include <sstream>
/* definitions */
const int stone_size = 8;
const int field_size = 32;
const int empty_val = -1; // 障害物やzkの無いことを表す
const int filled_val = 256; // 障害物を表す
FILE* dumpout = stdout; // dump系関数の出力先
struct Position {
/*座標を表現するクラス*/
int y, x;
bool operator==(const Position&obj) const {
return y == obj.y && x == obj.x;
}
bool operator<(const Position&obj) const {
if (y == obj.y) {
return x < obj.x;
}
return y < obj.y;
}
};
struct Stone {
/* 石 */
int raw[stone_size][stone_size]; // empty_val -> 空き, otherwise -> うまり
std::deque<Position> fills; // 埋まってる座標を持っておく
};
struct Field {
/* フィールド */
int raw[field_size][field_size];
std::deque<std::string> answer; // 答えとなる石の置き方を持っておく
};
int number_of_stones; // 与えられる石の数
Stone stones[256 * 8]; // 石を持っておくインスタンス(回転反転を考慮して8倍とってある)
Field initial_field; // 初期フィールド状態
std::deque<Position> initial_empties; // 初期フィールドで空いている場所を探す
int rotated(int deg) {
/* 石をdeg度まわした石の番号のバイアスを返す */
return number_of_stones * (deg/90);
}
int fliped() {
/* 石を反転した時の石の番号のバイアスを返す */
return number_of_stones * 4;
}
int operated(bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
if (flip) {
if (deg == 0) {
return fliped();
}
return fliped() + rotated(deg);
}
return rotated(deg);
}
int rotated(int n, int deg) {
/* 石をdeg度まわした石の番号を返す */
return n + rotated(deg);
}
int fliped(int n) {
/* 石を反転した時の石の番号を返す */
return n + fliped();
}
int operated(int n, bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
return n + operated(flip, deg);
}
int all_stones_num() {
/* 全部で石が何個になるか */
return 8*number_of_stones;
}
/* util */
std::string to_s(int n) {
/* std::to_stringとかぶるけど、本番環境では必要になりそう*/
std::stringstream ss;
ss << n;
return ss.str();
}
int get() {
return getc(stdin) - '0';
}
void read_br() {
/* CRLFを読み飛ばす */
get();
get();
};
/* dump */
void dump_stone(int n) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (stones[n].raw[i][j] == empty_val) {
/* 空き */
putc('.', dumpout);
} else {
/* うまり */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
void dump_field(Field& f) {
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (f.raw[i][j] == empty_val) {
/* あき */
putc('.', dumpout);
} else if (f.raw[i][j] == filled_val) {
/* 障害物 */
putc('#', dumpout);
} else {
/* 石 */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
/* stone manipurates */
void init_stone(int n) {
/* 石を初期化しておく */
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
stones[n].raw[i][j] = empty_val;
}
}
}
void rotate_stone(int n, int deg) {
/* 石を回す。deg = 90でよばれて、内部で180, 270をよぶ */
init_stone(rotated(n, deg));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].x;
int newx = 7 - stones[n].fills[i].y;
stones[rotated(n, deg)].fills.push_back(Position{newy, newx});
stones[rotated(n, deg)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
if (deg != 270) {
rotate_stone(n, deg+90);
}
}
void flip_stone(int n) {
/* 石を反転させる */
init_stone(fliped(n));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].y;
int newx = 7 - stones[n].fills[i].x;
stones[fliped(n)].fills.push_back(Position{newy, newx});
stones[fliped(n)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
}
/* parsing */
void get_field() {
/* 初期フィールドを得る */
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (get() == 0) {
initial_field.raw[i][j] = empty_val;
} else {
initial_field.raw[i][j] = filled_val;
}
}
read_br();
}
}
void get_stone(int index) {
/* 石をひとつ読む */
for (int i = 0; i < stone_size; ++i) {
for (int j = 0; j < stone_size; ++j) {
if (get() == 0) {
stones[index].raw[i][j] = empty_val;
} else {
stones[index].raw[i][j] = index;
stones[index].fills.push_back(Position{i, j});
}
}
read_br();
}
}
void get_stones() {
/* 石をnumber_of_stones個よむ */
for (int i = 0; i < number_of_stones; ++i) {
get_stone(i);
read_br();
flip_stone(i);
rotate_stone(i, 90);
rotate_stone(fliped(i), 90);
}
}
void get_input() {
/* 入力を読む */
get_field(); read_br();
scanf("%d\n", &number_of_stones);
get_stones();
}
/* helper */
void create_candidates(std::deque<Position>& next_candidates, int n, std::deque<Position>& empties) {
/* 石の埋まっている場所とフィールド上の候補から、次に石を置く可能性のある場所に置く*/
next_candidates.resize(empties.size() * stones[n].fills.size());
for (auto p1 : empties) {
for (auto p2 : stones[n].fills) {
next_candidates.push_back(Position{ p1.y - p2.y, p1.x - p2.x });
}
}
}
bool pos_check(int y, int x) {
return (0 <= y && y < field_size) && (0 <= x < field_size);
}
/* solver */
int put_stone(int n, Position base, Field& f, std::deque<Position>& next_candidates) {
/* 石を置く処理。ついでに次に石を置けそうな場所を探す */
int score = 0;
Field backup = f;
for (auto p : stones[n].fills) { // zkごとにおけるかどうかを判定する
int y = base.y + p.y;
int x = base.x + p.x;
if (!pos_check(y, x) || f.raw[y][x] != empty_val) { // 置きたい場所が空いてないと置けない
next_candidates.clear();
f = backup;
return 0;
}
score += 1;
f.raw[y][x] = n;
/* 置いたところは候補から外す */
auto exists = std::find(next_candidates.begin(), next_candidates.end(), Position{y, x});
if (exists != next_candidates.end()) {
next_candidates.erase(exists);
}
/* 隣接している空きマスを次の候補に */
int dy[] = {-1, 0, 0, 1};
int dx[] = {0, -1, 1, 0};
for (int i = 0; i < 4; ++i) {
if (pos_check(y + dy[i], x + dx[i]) &&
f.raw[y + dy[i]][x + dx[i]] == empty_val) {
next_candidates.push_back(Position{y+dy[i], x+dx[i]});
}
}
}
return score;
}
void dfs(int n, bool fliped, int deg, Position p, Field& f) {
/* n番の石をfliped + degの状態で、f上のpに置くところから深く */
if (n >= number_of_stones) {
return;
}
int m = operated(n, fliped, deg);
std::deque<Position> next_candidates;
if (put_stone(m, p, f, next_candidates) > 0) {
}
}
void solve() {
/* とりあえずこれを呼んでsolveする */
std::deque<Position> first_candidates; // 最初の石を置く場所
for (int i = 0; i < number_of_stones; ++i) {
for (int j = 0; j <= 270; j += 90) { // 回転
for (bool k = false; !k; k = true) { // 反転
create_candidates(first_candidates, operated(i, k, j), initial_empties); // 一個目の石を置く場所の候補を生成
for (auto p : first_candidates) {
dfs(i, k, j, p, initial_field);
}
}
}
}
}
/* main */
int main() {
initial_empties.resize(1024);
get_input();
// dump_field(initial_field);
// solve();
}
<commit_msg>答えを出力する部分作ったはず<commit_after>#include <cstdio>
#include <vector>
#include <deque>
#include <string>
#include <algorithm>
#include <sstream>
/* definitions */
const int stone_size = 8;
const int field_size = 32;
const int empty_val = -1; // 障害物やzkの無いことを表す
const int filled_val = 256; // 障害物を表す
FILE* dumpout = stdout; // dump系関数の出力先
struct Position {
/*座標を表現するクラス*/
int y, x;
bool operator==(const Position&obj) const {
return y == obj.y && x == obj.x;
}
bool operator<(const Position&obj) const {
if (y == obj.y) {
return x < obj.x;
}
return y < obj.y;
}
};
struct Stone {
/* 石 */
int raw[stone_size][stone_size]; // empty_val -> 空き, otherwise -> うまり
std::deque<Position> fills; // 埋まってる座標を持っておく
};
struct Field {
/* フィールド */
int raw[field_size][field_size];
std::deque<std::string> answer; // 答えとなる石の置き方を持っておく
};
int number_of_stones; // 与えられる石の数
Stone stones[256 * 8]; // 石を持っておくインスタンス(回転反転を考慮して8倍とってある)
Field initial_field; // 初期フィールド状態
std::deque<Position> initial_empties; // 初期フィールドで空いている場所を探す
int rotated(int deg) {
/* 石をdeg度まわした石の番号のバイアスを返す */
return number_of_stones * (deg/90);
}
int fliped() {
/* 石を反転した時の石の番号のバイアスを返す */
return number_of_stones * 4;
}
int operated(bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
if (flip) {
if (deg == 0) {
return fliped();
}
return fliped() + rotated(deg);
}
return rotated(deg);
}
int rotated(int n, int deg) {
/* 石をdeg度まわした石の番号を返す */
return n + rotated(deg);
}
int fliped(int n) {
/* 石を反転した時の石の番号を返す */
return n + fliped();
}
int operated(int n, bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
return n + operated(flip, deg);
}
int all_stones_num() {
/* 全部で石が何個になるか */
return 8*number_of_stones;
}
/* util */
std::string to_s(int n) {
/* std::to_stringとかぶるけど、本番環境では必要になりそう*/
std::stringstream ss;
ss << n;
return ss.str();
}
int get() {
return getc(stdin) - '0';
}
void read_br() {
/* CRLFを読み飛ばす */
get();
get();
};
/* dump */
void dump_stone(int n) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (stones[n].raw[i][j] == empty_val) {
/* 空き */
putc('.', dumpout);
} else {
/* うまり */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
void dump_field(Field& f) {
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (f.raw[i][j] == empty_val) {
/* あき */
putc('.', dumpout);
} else if (f.raw[i][j] == filled_val) {
/* 障害物 */
putc('#', dumpout);
} else {
/* 石 */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
/* stone manipurates */
void init_stone(int n) {
/* 石を初期化しておく */
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
stones[n].raw[i][j] = empty_val;
}
}
}
void rotate_stone(int n, int deg) {
/* 石を回す。deg = 90でよばれて、内部で180, 270をよぶ */
init_stone(rotated(n, deg));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].x;
int newx = 7 - stones[n].fills[i].y;
stones[rotated(n, deg)].fills.push_back(Position{newy, newx});
stones[rotated(n, deg)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
if (deg != 270) {
rotate_stone(n, deg+90);
}
}
void flip_stone(int n) {
/* 石を反転させる */
init_stone(fliped(n));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].y;
int newx = 7 - stones[n].fills[i].x;
stones[fliped(n)].fills.push_back(Position{newy, newx});
stones[fliped(n)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
}
/* parsing */
void get_field() {
/* 初期フィールドを得る */
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (get() == 0) {
initial_field.raw[i][j] = empty_val;
} else {
initial_field.raw[i][j] = filled_val;
}
}
read_br();
}
}
void get_stone(int index) {
/* 石をひとつ読む */
for (int i = 0; i < stone_size; ++i) {
for (int j = 0; j < stone_size; ++j) {
if (get() == 0) {
stones[index].raw[i][j] = empty_val;
} else {
stones[index].raw[i][j] = index;
stones[index].fills.push_back(Position{i, j});
}
}
read_br();
}
}
void get_stones() {
/* 石をnumber_of_stones個よむ */
for (int i = 0; i < number_of_stones; ++i) {
get_stone(i);
read_br();
flip_stone(i);
rotate_stone(i, 90);
rotate_stone(fliped(i), 90);
}
}
void get_input() {
/* 入力を読む */
get_field(); read_br();
scanf("%d\n", &number_of_stones);
get_stones();
}
/* helper */
void create_candidates(std::deque<Position>& next_candidates, int n, std::deque<Position>& empties) {
/* 石の埋まっている場所とフィールド上の候補から、次に石を置く可能性のある場所に置く*/
next_candidates.resize(empties.size() * stones[n].fills.size());
for (auto p1 : empties) {
for (auto p2 : stones[n].fills) {
next_candidates.push_back(Position{ p1.y - p2.y, p1.x - p2.x });
}
}
}
bool pos_check(int y, int x) {
/* 与えられた座標が、fieldからはみ出ていたらfalseを返す */
return (0 <= y && y < field_size) && (0 <= x < field_size);
}
std::string create_answer_format(int n, bool flip, int deg, Position p) {
/* 石を置いた様子から回答フォーマットに沿った文字列を返す */
return to_s(p.x) + " " + to_s(p.y) + " " + (flip ? "T" : "H") + " " + to_s(deg);
}
void print_anser(Field& f) {
for (auto l : f.answer) {
printf("%s\n", l.c_str());
}
}
/* solver */
int put_stone(int n, Position base, Field& f, std::deque<Position>& next_candidates) {
/* 石を置く処理。ついでに次に石を置けそうな場所を探す */
int score = 0;
Field backup = f;
for (auto p : stones[n].fills) { // zkごとにおけるかどうかを判定する
int y = base.y + p.y;
int x = base.x + p.x;
if (!pos_check(y, x) || f.raw[y][x] != empty_val) { // 置きたい場所が空いてないと置けない
next_candidates.clear();
f = backup;
return 0;
}
score += 1;
f.raw[y][x] = n;
/* 置いたところは候補から外す */
auto exists = std::find(next_candidates.begin(), next_candidates.end(), Position{y, x});
if (exists != next_candidates.end()) {
next_candidates.erase(exists);
}
/* 隣接している空きマスを次の候補に */
int dy[] = {-1, 0, 0, 1};
int dx[] = {0, -1, 1, 0};
for (int i = 0; i < 4; ++i) {
if (pos_check(y + dy[i], x + dx[i]) &&
f.raw[y + dy[i]][x + dx[i]] == empty_val) {
next_candidates.push_back(Position{y+dy[i], x+dx[i]});
}
}
}
return score;
}
void dfs(int n, bool fliped, int deg, Position p, Field& f) {
/* n番の石をfliped + degの状態で、f上のpに置くところから深く */
if (n >= number_of_stones) {
return;
}
int m = operated(n, fliped, deg);
std::deque<Position> next_empties, next_candidates;
if (put_stone(m, p, f, next_empties) > 0) {
/* 石を置いた時の処理 */
f.answer[n] = create_answer_format(n, fliped, deg, p);
print_anser(f);
}
/* 次の石を置く処理 */
for (int i = n + 1; i < number_of_stones; ++i) {
for (int j = 0; j <= 270; j += 90) { // 回転
for (bool k = false; !k; k = true) { // 反転
create_candidates(next_candidates, operated(i, k, j), next_empties); // 石を置く場所の候補を生成
for (auto p : next_candidates) {
dfs(i, k, j, p, f);
}
}
}
}
}
void solve() {
/* とりあえずこれを呼んでsolveする */
std::deque<Position> first_candidates; // 最初の石を置く場所
for (int i = 0; i < number_of_stones; ++i) {
for (int j = 0; j <= 270; j += 90) { // 回転
for (bool k = false; !k; k = true) { // 反転
create_candidates(first_candidates, operated(i, k, j), initial_empties); // 一個目の石を置く場所の候補を生成
for (auto p : first_candidates) {
dfs(i, k, j, p, initial_field);
}
}
}
}
}
/* main */
int main() {
initial_empties.resize(1024);
get_input();
initial_field.answer.resize(number_of_stones);
// dump_field(initial_field);
// solve();
}
<|endoftext|>
|
<commit_before>/*
* \copyright Copyright 2014 Xiang Zhang All Rights Reserved.
* \license @{
*
* 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.
*
* @}
*/
#ifndef THUNDER_LINALG_LINALG_HPP_
#define THUNDER_LINALG_LINALG_HPP_
#include "thunder/tensor.hpp"
namespace thunder {
namespace linalg {
template < typename T = DoubleTensor, typename H = int >
class Linalg {
public:
typedef typename T::value_type value_type;
typedef typename T::size_type size_type;
Linalg();
template < typename... G >
Linalg(G... g);
~Linalg();
// Const result BLAS level-1 routines
const T& asum(const T &x, const T &r);
const T& axpy(const value_type &a, const T &x, const T &y, const T &r);
const T& copy(const T &x, const T &y);
const T& dot(const T &x, const T &y, const T &r);
const T& sdot(const T &x, const T &y, const T &r);
const T& dotc(const T &x, const T &y, const T &r);
const T& nrm2(const T &x, const T &r);
const T& rot(const T &x, const T &y, const value_type &c,
const value_type &s);
const T& rotm(const T &x, const T &y, const T &P);
const T& scal(const value_type &a, const T &x);
const T& swap(const T &x, const T &y);
const SizeTensor& iamax(const T &x, const SizeTensor &r);
const SizeTensor& iamin(const T &x, const SizeTensor &r);
const T& cabs1(const T &x);
// Const result BLAS level-2 routines
const T& gbmv(size_type kl, size_type ku, const value_type &alpha, const T &a,
const T &x, const value_type &beta, const T&y);
const T& gemv(const value_type &alpha, const T &a, const T &x,
const value_type &beta, const T &y);
const T& ger(const value_type &alpha, const T &x, const T &y, const T &a);
const T& gerc(const value_type &alpha, const T &x, const T &y, const T &a);
};
} // namespace linalg
} // namespace thunder
#endif // THUNDER_LINALG_LINALG_HPP_
<commit_msg>Completed design for BLAS interfaces<commit_after>/*
* \copyright Copyright 2014 Xiang Zhang All Rights Reserved.
* \license @{
*
* 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.
*
* @}
*/
#ifndef THUNDER_LINALG_LINALG_HPP_
#define THUNDER_LINALG_LINALG_HPP_
#include "thunder/tensor.hpp"
namespace thunder {
namespace linalg {
template < typename T = DoubleTensor, typename H = int >
class Linalg {
public:
typedef typename T::value_type value_type;
typedef typename T::size_type size_type;
Linalg();
template < typename... G >
Linalg(G... g);
~Linalg();
// Needed constant types
enum BlasUplo {
BLAS_UPPER,
BLAS_LOWER
};
enum BlasDiag {
BLAS_NON_UNIT,
BLAS_UNIT
};
enum BlasSide {
BLAS_RIGHT,
BLAS_LEFT
};
// Const result BLAS level-1 routines
const T& asum(const T &x, const T &r);
const T& axpy(const value_type &a, const T &x, const T &y, const T &r);
const T& copy(const T &x, const T &y);
const T& dot(const T &x, const T &y, const T &r);
const T& sdot(const T &x, const T &y, const T &r);
const T& dotc(const T &x, const T &y, const T &r);
const T& nrm2(const T &x, const T &r);
const T& rot(const T &x, const T &y, const value_type &c,
const value_type &s);
const T& rotm(const T &x, const T &y, const T &P);
const T& scal(const value_type &a, const T &x);
const T& swap(const T &x, const T &y);
const SizeTensor& iamax(const T &x, const SizeTensor &r);
const SizeTensor& iamin(const T &x, const SizeTensor &r);
const T& cabs1(const T &x);
// Const result BLAS level-2 routines
const T& gbmv(size_type kl, size_type ku, const value_type &alpha, const T &a,
const T &x, const value_type &beta, const T&y);
const T& gemv(const value_type &alpha, const T &a, const T &x,
const value_type &beta, const T &y);
const T& ger(const value_type &alpha, const T &x, const T &y, const T &a);
const T& gerc(const value_type &alpha, const T &x, const T &y, const T &a);
const T& hbmv(BlasUplo uplo, size_type k, const value_type &alpha,
const T &a, const T &x, const value_type &beta, const T &y);
const T& hemv(BlasUplo uplo, const value_type &alpha, const T &a, const T &x,
const value_type &beta, const T &y);
const T& her(BlasUplo uplo, const value_type &alpha, const T &x, const T &a);
const T& her2(BlasUplo uplo, const value_type &alpha, const T &x, const T &y,
const T &a);
const T& hpmv(BlasUplo uplo, const value_type &alpha, const T &ap, const T &x,
const value_type &beta, const T &y);
const T& hpr(BlasUplo uplo, const value_type &alpha, const T &x, const T &ap);
const T& hpr2(BlasUplo uplo, const value_type &alpha, const T &x, const T &y,
const T &ap);
const T& sbmv(BlasUplo uplo, size_type k, const value_type &alpha,
const T &a, const T &x, const value_type &beta, const T &y);
const T& spmv(BlasUplo uplo, const value_type &alpha, const T &ap, const T &x,
const value_type &beta, const T &y);
const T& spr(BlasUplo uplo, const value_type &alpha, const T &x, const T &ap);
const T& spr2(BlasUplo uplo, const value_type &alpha, const T &x, const T &y,
const T &ap);
const T& symv(BlasUplo uplo, const value_type &alpha, const T &ap, const T &x,
const value_type &beta, const T &y);
const T& syr(BlasUplo uplo, const value_type &alpha, const T &x, const T &a);
const T& syr2(BlasUplo uplo, const value_type &alpha, const T &x, const T &y,
const T &a);
const T& tbmv(BlasUplo uplo, BlasDiag diag, size_type k, const T &a,
const T &x);
const T& tbsv(BlasUplo uplo, BlasDiag diag, size_type k, const T &a,
const T &x);
const T& tpmv(BlasUplo uplo, BlasDiag diag, const T &ap, const T &x);
const T& tpsv(BlasUplo uplo, BlasDiag diag, const T &ap, const T &x);
const T& trmv(BlasUplo uplo, BlasDiag diag, const T &a, const T &x);
const T& trsv(BlasUplo uplo, BlasDiag diag, const T &a, const T &x);
// Const result level-3 BLAS routines
const T& gemm(const value_type &alpha, const T &a, const T&b,
const value_type &beta, const T &c);
const T& hemm(BlasUplo uplo, const value_type &alpha, const T &a, const T&b,
const value_type &beta, const T &c);
const T& herk(BlasUplo uplo, const value_type &alpha, const T &a,
const value_type &beta, const T &c);
const T& herk2(BlasUplo uplo, const value_type &alpha, const T &a, const T&b,
const value_type &beta, const T &c);
const T& symm(BlasUplo uplo, const value_type &alpha, const T &a, const T&b,
const value_type &beta, const T &c);
const T& syrk(BlasUplo uplo, const value_type &alpha, const T &a,
const value_type &beta, const T &c);
const T& syrk2(BlasUplo uplo, const value_type &alpha, const T &a, const T&b,
const value_type &beta, const T &c);
const T& trmm(BlasUplo uplo, BlasDiag diag, const value_type &alpha,
const T &a, const T&b, const value_type &beta, const T &c);
const T& trsm(BlasSide side, BlasUplo uplo, BlasDiag diag,
const value_type &alpha, const T &a, const T &b);
};
} // namespace linalg
} // namespace thunder
#endif // THUNDER_LINALG_LINALG_HPP_
<|endoftext|>
|
<commit_before>// Copyright Steinwurf ApS 2011-2012.
// Distributed under the "STEINWURF RESEARCH LICENSE 1.0".
// See accompanying file LICENSE.rst or
// http://www.steinwurf.com/licensing
#pragma once
#include <ctime>
#include <cstdint>
#include <cstdio>
#include <gauge/gauge.hpp>
/// A test block represents an encoder and decoder pair
template<class Encoder, class Decoder>
struct throughput_benchmark : public gauge::time_benchmark
{
void init()
{
m_factor = 1;
gauge::time_benchmark::init();
}
void start()
{
m_encoded_symbols = 0;
m_decoded_symbols = 0;
gauge::time_benchmark::start();
}
void stop()
{
gauge::time_benchmark::stop();
}
double measurement()
{
// Get the time spent per iteration
double time = gauge::time_benchmark::measurement();
//printf("Coding time: %.3f us\n", time);
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
// The number of bytes {en|de}coded
uint64_t total_bytes = 0;
if (type == "decoder")
{
total_bytes = m_decoded_symbols * symbol_size;
}
else if (type == "encoder")
{
total_bytes = m_encoded_symbols * symbol_size;
}
else
{
assert(0);
}
// The bytes per iteration
uint64_t bytes =
total_bytes / gauge::time_benchmark::iteration_count();
return bytes / time; // MB/s for each iteration
}
void store_run(tables::table& results)
{
if(!results.has_column("throughput"))
results.add_column("throughput");
results.set_value("throughput", measurement());
}
bool needs_warmup_iteration()
{
return false;
}
bool accept_measurement()
{
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
if(type == "decoder")
{
// If we are benchmarking a decoder, we only accept
// the measurement if the decoding was successful
if (m_decoder->is_complete() == false)
{
return false;
}
// At this point, the output data should be equal to the input data
assert(m_decoder->verify_data(m_encoder));
}
// Force a single iteration (repeated tests produce unstable results)
return true;
//return gauge::time_benchmark::accept_measurement();
}
std::string unit_text() const
{
return "MB/s";
}
void get_options(gauge::po::variables_map& options)
{
auto symbols = options["symbols"].as<std::vector<uint32_t> >();
auto redundancy = options["redundancy"].as<std::vector<double> >();
auto symbol_size = options["symbol_size"].as<std::vector<uint32_t> >();
auto types = options["type"].as<std::vector<std::string> >();
assert(symbols.size() > 0);
assert(redundancy.size() > 0);
assert(symbol_size.size() > 0);
assert(types.size() > 0);
for (const auto& s : symbols)
{
for (const auto& r : redundancy)
{
for (const auto& p : symbol_size)
{
// Symbol size must be a multiple of 32
assert(p % 32 == 0);
for (const auto& t : types)
{
gauge::config_set cs;
cs.set_value<uint32_t>("symbols", s);
cs.set_value<uint32_t>("symbol_size", p);
cs.set_value<double>("redundancy", r);
cs.set_value<std::string>("type", t);
uint32_t encoded = (uint32_t)std::ceil(s * r);
cs.set_value<uint32_t>("encoded_symbols", encoded);
add_configuration(cs);
}
}
}
}
}
void setup()
{
gauge::config_set cs = get_current_configuration();
uint32_t symbols = cs.get_value<uint32_t>("symbols");
uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
uint32_t encoded_symbols = cs.get_value<uint32_t>("encoded_symbols");
m_encoder = std::make_shared<Encoder>(
symbols, symbol_size, encoded_symbols);
m_decoder = std::make_shared<Decoder>(
symbols, symbol_size, encoded_symbols);
}
void encode_payloads()
{
m_encoder->encode_all();
m_encoded_symbols += m_encoder->payload_count();
}
void decode_payloads()
{
m_decoder->decode_all(m_encoder);
m_decoded_symbols += m_encoder->payload_count();
}
/// Run the encoder
void run_encode()
{
// The clock is running
RUN
{
encode_payloads();
}
}
/// Run the decoder
void run_decode()
{
// Encode some data
encode_payloads();
// The clock is running
RUN
{
// Decode the payloads
decode_payloads();
}
}
void run_benchmark()
{
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
if (type == "encoder")
{
run_encode();
}
else if (type == "decoder")
{
run_decode();
}
else
{
assert(0);
}
}
protected:
/// The encoder
std::shared_ptr<Encoder> m_encoder;
/// The decoder
std::shared_ptr<Decoder> m_decoder;
/// The number of symbols encoded
uint32_t m_encoded_symbols;
/// The number of symbols decoded
uint32_t m_decoded_symbols;
/// Multiplication factor for payload_count
uint32_t m_factor;
};
<commit_msg>Fix decoding throughput<commit_after>// Copyright Steinwurf ApS 2011-2012.
// Distributed under the "STEINWURF RESEARCH LICENSE 1.0".
// See accompanying file LICENSE.rst or
// http://www.steinwurf.com/licensing
#pragma once
#include <ctime>
#include <cstdint>
#include <cstdio>
#include <gauge/gauge.hpp>
/// A test block represents an encoder and decoder pair
template<class Encoder, class Decoder>
struct throughput_benchmark : public gauge::time_benchmark
{
void init()
{
m_factor = 1;
gauge::time_benchmark::init();
}
void start()
{
m_encoded_symbols = 0;
m_decoded_symbols = 0;
gauge::time_benchmark::start();
}
void stop()
{
gauge::time_benchmark::stop();
}
double measurement()
{
// Get the time spent per iteration
double time = gauge::time_benchmark::measurement();
//printf("Coding time: %.3f us\n", time);
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
// The number of bytes {en|de}coded
uint64_t total_bytes = 0;
if (type == "decoder")
{
total_bytes = m_decoded_symbols * symbol_size;
}
else if (type == "encoder")
{
total_bytes = m_encoded_symbols * symbol_size;
}
else
{
assert(0);
}
// The bytes per iteration
uint64_t bytes =
total_bytes / gauge::time_benchmark::iteration_count();
return bytes / time; // MB/s for each iteration
}
void store_run(tables::table& results)
{
if(!results.has_column("throughput"))
results.add_column("throughput");
results.set_value("throughput", measurement());
}
bool needs_warmup_iteration()
{
return false;
}
bool accept_measurement()
{
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
if(type == "decoder")
{
// If we are benchmarking a decoder, we only accept
// the measurement if the decoding was successful
if (m_decoder->is_complete() == false)
{
return false;
}
// At this point, the output data should be equal to the input data
assert(m_decoder->verify_data(m_encoder));
}
// Force a single iteration (repeated tests produce unstable results)
return true;
//return gauge::time_benchmark::accept_measurement();
}
std::string unit_text() const
{
return "MB/s";
}
void get_options(gauge::po::variables_map& options)
{
auto symbols = options["symbols"].as<std::vector<uint32_t> >();
auto redundancy = options["redundancy"].as<std::vector<double> >();
auto symbol_size = options["symbol_size"].as<std::vector<uint32_t> >();
auto types = options["type"].as<std::vector<std::string> >();
assert(symbols.size() > 0);
assert(redundancy.size() > 0);
assert(symbol_size.size() > 0);
assert(types.size() > 0);
for (const auto& s : symbols)
{
for (const auto& r : redundancy)
{
for (const auto& p : symbol_size)
{
// Symbol size must be a multiple of 32
assert(p % 32 == 0);
for (const auto& t : types)
{
gauge::config_set cs;
cs.set_value<uint32_t>("symbols", s);
cs.set_value<uint32_t>("symbol_size", p);
cs.set_value<double>("redundancy", r);
cs.set_value<std::string>("type", t);
uint32_t encoded = (uint32_t)std::ceil(s * r);
cs.set_value<uint32_t>("encoded_symbols", encoded);
add_configuration(cs);
}
}
}
}
}
void setup()
{
gauge::config_set cs = get_current_configuration();
uint32_t symbols = cs.get_value<uint32_t>("symbols");
uint32_t symbol_size = cs.get_value<uint32_t>("symbol_size");
uint32_t encoded_symbols = cs.get_value<uint32_t>("encoded_symbols");
m_encoder = std::make_shared<Encoder>(
symbols, symbol_size, encoded_symbols);
m_decoder = std::make_shared<Decoder>(
symbols, symbol_size, encoded_symbols);
}
void encode_payloads()
{
m_encoder->encode_all();
m_encoded_symbols += m_encoder->payload_count();
}
void decode_payloads()
{
m_decoder->decode_all(m_encoder);
gauge::config_set cs = get_current_configuration();
uint32_t encoded_symbols = cs.get_value<uint32_t>("encoded_symbols");
m_decoded_symbols += encoded_symbols;
}
/// Run the encoder
void run_encode()
{
// The clock is running
RUN
{
encode_payloads();
}
}
/// Run the decoder
void run_decode()
{
// Encode some data
encode_payloads();
// The clock is running
RUN
{
// Decode the payloads
decode_payloads();
}
}
void run_benchmark()
{
gauge::config_set cs = get_current_configuration();
std::string type = cs.get_value<std::string>("type");
if (type == "encoder")
{
run_encode();
}
else if (type == "decoder")
{
run_decode();
}
else
{
assert(0);
}
}
protected:
/// The encoder
std::shared_ptr<Encoder> m_encoder;
/// The decoder
std::shared_ptr<Decoder> m_decoder;
/// The number of symbols encoded
uint32_t m_encoded_symbols;
/// The number of symbols decoded
uint32_t m_decoded_symbols;
/// Multiplication factor for payload_count
uint32_t m_factor;
};
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2015-2017 Vanamco AG, http://www.vanamco.com
*
* The MIT License (MIT)
* 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.
*
* Contributors:
* Matthias Christen, Vanamco AG
*******************************************************************************/
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <string>
#include "lib/cef/include/cef_app.h"
#include "lib/cef/include/cef_browser.h"
#include "lib/cef/include/cef_command_line.h"
#include "lib/cef/include/cef_frame.h"
#include "lib/cef/include/cef_web_plugin.h"
#include "base/app.h"
#include "base/cef/client_handler.h"
CefRefPtr<Zephyros::ClientHandler> g_handler;
CefRefPtr<CefCommandLine> g_command_line;
namespace Zephyros {
namespace App {
CefRefPtr<CefBrowser> GetBrowser()
{
if (!g_handler.get())
return NULL;
return g_handler->GetBrowser();
}
ClientWindowHandle GetMainHwnd()
{
if (!g_handler.get())
return NULL;
return g_handler->GetMainHwnd();
}
void InitCommandLine(int argc, const char* const* argv)
{
g_command_line = CefCommandLine::CreateCommandLine();
#if defined(OS_WIN)
g_command_line->InitFromString(::GetCommandLineW());
#else
g_command_line->InitFromArgv(argc, argv);
#endif
}
/**
* Returns the application command line object.
*/
CefRefPtr<CefCommandLine> GetCommandLine()
{
return g_command_line;
}
/**
* Returns the application settings based on command line arguments.
*/
void GetSettings(CefSettings& settings)
{
DCHECK(g_command_line.get());
if (!g_command_line.get())
return;
settings.no_sandbox = true;
#if defined(OS_WIN)
settings.multi_threaded_message_loop = false;
#endif
// CefString(&settings.cache_path) = g_command_line->GetSwitchValue(cefclient::kCachePath);
#ifndef NDEBUG
// Specify a port to enable DevTools if one isn't already specified.
if (!g_command_line->HasSwitch("remote-debugging-port"))
settings.remote_debugging_port = 19384;
#endif
// set the logging severity
#ifndef NDEBUG
settings.log_severity = LOGSEVERITY_VERBOSE;
#else
settings.log_severity = LOGSEVERITY_VERBOSE;
#endif
}
} // namespace App
} // namespace Zephyros
<commit_msg>make gui not inspectable in release build<commit_after>/*******************************************************************************
* Copyright (c) 2015-2017 Vanamco AG, http://www.vanamco.com
*
* The MIT License (MIT)
* 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.
*
* Contributors:
* Matthias Christen, Vanamco AG
*******************************************************************************/
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <string>
#include "lib/cef/include/cef_app.h"
#include "lib/cef/include/cef_browser.h"
#include "lib/cef/include/cef_command_line.h"
#include "lib/cef/include/cef_frame.h"
#include "lib/cef/include/cef_web_plugin.h"
#include "base/app.h"
#include "base/cef/client_handler.h"
CefRefPtr<Zephyros::ClientHandler> g_handler;
CefRefPtr<CefCommandLine> g_command_line;
namespace Zephyros {
namespace App {
CefRefPtr<CefBrowser> GetBrowser()
{
if (!g_handler.get())
return NULL;
return g_handler->GetBrowser();
}
ClientWindowHandle GetMainHwnd()
{
if (!g_handler.get())
return NULL;
return g_handler->GetMainHwnd();
}
void InitCommandLine(int argc, const char* const* argv)
{
g_command_line = CefCommandLine::CreateCommandLine();
#if defined(OS_WIN)
g_command_line->InitFromString(::GetCommandLineW());
#else
g_command_line->InitFromArgv(argc, argv);
#endif
}
/**
* Returns the application command line object.
*/
CefRefPtr<CefCommandLine> GetCommandLine()
{
return g_command_line;
}
/**
* Returns the application settings based on command line arguments.
*/
void GetSettings(CefSettings& settings)
{
DCHECK(g_command_line.get());
if (!g_command_line.get())
return;
settings.no_sandbox = true;
#if defined(OS_WIN)
settings.multi_threaded_message_loop = false;
#endif
// CefString(&settings.cache_path) = g_command_line->GetSwitchValue(cefclient::kCachePath);
#ifndef NDEBUG
// Specify a port to enable DevTools if one isn't already specified.
if (!g_command_line->HasSwitch("remote-debugging-port"))
settings.remote_debugging_port = 19384;
#else
settings.remote_debugging_port = 0;
#endif
// set the logging severity
#ifndef NDEBUG
settings.log_severity = LOGSEVERITY_VERBOSE;
#else
settings.log_severity = LOGSEVERITY_VERBOSE;
#endif
}
} // namespace App
} // namespace Zephyros
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: HTables.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-06-27 08:25:04 $
*
* 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 CONNECTIVITY_HSQLDB_TABLES_HXX
#include "hsqldb/HTables.hxx"
#endif
#ifndef _CONNECTIVITY_HSQLDB_VIEWS_HXX_
#include "hsqldb/HViews.hxx"
#endif
#ifndef CONNECTIVITY_HSQLDB_TABLE_HXX
#include "hsqldb/HTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_HSQLDB_CATALOG_HXX
#include "hsqldb/HCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace ::cppu;
using namespace connectivity::hsqldb;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));
Sequence< ::rtl::OUString > sTableTypes(3);
sTableTypes[0] = s_sTableTypeView;
sTableTypes[1] = s_sTableTypeTable;
sTableTypes[2] = s_sAll; // just to be sure to include anything else ....
Any aCatalog;
if ( sCatalog.getLength() )
aCatalog <<= sCatalog;
Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);
sdbcx::ObjectType xRet = NULL;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() ) // there can be only one table with this name
{
sal_Int32 nPrivileges = ::dbtools::getTablePrivileges( m_xMetaData, sCatalog, sSchema, sTable );
if ( m_xMetaData->isReadOnly() )
nPrivileges &= ~( Privilege::INSERT | Privilege::UPDATE | Privilege::DELETE | Privilege::CREATE | Privilege::ALTER | Privilege::DROP );
// obtain privileges
OHSQLTable* pRet = new OHSQLTable( this
,static_cast<OHCatalog&>(m_rParent).getConnection()
,sTable
,xRow->getString(4)
,xRow->getString(5)
,sSchema
,sCatalog
,nPrivileges);
xRet = pRet;
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh( ) throw(RuntimeException)
{
static_cast<OHCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
m_xMetaData = NULL;
OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
return new OHSQLTable(this,static_cast<OHCatalog&>(m_rParent).getConnection());
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
if(!aName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));
createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY);
sal_Bool bIsNew = sal_False;
if(xTunnel.is())
{
connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
if(pTable)
bIsNew = pTable->isNew();
}
if (!bIsNew)
{
Reference< XConnection > xConnection = static_cast<OHCatalog&>(m_rParent).getConnection();
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");
Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
sal_Bool bIsView;
if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
aSql += ::rtl::OUString::createFromAscii("VIEW ");
else
aSql += ::rtl::OUString::createFromAscii("TABLE ");
::rtl::OUString sComposedName;
::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
aSql += sComposedName;
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
// if no exception was thrown we must delete it from the views
if ( bIsView )
{
OViews* pViews = static_cast<OViews*>(static_cast<OHCatalog&>(m_rParent).getPrivateViews());
if ( pViews && pViews->hasByName(_sElementName) )
pViews->dropByNameImpl(_sElementName);
}
}
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
Reference< XConnection > xConnection = static_cast<OHCatalog&>(m_rParent).getConnection();
::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
insertElement(_rsNewTable,NULL);
// notify our container listeners
ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
while (aListenerLoop.hasMoreElements())
static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------
::rtl::OUString OTables::getNameForObject(const sdbcx::ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.38); FILE MERGED 2005/09/05 17:24:02 rt 1.3.38.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HTables.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:04:35 $
*
* 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 CONNECTIVITY_HSQLDB_TABLES_HXX
#include "hsqldb/HTables.hxx"
#endif
#ifndef _CONNECTIVITY_HSQLDB_VIEWS_HXX_
#include "hsqldb/HViews.hxx"
#endif
#ifndef CONNECTIVITY_HSQLDB_TABLE_HXX
#include "hsqldb/HTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_HSQLDB_CATALOG_HXX
#include "hsqldb/HCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace ::cppu;
using namespace connectivity::hsqldb;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));
Sequence< ::rtl::OUString > sTableTypes(3);
sTableTypes[0] = s_sTableTypeView;
sTableTypes[1] = s_sTableTypeTable;
sTableTypes[2] = s_sAll; // just to be sure to include anything else ....
Any aCatalog;
if ( sCatalog.getLength() )
aCatalog <<= sCatalog;
Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);
sdbcx::ObjectType xRet = NULL;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() ) // there can be only one table with this name
{
sal_Int32 nPrivileges = ::dbtools::getTablePrivileges( m_xMetaData, sCatalog, sSchema, sTable );
if ( m_xMetaData->isReadOnly() )
nPrivileges &= ~( Privilege::INSERT | Privilege::UPDATE | Privilege::DELETE | Privilege::CREATE | Privilege::ALTER | Privilege::DROP );
// obtain privileges
OHSQLTable* pRet = new OHSQLTable( this
,static_cast<OHCatalog&>(m_rParent).getConnection()
,sTable
,xRow->getString(4)
,xRow->getString(5)
,sSchema
,sCatalog
,nPrivileges);
xRet = pRet;
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh( ) throw(RuntimeException)
{
static_cast<OHCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
m_xMetaData = NULL;
OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
return new OHSQLTable(this,static_cast<OHCatalog&>(m_rParent).getConnection());
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
if(!aName.getLength())
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));
createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY);
sal_Bool bIsNew = sal_False;
if(xTunnel.is())
{
connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
if(pTable)
bIsNew = pTable->isNew();
}
if (!bIsNew)
{
Reference< XConnection > xConnection = static_cast<OHCatalog&>(m_rParent).getConnection();
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");
Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
sal_Bool bIsView;
if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
aSql += ::rtl::OUString::createFromAscii("VIEW ");
else
aSql += ::rtl::OUString::createFromAscii("TABLE ");
::rtl::OUString sComposedName;
::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
aSql += sComposedName;
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
// if no exception was thrown we must delete it from the views
if ( bIsView )
{
OViews* pViews = static_cast<OViews*>(static_cast<OHCatalog&>(m_rParent).getPrivateViews());
if ( pViews && pViews->hasByName(_sElementName) )
pViews->dropByNameImpl(_sElementName);
}
}
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
Reference< XConnection > xConnection = static_cast<OHCatalog&>(m_rParent).getConnection();
::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
insertElement(_rsNewTable,NULL);
// notify our container listeners
ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
while (aListenerLoop.hasMoreElements())
static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------
::rtl::OUString OTables::getNameForObject(const sdbcx::ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2018-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <blockfilter.h>
static void ConstructGCSFilter(benchmark::Bench& bench)
{
GCSFilter::ElementSet elements;
for (int i = 0; i < 10000; ++i) {
GCSFilter::Element element(32);
element[0] = static_cast<unsigned char>(i);
element[1] = static_cast<unsigned char>(i >> 8);
elements.insert(std::move(element));
}
uint64_t siphash_k0 = 0;
bench.batch(elements.size()).unit("elem").run([&] {
GCSFilter filter({siphash_k0, 0, 20, 1 << 20}, elements);
siphash_k0++;
});
}
static void MatchGCSFilter(benchmark::Bench& bench)
{
GCSFilter::ElementSet elements;
for (int i = 0; i < 10000; ++i) {
GCSFilter::Element element(32);
element[0] = static_cast<unsigned char>(i);
element[1] = static_cast<unsigned char>(i >> 8);
elements.insert(std::move(element));
}
GCSFilter filter({0, 0, 20, 1 << 20}, elements);
bench.unit("elem").run([&] {
filter.Match(GCSFilter::Element());
});
}
BENCHMARK(ConstructGCSFilter);
BENCHMARK(MatchGCSFilter);
<commit_msg>Add GCSFilterDecode and GCSBlockFilterGetHash benchmarks.<commit_after>// Copyright (c) 2018-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <blockfilter.h>
static const GCSFilter::ElementSet GenerateGCSTestElements()
{
GCSFilter::ElementSet elements;
for (int i = 0; i < 10000; ++i) {
GCSFilter::Element element(32);
element[0] = static_cast<unsigned char>(i);
element[1] = static_cast<unsigned char>(i >> 8);
elements.insert(std::move(element));
}
return elements;
}
static void GCSBlockFilterGetHash(benchmark::Bench& bench)
{
auto elements = GenerateGCSTestElements();
GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements);
BlockFilter block_filter(BlockFilterType::BASIC, {}, filter.GetEncoded(), /*skip_decode_check=*/false);
bench.run([&] {
block_filter.GetHash();
});
}
static void GCSFilterConstruct(benchmark::Bench& bench)
{
auto elements = GenerateGCSTestElements();
uint64_t siphash_k0 = 0;
bench.batch(elements.size()).unit("elem").run([&] {
GCSFilter filter({siphash_k0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements);
siphash_k0++;
});
}
static void GCSFilterDecode(benchmark::Bench& bench)
{
auto elements = GenerateGCSTestElements();
GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements);
auto encoded = filter.GetEncoded();
bench.run([&] {
GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, encoded, /*skip_decode_check=*/false);
});
}
static void GCSFilterMatch(benchmark::Bench& bench)
{
auto elements = GenerateGCSTestElements();
GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements);
bench.run([&] {
filter.Match(GCSFilter::Element());
});
}
BENCHMARK(GCSBlockFilterGetHash);
BENCHMARK(GCSFilterConstruct);
BENCHMARK(GCSFilterDecode);
BENCHMARK(GCSFilterMatch);
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
getpw.cpp
Helper function to get a password from the user
*****************************************************************************/
#include <config.h>
#include "getpw.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
// Get a password from the user
void getPW(char* pin, char* newPIN, CK_ULONG userType)
{
// Keep a copy of the PIN because getpass/getpassphrase
// will overwrite the previous PIN.
char password[MAX_PIN_LEN+1];
int length = 0;
if (pin)
{
length = strlen(pin);
}
while (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
{
if (userType == CKU_SO)
{
printf("*** SO PIN (%i-%i characters) ***\n",
MIN_PIN_LEN, MAX_PIN_LEN);
}
else
{
printf("*** User PIN (%i-%i characters) ***\n",
MIN_PIN_LEN, MAX_PIN_LEN);
}
#ifdef HAVE_GETPASSPHRASE
if (userType == CKU_SO)
{
pin = getpassphrase("Please enter SO PIN: ");
}
else
{
pin = getpassphrase("Please enter user PIN: ");
}
#else
if (userType == CKU_SO)
{
pin = getpass("Please enter SO PIN: ");
}
else
{
pin = getpass("Please enter user PIN: ");
}
#endif
length = strlen(pin);
if (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
{
fprintf(stderr, "ERROR: The length of the PIN is out of range.\n");
length = 0;
continue;
}
strcpy(password, pin);
#ifdef HAVE_GETPASSPHRASE
if (userType == CKU_SO)
{
pin = getpassphrase("Please reenter SO PIN: ");
}
else
{
pin = getpassphrase("Please reenter user PIN: ");
}
#else
if (userType == CKU_SO)
{
pin = getpass("Please reenter SO PIN: ");
}
else
{
pin = getpass("Please reenter user PIN: ");
}
#endif
if (strcmp(password, pin))
{
fprintf(stderr, "ERROR: The entered PINs are not equal.\n");
length = 0;
continue;
}
}
strcpy(newPIN, pin);
}
<commit_msg>SOFTHSM-64: Fix strcpy unsafe warning<commit_after>/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
getpw.cpp
Helper function to get a password from the user
*****************************************************************************/
#include <config.h>
#include "getpw.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
// Get a password from the user
void getPW(char* pin, char* newPIN, CK_ULONG userType)
{
// Keep a copy of the PIN because getpass/getpassphrase
// will overwrite the previous PIN.
char password[MAX_PIN_LEN+1];
int length = 0;
if (pin)
{
length = strlen(pin);
}
while (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
{
if (userType == CKU_SO)
{
printf("*** SO PIN (%i-%i characters) ***\n",
MIN_PIN_LEN, MAX_PIN_LEN);
}
else
{
printf("*** User PIN (%i-%i characters) ***\n",
MIN_PIN_LEN, MAX_PIN_LEN);
}
#ifdef HAVE_GETPASSPHRASE
if (userType == CKU_SO)
{
pin = getpassphrase("Please enter SO PIN: ");
}
else
{
pin = getpassphrase("Please enter user PIN: ");
}
#else
if (userType == CKU_SO)
{
pin = getpass("Please enter SO PIN: ");
}
else
{
pin = getpass("Please enter user PIN: ");
}
#endif
length = strlen(pin);
if (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
{
fprintf(stderr, "ERROR: The length of the PIN is out of range.\n");
length = 0;
continue;
}
memcpy(password, pin, length+1);
#ifdef HAVE_GETPASSPHRASE
if (userType == CKU_SO)
{
pin = getpassphrase("Please reenter SO PIN: ");
}
else
{
pin = getpassphrase("Please reenter user PIN: ");
}
#else
if (userType == CKU_SO)
{
pin = getpass("Please reenter SO PIN: ");
}
else
{
pin = getpass("Please reenter user PIN: ");
}
#endif
if (strcmp(password, pin))
{
fprintf(stderr, "ERROR: The entered PINs are not equal.\n");
length = 0;
continue;
}
}
memcpy(newPIN, pin, length+1);
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_OMP_SORT_HPP
#define MJOLNIR_OMP_SORT_HPP
#include <type_traits>
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
#include <omp.h>
namespace mjolnir
{
namespace omp
{
// Do NOT call this from parallel region.
template<typename Value, typename Alloc, typename Comparator>
void sort(std::vector<Value, Alloc>& vec, std::vector<Value, Alloc>& buf,
Comparator comp)
{
const std::size_t max_threads = omp_get_max_threads();
if(max_threads == 1 || vec.size() < max_threads * 4)
{
std::sort(vec.begin(), vec.end(), comp);
return;
}
if(vec.size() != buf.size())
{
buf.resize(vec.size());
}
#pragma omp parallel shared(vec, buf, comp)
{
const auto num_threads = omp_get_num_threads();
const auto thread_id = omp_get_thread_num();
const auto range_size = vec.size();
const auto subrange_size = (range_size % num_threads == 0) ?
(range_size / num_threads) : (range_size / num_threads + 1);
const auto offset = thread_id * subrange_size;
if(offset < range_size)
{
const auto first = vec.begin() + offset;
const auto last = vec.begin() +
std::min(offset + subrange_size, range_size);
std::sort(first, last, comp);
}
#pragma omp barrier
int num_ranges = num_threads;
int delta = 2;
int first = offset;
int middle = offset + subrange_size;
int last = std::min(offset + 2 * subrange_size, range_size);
while(num_ranges > 1)
{
if(thread_id % delta == 0 && middle < last)
{
std::merge(vec.begin() + first, vec.begin() + middle,
vec.begin() + middle, vec.begin() + last,
buf.begin() + first, comp);
// merged merged (by another thread)
// .------+------.------+------.
// |......|......|......|......|
// f m l -----+
// f +--> m2 +----> l2
middle = last;
last += delta * subrange_size;
last = std::min(last, static_cast<int>(range_size));
}
else if(thread_id % delta == 0)
{
std::copy(vec.begin() + first, vec.begin() + last, buf.begin() + first);
}
delta *= 2;
num_ranges = (num_ranges + 1) / 2;
#pragma omp barrier
#pragma omp single
{
// both are std::vector. we don't need to use ADL.
std::swap(vec, buf);
} // an implicit barrier here
}
}
return;
}
template<typename Value, typename Alloc>
void sort(std::vector<Value, Alloc>& vec, std::vector<Value, Alloc>& buf)
{
using comparator_type = std::less<Value>;
::mjolnir::omp::sort(vec, buf, comparator_type());
return;
}
} // omp
} // mjolnir
#endif // MJOLNIR_OMP_SORT_HPP
<commit_msg>refactor: check vector size is kept after sorting<commit_after>#ifndef MJOLNIR_OMP_SORT_HPP
#define MJOLNIR_OMP_SORT_HPP
#include <type_traits>
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
#include <omp.h>
namespace mjolnir
{
namespace omp
{
// Do NOT call this from parallel region.
template<typename Value, typename Alloc, typename Comparator>
void sort(std::vector<Value, Alloc>& vec, std::vector<Value, Alloc>& buf,
Comparator comp)
{
const std::size_t max_threads = omp_get_max_threads();
const std::size_t vec_size = vec.size();
if(max_threads == 1 || vec.size() < max_threads * 4)
{
std::sort(vec.begin(), vec.end(), comp);
return;
}
if(vec.size() != buf.size())
{
buf.resize(vec.size());
}
#pragma omp parallel shared(vec, buf, comp)
{
const auto num_threads = omp_get_num_threads();
const auto thread_id = omp_get_thread_num();
const auto range_size = vec.size();
const auto subrange_size = (range_size % num_threads == 0) ?
(range_size / num_threads) : (range_size / num_threads + 1);
const auto offset = thread_id * subrange_size;
if(offset < range_size)
{
const auto first = vec.begin() + offset;
const auto last = vec.begin() +
std::min(offset + subrange_size, range_size);
std::sort(first, last, comp);
}
#pragma omp barrier
int num_ranges = num_threads;
int delta = 2;
int first = offset;
int middle = offset + subrange_size;
int last = std::min(offset + 2 * subrange_size, range_size);
while(num_ranges > 1)
{
if(thread_id % delta == 0 && middle < last)
{
std::merge(vec.begin() + first, vec.begin() + middle,
vec.begin() + middle, vec.begin() + last,
buf.begin() + first, comp);
// merged merged (by another thread)
// .------+------.------+------.
// |......|......|......|......|
// f m l -----+
// f +--> m2 +----> l2
middle = last;
last += delta * subrange_size;
last = std::min(last, static_cast<int>(range_size));
}
else if(thread_id % delta == 0)
{
std::copy(vec.begin() + first, vec.begin() + last, buf.begin() + first);
}
delta *= 2;
num_ranges = (num_ranges + 1) / 2;
#pragma omp barrier
#pragma omp single
{
// both are std::vector. we don't need to use ADL.
std::swap(vec, buf);
} // an implicit barrier here
}
}
assert(vec.size() == vec_size);
return;
}
template<typename Value, typename Alloc>
void sort(std::vector<Value, Alloc>& vec, std::vector<Value, Alloc>& buf)
{
using comparator_type = std::less<Value>;
::mjolnir::omp::sort(vec, buf, comparator_type());
return;
}
} // omp
} // mjolnir
#endif // MJOLNIR_OMP_SORT_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "idevice.h"
#include "devicemanager.h"
#include <coreplugin/id.h>
#include <ssh/sshconnection.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QString>
#include <QUuid>
/*!
* \class ProjectExplorer::IDevice
* \brief This is the base class for all devices.
*
* The term "device" refers
* here to some host to which e.g. files can be deployed or on which an application can run.
* In the typical case, this would be some sort of embedded computer connected in some way to
* the PC on which QtCreator runs. This class itself does not specify a connection protocol; that
* kind of detail is to be added by subclasses.
* Devices are managed by a \c DeviceManager.
* \sa ProjectExplorer::DeviceManager
*/
/*!
* \fn QString ProjectExplorer::IDevice::type() const
* \brief Identifies the type of the device.
* Devices with the same type share certain abilities.
* This attribute is immutable.
* \sa ProjectExplorer::IDeviceFactory
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayName() const
* \brief A free-text name for the device to be displayed in GUI elements.
*/
/*!
* \fn bool ProjectExplorer::IDevice::isAutoDetected() const
* \brief True iff the device has been added via some sort of auto-detection mechanism.
* Devices that are not auto-detected can only ever be created interactively from the
* settings page.
* This attribute is immutable.
* \sa DeviceSettingsWidget
*/
/*!
* \fn Core::Id ProjectExplorer::IDevice::id() const
* \brief Identify the device.
* If an id is given when constructing a device then this id is used. Otherwise a UUID is
* generated and used to identity the device.
* \sa ProjectExplorer::DeviceManager::findInactiveAutoDetectedDevice()
*/
/*!
* \fn Core::Id ProjectExplorer::IDevice::invalidId()
* \brief A value that no device can ever have as its internal id.
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayType() const
* \brief Prints a representation of the device's type suitable for displaying to a user.
*/
/*!
* \fn ProjectExplorer::IDeviceWidget *ProjectExplorer::IDevice::createWidget() const
* \brief Creates a widget that displays device information not part of the IDevice base class.
* The widget can also be used to let the user change these attributes.
*/
/*!
* \fn QStringList ProjectExplorer::IDevice::actionIds() const
* \brief Returns a list of ids representing actions that can be run on this device.
* These actions will be available in the "Devices" options page.
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayNameForActionId(const QString &actionId) const
* \brief A human-readable string for the given id. Will be displayed on a button which,
* when clicked, starts the respective action.
*/
/*!
* \fn void ProjectExplorer::IDevice::executeAction(Core::Id actionId, QWidget *parent)
* \brief Executes the respective action. This is typically done via some sort of dialog or
* wizard, so a parent widget argument is provided.
*/
/*!
* \fn ProjectExplorer::IDevice::Ptr ProjectExplorer::IDevice::clone() const
* \brief Creates an identical copy of a device object.
*/
/*!
* \fn void fromMap(const QVariantMap &map)
* \brief Restores a device object from a serialized state as written by \c toMap().
* If subclasses override this to restore additional state, they must call the base class
* implementation.
*/
/*!
* \fn QVariantMap toMap() const
* \brief Serializes a device object, e.g. to save it to a file.
* If subclasses override this to save additional state, they must call the base class
* implementation.
*/
static Core::Id newId()
{
return Core::Id(QUuid::createUuid().toString());
}
namespace ProjectExplorer {
const char DisplayNameKey[] = "Name";
const char TypeKey[] = "OsType";
const char IdKey[] = "InternalId";
const char OriginKey[] = "Origin";
// Connection
const char HostKey[] = "Host";
const char SshPortKey[] = "SshPort";
const char PortsSpecKey[] = "FreePortsSpec";
const char UserNameKey[] = "Uname";
const char AuthKey[] = "Authentication";
const char KeyFileKey[] = "KeyFile";
const char PasswordKey[] = "Password";
const char TimeoutKey[] = "Timeout";
typedef QSsh::SshConnectionParameters::AuthenticationType AuthType;
const AuthType DefaultAuthType = QSsh::SshConnectionParameters::AuthenticationByKey;
const int DefaultTimeout = 10;
namespace Internal {
class IDevicePrivate
{
public:
IDevicePrivate() :
origin(IDevice::AutoDetected),
deviceState(IDevice::DeviceStateUnknown)
{ }
QString displayName;
Core::Id type;
IDevice::Origin origin;
Core::Id id;
IDevice::DeviceState deviceState;
QSsh::SshConnectionParameters sshParameters;
Utils::PortList freePorts;
};
} // namespace Internal
IDevice::IDevice() : d(new Internal::IDevicePrivate)
{ }
IDevice::IDevice(Core::Id type, Origin origin, Core::Id id) : d(new Internal::IDevicePrivate)
{
d->type = type;
d->origin = origin;
QTC_CHECK(origin == ManuallyAdded || id.isValid());
d->id = id.isValid() ? id : newId();
}
IDevice::IDevice(const IDevice &other) : d(new Internal::IDevicePrivate)
{
*d = *other.d;
}
IDevice::~IDevice()
{
delete d;
}
QString IDevice::displayName() const
{
return d->displayName;
}
void IDevice::setDisplayName(const QString &name)
{
if (d->displayName == name)
return;
d->displayName = name;
}
IDevice::DeviceInfo IDevice::deviceInformation() const
{
const QString key = QCoreApplication::translate("ProjectExplorer::IDevice", "Device");
return DeviceInfo() << IDevice::DeviceInfoItem(key, deviceStateToString());
}
Core::Id IDevice::type() const
{
return d->type;
}
bool IDevice::isAutoDetected() const
{
return d->origin == AutoDetected;
}
Core::Id IDevice::id() const
{
return d->id;
}
IDevice::DeviceState IDevice::deviceState() const
{
return d->deviceState;
}
void IDevice::setDeviceState(const IDevice::DeviceState state)
{
if (d->deviceState == state)
return;
d->deviceState = state;
}
Core::Id IDevice::invalidId()
{
return Core::Id();
}
Core::Id IDevice::typeFromMap(const QVariantMap &map)
{
return Core::Id(map.value(QLatin1String(TypeKey)).toByteArray().constData());
}
Core::Id IDevice::idFromMap(const QVariantMap &map)
{
return Core::Id(map.value(QLatin1String(IdKey)).toByteArray().constData());
}
void IDevice::fromMap(const QVariantMap &map)
{
d->type = typeFromMap(map);
d->displayName = map.value(QLatin1String(DisplayNameKey)).toString();
d->id = Core::Id(map.value(QLatin1String(IdKey), newId().name()).toByteArray().constData());
d->origin = static_cast<Origin>(map.value(QLatin1String(OriginKey), ManuallyAdded).toInt());
d->sshParameters.host = map.value(HostKey).toString();
d->sshParameters.port = map.value(SshPortKey, 22).toInt();
d->sshParameters.userName = map.value(UserNameKey).toString();
d->sshParameters.authenticationType
= static_cast<AuthType>(map.value(AuthKey, DefaultAuthType).toInt());
d->sshParameters.password = map.value(PasswordKey).toString();
d->sshParameters.privateKeyFile = map.value(KeyFileKey, defaultPrivateKeyFilePath()).toString();
d->sshParameters.timeout = map.value(TimeoutKey, DefaultTimeout).toInt();
d->freePorts = Utils::PortList::fromString(map.value(PortsSpecKey,
QLatin1String("10000-10100")).toString());
}
QVariantMap IDevice::toMap() const
{
QVariantMap map;
map.insert(QLatin1String(DisplayNameKey), d->displayName);
map.insert(QLatin1String(TypeKey), d->type.name());
map.insert(QLatin1String(IdKey), d->id.name());
map.insert(QLatin1String(OriginKey), d->origin);
map.insert(HostKey, d->sshParameters.host);
map.insert(SshPortKey, d->sshParameters.port);
map.insert(UserNameKey, d->sshParameters.userName);
map.insert(AuthKey, d->sshParameters.authenticationType);
map.insert(PasswordKey, d->sshParameters.password);
map.insert(KeyFileKey, d->sshParameters.privateKeyFile);
map.insert(TimeoutKey, d->sshParameters.timeout);
map.insert(PortsSpecKey, d->freePorts.toString());
return map;
}
IDevice::Ptr IDevice::sharedFromThis()
{
return DeviceManager::instance()->fromRawPointer(this);
}
IDevice::ConstPtr IDevice::sharedFromThis() const
{
return DeviceManager::instance()->fromRawPointer(this);
}
QString IDevice::deviceStateToString() const
{
const char context[] = "ProjectExplorer::IDevice";
switch (d->deviceState) {
case IDevice::DeviceReadyToUse: return QCoreApplication::translate(context, "Ready to use");
case IDevice::DeviceConnected: return QCoreApplication::translate(context, "Connected");
case IDevice::DeviceDisconnected: return QCoreApplication::translate(context, "Disconnected");
case IDevice::DeviceStateUnknown: return QCoreApplication::translate(context, "Unknown");
default: return QCoreApplication::translate(context, "Invalid");
}
}
QSsh::SshConnectionParameters IDevice::sshParameters() const
{
return d->sshParameters;
}
void IDevice::setSshParameters(const QSsh::SshConnectionParameters &sshParameters)
{
d->sshParameters = sshParameters;
}
void IDevice::setFreePorts(const Utils::PortList &freePorts)
{
d->freePorts = freePorts;
}
Utils::PortList IDevice::freePorts() const
{
return d->freePorts;
}
QString IDevice::defaultPrivateKeyFilePath()
{
return QDesktopServices::storageLocation(QDesktopServices::HomeLocation)
+ QLatin1String("/.ssh/id_rsa");
}
QString IDevice::defaultPublicKeyFilePath()
{
return defaultPrivateKeyFilePath() + QLatin1String(".pub");
}
} // namespace ProjectExplorer
<commit_msg>Device: Simplify code a bit<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "idevice.h"
#include "devicemanager.h"
#include <coreplugin/id.h>
#include <ssh/sshconnection.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QString>
#include <QUuid>
/*!
* \class ProjectExplorer::IDevice
* \brief This is the base class for all devices.
*
* The term "device" refers
* here to some host to which e.g. files can be deployed or on which an application can run.
* In the typical case, this would be some sort of embedded computer connected in some way to
* the PC on which QtCreator runs. This class itself does not specify a connection protocol; that
* kind of detail is to be added by subclasses.
* Devices are managed by a \c DeviceManager.
* \sa ProjectExplorer::DeviceManager
*/
/*!
* \fn QString ProjectExplorer::IDevice::type() const
* \brief Identifies the type of the device.
* Devices with the same type share certain abilities.
* This attribute is immutable.
* \sa ProjectExplorer::IDeviceFactory
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayName() const
* \brief A free-text name for the device to be displayed in GUI elements.
*/
/*!
* \fn bool ProjectExplorer::IDevice::isAutoDetected() const
* \brief True iff the device has been added via some sort of auto-detection mechanism.
* Devices that are not auto-detected can only ever be created interactively from the
* settings page.
* This attribute is immutable.
* \sa DeviceSettingsWidget
*/
/*!
* \fn Core::Id ProjectExplorer::IDevice::id() const
* \brief Identify the device.
* If an id is given when constructing a device then this id is used. Otherwise a UUID is
* generated and used to identity the device.
* \sa ProjectExplorer::DeviceManager::findInactiveAutoDetectedDevice()
*/
/*!
* \fn Core::Id ProjectExplorer::IDevice::invalidId()
* \brief A value that no device can ever have as its internal id.
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayType() const
* \brief Prints a representation of the device's type suitable for displaying to a user.
*/
/*!
* \fn ProjectExplorer::IDeviceWidget *ProjectExplorer::IDevice::createWidget() const
* \brief Creates a widget that displays device information not part of the IDevice base class.
* The widget can also be used to let the user change these attributes.
*/
/*!
* \fn QStringList ProjectExplorer::IDevice::actionIds() const
* \brief Returns a list of ids representing actions that can be run on this device.
* These actions will be available in the "Devices" options page.
*/
/*!
* \fn QString ProjectExplorer::IDevice::displayNameForActionId(const QString &actionId) const
* \brief A human-readable string for the given id. Will be displayed on a button which,
* when clicked, starts the respective action.
*/
/*!
* \fn void ProjectExplorer::IDevice::executeAction(Core::Id actionId, QWidget *parent)
* \brief Executes the respective action. This is typically done via some sort of dialog or
* wizard, so a parent widget argument is provided.
*/
/*!
* \fn ProjectExplorer::IDevice::Ptr ProjectExplorer::IDevice::clone() const
* \brief Creates an identical copy of a device object.
*/
/*!
* \fn void fromMap(const QVariantMap &map)
* \brief Restores a device object from a serialized state as written by \c toMap().
* If subclasses override this to restore additional state, they must call the base class
* implementation.
*/
/*!
* \fn QVariantMap toMap() const
* \brief Serializes a device object, e.g. to save it to a file.
* If subclasses override this to save additional state, they must call the base class
* implementation.
*/
static Core::Id newId()
{
return Core::Id(QUuid::createUuid().toString());
}
namespace ProjectExplorer {
const char DisplayNameKey[] = "Name";
const char TypeKey[] = "OsType";
const char IdKey[] = "InternalId";
const char OriginKey[] = "Origin";
// Connection
const char HostKey[] = "Host";
const char SshPortKey[] = "SshPort";
const char PortsSpecKey[] = "FreePortsSpec";
const char UserNameKey[] = "Uname";
const char AuthKey[] = "Authentication";
const char KeyFileKey[] = "KeyFile";
const char PasswordKey[] = "Password";
const char TimeoutKey[] = "Timeout";
typedef QSsh::SshConnectionParameters::AuthenticationType AuthType;
const AuthType DefaultAuthType = QSsh::SshConnectionParameters::AuthenticationByKey;
const int DefaultTimeout = 10;
namespace Internal {
class IDevicePrivate
{
public:
IDevicePrivate() :
origin(IDevice::AutoDetected),
deviceState(IDevice::DeviceStateUnknown)
{ }
QString displayName;
Core::Id type;
IDevice::Origin origin;
Core::Id id;
IDevice::DeviceState deviceState;
QSsh::SshConnectionParameters sshParameters;
Utils::PortList freePorts;
};
} // namespace Internal
IDevice::IDevice() : d(new Internal::IDevicePrivate)
{ }
IDevice::IDevice(Core::Id type, Origin origin, Core::Id id) : d(new Internal::IDevicePrivate)
{
d->type = type;
d->origin = origin;
QTC_CHECK(origin == ManuallyAdded || id.isValid());
d->id = id.isValid() ? id : newId();
}
IDevice::IDevice(const IDevice &other) : d(new Internal::IDevicePrivate)
{
*d = *other.d;
}
IDevice::~IDevice()
{
delete d;
}
QString IDevice::displayName() const
{
return d->displayName;
}
void IDevice::setDisplayName(const QString &name)
{
if (d->displayName == name)
return;
d->displayName = name;
}
IDevice::DeviceInfo IDevice::deviceInformation() const
{
const QString key = QCoreApplication::translate("ProjectExplorer::IDevice", "Device");
return DeviceInfo() << IDevice::DeviceInfoItem(key, deviceStateToString());
}
Core::Id IDevice::type() const
{
return d->type;
}
bool IDevice::isAutoDetected() const
{
return d->origin == AutoDetected;
}
Core::Id IDevice::id() const
{
return d->id;
}
IDevice::DeviceState IDevice::deviceState() const
{
return d->deviceState;
}
void IDevice::setDeviceState(const IDevice::DeviceState state)
{
if (d->deviceState == state)
return;
d->deviceState = state;
}
Core::Id IDevice::invalidId()
{
return Core::Id();
}
Core::Id IDevice::typeFromMap(const QVariantMap &map)
{
const QString idStr = map.value(QLatin1String(TypeKey)).toString();
if (idStr.isEmpty())
return Core::Id();
return Core::Id(idStr);
}
Core::Id IDevice::idFromMap(const QVariantMap &map)
{
return Core::Id(map.value(QLatin1String(IdKey)).toString());
}
void IDevice::fromMap(const QVariantMap &map)
{
d->type = typeFromMap(map);
d->displayName = map.value(QLatin1String(DisplayNameKey)).toString();
d->id = Core::Id(map.value(QLatin1String(IdKey), newId().name()).toByteArray().constData());
d->origin = static_cast<Origin>(map.value(QLatin1String(OriginKey), ManuallyAdded).toInt());
d->sshParameters.host = map.value(HostKey).toString();
d->sshParameters.port = map.value(SshPortKey, 22).toInt();
d->sshParameters.userName = map.value(UserNameKey).toString();
d->sshParameters.authenticationType
= static_cast<AuthType>(map.value(AuthKey, DefaultAuthType).toInt());
d->sshParameters.password = map.value(PasswordKey).toString();
d->sshParameters.privateKeyFile = map.value(KeyFileKey, defaultPrivateKeyFilePath()).toString();
d->sshParameters.timeout = map.value(TimeoutKey, DefaultTimeout).toInt();
d->freePorts = Utils::PortList::fromString(map.value(PortsSpecKey,
QLatin1String("10000-10100")).toString());
}
QVariantMap IDevice::toMap() const
{
QVariantMap map;
map.insert(QLatin1String(DisplayNameKey), d->displayName);
map.insert(QLatin1String(TypeKey), d->type.toString());
map.insert(QLatin1String(IdKey), d->id.name());
map.insert(QLatin1String(OriginKey), d->origin);
map.insert(HostKey, d->sshParameters.host);
map.insert(SshPortKey, d->sshParameters.port);
map.insert(UserNameKey, d->sshParameters.userName);
map.insert(AuthKey, d->sshParameters.authenticationType);
map.insert(PasswordKey, d->sshParameters.password);
map.insert(KeyFileKey, d->sshParameters.privateKeyFile);
map.insert(TimeoutKey, d->sshParameters.timeout);
map.insert(PortsSpecKey, d->freePorts.toString());
return map;
}
IDevice::Ptr IDevice::sharedFromThis()
{
return DeviceManager::instance()->fromRawPointer(this);
}
IDevice::ConstPtr IDevice::sharedFromThis() const
{
return DeviceManager::instance()->fromRawPointer(this);
}
QString IDevice::deviceStateToString() const
{
const char context[] = "ProjectExplorer::IDevice";
switch (d->deviceState) {
case IDevice::DeviceReadyToUse: return QCoreApplication::translate(context, "Ready to use");
case IDevice::DeviceConnected: return QCoreApplication::translate(context, "Connected");
case IDevice::DeviceDisconnected: return QCoreApplication::translate(context, "Disconnected");
case IDevice::DeviceStateUnknown: return QCoreApplication::translate(context, "Unknown");
default: return QCoreApplication::translate(context, "Invalid");
}
}
QSsh::SshConnectionParameters IDevice::sshParameters() const
{
return d->sshParameters;
}
void IDevice::setSshParameters(const QSsh::SshConnectionParameters &sshParameters)
{
d->sshParameters = sshParameters;
}
void IDevice::setFreePorts(const Utils::PortList &freePorts)
{
d->freePorts = freePorts;
}
Utils::PortList IDevice::freePorts() const
{
return d->freePorts;
}
QString IDevice::defaultPrivateKeyFilePath()
{
return QDesktopServices::storageLocation(QDesktopServices::HomeLocation)
+ QLatin1String("/.ssh/id_rsa");
}
QString IDevice::defaultPublicKeyFilePath()
{
return defaultPrivateKeyFilePath() + QLatin1String(".pub");
}
} // namespace ProjectExplorer
<|endoftext|>
|
<commit_before><commit_msg>Perception: clean up duplicated boolean value assignment<commit_after><|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "maemoinstalltosysrootstep.h"
#include "deploymentinfo.h"
#include "maemoglobal.h"
#include "maemopackagecreationstep.h"
#include "maemoqtversion.h"
#include "qt4maemodeployconfiguration.h"
#include <utils/fileutils.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4target.h>
#include <qtsupport/baseqtversion.h>
#include <QtCore/QLatin1Char>
#include <QtCore/QProcess>
#include <QtCore/QWeakPointer>
using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
namespace RemoteLinux {
namespace Internal {
class AbstractMaemoInstallPackageToSysrootWidget : public BuildStepConfigWidget
{
Q_OBJECT
public:
AbstractMaemoInstallPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: m_step(step)
{
BuildStepList * const list
= qobject_cast<BuildStepList *>(m_step->parent());
connect(list, SIGNAL(stepInserted(int)), SIGNAL(updateSummary()));
connect(list, SIGNAL(stepMoved(int,int)), SIGNAL(updateSummary()));
connect(list, SIGNAL(aboutToRemoveStep(int)), SLOT(handleStepToBeRemoved(int)));
connect(list, SIGNAL(stepRemoved(int)), SIGNAL(updateSummary()));
}
virtual QString summaryText() const
{
if (!MaemoGlobal::earlierBuildStep<AbstractMaemoPackageCreationStep>(m_step->deployConfiguration(), m_step)) {
return QLatin1String("<font color=\"red\">")
+ tr("Cannot deploy to sysroot: No packaging step found.")
+ QLatin1String("</font>");
}
return QLatin1String("<b>") + displayName() + QLatin1String("</b>");
}
private:
Q_SLOT void handleStepToBeRemoved(int step)
{
BuildStepList * const list
= qobject_cast<BuildStepList *>(m_step->parent());
if (list->steps().at(step) == m_step)
disconnect(list, 0, this, 0);
}
const AbstractMaemoInstallPackageToSysrootStep * const m_step;
};
class MaemoInstallDebianPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
Q_OBJECT
public:
MaemoInstallDebianPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: AbstractMaemoInstallPackageToSysrootWidget(step) {}
virtual QString displayName() const { return MaemoInstallDebianPackageToSysrootStep::displayName(); }
};
class MaemoInstallRpmPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
Q_OBJECT
public:
MaemoInstallRpmPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: AbstractMaemoInstallPackageToSysrootWidget(step) {}
virtual QString displayName() const { return MaemoInstallRpmPackageToSysrootStep::displayName(); }
};
class MaemoCopyFilesToSysrootWidget : public BuildStepConfigWidget
{
Q_OBJECT
public:
MaemoCopyFilesToSysrootWidget(const BuildStep *buildStep)
: m_buildStep(buildStep)
{
if (m_buildStep) {
connect(m_buildStep.data(), SIGNAL(displayNameChanged()),
SIGNAL(updateSummary()));
}
}
virtual QString summaryText() const {
return QLatin1String("<b>") + displayName() + QLatin1String("</b>"); }
virtual QString displayName() const {
return m_buildStep ? m_buildStep.data()->displayName() : QString();
}
private:
const QWeakPointer<const BuildStep> m_buildStep;
};
AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
const QString &id)
: BuildStep(bsl, id)
{
}
AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
AbstractMaemoInstallPackageToSysrootStep *other)
: BuildStep(bsl, other)
{
}
void AbstractMaemoInstallPackageToSysrootStep::run(QFutureInterface<bool> &fi)
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BaseTarget *>(target())->activeBuildConfiguration();
if (!bc) {
addOutput(tr("Cannot install to sysroot without build configuration."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
const AbstractMaemoPackageCreationStep * const pStep
= MaemoGlobal::earlierBuildStep<AbstractMaemoPackageCreationStep>(deployConfiguration(), this);
if (!pStep) {
addOutput(tr("Cannot install package to sysroot without packaging step."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
if (!bc->qtVersion()) {
addOutput(tr("Cannot install package to sysroot without a Qt version."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
m_installerProcess = new QProcess;
connect(m_installerProcess, SIGNAL(readyReadStandardOutput()),
SLOT(handleInstallerStdout()));
connect(m_installerProcess, SIGNAL(readyReadStandardError()),
SLOT(handleInstallerStderr()));
emit addOutput(tr("Installing package to sysroot ..."), MessageOutput);
const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
const QString packageFilePath = pStep->packageFilePath();
const int packageFileSize = QFileInfo(packageFilePath).size() / (1024*1024);
const QStringList args = madArguments() << packageFilePath;
MaemoGlobal::callMadAdmin(*m_installerProcess, args, qtVersion->qmakeCommand(), true);
if (!m_installerProcess->waitForFinished((2*packageFileSize + 10)*1000)
|| m_installerProcess->exitStatus() != QProcess::NormalExit
|| m_installerProcess->exitCode() != 0) {
emit addOutput(tr("Installation to sysroot failed, continuing anyway."),
ErrorMessageOutput);
if (m_installerProcess->state() != QProcess::NotRunning) {
m_installerProcess->terminate();
m_installerProcess->waitForFinished();
m_installerProcess->kill();
}
fi.reportResult(true);
return;
}
fi.reportResult(true);
m_installerProcess->deleteLater();
m_installerProcess = 0;
}
void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStdout()
{
if (m_installerProcess)
emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardOutput()), NormalOutput);
}
void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStderr()
{
if (m_installerProcess)
emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardError()), ErrorOutput);
}
MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl)
: AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl,
MaemoInstallDebianPackageToSysrootStep *other)
: AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
setDisplayName(displayName());
}
BuildStepConfigWidget *MaemoInstallDebianPackageToSysrootStep::createConfigWidget()
{
return new MaemoInstallDebianPackageToSysrootWidget(this);
}
QStringList MaemoInstallDebianPackageToSysrootStep::madArguments() const
{
return QStringList() << QLatin1String("xdpkg") << QLatin1String("-i")
<< QLatin1String("--no-force-downgrade");
}
const QString MaemoInstallDebianPackageToSysrootStep::Id
= QLatin1String("MaemoInstallDebianPackageToSysrootStep");
QString MaemoInstallDebianPackageToSysrootStep::displayName()
{
return tr("Install Debian package to sysroot");
}
MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl)
: AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl,
MaemoInstallRpmPackageToSysrootStep *other)
: AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
setDisplayName(displayName());
}
BuildStepConfigWidget *MaemoInstallRpmPackageToSysrootStep::createConfigWidget()
{
return new MaemoInstallRpmPackageToSysrootWidget(this);
}
QStringList MaemoInstallRpmPackageToSysrootStep::madArguments() const
{
return QStringList() << QLatin1String("xrpm") << QLatin1String("-i");
}
const QString MaemoInstallRpmPackageToSysrootStep::Id
= QLatin1String("MaemoInstallRpmPackageToSysrootStep");
QString MaemoInstallRpmPackageToSysrootStep::displayName()
{
return tr("Install RPM package to sysroot");
}
MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl)
: BuildStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl,
MaemoCopyToSysrootStep *other)
: BuildStep(bsl, other)
{
setDisplayName(displayName());
}
void MaemoCopyToSysrootStep::run(QFutureInterface<bool> &fi)
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BaseTarget *>(target())->activeBuildConfiguration();
if (!bc) {
addOutput(tr("Cannot copy to sysroot without build configuration."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
const MaemoQtVersion * const qtVersion = dynamic_cast<MaemoQtVersion *>(bc->qtVersion());
if (!qtVersion) {
addOutput(tr("Cannot copy to sysroot without valid Qt version."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
emit addOutput(tr("Copying files to sysroot ..."), MessageOutput);
QDir sysrootDir(qtVersion->systemRoot());
const QSharedPointer<DeploymentInfo> deploymentInfo
= qobject_cast<Qt4MaemoDeployConfiguration *>(deployConfiguration())->deploymentInfo();
const QChar sep = QLatin1Char('/');
for (int i = 0; i < deploymentInfo->deployableCount(); ++i) {
const DeployableFile &deployable = deploymentInfo->deployableAt(i);
const QFileInfo localFileInfo(deployable.localFilePath);
const QString targetFilePath = qtVersion->systemRoot() + sep
+ deployable.remoteDir + sep + localFileInfo.fileName();
sysrootDir.mkpath(deployable.remoteDir.mid(1));
QString errorMsg;
Utils::FileUtils::removeRecursively(targetFilePath, &errorMsg);
if (!Utils::FileUtils::copyRecursively(deployable.localFilePath,
targetFilePath, &errorMsg)) {
emit addOutput(tr("Sysroot installation failed: %1\n"
" Continuing anyway.").arg(errorMsg), ErrorMessageOutput);
}
QCoreApplication::processEvents();
if (fi.isCanceled()) {
fi.reportResult(false);
return;
}
}
fi.reportResult(true);
}
BuildStepConfigWidget *MaemoCopyToSysrootStep::createConfigWidget()
{
return new MaemoCopyFilesToSysrootWidget(this);
}
const QString MaemoCopyToSysrootStep::Id
= QLatin1String("MaemoCopyToSysrootStep");
QString MaemoCopyToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
}
MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl)
: AbstractProcessStep(bsl, Id)
{
setDefaultDisplayName(displayName());
}
MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl,
MaemoMakeInstallToSysrootStep *other)
: AbstractProcessStep(bsl, other)
{
setDefaultDisplayName(displayName());
}
bool MaemoMakeInstallToSysrootStep::init()
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
if (!bc) {
addOutput("Cannot deploy: No active build dconfiguration.",
ErrorMessageOutput);
return false;
}
const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
if (!qtVersion) {
addOutput("Cannot deploy: Unusable build configuration.",
ErrorMessageOutput);
return false;
}
Utils::Environment env = bc->environment();
MaemoGlobal::addMaddeEnvironment(env, qtVersion->qmakeCommand());
QString command = MaemoGlobal::madCommand(qtVersion->qmakeCommand());
QStringList args = QStringList() << QLatin1String("-t")
<< MaemoGlobal::targetName(qtVersion->qmakeCommand()) << QLatin1String("make")
<< QLatin1String("install") << (QLatin1String("INSTALL_ROOT=") + qtVersion->systemRoot());
MaemoGlobal::transformMaddeCall(command, args, qtVersion->qmakeCommand());
processParameters()->setCommand(command);
processParameters()->setArguments(args.join(QLatin1String(" ")));
processParameters()->setEnvironment(env);
processParameters()->setWorkingDirectory(bc->buildDirectory());
return true;
}
BuildStepConfigWidget *MaemoMakeInstallToSysrootStep::createConfigWidget()
{
return new MaemoCopyFilesToSysrootWidget(this);
}
const QString MaemoMakeInstallToSysrootStep::Id
= QLatin1String("MaemoMakeInstallToSysrootStep");
QString MaemoMakeInstallToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
}
} // namespace Internal
} // namespace RemoteLinux
#include "maemoinstalltosysrootstep.moc"
<commit_msg>Maemo: Fix order of command line options for sysroot installations.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "maemoinstalltosysrootstep.h"
#include "deploymentinfo.h"
#include "maemoglobal.h"
#include "maemopackagecreationstep.h"
#include "maemoqtversion.h"
#include "qt4maemodeployconfiguration.h"
#include <utils/fileutils.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4target.h>
#include <qtsupport/baseqtversion.h>
#include <QtCore/QLatin1Char>
#include <QtCore/QProcess>
#include <QtCore/QWeakPointer>
using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
namespace RemoteLinux {
namespace Internal {
class AbstractMaemoInstallPackageToSysrootWidget : public BuildStepConfigWidget
{
Q_OBJECT
public:
AbstractMaemoInstallPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: m_step(step)
{
BuildStepList * const list
= qobject_cast<BuildStepList *>(m_step->parent());
connect(list, SIGNAL(stepInserted(int)), SIGNAL(updateSummary()));
connect(list, SIGNAL(stepMoved(int,int)), SIGNAL(updateSummary()));
connect(list, SIGNAL(aboutToRemoveStep(int)), SLOT(handleStepToBeRemoved(int)));
connect(list, SIGNAL(stepRemoved(int)), SIGNAL(updateSummary()));
}
virtual QString summaryText() const
{
if (!MaemoGlobal::earlierBuildStep<AbstractMaemoPackageCreationStep>(m_step->deployConfiguration(), m_step)) {
return QLatin1String("<font color=\"red\">")
+ tr("Cannot deploy to sysroot: No packaging step found.")
+ QLatin1String("</font>");
}
return QLatin1String("<b>") + displayName() + QLatin1String("</b>");
}
private:
Q_SLOT void handleStepToBeRemoved(int step)
{
BuildStepList * const list
= qobject_cast<BuildStepList *>(m_step->parent());
if (list->steps().at(step) == m_step)
disconnect(list, 0, this, 0);
}
const AbstractMaemoInstallPackageToSysrootStep * const m_step;
};
class MaemoInstallDebianPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
Q_OBJECT
public:
MaemoInstallDebianPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: AbstractMaemoInstallPackageToSysrootWidget(step) {}
virtual QString displayName() const { return MaemoInstallDebianPackageToSysrootStep::displayName(); }
};
class MaemoInstallRpmPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
Q_OBJECT
public:
MaemoInstallRpmPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
: AbstractMaemoInstallPackageToSysrootWidget(step) {}
virtual QString displayName() const { return MaemoInstallRpmPackageToSysrootStep::displayName(); }
};
class MaemoCopyFilesToSysrootWidget : public BuildStepConfigWidget
{
Q_OBJECT
public:
MaemoCopyFilesToSysrootWidget(const BuildStep *buildStep)
: m_buildStep(buildStep)
{
if (m_buildStep) {
connect(m_buildStep.data(), SIGNAL(displayNameChanged()),
SIGNAL(updateSummary()));
}
}
virtual QString summaryText() const {
return QLatin1String("<b>") + displayName() + QLatin1String("</b>"); }
virtual QString displayName() const {
return m_buildStep ? m_buildStep.data()->displayName() : QString();
}
private:
const QWeakPointer<const BuildStep> m_buildStep;
};
AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
const QString &id)
: BuildStep(bsl, id)
{
}
AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
AbstractMaemoInstallPackageToSysrootStep *other)
: BuildStep(bsl, other)
{
}
void AbstractMaemoInstallPackageToSysrootStep::run(QFutureInterface<bool> &fi)
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BaseTarget *>(target())->activeBuildConfiguration();
if (!bc) {
addOutput(tr("Cannot install to sysroot without build configuration."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
const AbstractMaemoPackageCreationStep * const pStep
= MaemoGlobal::earlierBuildStep<AbstractMaemoPackageCreationStep>(deployConfiguration(), this);
if (!pStep) {
addOutput(tr("Cannot install package to sysroot without packaging step."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
if (!bc->qtVersion()) {
addOutput(tr("Cannot install package to sysroot without a Qt version."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
m_installerProcess = new QProcess;
connect(m_installerProcess, SIGNAL(readyReadStandardOutput()),
SLOT(handleInstallerStdout()));
connect(m_installerProcess, SIGNAL(readyReadStandardError()),
SLOT(handleInstallerStderr()));
emit addOutput(tr("Installing package to sysroot ..."), MessageOutput);
const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
const QString packageFilePath = pStep->packageFilePath();
const int packageFileSize = QFileInfo(packageFilePath).size() / (1024*1024);
const QStringList args = madArguments() << packageFilePath;
MaemoGlobal::callMadAdmin(*m_installerProcess, args, qtVersion->qmakeCommand(), true);
if (!m_installerProcess->waitForFinished((2*packageFileSize + 10)*1000)
|| m_installerProcess->exitStatus() != QProcess::NormalExit
|| m_installerProcess->exitCode() != 0) {
emit addOutput(tr("Installation to sysroot failed, continuing anyway."),
ErrorMessageOutput);
if (m_installerProcess->state() != QProcess::NotRunning) {
m_installerProcess->terminate();
m_installerProcess->waitForFinished();
m_installerProcess->kill();
}
fi.reportResult(true);
return;
}
fi.reportResult(true);
m_installerProcess->deleteLater();
m_installerProcess = 0;
}
void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStdout()
{
if (m_installerProcess)
emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardOutput()), NormalOutput);
}
void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStderr()
{
if (m_installerProcess)
emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardError()), ErrorOutput);
}
MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl)
: AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl,
MaemoInstallDebianPackageToSysrootStep *other)
: AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
setDisplayName(displayName());
}
BuildStepConfigWidget *MaemoInstallDebianPackageToSysrootStep::createConfigWidget()
{
return new MaemoInstallDebianPackageToSysrootWidget(this);
}
QStringList MaemoInstallDebianPackageToSysrootStep::madArguments() const
{
return QStringList() << QLatin1String("xdpkg") << QLatin1String("--no-force-downgrade")
<< QLatin1String("-i");
}
const QString MaemoInstallDebianPackageToSysrootStep::Id
= QLatin1String("MaemoInstallDebianPackageToSysrootStep");
QString MaemoInstallDebianPackageToSysrootStep::displayName()
{
return tr("Install Debian package to sysroot");
}
MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl)
: AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl,
MaemoInstallRpmPackageToSysrootStep *other)
: AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
setDisplayName(displayName());
}
BuildStepConfigWidget *MaemoInstallRpmPackageToSysrootStep::createConfigWidget()
{
return new MaemoInstallRpmPackageToSysrootWidget(this);
}
QStringList MaemoInstallRpmPackageToSysrootStep::madArguments() const
{
return QStringList() << QLatin1String("xrpm") << QLatin1String("-i");
}
const QString MaemoInstallRpmPackageToSysrootStep::Id
= QLatin1String("MaemoInstallRpmPackageToSysrootStep");
QString MaemoInstallRpmPackageToSysrootStep::displayName()
{
return tr("Install RPM package to sysroot");
}
MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl)
: BuildStep(bsl, Id)
{
setDisplayName(displayName());
}
MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl,
MaemoCopyToSysrootStep *other)
: BuildStep(bsl, other)
{
setDisplayName(displayName());
}
void MaemoCopyToSysrootStep::run(QFutureInterface<bool> &fi)
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BaseTarget *>(target())->activeBuildConfiguration();
if (!bc) {
addOutput(tr("Cannot copy to sysroot without build configuration."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
const MaemoQtVersion * const qtVersion = dynamic_cast<MaemoQtVersion *>(bc->qtVersion());
if (!qtVersion) {
addOutput(tr("Cannot copy to sysroot without valid Qt version."),
ErrorMessageOutput);
fi.reportResult(false);
return;
}
emit addOutput(tr("Copying files to sysroot ..."), MessageOutput);
QDir sysrootDir(qtVersion->systemRoot());
const QSharedPointer<DeploymentInfo> deploymentInfo
= qobject_cast<Qt4MaemoDeployConfiguration *>(deployConfiguration())->deploymentInfo();
const QChar sep = QLatin1Char('/');
for (int i = 0; i < deploymentInfo->deployableCount(); ++i) {
const DeployableFile &deployable = deploymentInfo->deployableAt(i);
const QFileInfo localFileInfo(deployable.localFilePath);
const QString targetFilePath = qtVersion->systemRoot() + sep
+ deployable.remoteDir + sep + localFileInfo.fileName();
sysrootDir.mkpath(deployable.remoteDir.mid(1));
QString errorMsg;
Utils::FileUtils::removeRecursively(targetFilePath, &errorMsg);
if (!Utils::FileUtils::copyRecursively(deployable.localFilePath,
targetFilePath, &errorMsg)) {
emit addOutput(tr("Sysroot installation failed: %1\n"
" Continuing anyway.").arg(errorMsg), ErrorMessageOutput);
}
QCoreApplication::processEvents();
if (fi.isCanceled()) {
fi.reportResult(false);
return;
}
}
fi.reportResult(true);
}
BuildStepConfigWidget *MaemoCopyToSysrootStep::createConfigWidget()
{
return new MaemoCopyFilesToSysrootWidget(this);
}
const QString MaemoCopyToSysrootStep::Id
= QLatin1String("MaemoCopyToSysrootStep");
QString MaemoCopyToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
}
MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl)
: AbstractProcessStep(bsl, Id)
{
setDefaultDisplayName(displayName());
}
MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl,
MaemoMakeInstallToSysrootStep *other)
: AbstractProcessStep(bsl, other)
{
setDefaultDisplayName(displayName());
}
bool MaemoMakeInstallToSysrootStep::init()
{
const Qt4BuildConfiguration * const bc
= qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
if (!bc) {
addOutput("Cannot deploy: No active build dconfiguration.",
ErrorMessageOutput);
return false;
}
const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
if (!qtVersion) {
addOutput("Cannot deploy: Unusable build configuration.",
ErrorMessageOutput);
return false;
}
Utils::Environment env = bc->environment();
MaemoGlobal::addMaddeEnvironment(env, qtVersion->qmakeCommand());
QString command = MaemoGlobal::madCommand(qtVersion->qmakeCommand());
QStringList args = QStringList() << QLatin1String("-t")
<< MaemoGlobal::targetName(qtVersion->qmakeCommand()) << QLatin1String("make")
<< QLatin1String("install") << (QLatin1String("INSTALL_ROOT=") + qtVersion->systemRoot());
MaemoGlobal::transformMaddeCall(command, args, qtVersion->qmakeCommand());
processParameters()->setCommand(command);
processParameters()->setArguments(args.join(QLatin1String(" ")));
processParameters()->setEnvironment(env);
processParameters()->setWorkingDirectory(bc->buildDirectory());
return true;
}
BuildStepConfigWidget *MaemoMakeInstallToSysrootStep::createConfigWidget()
{
return new MaemoCopyFilesToSysrootWidget(this);
}
const QString MaemoMakeInstallToSysrootStep::Id
= QLatin1String("MaemoMakeInstallToSysrootStep");
QString MaemoMakeInstallToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
}
} // namespace Internal
} // namespace RemoteLinux
#include "maemoinstalltosysrootstep.moc"
<|endoftext|>
|
<commit_before>#include "builder.h"
#include <fstream>
#include "../domain/mesh_cartesian.h"
namespace bart {
namespace framework {
template <int dim>
Builder<dim>::Builder(std::shared_ptr<problem::ParametersI> parameters)
: parameters_(parameters) {}
template <int dim>
std::unique_ptr<domain::Definition<dim>> Builder<dim>::BuildDefinition() const {
// Get material mapping from input file and build mesh
std::string material_mapping =
GetMaterialMapFromFile(parameters_->MaterialMapFilename());
domain::MeshCartesian mesh(parameters_->SpatialMax(),
parameters_->NCells(),
material_mapping);
}
template <int dim>
std::string Builder<dim>::GetMaterialMapFromFile(std::string filename) const {
std::ifstream input(filename);
std::string return_string(std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>());
return return_string;
}
} // namespace framework
} // namespace bart
<commit_msg>added finite element instantiation to BuilDefinition, fixed iterator in GetMaterialMapFromFile<commit_after>#include "builder.h"
#include <fstream>
#include "../domain/finite_element_gaussian.h"
#include "../domain/mesh_cartesian.h"
namespace bart {
namespace framework {
template <int dim>
Builder<dim>::Builder(std::shared_ptr<problem::ParametersI> parameters)
: parameters_(parameters) {}
template <int dim>
std::unique_ptr<domain::Definition<dim>> Builder<dim>::BuildDefinition() const {
// Get material mapping from input file and build mesh
std::string material_mapping =
GetMaterialMapFromFile(parameters_->MaterialMapFilename());
auto mesh = std::make_unique<domain::MeshCartesian<dim>>(
parameters_->SpatialMax(), parameters_->NCells(), material_mapping);
auto finite_element = std::make_unique<domain::FiniteElementGaussian<dim>>(
parameters_->Discretization(), parameters_->FEPolynomialDegree());
}
template <int dim>
std::string Builder<dim>::GetMaterialMapFromFile(std::string filename) const {
std::ifstream input(filename);
std::string return_string((std::istreambuf_iterator<char>(input)),
(std::istreambuf_iterator<char>()));
return return_string;
}
template class Builder<1>;
template class Builder<2>;
} // namespace framework
} // namespace bart
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/windows/video_capture_ds.h"
#include "webrtc/modules/video_capture/video_capture_config.h"
#include "webrtc/modules/video_capture/windows/help_functions_ds.h"
#include "webrtc/modules/video_capture/windows/sink_filter_ds.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include <Dvdmedia.h> // VIDEOINFOHEADER2
namespace webrtc
{
namespace videocapturemodule
{
VideoCaptureDS::VideoCaptureDS(const int32_t id)
: VideoCaptureImpl(id), _dsInfo(id), _captureFilter(NULL),
_graphBuilder(NULL), _mediaControl(NULL), _sinkFilter(NULL),
_inputSendPin(NULL), _outputCapturePin(NULL), _dvFilter(NULL),
_inputDvPin(NULL), _outputDvPin(NULL)
{
}
VideoCaptureDS::~VideoCaptureDS()
{
if (_mediaControl)
{
_mediaControl->Stop();
}
if (_graphBuilder)
{
if (_sinkFilter)
_graphBuilder->RemoveFilter(_sinkFilter);
if (_captureFilter)
_graphBuilder->RemoveFilter(_captureFilter);
if (_dvFilter)
_graphBuilder->RemoveFilter(_dvFilter);
}
RELEASE_AND_CLEAR(_captureFilter); // release the capture device
RELEASE_AND_CLEAR(_sinkFilter);
RELEASE_AND_CLEAR(_dvFilter);
RELEASE_AND_CLEAR(_mediaControl);
RELEASE_AND_CLEAR(_inputSendPin);
RELEASE_AND_CLEAR(_outputCapturePin);
RELEASE_AND_CLEAR(_inputDvPin);
RELEASE_AND_CLEAR(_outputDvPin);
RELEASE_AND_CLEAR(_graphBuilder);
}
int32_t VideoCaptureDS::Init(const int32_t id, const char* deviceUniqueIdUTF8)
{
const int32_t nameLength =
(int32_t) strlen((char*) deviceUniqueIdUTF8);
if (nameLength > kVideoCaptureUniqueNameLength)
return -1;
// Store the device name
_deviceUniqueId = new (std::nothrow) char[nameLength + 1];
memcpy(_deviceUniqueId, deviceUniqueIdUTF8, nameLength + 1);
if (_dsInfo.Init() != 0)
return -1;
_captureFilter = _dsInfo.GetDeviceFilter(deviceUniqueIdUTF8);
if (!_captureFilter)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create capture filter.");
return -1;
}
// Get the interface for DirectShow's GraphBuilder
HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC_SERVER, IID_IGraphBuilder,
(void **) &_graphBuilder);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create graph builder.");
return -1;
}
hr = _graphBuilder->QueryInterface(IID_IMediaControl,
(void **) &_mediaControl);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create media control builder.");
return -1;
}
hr = _graphBuilder->AddFilter(_captureFilter, CAPTURE_FILTER_NAME);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the capture device to the graph.");
return -1;
}
_outputCapturePin = GetOutputPin(_captureFilter, PIN_CATEGORY_CAPTURE);
// Create the sink filte used for receiving Captured frames.
_sinkFilter = new CaptureSinkFilter(SINK_FILTER_NAME, NULL, &hr,
*this, _id);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create send filter");
return -1;
}
_sinkFilter->AddRef();
hr = _graphBuilder->AddFilter(_sinkFilter, SINK_FILTER_NAME);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the send filter to the graph.");
return -1;
}
_inputSendPin = GetInputPin(_sinkFilter);
// Temporary connect here.
// This is done so that no one else can use the capture device.
if (SetCameraOutput(_requestedCapability) != 0)
{
return -1;
}
hr = _mediaControl->Pause();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to Pause the Capture device. Is it already occupied? %d.",
hr);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceVideoCapture, _id,
"Capture device '%s' initialized.", deviceUniqueIdUTF8);
return 0;
}
int32_t VideoCaptureDS::StartCapture(
const VideoCaptureCapability& capability)
{
CriticalSectionScoped cs(&_apiCs);
if (capability != _requestedCapability)
{
DisconnectGraph();
if (SetCameraOutput(capability) != 0)
{
return -1;
}
}
HRESULT hr = _mediaControl->Run();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to start the Capture device.");
return -1;
}
return 0;
}
int32_t VideoCaptureDS::StopCapture()
{
CriticalSectionScoped cs(&_apiCs);
HRESULT hr = _mediaControl->Pause();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to stop the capture graph. %d", hr);
return -1;
}
return 0;
}
bool VideoCaptureDS::CaptureStarted()
{
OAFilterState state = 0;
HRESULT hr = _mediaControl->GetState(1000, &state);
if (hr != S_OK && hr != VFW_S_CANT_CUE)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get the CaptureStarted status");
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"CaptureStarted %d", state);
return state == State_Running;
}
int32_t VideoCaptureDS::CaptureSettings(
VideoCaptureCapability& settings)
{
settings = _requestedCapability;
return 0;
}
int32_t VideoCaptureDS::SetCameraOutput(
const VideoCaptureCapability& requestedCapability)
{
// Get the best matching capability
VideoCaptureCapability capability;
int32_t capabilityIndex;
// Store the new requested size
_requestedCapability = requestedCapability;
// Match the requested capability with the supported.
if ((capabilityIndex = _dsInfo.GetBestMatchedCapability(_deviceUniqueId,
_requestedCapability,
capability)) < 0)
{
return -1;
}
//Reduce the frame rate if possible.
if (capability.maxFPS > requestedCapability.maxFPS)
{
capability.maxFPS = requestedCapability.maxFPS;
} else if (capability.maxFPS <= 0)
{
capability.maxFPS = 30;
}
// Store the new expected capture delay
_captureDelay = capability.expectedCaptureDelay;
// Convert it to the windows capability index since they are not nexessary
// the same
VideoCaptureCapabilityWindows windowsCapability;
if (_dsInfo.GetWindowsCapability(capabilityIndex, windowsCapability) != 0)
{
return -1;
}
IAMStreamConfig* streamConfig = NULL;
AM_MEDIA_TYPE *pmt = NULL;
VIDEO_STREAM_CONFIG_CAPS caps;
HRESULT hr = _outputCapturePin->QueryInterface(IID_IAMStreamConfig,
(void**) &streamConfig);
if (hr)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Can't get the Capture format settings.");
return -1;
}
//Get the windows capability from the capture device
bool isDVCamera = false;
hr = streamConfig->GetStreamCaps(
windowsCapability.directShowCapabilityIndex,
&pmt, reinterpret_cast<BYTE*> (&caps));
if (!FAILED(hr))
{
if (pmt->formattype == FORMAT_VideoInfo2)
{
VIDEOINFOHEADER2* h =
reinterpret_cast<VIDEOINFOHEADER2*> (pmt->pbFormat);
if (capability.maxFPS > 0
&& windowsCapability.supportFrameRateControl)
{
h->AvgTimePerFrame = REFERENCE_TIME(10000000.0
/ capability.maxFPS);
}
}
else
{
VIDEOINFOHEADER* h = reinterpret_cast<VIDEOINFOHEADER*>
(pmt->pbFormat);
if (capability.maxFPS > 0
&& windowsCapability.supportFrameRateControl)
{
h->AvgTimePerFrame = REFERENCE_TIME(10000000.0
/ capability.maxFPS);
}
}
// Set the sink filter to request this capability
_sinkFilter->SetMatchingMediaType(capability);
//Order the capture device to use this capability
hr += streamConfig->SetFormat(pmt);
//Check if this is a DV camera and we need to add MS DV Filter
if (pmt->subtype == MEDIASUBTYPE_dvsl
|| pmt->subtype == MEDIASUBTYPE_dvsd
|| pmt->subtype == MEDIASUBTYPE_dvhd)
isDVCamera = true; // This is a DV camera. Use MS DV filter
}
RELEASE_AND_CLEAR(streamConfig);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to set capture device output format");
return -1;
}
if (isDVCamera)
{
hr = ConnectDVCamera();
}
else
{
hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputSendPin,
NULL);
}
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect the Capture graph %d", hr);
return -1;
}
return 0;
}
int32_t VideoCaptureDS::DisconnectGraph()
{
HRESULT hr = _mediaControl->Stop();
hr += _graphBuilder->Disconnect(_outputCapturePin);
hr += _graphBuilder->Disconnect(_inputSendPin);
//if the DV camera filter exist
if (_dvFilter)
{
_graphBuilder->Disconnect(_inputDvPin);
_graphBuilder->Disconnect(_outputDvPin);
}
if (hr != S_OK)
{
WEBRTC_TRACE( webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to Stop the Capture device for reconfiguration %d",
hr);
return -1;
}
return 0;
}
HRESULT VideoCaptureDS::ConnectDVCamera()
{
HRESULT hr = S_OK;
if (!_dvFilter)
{
hr = CoCreateInstance(CLSID_DVVideoCodec, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (void **) &_dvFilter);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create the dv decoder: %x", hr);
return hr;
}
hr = _graphBuilder->AddFilter(_dvFilter, L"VideoDecoderDV");
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the dv decoder to the graph: %x", hr);
return hr;
}
_inputDvPin = GetInputPin(_dvFilter);
if (_inputDvPin == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get input pin from DV decoder");
return -1;
}
_outputDvPin = GetOutputPin(_dvFilter, GUID_NULL);
if (_outputDvPin == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get output pin from DV decoder");
return -1;
}
}
hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputDvPin, NULL);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect capture device to the dv devoder: %x",
hr);
return hr;
}
hr = _graphBuilder->ConnectDirect(_outputDvPin, _inputSendPin, NULL);
if (hr != S_OK)
{
if (hr == 0x80070004)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect the capture device, busy");
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect capture device to the send graph: 0x%x",
hr);
}
return hr;
}
return hr;
}
} // namespace videocapturemodule
} // namespace webrtc
<commit_msg>Release _inputSendPin & _outputCapturePin before _captureFilter & _sinkFilter since they should depend on the filters. The previous steps work fine for all the webcam, but have problem on SplitCam driver as in the issue report. Anyway it's always good to de-initial with the reversing order to initialization.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/windows/video_capture_ds.h"
#include "webrtc/modules/video_capture/video_capture_config.h"
#include "webrtc/modules/video_capture/windows/help_functions_ds.h"
#include "webrtc/modules/video_capture/windows/sink_filter_ds.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include <Dvdmedia.h> // VIDEOINFOHEADER2
namespace webrtc
{
namespace videocapturemodule
{
VideoCaptureDS::VideoCaptureDS(const int32_t id)
: VideoCaptureImpl(id), _dsInfo(id), _captureFilter(NULL),
_graphBuilder(NULL), _mediaControl(NULL), _sinkFilter(NULL),
_inputSendPin(NULL), _outputCapturePin(NULL), _dvFilter(NULL),
_inputDvPin(NULL), _outputDvPin(NULL)
{
}
VideoCaptureDS::~VideoCaptureDS()
{
if (_mediaControl)
{
_mediaControl->Stop();
}
if (_graphBuilder)
{
if (_sinkFilter)
_graphBuilder->RemoveFilter(_sinkFilter);
if (_captureFilter)
_graphBuilder->RemoveFilter(_captureFilter);
if (_dvFilter)
_graphBuilder->RemoveFilter(_dvFilter);
}
RELEASE_AND_CLEAR(_inputSendPin);
RELEASE_AND_CLEAR(_outputCapturePin);
RELEASE_AND_CLEAR(_captureFilter); // release the capture device
RELEASE_AND_CLEAR(_sinkFilter);
RELEASE_AND_CLEAR(_dvFilter);
RELEASE_AND_CLEAR(_mediaControl);
RELEASE_AND_CLEAR(_inputDvPin);
RELEASE_AND_CLEAR(_outputDvPin);
RELEASE_AND_CLEAR(_graphBuilder);
}
int32_t VideoCaptureDS::Init(const int32_t id, const char* deviceUniqueIdUTF8)
{
const int32_t nameLength =
(int32_t) strlen((char*) deviceUniqueIdUTF8);
if (nameLength > kVideoCaptureUniqueNameLength)
return -1;
// Store the device name
_deviceUniqueId = new (std::nothrow) char[nameLength + 1];
memcpy(_deviceUniqueId, deviceUniqueIdUTF8, nameLength + 1);
if (_dsInfo.Init() != 0)
return -1;
_captureFilter = _dsInfo.GetDeviceFilter(deviceUniqueIdUTF8);
if (!_captureFilter)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create capture filter.");
return -1;
}
// Get the interface for DirectShow's GraphBuilder
HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC_SERVER, IID_IGraphBuilder,
(void **) &_graphBuilder);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create graph builder.");
return -1;
}
hr = _graphBuilder->QueryInterface(IID_IMediaControl,
(void **) &_mediaControl);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create media control builder.");
return -1;
}
hr = _graphBuilder->AddFilter(_captureFilter, CAPTURE_FILTER_NAME);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the capture device to the graph.");
return -1;
}
_outputCapturePin = GetOutputPin(_captureFilter, PIN_CATEGORY_CAPTURE);
// Create the sink filte used for receiving Captured frames.
_sinkFilter = new CaptureSinkFilter(SINK_FILTER_NAME, NULL, &hr,
*this, _id);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create send filter");
return -1;
}
_sinkFilter->AddRef();
hr = _graphBuilder->AddFilter(_sinkFilter, SINK_FILTER_NAME);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the send filter to the graph.");
return -1;
}
_inputSendPin = GetInputPin(_sinkFilter);
// Temporary connect here.
// This is done so that no one else can use the capture device.
if (SetCameraOutput(_requestedCapability) != 0)
{
return -1;
}
hr = _mediaControl->Pause();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to Pause the Capture device. Is it already occupied? %d.",
hr);
return -1;
}
WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceVideoCapture, _id,
"Capture device '%s' initialized.", deviceUniqueIdUTF8);
return 0;
}
int32_t VideoCaptureDS::StartCapture(
const VideoCaptureCapability& capability)
{
CriticalSectionScoped cs(&_apiCs);
if (capability != _requestedCapability)
{
DisconnectGraph();
if (SetCameraOutput(capability) != 0)
{
return -1;
}
}
HRESULT hr = _mediaControl->Run();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to start the Capture device.");
return -1;
}
return 0;
}
int32_t VideoCaptureDS::StopCapture()
{
CriticalSectionScoped cs(&_apiCs);
HRESULT hr = _mediaControl->Pause();
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to stop the capture graph. %d", hr);
return -1;
}
return 0;
}
bool VideoCaptureDS::CaptureStarted()
{
OAFilterState state = 0;
HRESULT hr = _mediaControl->GetState(1000, &state);
if (hr != S_OK && hr != VFW_S_CANT_CUE)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get the CaptureStarted status");
}
WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCapture, _id,
"CaptureStarted %d", state);
return state == State_Running;
}
int32_t VideoCaptureDS::CaptureSettings(
VideoCaptureCapability& settings)
{
settings = _requestedCapability;
return 0;
}
int32_t VideoCaptureDS::SetCameraOutput(
const VideoCaptureCapability& requestedCapability)
{
// Get the best matching capability
VideoCaptureCapability capability;
int32_t capabilityIndex;
// Store the new requested size
_requestedCapability = requestedCapability;
// Match the requested capability with the supported.
if ((capabilityIndex = _dsInfo.GetBestMatchedCapability(_deviceUniqueId,
_requestedCapability,
capability)) < 0)
{
return -1;
}
//Reduce the frame rate if possible.
if (capability.maxFPS > requestedCapability.maxFPS)
{
capability.maxFPS = requestedCapability.maxFPS;
} else if (capability.maxFPS <= 0)
{
capability.maxFPS = 30;
}
// Store the new expected capture delay
_captureDelay = capability.expectedCaptureDelay;
// Convert it to the windows capability index since they are not nexessary
// the same
VideoCaptureCapabilityWindows windowsCapability;
if (_dsInfo.GetWindowsCapability(capabilityIndex, windowsCapability) != 0)
{
return -1;
}
IAMStreamConfig* streamConfig = NULL;
AM_MEDIA_TYPE *pmt = NULL;
VIDEO_STREAM_CONFIG_CAPS caps;
HRESULT hr = _outputCapturePin->QueryInterface(IID_IAMStreamConfig,
(void**) &streamConfig);
if (hr)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Can't get the Capture format settings.");
return -1;
}
//Get the windows capability from the capture device
bool isDVCamera = false;
hr = streamConfig->GetStreamCaps(
windowsCapability.directShowCapabilityIndex,
&pmt, reinterpret_cast<BYTE*> (&caps));
if (!FAILED(hr))
{
if (pmt->formattype == FORMAT_VideoInfo2)
{
VIDEOINFOHEADER2* h =
reinterpret_cast<VIDEOINFOHEADER2*> (pmt->pbFormat);
if (capability.maxFPS > 0
&& windowsCapability.supportFrameRateControl)
{
h->AvgTimePerFrame = REFERENCE_TIME(10000000.0
/ capability.maxFPS);
}
}
else
{
VIDEOINFOHEADER* h = reinterpret_cast<VIDEOINFOHEADER*>
(pmt->pbFormat);
if (capability.maxFPS > 0
&& windowsCapability.supportFrameRateControl)
{
h->AvgTimePerFrame = REFERENCE_TIME(10000000.0
/ capability.maxFPS);
}
}
// Set the sink filter to request this capability
_sinkFilter->SetMatchingMediaType(capability);
//Order the capture device to use this capability
hr += streamConfig->SetFormat(pmt);
//Check if this is a DV camera and we need to add MS DV Filter
if (pmt->subtype == MEDIASUBTYPE_dvsl
|| pmt->subtype == MEDIASUBTYPE_dvsd
|| pmt->subtype == MEDIASUBTYPE_dvhd)
isDVCamera = true; // This is a DV camera. Use MS DV filter
}
RELEASE_AND_CLEAR(streamConfig);
if (FAILED(hr))
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to set capture device output format");
return -1;
}
if (isDVCamera)
{
hr = ConnectDVCamera();
}
else
{
hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputSendPin,
NULL);
}
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect the Capture graph %d", hr);
return -1;
}
return 0;
}
int32_t VideoCaptureDS::DisconnectGraph()
{
HRESULT hr = _mediaControl->Stop();
hr += _graphBuilder->Disconnect(_outputCapturePin);
hr += _graphBuilder->Disconnect(_inputSendPin);
//if the DV camera filter exist
if (_dvFilter)
{
_graphBuilder->Disconnect(_inputDvPin);
_graphBuilder->Disconnect(_outputDvPin);
}
if (hr != S_OK)
{
WEBRTC_TRACE( webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to Stop the Capture device for reconfiguration %d",
hr);
return -1;
}
return 0;
}
HRESULT VideoCaptureDS::ConnectDVCamera()
{
HRESULT hr = S_OK;
if (!_dvFilter)
{
hr = CoCreateInstance(CLSID_DVVideoCodec, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (void **) &_dvFilter);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to create the dv decoder: %x", hr);
return hr;
}
hr = _graphBuilder->AddFilter(_dvFilter, L"VideoDecoderDV");
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to add the dv decoder to the graph: %x", hr);
return hr;
}
_inputDvPin = GetInputPin(_dvFilter);
if (_inputDvPin == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get input pin from DV decoder");
return -1;
}
_outputDvPin = GetOutputPin(_dvFilter, GUID_NULL);
if (_outputDvPin == NULL)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to get output pin from DV decoder");
return -1;
}
}
hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputDvPin, NULL);
if (hr != S_OK)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect capture device to the dv devoder: %x",
hr);
return hr;
}
hr = _graphBuilder->ConnectDirect(_outputDvPin, _inputSendPin, NULL);
if (hr != S_OK)
{
if (hr == 0x80070004)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect the capture device, busy");
}
else
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id,
"Failed to connect capture device to the send graph: 0x%x",
hr);
}
return hr;
}
return hr;
}
} // namespace videocapturemodule
} // namespace webrtc
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*
* This tool checks a cvmfs cache directory for consistency.
* If necessary, the managed cache db is removed so that
* it will be rebuilt on next mount.
*/
#define _FILE_OFFSET_BITS 64
#include "cvmfs_config.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "atomic.h"
#include "compression.h"
#include "hash.h"
#include "logging.h"
#include "platform.h"
#include "smalloc.h"
#include "util/posix.h"
using namespace std; // NOLINT
enum Errors {
kErrorOk = 0,
kErrorFixed = 1,
kErrorReboot = 2,
kErrorUnfixed = 4,
kErrorOperational = 8,
kErrorUsage = 16,
};
string *g_cache_dir;
atomic_int32 g_num_files;
atomic_int32 g_num_err_fixed;
atomic_int32 g_num_err_unfixed;
atomic_int32 g_num_err_operational;
atomic_int32 g_num_tmp_catalog;
/**
* Traversal of the file system tree is serialized.
*/
pthread_mutex_t g_lock_traverse = PTHREAD_MUTEX_INITIALIZER;
DIR *g_DIRP_current = NULL;
int g_num_dirs = -1; /**< Number of cache directories already examined. */
string *g_current_dir; /**< Current cache sub directory */
int g_num_threads = 1;
bool g_fix_errors = false;
bool g_verbose = false;
atomic_int32 g_force_rebuild;
atomic_int32 g_modified_cache;
static void Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM File System consistency checker, version %s\n\n"
"This tool checks a cvmfs cache directory for consistency.\n"
"If necessary, the managed cache db is removed so that\n"
"it will be rebuilt on next mount.\n\n"
"Usage: cvmfs_fsck [-v] [-p] [-f] [-j #threads] <cache directory>\n"
"Options:\n"
" -v verbose output\n"
" -p try to fix automatically\n"
" -f force rebuild of managed cache db on next mount\n"
" -j number of concurrent integrity check worker threads\n",
VERSION);
}
static bool GetNextFile(string *relative_path, string *hash_name) {
platform_dirent64 *d = NULL;
pthread_mutex_lock(&g_lock_traverse);
get_next_file_again:
while (g_DIRP_current && ((d = platform_readdir(g_DIRP_current)) != NULL)) {
const string name = d->d_name;
if ((name == ".") || (name == "..")) continue;
platform_stat64 info;
*relative_path = *g_current_dir + "/" + name;
*hash_name = *g_current_dir + name;
const string path = *g_cache_dir + "/" + *relative_path;
if (platform_lstat(relative_path->c_str(), &info) != 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Warning: failed to stat() %s (%d)",
path.c_str(), errno);
continue;
}
if (!S_ISREG(info.st_mode)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Warning: %s is not a regular file",
path.c_str());
continue;
}
break;
}
if (!d) {
if (g_DIRP_current) {
closedir(g_DIRP_current);
g_DIRP_current = NULL;
}
g_num_dirs++;
if (g_num_dirs < 256) {
char hex[3];
snprintf(hex, sizeof(hex), "%02x", g_num_dirs);
*g_current_dir = string(hex, 2);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Entering %s", g_current_dir->c_str());
if ((g_DIRP_current = opendir(hex)) == NULL) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Invalid cache directory, %s/%s does not exist",
g_cache_dir->c_str(), g_current_dir->c_str());
pthread_mutex_unlock(&g_lock_traverse);
exit(kErrorUnfixed);
}
goto get_next_file_again;
}
}
pthread_mutex_unlock(&g_lock_traverse);
if (d)
return true;
return false;
}
static void *MainCheck(void *data __attribute__((unused))) {
string relative_path;
string hash_name;
while (GetNextFile(&relative_path, &hash_name)) {
const string path = *g_cache_dir + "/" + relative_path;
int n = atomic_xadd32(&g_num_files, 1);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Checking file %s", path.c_str());
if (!g_verbose && ((n % 1000) == 0))
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, ".");
if (relative_path[relative_path.length()-1] == 'T') {
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: temporary file catalog %s found", path.c_str());
atomic_inc32(&g_num_tmp_catalog);
if (g_fix_errors) {
if (unlink(relative_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Fix: %s unlinked", path.c_str());
atomic_inc32(&g_num_err_fixed);
} else {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: failed to unlink %s",
path.c_str());
atomic_inc32(&g_num_err_unfixed);
}
}
continue;
}
int fd_src = open(relative_path.c_str() , O_RDONLY);
if (fd_src < 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: cannot open %s", path.c_str());
atomic_inc32(&g_num_err_operational);
continue;
}
// Don't thrash kernel buffers
platform_disable_kcache(fd_src);
// Compress every file and calculate SHA-1 of stream
shash::Any expected_hash = shash::MkFromHexPtr(shash::HexPtr(hash_name));
shash::Any hash(expected_hash.algorithm);
if (!zlib::CompressFd2Null(fd_src, &hash)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: could not compress %s",
path.c_str());
atomic_inc32(&g_num_err_operational);
} else {
if (hash != expected_hash) {
// If the hashes don't match, try hashing the uncompressed file
if (!shash::HashFile(relative_path, &hash)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: could not hash %s",
path.c_str());
atomic_inc32(&g_num_err_operational);
}
if (hash != expected_hash) {
if (g_fix_errors) {
const string quarantaine_path = "./quarantaine/" + hash_name;
bool fixed = false;
if (rename(relative_path.c_str(), quarantaine_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: %s is corrupted, moved to quarantaine folder",
path.c_str());
fixed = true;
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: failed to move %s into quarantaine folder",
path.c_str());
if (unlink(relative_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: %s is corrupted, file unlinked", path.c_str());
fixed = true;
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: %s is corrupted, could not unlink",
path.c_str());
}
}
if (fixed) {
atomic_inc32(&g_num_err_fixed);
// Changes made, we have to rebuild the managed cache db
atomic_cas32(&g_force_rebuild, 0, 1);
atomic_cas32(&g_modified_cache, 0, 1);
} else {
atomic_inc32(&g_num_err_unfixed);
}
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: %s has compressed checksum %s, "
"delete this file from cache directory!",
path.c_str(), hash.ToString().c_str());
atomic_inc32(&g_num_err_unfixed);
}
}
}
}
close(fd_src);
}
return NULL;
}
int main(int argc, char **argv) {
atomic_init32(&g_force_rebuild);
atomic_init32(&g_modified_cache);
g_current_dir = new string();
int c;
while ((c = getopt(argc, argv, "hvpfj:")) != -1) {
switch (c) {
case 'h':
Usage();
return kErrorOk;
case 'v':
g_verbose = true;
break;
case 'p':
g_fix_errors = true;
break;
case 'f':
atomic_cas32(&g_force_rebuild, 0, 1);
break;
case 'j':
g_num_threads = atoi(optarg);
if (g_num_threads < 1) {
LogCvmfs(kLogCvmfs, kLogStdout,
"There is at least one worker thread required");
return kErrorUsage;
}
break;
case '?':
default:
Usage();
return kErrorUsage;
}
}
// Switch to cache directory
if (optind >= argc) {
Usage();
return kErrorUsage;
}
g_cache_dir = new string(MakeCanonicalPath(argv[optind]));
if (chdir(g_cache_dir->c_str()) != 0) {
LogCvmfs(kLogCvmfs, kLogStderr, "Could not chdir to %s",
g_cache_dir->c_str());
return kErrorOperational;
}
// Check if txn directory is empty
DIR *dirp_txn;
if ((dirp_txn = opendir("txn")) == NULL) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Invalid cache directory, %s/txn does not exist",
g_cache_dir->c_str());
return kErrorOperational;
}
platform_dirent64 *d;
while ((d = platform_readdir(dirp_txn)) != NULL) {
const string name = d->d_name;
if ((name == ".") || (name == "..")) continue;
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: temporary directory %s/txn is not empty\n"
"If this repository is currently _not_ mounted, "
"you can remove its contents", g_cache_dir->c_str());
break;
}
closedir(dirp_txn);
// Run workers to recalculate checksums
atomic_init32(&g_num_files);
atomic_init32(&g_num_err_fixed);
atomic_init32(&g_num_err_unfixed);
atomic_init32(&g_num_err_operational);
atomic_init32(&g_num_tmp_catalog);
pthread_t *workers = reinterpret_cast<pthread_t *>(
smalloc(g_num_threads * sizeof(pthread_t)));
if (!g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "Verifying: ");
for (int i = 0; i < g_num_threads; ++i) {
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Starting worker %d", i+1);
if (pthread_create(&workers[i], NULL, MainCheck, NULL) != 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Fatal: could not create worker thread");
return kErrorOperational;
}
}
for (int i = g_num_threads-1; i >= 0; --i) {
pthread_join(workers[i], NULL);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Stopping worker %d", i+1);
}
free(workers);
if (!g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "Verified %d files",
atomic_read32(&g_num_files));
if (atomic_read32(&g_num_tmp_catalog) > 0)
LogCvmfs(kLogCvmfs, kLogStdout, "Temporary file catalogs were found.");
if (atomic_read32(&g_force_rebuild)) {
if (unlink("cachedb") == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: managed cache db unlinked, will be rebuilt on next mount");
atomic_inc32(&g_num_err_fixed);
} else {
if (errno != ENOENT) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: could not unlink managed cache database (%d)", errno);
atomic_inc32(&g_num_err_unfixed);
}
}
}
if (atomic_read32(&g_modified_cache)) {
LogCvmfs(kLogCvmfs, kLogStdout, "\n"
"WARNING: There might by corrupted files in the kernel buffers.\n"
"Remount CernVM-FS or run 'echo 3 > /proc/sys/vm/drop_caches'"
"\n\n");
}
int retval = 0;
if (atomic_read32(&g_num_err_fixed) > 0)
retval |= kErrorFixed;
if (atomic_read32(&g_num_err_unfixed) > 0)
retval |= kErrorUnfixed;
if (atomic_read32(&g_num_err_operational) > 0)
retval |= kErrorOperational;
return retval;
}
<commit_msg>remove raw mutex from cvmfs_fsck.cc<commit_after>/**
* This file is part of the CernVM File System.
*
* This tool checks a cvmfs cache directory for consistency.
* If necessary, the managed cache db is removed so that
* it will be rebuilt on next mount.
*/
#define _FILE_OFFSET_BITS 64
#include "cvmfs_config.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "atomic.h"
#include "compression.h"
#include "hash.h"
#include "logging.h"
#include "platform.h"
#include "smalloc.h"
#include "util/posix.h"
#include "util_concurrency.h"
using namespace std; // NOLINT
enum Errors {
kErrorOk = 0,
kErrorFixed = 1,
kErrorReboot = 2,
kErrorUnfixed = 4,
kErrorOperational = 8,
kErrorUsage = 16,
};
string *g_cache_dir;
atomic_int32 g_num_files;
atomic_int32 g_num_err_fixed;
atomic_int32 g_num_err_unfixed;
atomic_int32 g_num_err_operational;
atomic_int32 g_num_tmp_catalog;
/**
* Traversal of the file system tree is serialized.
*/
pthread_mutex_t g_lock_traverse = PTHREAD_MUTEX_INITIALIZER;
DIR *g_DIRP_current = NULL;
int g_num_dirs = -1; /**< Number of cache directories already examined. */
string *g_current_dir; /**< Current cache sub directory */
int g_num_threads = 1;
bool g_fix_errors = false;
bool g_verbose = false;
atomic_int32 g_force_rebuild;
atomic_int32 g_modified_cache;
static void Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM File System consistency checker, version %s\n\n"
"This tool checks a cvmfs cache directory for consistency.\n"
"If necessary, the managed cache db is removed so that\n"
"it will be rebuilt on next mount.\n\n"
"Usage: cvmfs_fsck [-v] [-p] [-f] [-j #threads] <cache directory>\n"
"Options:\n"
" -v verbose output\n"
" -p try to fix automatically\n"
" -f force rebuild of managed cache db on next mount\n"
" -j number of concurrent integrity check worker threads\n",
VERSION);
}
static bool GetNextFile(string *relative_path, string *hash_name) {
platform_dirent64 *d = NULL;
{
MutexLockGuard m(&g_lock_traverse);
get_next_file_again:
while (g_DIRP_current && ((d = platform_readdir(g_DIRP_current)) != NULL)) {
const string name = d->d_name;
if ((name == ".") || (name == "..")) continue;
platform_stat64 info;
*relative_path = *g_current_dir + "/" + name;
*hash_name = *g_current_dir + name;
const string path = *g_cache_dir + "/" + *relative_path;
if (platform_lstat(relative_path->c_str(), &info) != 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Warning: failed to stat() %s (%d)",
path.c_str(), errno);
continue;
}
if (!S_ISREG(info.st_mode)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Warning: %s is not a regular file",
path.c_str());
continue;
}
break;
}
if (!d) {
if (g_DIRP_current) {
closedir(g_DIRP_current);
g_DIRP_current = NULL;
}
g_num_dirs++;
if (g_num_dirs < 256) {
char hex[3];
snprintf(hex, sizeof(hex), "%02x", g_num_dirs);
*g_current_dir = string(hex, 2);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Entering %s",
g_current_dir->c_str());
if ((g_DIRP_current = opendir(hex)) == NULL) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Invalid cache directory, %s/%s does not exist",
g_cache_dir->c_str(), g_current_dir->c_str());
pthread_mutex_unlock(&g_lock_traverse);
exit(kErrorUnfixed);
}
goto get_next_file_again;
}
}
}
if (d)
return true;
return false;
}
static void *MainCheck(void *data __attribute__((unused))) {
string relative_path;
string hash_name;
while (GetNextFile(&relative_path, &hash_name)) {
const string path = *g_cache_dir + "/" + relative_path;
int n = atomic_xadd32(&g_num_files, 1);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Checking file %s", path.c_str());
if (!g_verbose && ((n % 1000) == 0))
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, ".");
if (relative_path[relative_path.length()-1] == 'T') {
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: temporary file catalog %s found", path.c_str());
atomic_inc32(&g_num_tmp_catalog);
if (g_fix_errors) {
if (unlink(relative_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Fix: %s unlinked", path.c_str());
atomic_inc32(&g_num_err_fixed);
} else {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: failed to unlink %s",
path.c_str());
atomic_inc32(&g_num_err_unfixed);
}
}
continue;
}
int fd_src = open(relative_path.c_str() , O_RDONLY);
if (fd_src < 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: cannot open %s", path.c_str());
atomic_inc32(&g_num_err_operational);
continue;
}
// Don't thrash kernel buffers
platform_disable_kcache(fd_src);
// Compress every file and calculate SHA-1 of stream
shash::Any expected_hash = shash::MkFromHexPtr(shash::HexPtr(hash_name));
shash::Any hash(expected_hash.algorithm);
if (!zlib::CompressFd2Null(fd_src, &hash)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: could not compress %s",
path.c_str());
atomic_inc32(&g_num_err_operational);
} else {
if (hash != expected_hash) {
// If the hashes don't match, try hashing the uncompressed file
if (!shash::HashFile(relative_path, &hash)) {
LogCvmfs(kLogCvmfs, kLogStdout, "Error: could not hash %s",
path.c_str());
atomic_inc32(&g_num_err_operational);
}
if (hash != expected_hash) {
if (g_fix_errors) {
const string quarantaine_path = "./quarantaine/" + hash_name;
bool fixed = false;
if (rename(relative_path.c_str(), quarantaine_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: %s is corrupted, moved to quarantaine folder",
path.c_str());
fixed = true;
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: failed to move %s into quarantaine folder",
path.c_str());
if (unlink(relative_path.c_str()) == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: %s is corrupted, file unlinked", path.c_str());
fixed = true;
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: %s is corrupted, could not unlink",
path.c_str());
}
}
if (fixed) {
atomic_inc32(&g_num_err_fixed);
// Changes made, we have to rebuild the managed cache db
atomic_cas32(&g_force_rebuild, 0, 1);
atomic_cas32(&g_modified_cache, 0, 1);
} else {
atomic_inc32(&g_num_err_unfixed);
}
} else {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: %s has compressed checksum %s, "
"delete this file from cache directory!",
path.c_str(), hash.ToString().c_str());
atomic_inc32(&g_num_err_unfixed);
}
}
}
}
close(fd_src);
}
return NULL;
}
int main(int argc, char **argv) {
atomic_init32(&g_force_rebuild);
atomic_init32(&g_modified_cache);
g_current_dir = new string();
int c;
while ((c = getopt(argc, argv, "hvpfj:")) != -1) {
switch (c) {
case 'h':
Usage();
return kErrorOk;
case 'v':
g_verbose = true;
break;
case 'p':
g_fix_errors = true;
break;
case 'f':
atomic_cas32(&g_force_rebuild, 0, 1);
break;
case 'j':
g_num_threads = atoi(optarg);
if (g_num_threads < 1) {
LogCvmfs(kLogCvmfs, kLogStdout,
"There is at least one worker thread required");
return kErrorUsage;
}
break;
case '?':
default:
Usage();
return kErrorUsage;
}
}
// Switch to cache directory
if (optind >= argc) {
Usage();
return kErrorUsage;
}
g_cache_dir = new string(MakeCanonicalPath(argv[optind]));
if (chdir(g_cache_dir->c_str()) != 0) {
LogCvmfs(kLogCvmfs, kLogStderr, "Could not chdir to %s",
g_cache_dir->c_str());
return kErrorOperational;
}
// Check if txn directory is empty
DIR *dirp_txn;
if ((dirp_txn = opendir("txn")) == NULL) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Invalid cache directory, %s/txn does not exist",
g_cache_dir->c_str());
return kErrorOperational;
}
platform_dirent64 *d;
while ((d = platform_readdir(dirp_txn)) != NULL) {
const string name = d->d_name;
if ((name == ".") || (name == "..")) continue;
LogCvmfs(kLogCvmfs, kLogStdout,
"Warning: temporary directory %s/txn is not empty\n"
"If this repository is currently _not_ mounted, "
"you can remove its contents", g_cache_dir->c_str());
break;
}
closedir(dirp_txn);
// Run workers to recalculate checksums
atomic_init32(&g_num_files);
atomic_init32(&g_num_err_fixed);
atomic_init32(&g_num_err_unfixed);
atomic_init32(&g_num_err_operational);
atomic_init32(&g_num_tmp_catalog);
pthread_t *workers = reinterpret_cast<pthread_t *>(
smalloc(g_num_threads * sizeof(pthread_t)));
if (!g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "Verifying: ");
for (int i = 0; i < g_num_threads; ++i) {
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Starting worker %d", i+1);
if (pthread_create(&workers[i], NULL, MainCheck, NULL) != 0) {
LogCvmfs(kLogCvmfs, kLogStdout, "Fatal: could not create worker thread");
return kErrorOperational;
}
}
for (int i = g_num_threads-1; i >= 0; --i) {
pthread_join(workers[i], NULL);
if (g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "Stopping worker %d", i+1);
}
free(workers);
if (!g_verbose)
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "Verified %d files",
atomic_read32(&g_num_files));
if (atomic_read32(&g_num_tmp_catalog) > 0)
LogCvmfs(kLogCvmfs, kLogStdout, "Temporary file catalogs were found.");
if (atomic_read32(&g_force_rebuild)) {
if (unlink("cachedb") == 0) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Fix: managed cache db unlinked, will be rebuilt on next mount");
atomic_inc32(&g_num_err_fixed);
} else {
if (errno != ENOENT) {
LogCvmfs(kLogCvmfs, kLogStdout,
"Error: could not unlink managed cache database (%d)", errno);
atomic_inc32(&g_num_err_unfixed);
}
}
}
if (atomic_read32(&g_modified_cache)) {
LogCvmfs(kLogCvmfs, kLogStdout, "\n"
"WARNING: There might by corrupted files in the kernel buffers.\n"
"Remount CernVM-FS or run 'echo 3 > /proc/sys/vm/drop_caches'"
"\n\n");
}
int retval = 0;
if (atomic_read32(&g_num_err_fixed) > 0)
retval |= kErrorFixed;
if (atomic_read32(&g_num_err_unfixed) > 0)
retval |= kErrorUnfixed;
if (atomic_read32(&g_num_err_operational) > 0)
retval |= kErrorOperational;
return retval;
}
<|endoftext|>
|
<commit_before>/**
* @file cache.cpp
*
* @date Nov 21, 2012
* @author perämäki
*/
#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
cache::cache()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache"));
}
string cache::UniqueName(const shared_ptr<const himan::info> info)
{
string forecast_time = info->Time().OriginDateTime()->String("%Y-%m-%d_%H:%M:%S");
string valid_time = info->Time().ValidDateTime()->String("%Y-%m-%d_%H:%M:%S");
string param = info->Param().Name();
string level_value = boost::lexical_cast<string>(info->Level().Value());
string level = HPLevelTypeToString.at(info->Level().Type());
return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
string cache::UniqueNameFromOptions(const search_options& options)
{
string forecast_time = (options.time.OriginDateTime())->String("%Y-%m-%d_%H:%M:%S");
string valid_time = (options.time.ValidDateTime())->String("%Y-%m-%d_%H:%M:%S");
string param = (options.param).Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
void cache::Insert(shared_ptr<himan::info> anInfo, bool activeOnly)
{
if (activeOnly)
{
SplitToPool(anInfo);
}
else
{
for (anInfo->ResetTime(); anInfo->NextTime(); )
{
for (anInfo->ResetLevel(); anInfo->NextLevel(); )
{
for (anInfo->ResetParam(); anInfo->NextParam(); )
{
SplitToPool(anInfo);
}
}
}
}
}
void cache::SplitToPool(const shared_ptr<info> anInfo)
{
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
params.push_back(anInfo->Param());
levels.push_back(anInfo->Level());
times.push_back(anInfo->Time());
shared_ptr<grid> aGrid = anInfo->Grid();
shared_ptr<info> newInfo (new info(*anInfo));
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->Create();
newInfo->First();
newInfo->Grid(aGrid);
string uniqueName = UniqueName(newInfo);
if (!(cache_pool::Instance()->Find(uniqueName)))
{
cache_pool::Instance()->Insert(uniqueName, newInfo);
}
}
void cache::Insert(const vector<shared_ptr<himan::info>>& infos, bool activeOnly)
{
for (size_t i = 0; i < infos.size(); i++)
{
Insert(infos[i], activeOnly);
//Clean();
}
}
vector<shared_ptr<himan::info>> cache::GetInfo(const search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger->Trace( "Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean()
{
cache_pool::Instance()->Clean();
}
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
bool cache_pool::Find(const string& uniqueName)
{
for (map<string, shared_ptr<himan::info>>::iterator it = itsCache.begin(); it != itsCache.end(); ++it)
{
if (it->first == uniqueName)
{
return true;
}
}
return false;
}
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo)
{
Lock lock(itsInsertMutex);
itsCache.insert(pair<string, shared_ptr<himan::info>>(uniqueName, anInfo));
time_t timer;
time(&timer);
itsCacheItems.insert(pair<string, time_t>(uniqueName, timer));
itsLogger->Trace("Data added to cache. UniqueName: " + uniqueName);
}
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
for (map<string, time_t>::iterator it = itsCacheItems.begin(); it != itsCacheItems.end(); ++it)
{
time_t timer;
time(&timer);
if (timer - it->second > 10)
{
string name = it->first;
itsCache.erase(name);
itsCacheItems.erase(name);
itsLogger->Trace("Data cleared from cache: " + name);
}
}
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return itsCache[uniqueName];
}
<commit_msg>Change in info-class' Create() function<commit_after>/**
* @file cache.cpp
*
* @date Nov 21, 2012
* @author perämäki
*/
#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
cache::cache()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache"));
}
string cache::UniqueName(const shared_ptr<const himan::info> info)
{
string forecast_time = info->Time().OriginDateTime()->String("%Y-%m-%d_%H:%M:%S");
string valid_time = info->Time().ValidDateTime()->String("%Y-%m-%d_%H:%M:%S");
string param = info->Param().Name();
string level_value = boost::lexical_cast<string>(info->Level().Value());
string level = HPLevelTypeToString.at(info->Level().Type());
return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
string cache::UniqueNameFromOptions(const search_options& options)
{
string forecast_time = (options.time.OriginDateTime())->String("%Y-%m-%d_%H:%M:%S");
string valid_time = (options.time.ValidDateTime())->String("%Y-%m-%d_%H:%M:%S");
string param = (options.param).Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
return forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
void cache::Insert(shared_ptr<himan::info> anInfo, bool activeOnly)
{
if (activeOnly)
{
SplitToPool(anInfo);
}
else
{
for (anInfo->ResetTime(); anInfo->NextTime(); )
{
for (anInfo->ResetLevel(); anInfo->NextLevel(); )
{
for (anInfo->ResetParam(); anInfo->NextParam(); )
{
SplitToPool(anInfo);
}
}
}
}
}
void cache::SplitToPool(const shared_ptr<info> anInfo)
{
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
params.push_back(anInfo->Param());
levels.push_back(anInfo->Level());
times.push_back(anInfo->Time());
shared_ptr<grid> aGrid = anInfo->Grid();
auto newInfo = make_shared<info> (*anInfo);
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->Create(aGrid);
newInfo->First();
string uniqueName = UniqueName(newInfo);
if (!(cache_pool::Instance()->Find(uniqueName)))
{
cache_pool::Instance()->Insert(uniqueName, newInfo);
}
}
void cache::Insert(const vector<shared_ptr<himan::info>>& infos, bool activeOnly)
{
for (size_t i = 0; i < infos.size(); i++)
{
Insert(infos[i], activeOnly);
//Clean();
}
}
vector<shared_ptr<himan::info>> cache::GetInfo(const search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger->Trace( "Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean()
{
cache_pool::Instance()->Clean();
}
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool()
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
bool cache_pool::Find(const string& uniqueName)
{
for (map<string, shared_ptr<himan::info>>::iterator it = itsCache.begin(); it != itsCache.end(); ++it)
{
if (it->first == uniqueName)
{
return true;
}
}
return false;
}
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo)
{
Lock lock(itsInsertMutex);
itsCache.insert(pair<string, shared_ptr<himan::info>>(uniqueName, anInfo));
time_t timer;
time(&timer);
itsCacheItems.insert(pair<string, time_t>(uniqueName, timer));
itsLogger->Trace("Data added to cache. UniqueName: " + uniqueName);
}
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
for (map<string, time_t>::iterator it = itsCacheItems.begin(); it != itsCacheItems.end(); ++it)
{
time_t timer;
time(&timer);
if (timer - it->second > 10)
{
string name = it->first;
itsCache.erase(name);
itsCacheItems.erase(name);
itsLogger->Trace("Data cleared from cache: " + name);
}
}
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return itsCache[uniqueName];
}
<|endoftext|>
|
<commit_before>/*
* Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleAreaTriggerOpcode(WorldPacket & recv_data)
{
if(!_player->IsInWorld()) return;
CHECK_PACKET_SIZE(recv_data, 4);
uint32 id ;
recv_data >> id;
_HandleAreaTriggerOpcode(id);
}
enum AreaTriggerFailures
{
AREA_TRIGGER_FAILURE_OK = 0,
AREA_TRIGGER_FAILURE_UNAVAILABLE = 1,
AREA_TRIGGER_FAILURE_NO_BC = 2,
AREA_TRIGGER_FAILURE_NO_HEROIC = 3,
AREA_TRIGGER_FAILURE_NO_RAID = 4,
AREA_TRIGGER_FAILURE_NO_ATTUNE_Q = 5,
AREA_TRIGGER_FAILURE_NO_ATTUNE_I = 6,
AREA_TRIGGER_FAILURE_LEVEL = 7,
AREA_TRIGGER_FAILURE_NO_GROUP = 8,
AREA_TRIGGER_FAILURE_NO_KEY = 9,
AREA_TRIGGER_FAILURE_LEVEL_HEROIC = 9,
AREA_TRIGGER_FAILURE_NO_CHECK = 10,
};
const char * AreaTriggerFailureMessages[] = {
"-",
"This instance is unavailable",
"You must have The Burning Crusade Expansion to access this content.",
"Heroic mode unavailable for this instance.",
"You must be in a raid group to pass through here.",
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You must be at least level %u to pass through here.",
"You must be in a party to pass through here.",
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You must be level 70 to enter heroic mode.",
};
uint32 CheckTriggerPrerequsites(AreaTrigger * pAreaTrigger, WorldSession * pSession, Player * pPlayer, MapInfo * pMapInfo)
{
if(pAreaTrigger->required_level && pPlayer->getLevel() < pAreaTrigger->required_level)
return AREA_TRIGGER_FAILURE_LEVEL;
if(!pMapInfo || !pMapInfo->HasFlag(WMI_INSTANCE_ENABLED))
return AREA_TRIGGER_FAILURE_UNAVAILABLE;
if(!pSession->HasFlag(ACCOUNT_FLAG_XPACK_01) && pMapInfo->HasFlag(WMI_INSTANCE_XPACK_01))
return AREA_TRIGGER_FAILURE_NO_BC;
// These can be overridden by cheats/GM
if(pPlayer->triggerpass_cheat)
return AREA_TRIGGER_FAILURE_OK;
if(pPlayer->iInstanceType >= MODE_HEROIC && pMapInfo->type != INSTANCE_MULTIMODE && pMapInfo->type != INSTANCE_NULL)
return AREA_TRIGGER_FAILURE_NO_HEROIC;
if(pMapInfo->type == INSTANCE_RAID && (!pPlayer->GetGroup() || (pPlayer->GetGroup() && pPlayer->GetGroup()->GetGroupType() != GROUP_TYPE_RAID)))
return AREA_TRIGGER_FAILURE_NO_RAID;
if(pMapInfo->type == INSTANCE_MULTIMODE && !pPlayer->GetGroup())
return AREA_TRIGGER_FAILURE_NO_GROUP;
if(pMapInfo && pMapInfo->required_quest && !pPlayer->HasFinishedQuest(pMapInfo->required_quest))
return AREA_TRIGGER_FAILURE_NO_ATTUNE_Q;
if(pMapInfo && pMapInfo->required_item && !pPlayer->GetItemInterface()->GetItemCount(pMapInfo->required_item, true))
return AREA_TRIGGER_FAILURE_NO_ATTUNE_I;
if (pPlayer->iInstanceType >= MODE_HEROIC &&
pMapInfo->type == INSTANCE_MULTIMODE &&
!pPlayer->GetItemInterface()->GetItemCount(pMapInfo->heroic_key_1, false) &&
!pPlayer->GetItemInterface()->GetItemCount(pMapInfo->heroic_key_2, false))
return AREA_TRIGGER_FAILURE_NO_KEY;
if(pPlayer->getLevel()<70 && pPlayer->iInstanceType>=MODE_HEROIC && pMapInfo->type != INSTANCE_NULL)
return AREA_TRIGGER_FAILURE_LEVEL_HEROIC;
#ifdef ENABLE_CHECKPOINT_SYSTEM
if(pMapInfo->checkpoint_id)
{
MapCheckPoint * pcp = CheckpointStorage.LookupEntry(pMapInfo->checkpoint_id);
if(pcp && ((pPlayer->GetGuildId() && !CheckpointMgr::getSingleton().HasCompletedCheckpointAndPrequsites(pPlayer->GetGuildId(), pcp)) ||
!pPlayer->GetGuildId()))
{
return AREA_TRIGGER_FAILURE_NO_CHECK;
}
}
#endif
return AREA_TRIGGER_FAILURE_OK;
}
void WorldSession::_HandleAreaTriggerOpcode(uint32 id)
{
sLog.outDebug("AreaTrigger: %u", id);
AreaTrigger * pAreaTrigger = AreaTriggerStorage.LookupEntry(id);
// Are we REALLY here?
if(!pAreaTrigger || !_player->IsInWorld())
return;
// Search quest log, find any exploration quests
sQuestMgr.OnPlayerExploreArea(GetPlayer(),id);
// if in BG handle is triggers
if(_player->m_bg)
{
_player->m_bg->HookOnAreaTrigger(_player, id);
return;
}
switch(pAreaTrigger->Type)
{
case ATTYPE_INSTANCE:
{
if(GetPlayer()->GetPlayerStatus() != TRANSFER_PENDING) //only ports if player is out of pendings
{
uint32 reason = CheckTriggerPrerequsites(pAreaTrigger, this, _player, WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid));
if(reason != AREA_TRIGGER_FAILURE_OK)
{
const char * pReason = AreaTriggerFailureMessages[reason];
char msg[200];
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 50);
data << uint32(0);
switch (reason)
{
case AREA_TRIGGER_FAILURE_LEVEL:
snprintf(msg,200,pReason,pAreaTrigger->required_level);
data << msg;
break;
case AREA_TRIGGER_FAILURE_NO_ATTUNE_I:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
ItemPrototype * pItem = ItemPrototypeStorage.LookupEntry(pMi->required_item);
if(pItem)
snprintf(msg,200,"You must have the item, `%s` to pass through here.",pItem->Name1);
else
snprintf(msg,200,"You must have the item, UNKNOWN to pass through here.");
data << msg;
}break;
case AREA_TRIGGER_FAILURE_NO_ATTUNE_Q:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
Quest * pQuest = QuestStorage.LookupEntry(pMi->required_quest);
if(pQuest)
snprintf(msg,200,"You must have finished the quest, `%s` to pass through here.",pQuest->title);
else
snprintf(msg,200,"You must have finished the quest, UNKNOWN to pass through here.");
data << msg;
}break;
#ifdef ENABLE_CHECKPOINT_SYSTEM
case AREA_TRIGGER_FAILURE_NO_CHECK:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
MapCheckPoint * pCp = CheckpointStorage.LookupEntry(pMi->checkpoint_id);
if(pCp)
snprintf(msg,200,"You/your guild must have completed the checkpoint, `%s` to pass through here.",pCp->name);
else
snprintf(msg,200,"You/your guild must have completed the checkpoint, `%s` to pass through here.","UNKNOWN");
data << msg;
}break;
#endif
default:
data << pReason;
break;
}
data << uint8(0);
SendPacket(&data);
return;
}
GetPlayer()->SaveEntryPoint(pAreaTrigger->Mapid);
GetPlayer()->SafeTeleport(pAreaTrigger->Mapid, 0, LocationVector(pAreaTrigger->x, pAreaTrigger->y, pAreaTrigger->z, pAreaTrigger->o));
}
}break;
case ATTYPE_QUESTTRIGGER:
{
}break;
case ATTYPE_INN:
{
// Inn
if (!GetPlayer()->m_isResting) GetPlayer()->ApplyPlayerRestState(true);
}break;
case ATTYPE_TELEPORT:
{
if(GetPlayer()->GetPlayerStatus() != TRANSFER_PENDING) //only ports if player is out of pendings
{
GetPlayer()->SaveEntryPoint(pAreaTrigger->Mapid);
GetPlayer()->SafeTeleport(pAreaTrigger->Mapid, 0, LocationVector(pAreaTrigger->x, pAreaTrigger->y, pAreaTrigger->z, pAreaTrigger->o));
}
}break;
default:break;
}
}
<commit_msg>fixed explore area quests with missing triggers <commit_after>/*
* Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleAreaTriggerOpcode(WorldPacket & recv_data)
{
if(!_player->IsInWorld()) return;
CHECK_PACKET_SIZE(recv_data, 4);
uint32 id ;
recv_data >> id;
_HandleAreaTriggerOpcode(id);
}
enum AreaTriggerFailures
{
AREA_TRIGGER_FAILURE_OK = 0,
AREA_TRIGGER_FAILURE_UNAVAILABLE = 1,
AREA_TRIGGER_FAILURE_NO_BC = 2,
AREA_TRIGGER_FAILURE_NO_HEROIC = 3,
AREA_TRIGGER_FAILURE_NO_RAID = 4,
AREA_TRIGGER_FAILURE_NO_ATTUNE_Q = 5,
AREA_TRIGGER_FAILURE_NO_ATTUNE_I = 6,
AREA_TRIGGER_FAILURE_LEVEL = 7,
AREA_TRIGGER_FAILURE_NO_GROUP = 8,
AREA_TRIGGER_FAILURE_NO_KEY = 9,
AREA_TRIGGER_FAILURE_LEVEL_HEROIC = 9,
AREA_TRIGGER_FAILURE_NO_CHECK = 10,
};
const char * AreaTriggerFailureMessages[] = {
"-",
"This instance is unavailable",
"You must have The Burning Crusade Expansion to access this content.",
"Heroic mode unavailable for this instance.",
"You must be in a raid group to pass through here.",
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You must be at least level %u to pass through here.",
"You must be in a party to pass through here.",
"You do not have the required attunement to pass through here.", //TODO: Replace attunment with real itemname
"You must be level 70 to enter heroic mode.",
};
uint32 CheckTriggerPrerequsites(AreaTrigger * pAreaTrigger, WorldSession * pSession, Player * pPlayer, MapInfo * pMapInfo)
{
if(pAreaTrigger->required_level && pPlayer->getLevel() < pAreaTrigger->required_level)
return AREA_TRIGGER_FAILURE_LEVEL;
if(!pMapInfo || !pMapInfo->HasFlag(WMI_INSTANCE_ENABLED))
return AREA_TRIGGER_FAILURE_UNAVAILABLE;
if(!pSession->HasFlag(ACCOUNT_FLAG_XPACK_01) && pMapInfo->HasFlag(WMI_INSTANCE_XPACK_01))
return AREA_TRIGGER_FAILURE_NO_BC;
// These can be overridden by cheats/GM
if(pPlayer->triggerpass_cheat)
return AREA_TRIGGER_FAILURE_OK;
if(pPlayer->iInstanceType >= MODE_HEROIC && pMapInfo->type != INSTANCE_MULTIMODE && pMapInfo->type != INSTANCE_NULL)
return AREA_TRIGGER_FAILURE_NO_HEROIC;
if(pMapInfo->type == INSTANCE_RAID && (!pPlayer->GetGroup() || (pPlayer->GetGroup() && pPlayer->GetGroup()->GetGroupType() != GROUP_TYPE_RAID)))
return AREA_TRIGGER_FAILURE_NO_RAID;
if(pMapInfo->type == INSTANCE_MULTIMODE && !pPlayer->GetGroup())
return AREA_TRIGGER_FAILURE_NO_GROUP;
if(pMapInfo && pMapInfo->required_quest && !pPlayer->HasFinishedQuest(pMapInfo->required_quest))
return AREA_TRIGGER_FAILURE_NO_ATTUNE_Q;
if(pMapInfo && pMapInfo->required_item && !pPlayer->GetItemInterface()->GetItemCount(pMapInfo->required_item, true))
return AREA_TRIGGER_FAILURE_NO_ATTUNE_I;
if (pPlayer->iInstanceType >= MODE_HEROIC &&
pMapInfo->type == INSTANCE_MULTIMODE &&
!pPlayer->GetItemInterface()->GetItemCount(pMapInfo->heroic_key_1, false) &&
!pPlayer->GetItemInterface()->GetItemCount(pMapInfo->heroic_key_2, false))
return AREA_TRIGGER_FAILURE_NO_KEY;
if(pPlayer->getLevel()<70 && pPlayer->iInstanceType>=MODE_HEROIC && pMapInfo->type != INSTANCE_NULL)
return AREA_TRIGGER_FAILURE_LEVEL_HEROIC;
#ifdef ENABLE_CHECKPOINT_SYSTEM
if(pMapInfo->checkpoint_id)
{
MapCheckPoint * pcp = CheckpointStorage.LookupEntry(pMapInfo->checkpoint_id);
if(pcp && ((pPlayer->GetGuildId() && !CheckpointMgr::getSingleton().HasCompletedCheckpointAndPrequsites(pPlayer->GetGuildId(), pcp)) ||
!pPlayer->GetGuildId()))
{
return AREA_TRIGGER_FAILURE_NO_CHECK;
}
}
#endif
return AREA_TRIGGER_FAILURE_OK;
}
void WorldSession::_HandleAreaTriggerOpcode(uint32 id)
{
sLog.outDebug("AreaTrigger: %u", id);
// Are we REALLY here?
if( !_player->IsInWorld() )
return;
// Search quest log, find any exploration quests
sQuestMgr.OnPlayerExploreArea(GetPlayer(),id);
AreaTrigger* pAreaTrigger = AreaTriggerStorage.LookupEntry( id );
if( _player->pAreaTrigger == NULL )
{
sLog.outDebug("Missing AreaTrigger: %u", id);
return;
}
// if in BG handle is triggers
if(_player->m_bg)
{
_player->m_bg->HookOnAreaTrigger(_player, id);
return;
}
switch(pAreaTrigger->Type)
{
case ATTYPE_INSTANCE:
{
if(GetPlayer()->GetPlayerStatus() != TRANSFER_PENDING) //only ports if player is out of pendings
{
uint32 reason = CheckTriggerPrerequsites(pAreaTrigger, this, _player, WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid));
if(reason != AREA_TRIGGER_FAILURE_OK)
{
const char * pReason = AreaTriggerFailureMessages[reason];
char msg[200];
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 50);
data << uint32(0);
switch (reason)
{
case AREA_TRIGGER_FAILURE_LEVEL:
snprintf(msg,200,pReason,pAreaTrigger->required_level);
data << msg;
break;
case AREA_TRIGGER_FAILURE_NO_ATTUNE_I:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
ItemPrototype * pItem = ItemPrototypeStorage.LookupEntry(pMi->required_item);
if(pItem)
snprintf(msg,200,"You must have the item, `%s` to pass through here.",pItem->Name1);
else
snprintf(msg,200,"You must have the item, UNKNOWN to pass through here.");
data << msg;
}break;
case AREA_TRIGGER_FAILURE_NO_ATTUNE_Q:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
Quest * pQuest = QuestStorage.LookupEntry(pMi->required_quest);
if(pQuest)
snprintf(msg,200,"You must have finished the quest, `%s` to pass through here.",pQuest->title);
else
snprintf(msg,200,"You must have finished the quest, UNKNOWN to pass through here.");
data << msg;
}break;
#ifdef ENABLE_CHECKPOINT_SYSTEM
case AREA_TRIGGER_FAILURE_NO_CHECK:
{
MapInfo * pMi = WorldMapInfoStorage.LookupEntry(pAreaTrigger->Mapid);
MapCheckPoint * pCp = CheckpointStorage.LookupEntry(pMi->checkpoint_id);
if(pCp)
snprintf(msg,200,"You/your guild must have completed the checkpoint, `%s` to pass through here.",pCp->name);
else
snprintf(msg,200,"You/your guild must have completed the checkpoint, `%s` to pass through here.","UNKNOWN");
data << msg;
}break;
#endif
default:
data << pReason;
break;
}
data << uint8(0);
SendPacket(&data);
return;
}
GetPlayer()->SaveEntryPoint(pAreaTrigger->Mapid);
GetPlayer()->SafeTeleport(pAreaTrigger->Mapid, 0, LocationVector(pAreaTrigger->x, pAreaTrigger->y, pAreaTrigger->z, pAreaTrigger->o));
}
}break;
case ATTYPE_QUESTTRIGGER:
{
}break;
case ATTYPE_INN:
{
// Inn
if (!GetPlayer()->m_isResting) GetPlayer()->ApplyPlayerRestState(true);
}break;
case ATTYPE_TELEPORT:
{
if(GetPlayer()->GetPlayerStatus() != TRANSFER_PENDING) //only ports if player is out of pendings
{
GetPlayer()->SaveEntryPoint(pAreaTrigger->Mapid);
GetPlayer()->SafeTeleport(pAreaTrigger->Mapid, 0, LocationVector(pAreaTrigger->x, pAreaTrigger->y, pAreaTrigger->z, pAreaTrigger->o));
}
}break;
default:break;
}
}
<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "geos/geom/CoordinateFilter.h"
#include "geos/geom/PrecisionModel.h"
#ifdef Q_OS_WIN
#include "geos/geom/PrecisionModel.inl"
#endif
#include "geos/geom/GeometryFactory.h"
#include "geos/io/ParseException.h"
#include "geometryhelper.h"
#include "csytransform.h"
using namespace Ilwis;
FeatureCoverage::FeatureCoverage() : _featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::FeatureCoverage(const Resource& resource) : Coverage(resource),_featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel( geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::~FeatureCoverage() {
}
bool FeatureCoverage::prepare( ) {
bool ok = Coverage::prepare();
if ( ok && !attributeTable().isValid()){
if ( isAnonymous())
ok = attributeTable().prepare();
else
ok = attributeTable().prepare(name());
}
return ok;
}
Indices FeatureCoverage::select(const QString &spatialQuery) const
{
ExecutionContext ctx;
QString expr = QString("script %1=indexes from \"%2\" where %3").arg(Identity::newAnonymousName()).arg(source().url().toString()).arg(spatialQuery);
Ilwis::SymbolTable tbl;
if ( Ilwis::commandhandler()->execute(expr, &ctx, tbl) ){
if ( ctx._results.size() == 1)
return tbl.getValue<Indices>(ctx._results[0]);
}
return Indices();
}
IlwisTypes FeatureCoverage::featureTypes() const
{
return _featureTypes;
}
void FeatureCoverage::featureTypes(IlwisTypes types)
{
_featureTypes = types;
}
UPFeatureI& FeatureCoverage::newFeature(const QString& wkt, const ICoordinateSystem& foreigncsy, bool load){
geos::geom::Geometry *geom = GeometryHelper::fromWKT(wkt, foreigncsy.isValid() ? foreigncsy : coordinateSystem());
if ( !geom)
throw FeatureCreationError(TR("failed to create feature, is the wkt valid?"));
return newFeature(geom,load);
}
UPFeatureI &FeatureCoverage::newFeature(geos::geom::Geometry *geom, bool load) {
if ( load) {
Locker<std::mutex> lock(_loadmutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
}
Locker<> lock(_mutex);
IlwisTypes tp = geometryType(geom);
UPFeatureI& newfeature = createNewFeature(tp);
if (newfeature ){
if ( geom) {
CoordinateSystem *csy = GeometryHelper::getCoordinateSystem(geom);
if ( csy && !csy->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csy, coordinateSystem());
geom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(geom, coordinateSystem().ptr());
newfeature->add(geom);
}
}
return newfeature;
}
UPFeatureI &FeatureCoverage::newFeatureFrom(const UPFeatureI& existingFeature, const ICoordinateSystem& csySource) {
Locker<> lock(_mutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
UPFeatureI& newfeature = createNewFeature(existingFeature->geometryType());
if (newfeature == nullptr)
return newfeature;
for(int i=0; i < existingFeature->trackSize(); ++i){
UPGeometry& geom = existingFeature->geometry(i);
geos::geom::Geometry *newgeom = geom->clone();
if ( csySource.isValid() && !csySource->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csySource, coordinateSystem());
newgeom->apply_rw(&trans);
newgeom->geometryChangedAction();
}
GeometryHelper::setCoordinateSystem(newgeom, coordinateSystem().ptr());
newfeature->add(newgeom, existingFeature->trackIndexValue(i));
//setFeatureCount(newfeature->geometryType(),i, newgeom->getNumGeometries() );
}
return newfeature;
}
Ilwis::UPFeatureI &FeatureCoverage::createNewFeature(IlwisTypes tp) {
if ( !coordinateSystem().isValid())
throw FeatureCreationError(TR("No coordinate system set"));
if ( isReadOnly()){
throw FeatureCreationError(TR("Readonly feature coverage, no creation allowed"));
}
changed(true);
_featureTypes |= tp;
if ( _featureFactory == 0) {
_featureFactory = kernel()->factory<FeatureFactory>("FeatureFactory","ilwis");
}
//_record.reset(new AttributeRecord(attributeTable(),FEATUREIDCOLUMN ));
CreateFeature create = _featureFactory->getCreator("feature");
FeatureInterface *newFeature = create(this);
_features.resize(_features.size() + 1);
_features.back().reset(newFeature);
return _features.back();
}
void FeatureCoverage::adaptFeatureCounts(int tp, quint32 geomCnt, quint32 subGeomCnt, int index) {
auto adapt = [&] () {
quint32 current =_featureInfo[tp]._perIndex[index];
qint32 delta = geomCnt - _featureInfo[tp]._geomCnt;
_featureInfo[tp]._perIndex[index] = current + delta;
};
if ( index < _featureInfo[tp]._perIndex.size()){
adapt();
} else {
if ( index >= _featureInfo[tp]._perIndex.size() ) {
_featureInfo[tp]._perIndex.resize(index + 1,0);
_maxIndex = index + 1;
}
adapt();
}
_featureInfo[tp]._geomCnt += geomCnt;
if ( geomCnt != 0)
_featureInfo[tp]._subGeomCnt += geomCnt > 0 ? subGeomCnt : -subGeomCnt;
else {
_featureInfo[tp]._subGeomCnt = 0;
_featureInfo[tp]._geomCnt = 0;
}
}
void FeatureCoverage::setFeatureCount(IlwisTypes types, quint32 geomCnt, quint32 subGeomCnt, int index)
{
Locker<std::mutex> lock(_mutex2);
if (geomCnt > 0)
_featureTypes |= types;
else
_featureTypes &= !types;
switch(types){
case itPOINT:
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);break;
case itLINE:
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);break;
case itPOLYGON:
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);break;
case itFEATURE:
//usually only used for resetting the count to 0
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);
break;
}
}
quint32 FeatureCoverage::maxIndex() const
{
return _maxIndex;
}
void FeatureCoverage::attributeTable(const ITable &tbl, AttributeType attType)
{
if ( featureCount() != tbl->recordCount() && attType == Coverage::atCOVERAGE){
ERROR2(ERR_NOT_COMPATIBLE2,TR("feature count"), TR("record count in attribute table"));
return;
}
Coverage::attributeTable(tbl,attType);
}
AttributeTable FeatureCoverage::attributeTable(AttributeType attType) const
{
return Coverage::attributeTable(attType);
}
IlwisTypes FeatureCoverage::ilwisType() const
{
return itFEATURE;
}
FeatureCoverage *FeatureCoverage::clone()
{
FeatureCoverage *fcov = new FeatureCoverage();
copyTo(fcov);
return fcov;
}
void FeatureCoverage::copyTo(IlwisObject *obj)
{
Coverage::copyTo(obj);
FeatureCoverage *fcov = static_cast<FeatureCoverage *>(obj);
fcov->_featureTypes = _featureTypes;
fcov->_featureInfo = _featureInfo;
fcov->_features.resize(_features.size());
for(int i=0; i < _features.size(); ++i){
if ( _features[i])
fcov->_features[i].reset(_features[i]->clone());
}
}
quint32 FeatureCoverage::featureCount(IlwisTypes types, bool subAsDistinct, int index) const
{
auto countFeatures = [&] (int tp){
if ( index == iUNDEF){
if (subAsDistinct)
return _featureInfo[tp]._subGeomCnt;
return _featureInfo[tp]._geomCnt;
}
else
return _featureInfo[tp]._perIndex.size() < index ? _featureInfo[tp]._perIndex[index] : 0;
};
quint32 count=0;
if ( hasType(types, itPOINT))
count += countFeatures(0);
if ( hasType(types, itLINE))
count += countFeatures(1);
if ( hasType(types, itPOLYGON))
count += countFeatures(2);
return count;
}
IlwisTypes FeatureCoverage::geometryType(const geos::geom::Geometry *geom){
return GeometryHelper::geometryType(geom);
}
const UPGeomFactory& FeatureCoverage::geomfactory() const{
return _geomfactory;
}
<commit_msg>added exception for adding attribute tbales to featurecoverage; with count == 0 it is allowed as this can happen during loading process of the coverage<commit_after>#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "geos/geom/CoordinateFilter.h"
#include "geos/geom/PrecisionModel.h"
#ifdef Q_OS_WIN
#include "geos/geom/PrecisionModel.inl"
#endif
#include "geos/geom/GeometryFactory.h"
#include "geos/io/ParseException.h"
#include "geometryhelper.h"
#include "csytransform.h"
using namespace Ilwis;
FeatureCoverage::FeatureCoverage() : _featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::FeatureCoverage(const Resource& resource) : Coverage(resource),_featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel( geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::~FeatureCoverage() {
}
bool FeatureCoverage::prepare( ) {
bool ok = Coverage::prepare();
if ( ok && !attributeTable().isValid()){
if ( isAnonymous())
ok = attributeTable().prepare();
else
ok = attributeTable().prepare(name());
}
return ok;
}
Indices FeatureCoverage::select(const QString &spatialQuery) const
{
ExecutionContext ctx;
QString expr = QString("script %1=indexes from \"%2\" where %3").arg(Identity::newAnonymousName()).arg(source().url().toString()).arg(spatialQuery);
Ilwis::SymbolTable tbl;
if ( Ilwis::commandhandler()->execute(expr, &ctx, tbl) ){
if ( ctx._results.size() == 1)
return tbl.getValue<Indices>(ctx._results[0]);
}
return Indices();
}
IlwisTypes FeatureCoverage::featureTypes() const
{
return _featureTypes;
}
void FeatureCoverage::featureTypes(IlwisTypes types)
{
_featureTypes = types;
}
UPFeatureI& FeatureCoverage::newFeature(const QString& wkt, const ICoordinateSystem& foreigncsy, bool load){
geos::geom::Geometry *geom = GeometryHelper::fromWKT(wkt, foreigncsy.isValid() ? foreigncsy : coordinateSystem());
if ( !geom)
throw FeatureCreationError(TR("failed to create feature, is the wkt valid?"));
return newFeature(geom,load);
}
UPFeatureI &FeatureCoverage::newFeature(geos::geom::Geometry *geom, bool load) {
if ( load) {
Locker<std::mutex> lock(_loadmutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
}
Locker<> lock(_mutex);
IlwisTypes tp = geometryType(geom);
UPFeatureI& newfeature = createNewFeature(tp);
if (newfeature ){
if ( geom) {
CoordinateSystem *csy = GeometryHelper::getCoordinateSystem(geom);
if ( csy && !csy->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csy, coordinateSystem());
geom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(geom, coordinateSystem().ptr());
newfeature->add(geom);
}
}
return newfeature;
}
UPFeatureI &FeatureCoverage::newFeatureFrom(const UPFeatureI& existingFeature, const ICoordinateSystem& csySource) {
Locker<> lock(_mutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
UPFeatureI& newfeature = createNewFeature(existingFeature->geometryType());
if (newfeature == nullptr)
return newfeature;
for(int i=0; i < existingFeature->trackSize(); ++i){
UPGeometry& geom = existingFeature->geometry(i);
geos::geom::Geometry *newgeom = geom->clone();
if ( csySource.isValid() && !csySource->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csySource, coordinateSystem());
newgeom->apply_rw(&trans);
newgeom->geometryChangedAction();
}
GeometryHelper::setCoordinateSystem(newgeom, coordinateSystem().ptr());
newfeature->add(newgeom, existingFeature->trackIndexValue(i));
//setFeatureCount(newfeature->geometryType(),i, newgeom->getNumGeometries() );
}
return newfeature;
}
Ilwis::UPFeatureI &FeatureCoverage::createNewFeature(IlwisTypes tp) {
if ( !coordinateSystem().isValid())
throw FeatureCreationError(TR("No coordinate system set"));
if ( isReadOnly()){
throw FeatureCreationError(TR("Readonly feature coverage, no creation allowed"));
}
changed(true);
_featureTypes |= tp;
if ( _featureFactory == 0) {
_featureFactory = kernel()->factory<FeatureFactory>("FeatureFactory","ilwis");
}
//_record.reset(new AttributeRecord(attributeTable(),FEATUREIDCOLUMN ));
CreateFeature create = _featureFactory->getCreator("feature");
FeatureInterface *newFeature = create(this);
_features.resize(_features.size() + 1);
_features.back().reset(newFeature);
return _features.back();
}
void FeatureCoverage::adaptFeatureCounts(int tp, quint32 geomCnt, quint32 subGeomCnt, int index) {
auto adapt = [&] () {
quint32 current =_featureInfo[tp]._perIndex[index];
qint32 delta = geomCnt - _featureInfo[tp]._geomCnt;
_featureInfo[tp]._perIndex[index] = current + delta;
};
if ( index < _featureInfo[tp]._perIndex.size()){
adapt();
} else {
if ( index >= _featureInfo[tp]._perIndex.size() ) {
_featureInfo[tp]._perIndex.resize(index + 1,0);
_maxIndex = index + 1;
}
adapt();
}
_featureInfo[tp]._geomCnt += geomCnt;
if ( geomCnt != 0)
_featureInfo[tp]._subGeomCnt += geomCnt > 0 ? subGeomCnt : -subGeomCnt;
else {
_featureInfo[tp]._subGeomCnt = 0;
_featureInfo[tp]._geomCnt = 0;
}
}
void FeatureCoverage::setFeatureCount(IlwisTypes types, quint32 geomCnt, quint32 subGeomCnt, int index)
{
Locker<std::mutex> lock(_mutex2);
if (geomCnt > 0)
_featureTypes |= types;
else
_featureTypes &= !types;
switch(types){
case itPOINT:
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);break;
case itLINE:
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);break;
case itPOLYGON:
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);break;
case itFEATURE:
//usually only used for resetting the count to 0
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);
break;
}
}
quint32 FeatureCoverage::maxIndex() const
{
return _maxIndex;
}
void FeatureCoverage::attributeTable(const ITable &tbl, AttributeType attType)
{
if ( featureCount() != 0){ // we make an exception for count == 0 as this happens during loading process before features are there
if ( featureCount() != tbl->recordCount() && attType == Coverage::atCOVERAGE){
ERROR2(ERR_NOT_COMPATIBLE2,TR("feature count"), TR("record count in attribute table"));
return;
}
}
Coverage::attributeTable(tbl,attType);
}
AttributeTable FeatureCoverage::attributeTable(AttributeType attType) const
{
return Coverage::attributeTable(attType);
}
IlwisTypes FeatureCoverage::ilwisType() const
{
return itFEATURE;
}
FeatureCoverage *FeatureCoverage::clone()
{
FeatureCoverage *fcov = new FeatureCoverage();
copyTo(fcov);
return fcov;
}
void FeatureCoverage::copyTo(IlwisObject *obj)
{
Coverage::copyTo(obj);
FeatureCoverage *fcov = static_cast<FeatureCoverage *>(obj);
fcov->_featureTypes = _featureTypes;
fcov->_featureInfo = _featureInfo;
fcov->_features.resize(_features.size());
for(int i=0; i < _features.size(); ++i){
if ( _features[i])
fcov->_features[i].reset(_features[i]->clone());
}
}
quint32 FeatureCoverage::featureCount(IlwisTypes types, bool subAsDistinct, int index) const
{
auto countFeatures = [&] (int tp){
if ( index == iUNDEF){
if (subAsDistinct)
return _featureInfo[tp]._subGeomCnt;
return _featureInfo[tp]._geomCnt;
}
else
return _featureInfo[tp]._perIndex.size() < index ? _featureInfo[tp]._perIndex[index] : 0;
};
quint32 count=0;
if ( hasType(types, itPOINT))
count += countFeatures(0);
if ( hasType(types, itLINE))
count += countFeatures(1);
if ( hasType(types, itPOLYGON))
count += countFeatures(2);
return count;
}
IlwisTypes FeatureCoverage::geometryType(const geos::geom::Geometry *geom){
return GeometryHelper::geometryType(geom);
}
const UPGeomFactory& FeatureCoverage::geomfactory() const{
return _geomfactory;
}
<|endoftext|>
|
<commit_before>#include <agency/execution_policy.hpp>
#include <vector>
int sum(const std::vector<int>& data)
{
using namespace agency;
int result = 0;
bulk_invoke(con(data.size() / 2), [&](concurrent_agent& self, std::vector<int>& scratch)
{
auto i = self.index();
auto n = scratch.size();
while(n > 1)
{
if(i < n/2)
{
scratch[i] += scratch[n - i - 1];
}
// wait for every agent in the group to reach this point
self.wait();
// cut the number of active agents in half
n -= n/2;
// the first agent stores the result
if(i == 0)
{
result = scratch[0];
}
}
},
share<0>(data));
return result;
}
int main()
{
size_t n = 10;
std::vector<int> data(n, 1);
auto result = sum(data);
std::cout << "sum is " << result << std::endl;
assert(result == n);
std::cout << "OK" << std::endl;
return 0;
}
<commit_msg>Tweak to concurrent_sum code<commit_after>#include <agency/execution_policy.hpp>
#include <vector>
int sum(const std::vector<int>& data)
{
using namespace agency;
int result = 0;
bulk_invoke(con(data.size()), [&](concurrent_agent& self, std::vector<int>& scratch)
{
auto i = self.index();
auto n = scratch.size();
while(n > 1)
{
if(i < n/2)
{
scratch[i] += scratch[n - i - 1];
}
// wait for every agent in the group to reach this point
self.wait();
// cut the number of active agents in half
n -= n/2;
// the first agent stores the result
if(i == 0)
{
result = scratch[0];
}
}
},
share<0>(data));
return result;
}
int main()
{
size_t n = 10;
std::vector<int> data(n, 1);
auto result = sum(data);
std::cout << "sum is " << result << std::endl;
assert(result == n);
std::cout << "OK" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "geos/geom/CoordinateFilter.h"
#include "geos/geom/PrecisionModel.h"
#ifdef Q_OS_WIN
#include "geos/geom/PrecisionModel.inl"
#endif
#include "geos/geom/GeometryFactory.h"
#include "geos/io/ParseException.h"
#include "geometryhelper.h"
#include "csytransform.h"
using namespace Ilwis;
FeatureCoverage::FeatureCoverage() : _featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::FeatureCoverage(const Resource& resource) : Coverage(resource),_featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel( geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::~FeatureCoverage() {
}
bool FeatureCoverage::prepare( ) {
bool ok = Coverage::prepare();
if ( ok && !attributeTable().isValid()){
if ( isAnonymous())
ok = attributeTable().prepare();
else
ok = attributeTable().prepare(name());
}
if ( ok && attributeTable()->columnIndex(FEATUREIDCOLUMN) == iUNDEF)
attributeTable()->addColumn(FEATUREIDCOLUMN,"count");
return ok;
}
Indices FeatureCoverage::select(const QString &spatialQuery) const
{
ExecutionContext ctx;
QString expr = QString("script %1=indexes from \"%2\" where %3").arg(Identity::newAnonymousName()).arg(source().url().toString()).arg(spatialQuery);
Ilwis::SymbolTable tbl;
if ( Ilwis::commandhandler()->execute(expr, &ctx, tbl) ){
if ( ctx._results.size() == 1)
return tbl.getValue<Indices>(ctx._results[0]);
}
return Indices();
}
IlwisTypes FeatureCoverage::featureTypes() const
{
return _featureTypes;
}
void FeatureCoverage::featureTypes(IlwisTypes types)
{
_featureTypes = types;
}
UPFeatureI& FeatureCoverage::newFeature(const QString& wkt, const ICoordinateSystem& foreigncsy, bool load){
geos::geom::Geometry *geom = GeometryHelper::fromWKT(wkt, foreigncsy.isValid() ? foreigncsy : coordinateSystem());
if ( !geom)
throw FeatureCreationError(TR("failed to create feature, is the wkt valid?"));
return newFeature(geom,load);
}
UPFeatureI &FeatureCoverage::newFeature(geos::geom::Geometry *geom, bool load) {
if ( load) {
Locker lock(_loadmutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
}
Locker lock(_mutex);
IlwisTypes tp = geometryType(geom);
UPFeatureI& newfeature = createNewFeature(tp);
if (newfeature ){
CoordinateSystem *csy = GeometryHelper::getCoordinateSystem(geom);
if ( csy && !csy->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csy, coordinateSystem());
geom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(geom, coordinateSystem().ptr());
newfeature->set(geom);
quint32 cnt = featureCount(tp);
setFeatureCount(tp,++cnt, geom->getNumGeometries() );
}
return newfeature;
}
UPFeatureI &FeatureCoverage::newFeatureFrom(const UPFeatureI& existingFeature, const ICoordinateSystem& csySource) {
Locker lock(_mutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
UPFeatureI& newfeature = createNewFeature(existingFeature->geometryType());
if (newfeature == nullptr)
return newfeature;
for(int i=0; i < existingFeature->trackSize(); ++i){
UPGeometry& geom = existingFeature->geometry(i);
geos::geom::Geometry *newgeom = geom->clone();
if ( csySource.isValid() && csySource->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csySource, coordinateSystem());
newgeom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(newgeom, coordinateSystem().ptr());
newfeature->set(newgeom, i);
setFeatureCount(newfeature->geometryType(),i, newgeom->getNumGeometries() );
}
return newfeature;
}
Ilwis::UPFeatureI &FeatureCoverage::createNewFeature(IlwisTypes tp) {
if ( !coordinateSystem().isValid())
throw FeatureCreationError(TR("No coordinate system set"));
if ( isReadOnly()){
throw FeatureCreationError(TR("Readonly feature coverage, no creation allowed"));
}
changed(true);
_featureTypes |= tp;
if ( _featureFactory == 0) {
_featureFactory = kernel()->factory<FeatureFactory>("FeatureFactory","ilwis");
}
//_record.reset(new AttributeRecord(attributeTable(),FEATUREIDCOLUMN ));
CreateFeature create = _featureFactory->getCreator("feature");
FeatureInterface *newFeature = create(this);
qint32 colIndex = this->attributeTable()->columnIndex(FEATUREIDCOLUMN);
if ( colIndex == iUNDEF) {
ERROR1(ERR_NO_INITIALIZED_1, TR("attribute table"));
throw FeatureCreationError(TR("failed to create feature"));
}
newFeature->setCell(colIndex, QVariant(newFeature->featureid()));
_features.resize(_features.size() + 1);
_features.back().reset(newFeature);
return _features.back();
}
void FeatureCoverage::adaptFeatureCounts(int tp, quint32 geomCnt, quint32 subGeomCnt, int index) {
auto adapt = [&] () {
quint32 current =_featureInfo[tp]._perIndex[index];
qint32 delta = geomCnt - _featureInfo[tp]._geomCnt;
_featureInfo[tp]._perIndex[index] = current + delta;
};
if ( index < _featureInfo[tp]._perIndex.size()){
adapt();
} else {
if ( index >= _featureInfo[tp]._perIndex.size() ) {
_featureInfo[tp]._perIndex.resize(index + 1,0);
_maxIndex = index + 1;
}
adapt();
}
_featureInfo[tp]._geomCnt = geomCnt;
if ( geomCnt != 0)
_featureInfo[tp]._subGeomCnt += geomCnt > 0 ? subGeomCnt : -subGeomCnt;
else
_featureInfo[tp]._subGeomCnt = 0;
}
void FeatureCoverage::setFeatureCount(IlwisTypes types, quint32 geomCnt, quint32 subGeomCnt, int index)
{
Locker lock(_mutex2);
if (geomCnt > 0)
_featureTypes |= types;
else
_featureTypes &= !types;
switch(types){
case itPOINT:
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);break;
case itLINE:
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);break;
case itPOLYGON:
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);break;
}
}
quint32 FeatureCoverage::maxIndex() const
{
return _maxIndex;
}
IlwisTypes FeatureCoverage::ilwisType() const
{
return itFEATURE;
}
FeatureCoverage *FeatureCoverage::clone()
{
FeatureCoverage *fcov = new FeatureCoverage();
copyTo(fcov);
return fcov;
}
void FeatureCoverage::copyTo(IlwisObject *obj)
{
Coverage::copyTo(obj);
FeatureCoverage *fcov = static_cast<FeatureCoverage *>(obj);
fcov->_featureTypes = _featureTypes;
fcov->_featureInfo = _featureInfo;
fcov->_features.resize(_features.size());
for(int i=0; i < _features.size(); ++i){
if ( _features[i])
fcov->_features[i].reset(_features[i]->clone());
}
}
quint32 FeatureCoverage::featureCount(IlwisTypes types, bool subAsDistinct, int index) const
{
auto countFeatures = [&] (int tp){
if ( index == iUNDEF){
if (subAsDistinct)
return _featureInfo[tp]._subGeomCnt;
return _featureInfo[tp]._geomCnt;
}
else
return _featureInfo[tp]._perIndex.size() < index ? _featureInfo[tp]._perIndex[index] : 0;
};
quint32 count=0;
if ( hasType(types, itPOINT))
count += countFeatures(0);
if ( hasType(types, itLINE))
count += countFeatures(1);
if ( hasType(types, itPOLYGON))
count += countFeatures(2);
return count;
}
IlwisTypes FeatureCoverage::geometryType(const geos::geom::Geometry *geom){
return GeometryHelper::geometryType(geom);
}
const UPGeomFactory& FeatureCoverage::geomfactory() const{
return _geomfactory;
}
<commit_msg>added the ability to reset the featurecount of a coverage<commit_after>#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "geos/geom/CoordinateFilter.h"
#include "geos/geom/PrecisionModel.h"
#ifdef Q_OS_WIN
#include "geos/geom/PrecisionModel.inl"
#endif
#include "geos/geom/GeometryFactory.h"
#include "geos/io/ParseException.h"
#include "geometryhelper.h"
#include "csytransform.h"
using namespace Ilwis;
FeatureCoverage::FeatureCoverage() : _featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::FeatureCoverage(const Resource& resource) : Coverage(resource),_featureTypes(itUNKNOWN),_featureFactory(0), _maxIndex(0)
{
_featureInfo.resize(3);
geos::geom::PrecisionModel *pm = new geos::geom::PrecisionModel( geos::geom::PrecisionModel::FLOATING);
_geomfactory.reset(new geos::geom::GeometryFactory(pm,-1));
delete pm;
}
FeatureCoverage::~FeatureCoverage() {
}
bool FeatureCoverage::prepare( ) {
bool ok = Coverage::prepare();
if ( ok && !attributeTable().isValid()){
if ( isAnonymous())
ok = attributeTable().prepare();
else
ok = attributeTable().prepare(name());
}
if ( ok && attributeTable()->columnIndex(FEATUREIDCOLUMN) == iUNDEF)
attributeTable()->addColumn(FEATUREIDCOLUMN,"count");
return ok;
}
Indices FeatureCoverage::select(const QString &spatialQuery) const
{
ExecutionContext ctx;
QString expr = QString("script %1=indexes from \"%2\" where %3").arg(Identity::newAnonymousName()).arg(source().url().toString()).arg(spatialQuery);
Ilwis::SymbolTable tbl;
if ( Ilwis::commandhandler()->execute(expr, &ctx, tbl) ){
if ( ctx._results.size() == 1)
return tbl.getValue<Indices>(ctx._results[0]);
}
return Indices();
}
IlwisTypes FeatureCoverage::featureTypes() const
{
return _featureTypes;
}
void FeatureCoverage::featureTypes(IlwisTypes types)
{
_featureTypes = types;
}
UPFeatureI& FeatureCoverage::newFeature(const QString& wkt, const ICoordinateSystem& foreigncsy, bool load){
geos::geom::Geometry *geom = GeometryHelper::fromWKT(wkt, foreigncsy.isValid() ? foreigncsy : coordinateSystem());
if ( !geom)
throw FeatureCreationError(TR("failed to create feature, is the wkt valid?"));
return newFeature(geom,load);
}
UPFeatureI &FeatureCoverage::newFeature(geos::geom::Geometry *geom, bool load) {
if ( load) {
Locker lock(_loadmutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
}
Locker lock(_mutex);
IlwisTypes tp = geometryType(geom);
UPFeatureI& newfeature = createNewFeature(tp);
if (newfeature ){
CoordinateSystem *csy = GeometryHelper::getCoordinateSystem(geom);
if ( csy && !csy->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csy, coordinateSystem());
geom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(geom, coordinateSystem().ptr());
newfeature->set(geom);
quint32 cnt = featureCount(tp);
setFeatureCount(tp,++cnt, geom->getNumGeometries() );
}
return newfeature;
}
UPFeatureI &FeatureCoverage::newFeatureFrom(const UPFeatureI& existingFeature, const ICoordinateSystem& csySource) {
Locker lock(_mutex);
if (!connector()->dataIsLoaded()) {
connector()->loadData(this);
}
UPFeatureI& newfeature = createNewFeature(existingFeature->geometryType());
if (newfeature == nullptr)
return newfeature;
for(int i=0; i < existingFeature->trackSize(); ++i){
UPGeometry& geom = existingFeature->geometry(i);
geos::geom::Geometry *newgeom = geom->clone();
if ( csySource.isValid() && csySource->isEqual(coordinateSystem().ptr())){
CsyTransform trans(csySource, coordinateSystem());
newgeom->apply_rw(&trans);
}
GeometryHelper::setCoordinateSystem(newgeom, coordinateSystem().ptr());
newfeature->set(newgeom, i);
setFeatureCount(newfeature->geometryType(),i, newgeom->getNumGeometries() );
}
return newfeature;
}
Ilwis::UPFeatureI &FeatureCoverage::createNewFeature(IlwisTypes tp) {
if ( !coordinateSystem().isValid())
throw FeatureCreationError(TR("No coordinate system set"));
if ( isReadOnly()){
throw FeatureCreationError(TR("Readonly feature coverage, no creation allowed"));
}
changed(true);
_featureTypes |= tp;
if ( _featureFactory == 0) {
_featureFactory = kernel()->factory<FeatureFactory>("FeatureFactory","ilwis");
}
//_record.reset(new AttributeRecord(attributeTable(),FEATUREIDCOLUMN ));
CreateFeature create = _featureFactory->getCreator("feature");
FeatureInterface *newFeature = create(this);
qint32 colIndex = this->attributeTable()->columnIndex(FEATUREIDCOLUMN);
if ( colIndex == iUNDEF) {
ERROR1(ERR_NO_INITIALIZED_1, TR("attribute table"));
throw FeatureCreationError(TR("failed to create feature"));
}
newFeature->setCell(colIndex, QVariant(newFeature->featureid()));
_features.resize(_features.size() + 1);
_features.back().reset(newFeature);
return _features.back();
}
void FeatureCoverage::adaptFeatureCounts(int tp, quint32 geomCnt, quint32 subGeomCnt, int index) {
auto adapt = [&] () {
quint32 current =_featureInfo[tp]._perIndex[index];
qint32 delta = geomCnt - _featureInfo[tp]._geomCnt;
_featureInfo[tp]._perIndex[index] = current + delta;
};
if ( index < _featureInfo[tp]._perIndex.size()){
adapt();
} else {
if ( index >= _featureInfo[tp]._perIndex.size() ) {
_featureInfo[tp]._perIndex.resize(index + 1,0);
_maxIndex = index + 1;
}
adapt();
}
_featureInfo[tp]._geomCnt = geomCnt;
if ( geomCnt != 0)
_featureInfo[tp]._subGeomCnt += geomCnt > 0 ? subGeomCnt : -subGeomCnt;
else
_featureInfo[tp]._subGeomCnt = 0;
}
void FeatureCoverage::setFeatureCount(IlwisTypes types, quint32 geomCnt, quint32 subGeomCnt, int index)
{
Locker lock(_mutex2);
if (geomCnt > 0)
_featureTypes |= types;
else
_featureTypes &= !types;
switch(types){
case itPOINT:
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);break;
case itLINE:
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);break;
case itPOLYGON:
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);break;
case itFEATURE:
//usually only used for resetting the count to 0
adaptFeatureCounts(0, geomCnt, subGeomCnt, index);
adaptFeatureCounts(1, geomCnt, subGeomCnt, index);
adaptFeatureCounts(2, geomCnt, subGeomCnt, index);
break;
}
}
quint32 FeatureCoverage::maxIndex() const
{
return _maxIndex;
}
IlwisTypes FeatureCoverage::ilwisType() const
{
return itFEATURE;
}
FeatureCoverage *FeatureCoverage::clone()
{
FeatureCoverage *fcov = new FeatureCoverage();
copyTo(fcov);
return fcov;
}
void FeatureCoverage::copyTo(IlwisObject *obj)
{
Coverage::copyTo(obj);
FeatureCoverage *fcov = static_cast<FeatureCoverage *>(obj);
fcov->_featureTypes = _featureTypes;
fcov->_featureInfo = _featureInfo;
fcov->_features.resize(_features.size());
for(int i=0; i < _features.size(); ++i){
if ( _features[i])
fcov->_features[i].reset(_features[i]->clone());
}
}
quint32 FeatureCoverage::featureCount(IlwisTypes types, bool subAsDistinct, int index) const
{
auto countFeatures = [&] (int tp){
if ( index == iUNDEF){
if (subAsDistinct)
return _featureInfo[tp]._subGeomCnt;
return _featureInfo[tp]._geomCnt;
}
else
return _featureInfo[tp]._perIndex.size() < index ? _featureInfo[tp]._perIndex[index] : 0;
};
quint32 count=0;
if ( hasType(types, itPOINT))
count += countFeatures(0);
if ( hasType(types, itLINE))
count += countFeatures(1);
if ( hasType(types, itPOLYGON))
count += countFeatures(2);
return count;
}
IlwisTypes FeatureCoverage::geometryType(const geos::geom::Geometry *geom){
return GeometryHelper::geometryType(geom);
}
const UPGeomFactory& FeatureCoverage::geomfactory() const{
return _geomfactory;
}
<|endoftext|>
|
<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __STORE_H
#define __STORE_H
#include "memword.hh"
#include "storage.hh"
#include "type.hh"
class UnstableNode;
class Node;
/**
* A value node in the store.
* The store is entirely made of nodes. A node is basically a typed value.
* Non-atomic values, such as records, contain references to other nodes in the
* store, hence forming a graph, and the name "node".
* There are two kinds of node: stable and unstable node. A stable node is
* guaranteed never to change, whereas unstable node can change. In order to
* maintain consistency in the store, non-atomic values are only allowed to
* reference stable nodes. Unstable nodes are used for working data, and
* inherently mutable data (such as the contents of a cell).
*/
class Node {
public:
template<class T, class... Args>
void make(VM vm, Args... args) {
typedef Accessor<T, typename Storage<T>::Type> Access;
Access::init(type, value, vm, args...);
}
inline void reset(VM vm);
union {
// Regular structure of a node
struct {
const Type* type;
MemWord value;
};
// Garbage collector hack
struct {
Node* gcNext;
Node* gcFrom;
};
};
};
/**
* Stable node, which is guaranteed never to change
*/
class StableNode {
public:
inline void init(VM vm, UnstableNode& from);
private:
friend class UnstableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Unstable node, which is allowed to change over time
*/
class UnstableNode {
public:
inline void copy(VM vm, StableNode& from);
inline void copy(VM vm, UnstableNode& from);
inline void swap(UnstableNode& from);
inline void reset(VM vm);
template<class T, class... Args>
void make(VM vm, Args... args) {
node.make<T>(vm, args...);
}
private:
friend class StableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Extractor function for the template parameters of ImplWithArray
* Given
* typedef ImplWithArray<I, E> T;
* this provides
* ExtractImplWithArray<T>::Impl === I
* ExtractImplWithArray<T>::Elem === E
*/
template <class S>
struct ExtractImplWithArray {};
template <class I, class E>
struct ExtractImplWithArray<ImplWithArray<I, E>> {
typedef I Impl;
typedef E Elem;
};
/**
* A Self type for ImplWithArray storages
*/
template <class T>
class ImplWithArraySelf {
private:
typedef typename Storage<T>::Type StorageType;
typedef typename ExtractImplWithArray<StorageType>::Impl Impl;
typedef typename ExtractImplWithArray<StorageType>::Elem Elem;
typedef Accessor<T, StorageType> Access;
public:
ImplWithArraySelf(Node* node) : _node(node) {}
template<class U, class... Args>
void make(VM vm, Args... args) {
_node->make<U>(vm, args...);
}
Impl* operator->() {
return get().operator->();
}
Elem& operator[](size_t i) {
return get().operator[](i);
}
StaticArray<Elem> getArray(size_t size) {
return get().getArray(size);
}
private:
ImplWithArray<Impl, Elem> get() {
return ImplWithArray<Impl, Elem>(&Access::get(_node->value));
}
Node* _node;
};
/**
* Default Self type
*/
template <class T, class S>
struct SelfTypeInner {
typedef Node* Self;
};
/**
* Specialized Self type for types stored as an ImplWithArray
*/
template <class T, class I, class E>
struct SelfTypeInner<T, ImplWithArray<I, E>> {
typedef ImplWithArraySelf<T> Self;
};
/**
* Metafunction from type to its Self type
* Use as SelfType<T>::Self
*/
template <class T>
struct SelfType {
typedef typename SelfTypeInner<T, typename Storage<T>::Type>::Self Self;
};
/**
* Result of the call to a builtin.
* It always represents a node that must be waited upon. The value 'nullptr' is
* valid, and denotes that no value must be waited upon, i.e., the execution can
* continue.
* Throwing an exception is achieved by pointing to a failed value.
*/
typedef Node* BuiltinResult;
const BuiltinResult BuiltinResultContinue = nullptr;
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class Impl {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(typename SelfType<T>::Self(it), args...);
}
};
#define IMPL(ResType, Type, method, args...) \
(Impl<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class ImplNoSelf {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(args...);
}
};
#define IMPLNOSELF(ResType, Type, method, args...) \
(ImplNoSelf<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
///////////////
// Reference //
///////////////
class Reference;
template <>
class Storage<Reference> {
public:
typedef StableNode* Type;
};
template <>
class Implementation<Reference> {
public:
Implementation<Reference>(StableNode* dest) : _dest(dest) {}
StableNode* dest() const { return _dest; }
private:
StableNode* _dest;
};
/**
* Type of a reference
*/
class Reference {
public:
typedef Node* Self;
static const Type* const type;
static StableNode* build(StableNode* dest) { return dest; }
// This is optimized for the 0- and 1-dereference paths
// Normally it would have been only a while loop
static Node& dereference(Node& node) {
if (node.type != type)
return node;
else {
Node* result = &IMPLNOSELF(StableNode*, Reference, dest, &node)->node;
if (result->type != type)
return *result;
else
return dereferenceLoop(result);
}
}
static void makeFor(VM vm, UnstableNode& node) {
StableNode* stable = new (vm) StableNode;
stable->init(vm, node);
}
static void makeFor(VM vm, Node& node) {
UnstableNode temp;
temp.node = node;
makeFor(vm, temp);
node = temp.node;
}
// This is optimized for the 0- and 1-dereference paths
// Normally the else case would have been only a while loop
static StableNode* getStableRefFor(VM vm, Node& node) {
if (node.type != type) {
makeFor(vm, node);
return IMPLNOSELF(StableNode*, Reference, dest, &node);
} else {
StableNode* result = IMPLNOSELF(StableNode*, Reference, dest, &node);
if (result->node.type != type)
return result;
else
return getStableRefForLoop(result);
}
}
static StableNode* getStableRefFor(VM vm, UnstableNode& node) {
return getStableRefFor(vm, node.node);
}
static StableNode* getStableRefFor(VM vm, StableNode& node) {
if (node.node.type != type)
return &node;
else
return getStableRefFor(vm, node.node);
}
private:
static Node& dereferenceLoop(Node* node) {
while (node->type == type)
node = &(IMPLNOSELF(StableNode*, Reference, dest, node)->node);
return *node;
}
static StableNode* getStableRefForLoop(StableNode* node) {
do {
node = IMPLNOSELF(StableNode*, Reference, dest, &node->node);
} while (node->node.type == type);
return node;
}
static const Type rawType;
};
/////////////////////////
// Node implementation //
/////////////////////////
void Node::reset(VM vm) {
type = nullptr;
value.init<void*>(vm, nullptr);
}
void StableNode::init(VM vm, UnstableNode& from) {
node = from.node;
if (!node.type->isCopiable())
from.make<Reference>(vm, this);
}
void UnstableNode::copy(VM vm, StableNode& from) {
if (from.node.type->isCopiable())
node = from.node;
else
make<Reference>(vm, &from);
}
void UnstableNode::copy(VM vm, UnstableNode& from) {
if (!from.node.type->isCopiable())
Reference::makeFor(vm, from);
node = from.node;
}
void UnstableNode::reset(VM vm) {
node.reset(vm);
}
void UnstableNode::swap(UnstableNode& from) {
Node temp = node;
node = from.node;
from.node = temp;
}
#include "vm.hh"
#endif // __STORE_H
<commit_msg>Convenience constructors in UnstableNode, calling copy().<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __STORE_H
#define __STORE_H
#include "memword.hh"
#include "storage.hh"
#include "type.hh"
class UnstableNode;
class Node;
/**
* A value node in the store.
* The store is entirely made of nodes. A node is basically a typed value.
* Non-atomic values, such as records, contain references to other nodes in the
* store, hence forming a graph, and the name "node".
* There are two kinds of node: stable and unstable node. A stable node is
* guaranteed never to change, whereas unstable node can change. In order to
* maintain consistency in the store, non-atomic values are only allowed to
* reference stable nodes. Unstable nodes are used for working data, and
* inherently mutable data (such as the contents of a cell).
*/
class Node {
public:
template<class T, class... Args>
void make(VM vm, Args... args) {
typedef Accessor<T, typename Storage<T>::Type> Access;
Access::init(type, value, vm, args...);
}
inline void reset(VM vm);
union {
// Regular structure of a node
struct {
const Type* type;
MemWord value;
};
// Garbage collector hack
struct {
Node* gcNext;
Node* gcFrom;
};
};
};
/**
* Stable node, which is guaranteed never to change
*/
class StableNode {
public:
inline void init(VM vm, UnstableNode& from);
private:
friend class UnstableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Unstable node, which is allowed to change over time
*/
class UnstableNode {
public:
UnstableNode() {}
UnstableNode(VM vm, StableNode& from) {
copy(vm, from);
}
UnstableNode(VM vm, UnstableNode& from) {
copy(vm, from);
}
inline void copy(VM vm, StableNode& from);
inline void copy(VM vm, UnstableNode& from);
inline void swap(UnstableNode& from);
inline void reset(VM vm);
template<class T, class... Args>
void make(VM vm, Args... args) {
node.make<T>(vm, args...);
}
private:
friend class StableNode;
public: // TODO make it private once the development has been bootstrapped
Node node;
};
/**
* Extractor function for the template parameters of ImplWithArray
* Given
* typedef ImplWithArray<I, E> T;
* this provides
* ExtractImplWithArray<T>::Impl === I
* ExtractImplWithArray<T>::Elem === E
*/
template <class S>
struct ExtractImplWithArray {};
template <class I, class E>
struct ExtractImplWithArray<ImplWithArray<I, E>> {
typedef I Impl;
typedef E Elem;
};
/**
* A Self type for ImplWithArray storages
*/
template <class T>
class ImplWithArraySelf {
private:
typedef typename Storage<T>::Type StorageType;
typedef typename ExtractImplWithArray<StorageType>::Impl Impl;
typedef typename ExtractImplWithArray<StorageType>::Elem Elem;
typedef Accessor<T, StorageType> Access;
public:
ImplWithArraySelf(Node* node) : _node(node) {}
template<class U, class... Args>
void make(VM vm, Args... args) {
_node->make<U>(vm, args...);
}
Impl* operator->() {
return get().operator->();
}
Elem& operator[](size_t i) {
return get().operator[](i);
}
StaticArray<Elem> getArray(size_t size) {
return get().getArray(size);
}
private:
ImplWithArray<Impl, Elem> get() {
return ImplWithArray<Impl, Elem>(&Access::get(_node->value));
}
Node* _node;
};
/**
* Default Self type
*/
template <class T, class S>
struct SelfTypeInner {
typedef Node* Self;
};
/**
* Specialized Self type for types stored as an ImplWithArray
*/
template <class T, class I, class E>
struct SelfTypeInner<T, ImplWithArray<I, E>> {
typedef ImplWithArraySelf<T> Self;
};
/**
* Metafunction from type to its Self type
* Use as SelfType<T>::Self
*/
template <class T>
struct SelfType {
typedef typename SelfTypeInner<T, typename Storage<T>::Type>::Self Self;
};
/**
* Result of the call to a builtin.
* It always represents a node that must be waited upon. The value 'nullptr' is
* valid, and denotes that no value must be waited upon, i.e., the execution can
* continue.
* Throwing an exception is achieved by pointing to a failed value.
*/
typedef Node* BuiltinResult;
const BuiltinResult BuiltinResultContinue = nullptr;
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class Impl {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(typename SelfType<T>::Self(it), args...);
}
};
#define IMPL(ResType, Type, method, args...) \
(Impl<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
/**
* Strange and magical class that allows to call methods on storage-typed nodes
*/
template<class T, class R, class M, M m>
class ImplNoSelf {
public:
typedef Accessor<T, typename Storage<T>::Type> Type;
template<class... Args>
static R f(Node* it, Args... args) {
return (Type::get(it->value).*m)(args...);
}
};
#define IMPLNOSELF(ResType, Type, method, args...) \
(ImplNoSelf<Type, ResType, decltype(&Implementation<Type>::method), \
&Implementation<Type>::method>::f(args))
///////////////
// Reference //
///////////////
class Reference;
template <>
class Storage<Reference> {
public:
typedef StableNode* Type;
};
template <>
class Implementation<Reference> {
public:
Implementation<Reference>(StableNode* dest) : _dest(dest) {}
StableNode* dest() const { return _dest; }
private:
StableNode* _dest;
};
/**
* Type of a reference
*/
class Reference {
public:
typedef Node* Self;
static const Type* const type;
static StableNode* build(StableNode* dest) { return dest; }
// This is optimized for the 0- and 1-dereference paths
// Normally it would have been only a while loop
static Node& dereference(Node& node) {
if (node.type != type)
return node;
else {
Node* result = &IMPLNOSELF(StableNode*, Reference, dest, &node)->node;
if (result->type != type)
return *result;
else
return dereferenceLoop(result);
}
}
static void makeFor(VM vm, UnstableNode& node) {
StableNode* stable = new (vm) StableNode;
stable->init(vm, node);
}
static void makeFor(VM vm, Node& node) {
UnstableNode temp;
temp.node = node;
makeFor(vm, temp);
node = temp.node;
}
// This is optimized for the 0- and 1-dereference paths
// Normally the else case would have been only a while loop
static StableNode* getStableRefFor(VM vm, Node& node) {
if (node.type != type) {
makeFor(vm, node);
return IMPLNOSELF(StableNode*, Reference, dest, &node);
} else {
StableNode* result = IMPLNOSELF(StableNode*, Reference, dest, &node);
if (result->node.type != type)
return result;
else
return getStableRefForLoop(result);
}
}
static StableNode* getStableRefFor(VM vm, UnstableNode& node) {
return getStableRefFor(vm, node.node);
}
static StableNode* getStableRefFor(VM vm, StableNode& node) {
if (node.node.type != type)
return &node;
else
return getStableRefFor(vm, node.node);
}
private:
static Node& dereferenceLoop(Node* node) {
while (node->type == type)
node = &(IMPLNOSELF(StableNode*, Reference, dest, node)->node);
return *node;
}
static StableNode* getStableRefForLoop(StableNode* node) {
do {
node = IMPLNOSELF(StableNode*, Reference, dest, &node->node);
} while (node->node.type == type);
return node;
}
static const Type rawType;
};
/////////////////////////
// Node implementation //
/////////////////////////
void Node::reset(VM vm) {
type = nullptr;
value.init<void*>(vm, nullptr);
}
void StableNode::init(VM vm, UnstableNode& from) {
node = from.node;
if (!node.type->isCopiable())
from.make<Reference>(vm, this);
}
void UnstableNode::copy(VM vm, StableNode& from) {
if (from.node.type->isCopiable())
node = from.node;
else
make<Reference>(vm, &from);
}
void UnstableNode::copy(VM vm, UnstableNode& from) {
if (!from.node.type->isCopiable())
Reference::makeFor(vm, from);
node = from.node;
}
void UnstableNode::reset(VM vm) {
node.reset(vm);
}
void UnstableNode::swap(UnstableNode& from) {
Node temp = node;
node = from.node;
from.node = temp;
}
#include "vm.hh"
#endif // __STORE_H
<|endoftext|>
|
<commit_before>#include <osg/Texture2D>
#include <osg/TexGen>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderToTextureStage>
#include "CreateShadowedScene.h"
using namespace osg;
class CreateShadowTextureCullCallback : public osg::NodeCallback
{
public:
CreateShadowTextureCullCallback(osg::Node* shadower,const osg::Vec3& position, const osg::Vec4& ambientLightColor, unsigned int textureUnit):
_shadower(shadower),
_position(position),
_ambientLightColor(ambientLightColor),
_unit(textureUnit),
_shadowState(new osg::StateSet)
{
_texture = new osg::Texture2D;
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cullVisitor && (_texture.valid() && _shadower.valid()))
{
doPreRender(*node,*cullVisitor);
}
else
{
// must traverse the shadower
traverse(node,nv);
}
}
protected:
void doPreRender(osg::Node& node, osgUtil::CullVisitor& cv);
osg::ref_ptr<osg::Node> _shadower;
osg::ref_ptr<osg::Texture2D> _texture;
osg::Vec3 _position;
osg::Vec4 _ambientLightColor;
unsigned int _unit;
osg::ref_ptr<osg::StateSet> _shadowState;
// we need this to get round the order dependance
// of eye linear tex gen...
class MyTexGen : public TexGen
{
public:
void setMatrix(const osg::Matrix& matrix)
{
_matrix = matrix;
}
virtual void apply(osg::State& state) const
{
glPushMatrix();
glLoadMatrix(_matrix.ptr());
TexGen::apply(state);
glPopMatrix();
}
osg::Matrix _matrix;
};
};
void CreateShadowTextureCullCallback::doPreRender(osg::Node& node, osgUtil::CullVisitor& cv)
{
const osg::BoundingSphere& bs = _shadower->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<_shadower.get()<<std::endl;
return;
}
// create the render to texture stage.
osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
// set up lighting.
// currently ignore lights in the scene graph itself..
// will do later.
osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->_stage;
// set up the background color and clear mask.
rtts->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
rtts->setClearMask(previous_stage->getClearMask());
// set up to charge the same RenderStageLighting is the parent previous stage.
rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv.setCurrentRenderBin(rtts.get());
float centerDistance = (_position-bs.center()).length();
float znear = centerDistance-bs.radius();
float zfar = centerDistance+bs.radius();
float zNearRatio = 0.001f;
if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
// 2:1 aspect ratio as per flag geomtry below.
float top = (bs.radius()/centerDistance)*znear;
float right = top;
// set up projection.
osg::RefMatrix* projection = new osg::RefMatrix;
projection->makeFrustum(-right,right,-top,top,znear,zfar);
cv.pushProjectionMatrix(projection);
osg::RefMatrix* matrix = new osg::RefMatrix;
matrix->makeLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));
osg::Matrix MV = cv.getModelViewMatrix();
// compute the matrix which takes a vertex from local coords into tex coords
// will use this later to specify osg::TexGen..
osg::Matrix MVPT =
*matrix *
*projection *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5f,0.5f,0.5f);
cv.pushModelViewMatrix(matrix);
// make the material black for a shadow.
osg::Material* material = new osg::Material;
material->setAmbient(osg::Material::FRONT_AND_BACK,_ambientLightColor);
material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
_shadowState->setAttribute(material,osg::StateAttribute::OVERRIDE);
cv.pushStateSet(_shadowState.get());
{
// traverse the shadower
_shadower->accept(cv);
}
cv.popStateSet();
// restore the previous model view matrix.
cv.popModelViewMatrix();
// restore the previous model view matrix.
cv.popProjectionMatrix();
// restore the previous renderbin.
cv.setCurrentRenderBin(previousRenderBin);
if (rtts->_renderGraphList.size()==0 && rtts->_bins.size()==0)
{
// getting to this point means that all the shadower has been
// culled by small feature culling or is beyond LOD ranges.
return;
}
int height = 256;
int width = 256;
const osg::Viewport& viewport = *cv.getViewport();
// offset the impostor viewport from the center of the main window
// viewport as often the edges of the viewport might be obscured by
// other windows, which can cause image/reading writing problems.
int center_x = viewport.x()+viewport.width()/2;
int center_y = viewport.y()+viewport.height()/2;
osg::Viewport* new_viewport = new osg::Viewport;
new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
rtts->setViewport(new_viewport);
_shadowState->setAttribute(new_viewport);
// and the render to texture stage to the current stages
// dependancy list.
cv.getCurrentRenderBin()->_stage->addToDependencyList(rtts.get());
// if one exist attach texture to the RenderToTextureStage.
if (_texture.valid()) rtts->setTexture(_texture.get());
// set up the stateset to decorate the shadower with the shadow texture
// with the appropriate tex gen coords.
osg::StateSet* stateset = new osg::StateSet;
MyTexGen* texgen = new MyTexGen;
texgen->setMatrix(MV);
texgen->setMode(osg::TexGen::EYE_LINEAR);
texgen->setPlane(osg::TexGen::S,osg::Plane(MVPT(0,0),MVPT(1,0),MVPT(2,0),MVPT(3,0)));
texgen->setPlane(osg::TexGen::T,osg::Plane(MVPT(0,1),MVPT(1,1),MVPT(2,1),MVPT(3,1)));
texgen->setPlane(osg::TexGen::R,osg::Plane(MVPT(0,2),MVPT(1,2),MVPT(2,2),MVPT(3,2)));
texgen->setPlane(osg::TexGen::Q,osg::Plane(MVPT(0,3),MVPT(1,3),MVPT(2,3),MVPT(3,3)));
stateset->setTextureAttributeAndModes(_unit,_texture.get(),osg::StateAttribute::ON);
stateset->setTextureAttribute(_unit,texgen);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(_unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
cv.pushStateSet(stateset);
// must traverse the shadower
traverse(&node,&cv);
cv.popStateSet();
}
// set up a light source with the shadower and shodower subgraphs below it
// with the appropriate callbacks set up.
osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int textureUnit)
{
osg::LightSource* lightgroup = new osg::LightSource;
osg::Light* light = new osg::Light;
light->setPosition(osg::Vec4(lightPosition,1.0f));
light->setLightNum(0);
lightgroup->setLight(light);
osg::Vec4 ambientLightColor(0.1f,0.1f,0.1f,1.0f);
// add the shadower
lightgroup->addChild(shadower);
// add the shadowed with the callback to generate the shadow texture.
shadowed->setCullCallback(new CreateShadowTextureCullCallback(shadower,lightPosition,ambientLightColor,textureUnit));
lightgroup->addChild(shadowed);
osg::Geode* lightgeode = new osg::Geode;
lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
lightgroup->addChild(lightgeode);
return lightgroup;
}
<commit_msg>Moved a local new StateSet into cull callback as a ref_ptr to prevent memory leaks.<commit_after>#include <osg/Texture2D>
#include <osg/TexGen>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderToTextureStage>
#include "CreateShadowedScene.h"
using namespace osg;
class CreateShadowTextureCullCallback : public osg::NodeCallback
{
public:
CreateShadowTextureCullCallback(osg::Node* shadower,const osg::Vec3& position, const osg::Vec4& ambientLightColor, unsigned int textureUnit):
_shadower(shadower),
_position(position),
_ambientLightColor(ambientLightColor),
_unit(textureUnit),
_shadowState(new osg::StateSet),
_shadowedState(new osg::StateSet)
{
_texture = new osg::Texture2D;
_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
_texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
_texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cullVisitor && (_texture.valid() && _shadower.valid()))
{
doPreRender(*node,*cullVisitor);
}
else
{
// must traverse the shadower
traverse(node,nv);
}
}
protected:
void doPreRender(osg::Node& node, osgUtil::CullVisitor& cv);
osg::ref_ptr<osg::Node> _shadower;
osg::ref_ptr<osg::Texture2D> _texture;
osg::Vec3 _position;
osg::Vec4 _ambientLightColor;
unsigned int _unit;
osg::ref_ptr<osg::StateSet> _shadowState;
osg::ref_ptr<osg::StateSet> _shadowedState;
// we need this to get round the order dependance
// of eye linear tex gen...
class MyTexGen : public TexGen
{
public:
void setMatrix(const osg::Matrix& matrix)
{
_matrix = matrix;
}
virtual void apply(osg::State& state) const
{
glPushMatrix();
glLoadMatrix(_matrix.ptr());
TexGen::apply(state);
glPopMatrix();
}
osg::Matrix _matrix;
};
};
void CreateShadowTextureCullCallback::doPreRender(osg::Node& node, osgUtil::CullVisitor& cv)
{
const osg::BoundingSphere& bs = _shadower->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<_shadower.get()<<std::endl;
return;
}
// create the render to texture stage.
osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
// set up lighting.
// currently ignore lights in the scene graph itself..
// will do later.
osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->_stage;
// set up the background color and clear mask.
rtts->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
rtts->setClearMask(previous_stage->getClearMask());
// set up to charge the same RenderStageLighting is the parent previous stage.
rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv.setCurrentRenderBin(rtts.get());
float centerDistance = (_position-bs.center()).length();
float znear = centerDistance-bs.radius();
float zfar = centerDistance+bs.radius();
float zNearRatio = 0.001f;
if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;
// 2:1 aspect ratio as per flag geomtry below.
float top = (bs.radius()/centerDistance)*znear;
float right = top;
// set up projection.
osg::RefMatrix* projection = new osg::RefMatrix;
projection->makeFrustum(-right,right,-top,top,znear,zfar);
cv.pushProjectionMatrix(projection);
osg::RefMatrix* matrix = new osg::RefMatrix;
matrix->makeLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));
osg::Matrix MV = cv.getModelViewMatrix();
// compute the matrix which takes a vertex from local coords into tex coords
// will use this later to specify osg::TexGen..
osg::Matrix MVPT =
*matrix *
*projection *
osg::Matrix::translate(1.0,1.0,1.0) *
osg::Matrix::scale(0.5f,0.5f,0.5f);
cv.pushModelViewMatrix(matrix);
// make the material black for a shadow.
osg::Material* material = new osg::Material;
material->setAmbient(osg::Material::FRONT_AND_BACK,_ambientLightColor);
material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
_shadowState->setAttribute(material,osg::StateAttribute::OVERRIDE);
cv.pushStateSet(_shadowState.get());
{
// traverse the shadower
_shadower->accept(cv);
}
cv.popStateSet();
// restore the previous model view matrix.
cv.popModelViewMatrix();
// restore the previous model view matrix.
cv.popProjectionMatrix();
// restore the previous renderbin.
cv.setCurrentRenderBin(previousRenderBin);
if (rtts->_renderGraphList.size()==0 && rtts->_bins.size()==0)
{
// getting to this point means that all the shadower has been
// culled by small feature culling or is beyond LOD ranges.
return;
}
int height = 256;
int width = 256;
const osg::Viewport& viewport = *cv.getViewport();
// offset the impostor viewport from the center of the main window
// viewport as often the edges of the viewport might be obscured by
// other windows, which can cause image/reading writing problems.
int center_x = viewport.x()+viewport.width()/2;
int center_y = viewport.y()+viewport.height()/2;
osg::Viewport* new_viewport = new osg::Viewport;
new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
rtts->setViewport(new_viewport);
_shadowState->setAttribute(new_viewport);
// and the render to texture stage to the current stages
// dependancy list.
cv.getCurrentRenderBin()->_stage->addToDependencyList(rtts.get());
// if one exist attach texture to the RenderToTextureStage.
if (_texture.valid()) rtts->setTexture(_texture.get());
// set up the stateset to decorate the shadower with the shadow texture
// with the appropriate tex gen coords.
MyTexGen* texgen = new MyTexGen;
texgen->setMatrix(MV);
texgen->setMode(osg::TexGen::EYE_LINEAR);
texgen->setPlane(osg::TexGen::S,osg::Plane(MVPT(0,0),MVPT(1,0),MVPT(2,0),MVPT(3,0)));
texgen->setPlane(osg::TexGen::T,osg::Plane(MVPT(0,1),MVPT(1,1),MVPT(2,1),MVPT(3,1)));
texgen->setPlane(osg::TexGen::R,osg::Plane(MVPT(0,2),MVPT(1,2),MVPT(2,2),MVPT(3,2)));
texgen->setPlane(osg::TexGen::Q,osg::Plane(MVPT(0,3),MVPT(1,3),MVPT(2,3),MVPT(3,3)));
_shadowedState->setTextureAttributeAndModes(_unit,_texture.get(),osg::StateAttribute::ON);
_shadowedState->setTextureAttribute(_unit,texgen);
_shadowedState->setTextureMode(_unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
_shadowedState->setTextureMode(_unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
_shadowedState->setTextureMode(_unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
_shadowedState->setTextureMode(_unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
cv.pushStateSet(_shadowedState.get());
// must traverse the shadower
traverse(&node,&cv);
cv.popStateSet();
}
// set up a light source with the shadower and shodower subgraphs below it
// with the appropriate callbacks set up.
osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int textureUnit)
{
osg::LightSource* lightgroup = new osg::LightSource;
osg::Light* light = new osg::Light;
light->setPosition(osg::Vec4(lightPosition,1.0f));
light->setLightNum(0);
lightgroup->setLight(light);
osg::Vec4 ambientLightColor(0.1f,0.1f,0.1f,1.0f);
// add the shadower
lightgroup->addChild(shadower);
// add the shadowed with the callback to generate the shadow texture.
shadowed->setCullCallback(new CreateShadowTextureCullCallback(shadower,lightPosition,ambientLightColor,textureUnit));
lightgroup->addChild(shadowed);
osg::Geode* lightgeode = new osg::Geode;
lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
lightgroup->addChild(lightgeode);
return lightgroup;
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/23
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 "ClientSM.h"
#include "ChunkManager.h"
#include "ChunkServer.h"
#include "Utils.h"
#include "KfsOps.h"
#include <string>
#include <sstream>
using std::string;
using std::ostringstream;
#include "common/log.h"
#include "libkfsIO/Globals.h"
#include <boost/scoped_array.hpp>
using boost::scoped_array;
using namespace KFS;
using namespace KFS::libkfsio;
ClientSM::ClientSM(NetConnectionPtr &conn)
{
mNetConnection = conn;
SET_HANDLER(this, &ClientSM::HandleRequest);
}
ClientSM::~ClientSM()
{
KfsOp *op;
assert(mOps.empty());
while (!mOps.empty()) {
op = mOps.front();
mOps.pop_front();
delete op;
}
gClientManager.Remove(this);
}
///
/// Send out the response to the client request. The response is
/// generated by MetaRequest as per the protocol.
/// @param[in] op The request for which we finished execution.
///
void
ClientSM::SendResponse(KfsOp *op)
{
ostringstream os;
ReadOp *rop;
string s = op->Show();
int len;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
op->Response(os);
KFS_LOG_VA_DEBUG("Command %s: Response status: %d\n",
s.c_str(), op->status);
len = os.str().length();
if (len > 0)
mNetConnection->Write(os.str().c_str(), len);
if (op->op == CMD_READ) {
// need to send out the data read
rop = static_cast<ReadOp *> (op);
if (op->status >= 0) {
KFS_LOG_VA_DEBUG("Bytes avail from read: %d\n",
rop->dataBuf->BytesConsumable());
assert(rop->dataBuf->BytesConsumable() == rop->status);
mNetConnection->Write(rop->dataBuf, rop->numBytesIO);
}
} else if (op->op == CMD_GET_CHUNK_METADATA) {
GetChunkMetadataOp *gcm = static_cast<GetChunkMetadataOp *>(op);
if (op->status >= 0)
mNetConnection->Write(gcm->dataBuf, gcm->numBytesIO);
}
}
///
/// Generic event handler. Decode the event that occurred and
/// appropriately extract out the data and deal with the event.
/// @param[in] code: The type of event that occurred
/// @param[in] data: Data being passed in relative to the event that
/// occurred.
/// @retval 0 to indicate successful event handling; -1 otherwise.
///
int
ClientSM::HandleRequest(int code, void *data)
{
IOBuffer *iobuf;
KfsOp *op;
int cmdLen;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
switch (code) {
case EVENT_NET_READ:
// We read something from the network. Run the RPC that
// came in.
iobuf = (IOBuffer *) data;
while (IsMsgAvail(iobuf, &cmdLen)) {
// if we don't have all the data for the command, wait
if (!HandleClientCmd(iobuf, cmdLen))
break;
}
break;
case EVENT_NET_WROTE:
// Something went out on the network. For now, we don't
// track it. Later, we may use it for tracking throttling
// and such.
break;
case EVENT_CMD_DONE:
// An op finished execution. Send response back in FIFO
gChunkServer.OpFinished();
op = (KfsOp *) data;
op->done = true;
assert(!mOps.empty());
while (!mOps.empty()) {
KfsOp *qop = mOps.front();
if (!qop->done)
break;
SendResponse(qop);
mOps.pop_front();
OpFinished(qop);
delete qop;
}
mNetConnection->StartFlush();
break;
case EVENT_NET_ERROR:
// KFS_LOG_VA_DEBUG("Closing connection");
if (mNetConnection)
mNetConnection->Close();
// wait for the ops to finish
SET_HANDLER(this, &ClientSM::HandleTerminate);
if (mOps.empty()) {
delete this;
}
break;
default:
assert(!"Unknown event");
break;
}
return 0;
}
///
/// Termination handler. For the client state machine, we could have
/// ops queued at the logger. So, for cleanup wait for all the
/// outstanding ops to finish and then delete this. In this state,
/// the only event that gets raised is that an op finished; anything
/// else is bad.
///
int
ClientSM::HandleTerminate(int code, void *data)
{
KfsOp *op;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
switch (code) {
case EVENT_CMD_DONE:
gChunkServer.OpFinished();
// An op finished execution. Send a response back
op = (KfsOp *) data;
op->done = true;
if (op != mOps.front())
break;
while (!mOps.empty()) {
op = mOps.front();
if (!op->done)
break;
OpFinished(op);
// we are done with the op
mOps.pop_front();
delete op;
}
break;
default:
assert(!"Unknown event");
break;
}
if (mOps.empty()) {
// all ops are done...so, now, we can nuke ourself.
assert(mPendingOps.empty());
delete this;
}
return 0;
}
///
/// We have a command in a buffer. It is possible that we don't have
/// everything we need to execute it (for example, for a write we may
/// not have received all the data the client promised). So, parse
/// out the command and if we have everything execute it.
///
bool
ClientSM::HandleClientCmd(IOBuffer *iobuf,
int cmdLen)
{
scoped_array<char> buf;
KfsOp *op;
size_t nAvail;
buf.reset(new char[cmdLen + 1]);
iobuf->CopyOut(buf.get(), cmdLen);
buf[cmdLen] = '\0';
if (ParseCommand(buf.get(), cmdLen, &op) != 0) {
iobuf->Consume(cmdLen);
KFS_LOG_VA_DEBUG("Aye?: %s", buf.get());
// got a bogus command
return true;
}
if (op->op == CMD_WRITE_PREPARE) {
WritePrepareOp *wop = static_cast<WritePrepareOp *> (op);
assert(wop != NULL);
// if we don't have all the data for the write, hold on...
nAvail = iobuf->BytesConsumable() - cmdLen;
if (nAvail < wop->numBytes) {
delete op;
// we couldn't process the command...so, wait
return false;
}
iobuf->Consume(cmdLen);
wop->dataBuf = new IOBuffer();
wop->dataBuf->Move(iobuf, wop->numBytes);
nAvail = wop->dataBuf->BytesConsumable();
// KFS_LOG_VA_DEBUG("Got command: %s", buf.get());
// KFS_LOG_VA_DEBUG("# of bytes avail for write: %lu", nAvail);
} else {
string s = op->Show();
KFS_LOG_VA_DEBUG("Got command: %s\n", s.c_str());
iobuf->Consume(cmdLen);
}
if (op->op == CMD_WRITE_SYNC) {
// make the write sync depend on a previous write
KfsOp *w = NULL;
for (deque<KfsOp *>::iterator i = mOps.begin(); i != mOps.end(); i++) {
if ((*i)->op == CMD_WRITE)
w = *i;
}
if (w != NULL) {
OpPair p;
op->clnt = this;
p.op = w;
p.dependentOp = op;
mPendingOps.push_back(p);
KFS_LOG_VA_DEBUG("Keeping write-sync (%d) pending and depends on %d",
op->seq, p.op->seq);
return true;
}
}
mOps.push_back(op);
op->clnt = this;
// op->Execute();
gChunkServer.OpInserted();
SubmitOp(op);
return true;
}
void
ClientSM::OpFinished(KfsOp *doneOp)
{
// multiple ops could be waiting for a single op to finish...
while (1) {
if (mPendingOps.empty())
return;
OpPair p;
p = mPendingOps.front();
if (p.op->seq != doneOp->seq) {
break;
}
KFS_LOG_VA_DEBUG("Submitting write-sync (%d) since %d finished", p.dependentOp->seq,
p.op->seq);
mOps.push_back(p.dependentOp);
gChunkServer.OpInserted();
mPendingOps.pop_front();
SubmitOp(p.dependentOp);
}
}
<commit_msg> -- Fixed a race condition as it dealt with small writes: a sequence of write, flush, write, flush for small writes can cause the checksums/sizes to not get updated.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/23
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 "ClientSM.h"
#include "ChunkManager.h"
#include "ChunkServer.h"
#include "Utils.h"
#include "KfsOps.h"
#include <string>
#include <sstream>
using std::string;
using std::ostringstream;
#include "common/log.h"
#include "libkfsIO/Globals.h"
#include <boost/scoped_array.hpp>
using boost::scoped_array;
using namespace KFS;
using namespace KFS::libkfsio;
ClientSM::ClientSM(NetConnectionPtr &conn)
{
mNetConnection = conn;
SET_HANDLER(this, &ClientSM::HandleRequest);
}
ClientSM::~ClientSM()
{
KfsOp *op;
assert(mOps.empty());
while (!mOps.empty()) {
op = mOps.front();
mOps.pop_front();
delete op;
}
gClientManager.Remove(this);
}
///
/// Send out the response to the client request. The response is
/// generated by MetaRequest as per the protocol.
/// @param[in] op The request for which we finished execution.
///
void
ClientSM::SendResponse(KfsOp *op)
{
ostringstream os;
ReadOp *rop;
string s = op->Show();
int len;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
op->Response(os);
KFS_LOG_VA_DEBUG("Command %s: Response status: %d\n",
s.c_str(), op->status);
len = os.str().length();
if (len > 0)
mNetConnection->Write(os.str().c_str(), len);
if (op->op == CMD_READ) {
// need to send out the data read
rop = static_cast<ReadOp *> (op);
if (op->status >= 0) {
KFS_LOG_VA_DEBUG("Bytes avail from read: %d\n",
rop->dataBuf->BytesConsumable());
assert(rop->dataBuf->BytesConsumable() == rop->status);
mNetConnection->Write(rop->dataBuf, rop->numBytesIO);
}
} else if (op->op == CMD_GET_CHUNK_METADATA) {
GetChunkMetadataOp *gcm = static_cast<GetChunkMetadataOp *>(op);
if (op->status >= 0)
mNetConnection->Write(gcm->dataBuf, gcm->numBytesIO);
}
}
///
/// Generic event handler. Decode the event that occurred and
/// appropriately extract out the data and deal with the event.
/// @param[in] code: The type of event that occurred
/// @param[in] data: Data being passed in relative to the event that
/// occurred.
/// @retval 0 to indicate successful event handling; -1 otherwise.
///
int
ClientSM::HandleRequest(int code, void *data)
{
IOBuffer *iobuf;
KfsOp *op;
int cmdLen;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
switch (code) {
case EVENT_NET_READ:
// We read something from the network. Run the RPC that
// came in.
iobuf = (IOBuffer *) data;
while (IsMsgAvail(iobuf, &cmdLen)) {
// if we don't have all the data for the command, wait
if (!HandleClientCmd(iobuf, cmdLen))
break;
}
break;
case EVENT_NET_WROTE:
// Something went out on the network. For now, we don't
// track it. Later, we may use it for tracking throttling
// and such.
break;
case EVENT_CMD_DONE:
// An op finished execution. Send response back in FIFO
gChunkServer.OpFinished();
op = (KfsOp *) data;
op->done = true;
assert(!mOps.empty());
while (!mOps.empty()) {
KfsOp *qop = mOps.front();
if (!qop->done)
break;
SendResponse(qop);
mOps.pop_front();
OpFinished(qop);
delete qop;
}
mNetConnection->StartFlush();
break;
case EVENT_NET_ERROR:
// KFS_LOG_VA_DEBUG("Closing connection");
if (mNetConnection)
mNetConnection->Close();
// wait for the ops to finish
SET_HANDLER(this, &ClientSM::HandleTerminate);
if (mOps.empty()) {
delete this;
}
break;
default:
assert(!"Unknown event");
break;
}
return 0;
}
///
/// Termination handler. For the client state machine, we could have
/// ops queued at the logger. So, for cleanup wait for all the
/// outstanding ops to finish and then delete this. In this state,
/// the only event that gets raised is that an op finished; anything
/// else is bad.
///
int
ClientSM::HandleTerminate(int code, void *data)
{
KfsOp *op;
#ifdef DEBUG
verifyExecutingOnNetProcessor();
#endif
switch (code) {
case EVENT_CMD_DONE:
gChunkServer.OpFinished();
// An op finished execution. Send a response back
op = (KfsOp *) data;
op->done = true;
if (op != mOps.front())
break;
while (!mOps.empty()) {
op = mOps.front();
if (!op->done)
break;
OpFinished(op);
// we are done with the op
mOps.pop_front();
delete op;
}
break;
default:
assert(!"Unknown event");
break;
}
if (mOps.empty()) {
// all ops are done...so, now, we can nuke ourself.
assert(mPendingOps.empty());
delete this;
}
return 0;
}
///
/// We have a command in a buffer. It is possible that we don't have
/// everything we need to execute it (for example, for a write we may
/// not have received all the data the client promised). So, parse
/// out the command and if we have everything execute it.
///
bool
ClientSM::HandleClientCmd(IOBuffer *iobuf,
int cmdLen)
{
scoped_array<char> buf;
KfsOp *op;
size_t nAvail;
buf.reset(new char[cmdLen + 1]);
iobuf->CopyOut(buf.get(), cmdLen);
buf[cmdLen] = '\0';
if (ParseCommand(buf.get(), cmdLen, &op) != 0) {
iobuf->Consume(cmdLen);
KFS_LOG_VA_DEBUG("Aye?: %s", buf.get());
// got a bogus command
return true;
}
if (op->op == CMD_WRITE_PREPARE) {
WritePrepareOp *wop = static_cast<WritePrepareOp *> (op);
assert(wop != NULL);
// if we don't have all the data for the write, hold on...
nAvail = iobuf->BytesConsumable() - cmdLen;
if (nAvail < wop->numBytes) {
delete op;
// we couldn't process the command...so, wait
return false;
}
iobuf->Consume(cmdLen);
wop->dataBuf = new IOBuffer();
wop->dataBuf->Move(iobuf, wop->numBytes);
nAvail = wop->dataBuf->BytesConsumable();
// KFS_LOG_VA_DEBUG("Got command: %s", buf.get());
// KFS_LOG_VA_DEBUG("# of bytes avail for write: %lu", nAvail);
} else {
string s = op->Show();
KFS_LOG_VA_DEBUG("Got command: %s\n", s.c_str());
iobuf->Consume(cmdLen);
}
if (op->op == CMD_WRITE_SYNC) {
// make the write sync depend on a previous write
KfsOp *w = NULL;
for (deque<KfsOp *>::iterator i = mOps.begin(); i != mOps.end(); i++) {
if (((*i)->op == CMD_WRITE_PREPARE) || ((*i)->op == CMD_WRITE_PREPARE_FWD) ||
((*i)->op == CMD_WRITE)) {
w = *i;
}
}
if (w != NULL) {
OpPair p;
op->clnt = this;
p.op = w;
p.dependentOp = op;
mPendingOps.push_back(p);
KFS_LOG_VA_DEBUG("Keeping write-sync (%d) pending and depends on %d",
op->seq, p.op->seq);
return true;
} else {
KFS_LOG_VA_DEBUG("Write-sync is being pushed down; no writes left... (%d ops left in q)",
mOps.size());
}
}
mOps.push_back(op);
op->clnt = this;
// op->Execute();
gChunkServer.OpInserted();
SubmitOp(op);
return true;
}
void
ClientSM::OpFinished(KfsOp *doneOp)
{
// multiple ops could be waiting for a single op to finish...
while (1) {
if (mPendingOps.empty())
return;
OpPair p;
p = mPendingOps.front();
if (p.op->seq != doneOp->seq) {
break;
}
KFS_LOG_VA_DEBUG("Submitting write-sync (%d) since %d finished", p.dependentOp->seq,
p.op->seq);
mOps.push_back(p.dependentOp);
gChunkServer.OpInserted();
mPendingOps.pop_front();
SubmitOp(p.dependentOp);
}
}
<|endoftext|>
|
<commit_before>#include <clpeak.h>
#define FETCH_PER_WI 16
int clPeak::runGlobalBandwidthTest(cl::CommandQueue &queue, cl::Program &prog, device_info_t &devInfo)
{
float timed_lo, timed_go, timed, gbps;
cl::NDRange globalSize, localSize;
float *arr = NULL;
if(!isGlobalBW)
return 0;
cl::Context ctx = queue.getInfo<CL_QUEUE_CONTEXT>();
int iters = devInfo.gloalBWIters;
cl_uint maxItems = devInfo.maxAllocSize / sizeof(float) / 2;
cl_uint numItems;
// Set an upper-limit for cpu devies
if(devInfo.deviceType & CL_DEVICE_TYPE_CPU) {
numItems = roundToMultipleOf(maxItems, devInfo.maxWGSize, 1 << 25);
} else {
numItems = roundToMultipleOf(maxItems, devInfo.maxWGSize);
}
try
{
arr = new float[numItems];
populate(arr, numItems);
log->print(NEWLINE TAB TAB "Global memory bandwidth (GBPS)" NEWLINE);
log->xmlOpenTag("global_memory_bandwidth");
log->xmlAppendAttribs("unit", "gbps");
cl::Buffer inputBuf = cl::Buffer(ctx, CL_MEM_READ_ONLY, (numItems * sizeof(float)));
cl::Buffer outputBuf = cl::Buffer(ctx, CL_MEM_WRITE_ONLY, (numItems * sizeof(float)));
queue.enqueueWriteBuffer(inputBuf, CL_TRUE, 0, (numItems * sizeof(float)), arr);
cl::Kernel kernel_v1_lo(prog, "global_bandwidth_v1_local_offset");
kernel_v1_lo.setArg(0, inputBuf), kernel_v1_lo.setArg(1, outputBuf);
cl::Kernel kernel_v2_lo(prog, "global_bandwidth_v2_local_offset");
kernel_v2_lo.setArg(0, inputBuf), kernel_v2_lo.setArg(1, outputBuf);
cl::Kernel kernel_v4_lo(prog, "global_bandwidth_v4_local_offset");
kernel_v4_lo.setArg(0, inputBuf), kernel_v4_lo.setArg(1, outputBuf);
cl::Kernel kernel_v8_lo(prog, "global_bandwidth_v8_local_offset");
kernel_v8_lo.setArg(0, inputBuf), kernel_v8_lo.setArg(1, outputBuf);
cl::Kernel kernel_v16_lo(prog, "global_bandwidth_v16_local_offset");
kernel_v16_lo.setArg(0, inputBuf), kernel_v16_lo.setArg(1, outputBuf);
cl::Kernel kernel_v1_go(prog, "global_bandwidth_v1_global_offset");
kernel_v1_go.setArg(0, inputBuf), kernel_v1_go.setArg(1, outputBuf);
cl::Kernel kernel_v2_go(prog, "global_bandwidth_v2_global_offset");
kernel_v2_go.setArg(0, inputBuf), kernel_v2_go.setArg(1, outputBuf);
cl::Kernel kernel_v4_go(prog, "global_bandwidth_v4_global_offset");
kernel_v4_go.setArg(0, inputBuf), kernel_v4_go.setArg(1, outputBuf);
cl::Kernel kernel_v8_go(prog, "global_bandwidth_v8_global_offset");
kernel_v8_go.setArg(0, inputBuf), kernel_v8_go.setArg(1, outputBuf);
cl::Kernel kernel_v16_go(prog, "global_bandwidth_v16_global_offset");
kernel_v16_go.setArg(0, inputBuf), kernel_v16_go.setArg(1, outputBuf);
localSize = devInfo.maxWGSize;
///////////////////////////////////////////////////////////////////////////
// Vector width 1
log->print(TAB TAB TAB "float : ");
globalSize = numItems / FETCH_PER_WI;
// Run 2 kind of bandwidth kernel
// lo -- local_size offset - subsequent fetches at local_size offset
// go -- global_size offset
timed_lo = run_kernel(queue, kernel_v1_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v1_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 2
log->print(TAB TAB TAB "float2 : ");
globalSize = (numItems / 2 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v2_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v2_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float2", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 4
log->print(TAB TAB TAB "float4 : ");
globalSize = (numItems / 4 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v4_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v4_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float4", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 8
log->print(TAB TAB TAB "float8 : ");
globalSize = (numItems / 8 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v8_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v8_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float8", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 16
log->print(TAB TAB TAB "float16 : ");
globalSize = (numItems / 16 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v16_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v16_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float16", gbps);
///////////////////////////////////////////////////////////////////////////
log->xmlCloseTag(); // global_memory_bandwidth
if(arr) delete [] arr;
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE
<< TAB TAB TAB "Tests skipped" NEWLINE;
log->print(ss.str());
if(arr) delete [] arr;
return -1;
}
return 0;
}
<commit_msg>fix global bw test to use right multiplier<commit_after>#include <clpeak.h>
#define FETCH_PER_WI 16
int clPeak::runGlobalBandwidthTest(cl::CommandQueue &queue, cl::Program &prog, device_info_t &devInfo)
{
float timed_lo, timed_go, timed, gbps;
cl::NDRange globalSize, localSize;
float *arr = NULL;
if(!isGlobalBW)
return 0;
cl::Context ctx = queue.getInfo<CL_QUEUE_CONTEXT>();
int iters = devInfo.gloalBWIters;
cl_uint maxItems = devInfo.maxAllocSize / sizeof(float) / 2;
cl_uint numItems;
// Set an upper-limit for cpu devies
if(devInfo.deviceType & CL_DEVICE_TYPE_CPU) {
numItems = roundToMultipleOf(maxItems, (devInfo.maxWGSize * FETCH_PER_WI * 16), 1 << 25);
} else {
numItems = roundToMultipleOf(maxItems, (devInfo.maxWGSize * FETCH_PER_WI * 16));
}
try
{
arr = new float[numItems];
populate(arr, numItems);
log->print(NEWLINE TAB TAB "Global memory bandwidth (GBPS)" NEWLINE);
log->xmlOpenTag("global_memory_bandwidth");
log->xmlAppendAttribs("unit", "gbps");
cl::Buffer inputBuf = cl::Buffer(ctx, CL_MEM_READ_ONLY, (numItems * sizeof(float)));
cl::Buffer outputBuf = cl::Buffer(ctx, CL_MEM_WRITE_ONLY, (numItems * sizeof(float)));
queue.enqueueWriteBuffer(inputBuf, CL_TRUE, 0, (numItems * sizeof(float)), arr);
cl::Kernel kernel_v1_lo(prog, "global_bandwidth_v1_local_offset");
kernel_v1_lo.setArg(0, inputBuf), kernel_v1_lo.setArg(1, outputBuf);
cl::Kernel kernel_v2_lo(prog, "global_bandwidth_v2_local_offset");
kernel_v2_lo.setArg(0, inputBuf), kernel_v2_lo.setArg(1, outputBuf);
cl::Kernel kernel_v4_lo(prog, "global_bandwidth_v4_local_offset");
kernel_v4_lo.setArg(0, inputBuf), kernel_v4_lo.setArg(1, outputBuf);
cl::Kernel kernel_v8_lo(prog, "global_bandwidth_v8_local_offset");
kernel_v8_lo.setArg(0, inputBuf), kernel_v8_lo.setArg(1, outputBuf);
cl::Kernel kernel_v16_lo(prog, "global_bandwidth_v16_local_offset");
kernel_v16_lo.setArg(0, inputBuf), kernel_v16_lo.setArg(1, outputBuf);
cl::Kernel kernel_v1_go(prog, "global_bandwidth_v1_global_offset");
kernel_v1_go.setArg(0, inputBuf), kernel_v1_go.setArg(1, outputBuf);
cl::Kernel kernel_v2_go(prog, "global_bandwidth_v2_global_offset");
kernel_v2_go.setArg(0, inputBuf), kernel_v2_go.setArg(1, outputBuf);
cl::Kernel kernel_v4_go(prog, "global_bandwidth_v4_global_offset");
kernel_v4_go.setArg(0, inputBuf), kernel_v4_go.setArg(1, outputBuf);
cl::Kernel kernel_v8_go(prog, "global_bandwidth_v8_global_offset");
kernel_v8_go.setArg(0, inputBuf), kernel_v8_go.setArg(1, outputBuf);
cl::Kernel kernel_v16_go(prog, "global_bandwidth_v16_global_offset");
kernel_v16_go.setArg(0, inputBuf), kernel_v16_go.setArg(1, outputBuf);
localSize = devInfo.maxWGSize;
///////////////////////////////////////////////////////////////////////////
// Vector width 1
log->print(TAB TAB TAB "float : ");
globalSize = numItems / FETCH_PER_WI;
// Run 2 kind of bandwidth kernel
// lo -- local_size offset - subsequent fetches at local_size offset
// go -- global_size offset
timed_lo = run_kernel(queue, kernel_v1_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v1_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 2
log->print(TAB TAB TAB "float2 : ");
globalSize = (numItems / 2 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v2_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v2_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float2", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 4
log->print(TAB TAB TAB "float4 : ");
globalSize = (numItems / 4 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v4_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v4_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float4", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 8
log->print(TAB TAB TAB "float8 : ");
globalSize = (numItems / 8 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v8_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v8_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float8", gbps);
///////////////////////////////////////////////////////////////////////////
// Vector width 16
log->print(TAB TAB TAB "float16 : ");
globalSize = (numItems / 16 / FETCH_PER_WI);
timed_lo = run_kernel(queue, kernel_v16_lo, globalSize, localSize, iters);
timed_go = run_kernel(queue, kernel_v16_go, globalSize, localSize, iters);
timed = (timed_lo < timed_go)? timed_lo: timed_go;
gbps = ((float)numItems * sizeof(float)) / timed / 1e3f;
log->print(gbps); log->print(NEWLINE);
log->xmlRecord("float16", gbps);
///////////////////////////////////////////////////////////////////////////
log->xmlCloseTag(); // global_memory_bandwidth
if(arr) delete [] arr;
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE
<< TAB TAB TAB "Tests skipped" NEWLINE;
log->print(ss.str());
if(arr) delete [] arr;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <deque>
using namespace std;
void remove_trailing_spaces(string& str)
{
string::iterator erase_begin=str.end();
while(erase_begin!=str.begin() && isspace(*(erase_begin-1))) --erase_begin;
str.erase(erase_begin, str.end());
}
int main(int argc, char **argv) // argv[0] command, argv[1] test_in, argv[2] test_out (right answer), argv[3] answer to check
{
ios_base::sync_with_stdio(false);
fstream out(argv[3], ios_base::in), ans(argv[2], ios_base::in);
if(!out.good() && !ans.good())
return 2;// Evaluation failure
deque<string> out_in, ans_in;
string out_tmp, ans_tmp;
while(out.good() && ans.good())
{
getline(out, out_tmp);
getline(ans, ans_tmp);
remove_trailing_spaces(out_tmp);
remove_trailing_spaces(ans_tmp);
out_in.push_back(out_tmp);
ans_in.push_back(ans_tmp);
}
while(!out_in.empty() && out_in.back().empty()) out_in.pop_back();
while(!ans_in.empty() && ans_in.back().empty()) ans_in.pop_back();
int line=-1;
while(++line<out_in.size() && line<ans_in.size())
if(ans_in[line]!=out_in[line])
return 1; // Wrong answer
if(ans_in.size()>out_in.size())
return 1; // Wrong answer
return 0; // OK
}<commit_msg>Little chamges in default checker<commit_after>#include <fstream>
#include <deque>
using namespace std;
void remove_trailing_spaces(string& str)
{
string::iterator erase_begin=str.end();
while(erase_begin!=str.begin() && isspace(*(erase_begin-1))) --erase_begin;
str.erase(erase_begin, str.end());
}
int main(int argc, char **argv) // argv[0] command, argv[1] test_in, argv[2] test_out (right answer), argv[3] answer to check
{
ios_base::sync_with_stdio(false);
fstream out(argv[2], ios_base::in), ans(argv[3], ios_base::in);
if(!ans.good() && !out.good())
return 2;// Evaluation failure
deque<string> ans_in, out_in;
string ans_tmp, out_tmp;
while(ans.good() && out.good())
{
getline(ans, ans_tmp);
getline(out, out_tmp);
remove_trailing_spaces(ans_tmp);
remove_trailing_spaces(out_tmp);
ans_in.push_back(ans_tmp);
out_in.push_back(out_tmp);
}
while(!ans_in.empty() && ans_in.back().empty()) ans_in.pop_back();
while(!out_in.empty() && out_in.back().empty()) out_in.pop_back();
int line=-1;
while(++line<ans_in.size() && line<out_in.size())
if(out_in[line]!=ans_in[line])
return 1; // Wrong answer
if(out_in.size()>ans_in.size())
return 1; // Wrong answer
return 0; // OK
}<|endoftext|>
|
<commit_before>#ifndef GRAPH_LIB_PROPERTIES_HPP
#define GRAPH_LIB_PROPERTIES_HPP
namespace graph {
struct WeightedProperty {
int weight;
bool operator==(WeightedProperty other) const {
return weight == other.weight;
}
};
struct AstarNodeProperty {
int gScore;
int fScore;
bool operator==(AstarNodeProperty other) const {
return (gScore == other.fScore) && (fScore == other.fScore);
}
};
struct NoProperty {
bool operator==(NoProperty) const {
return true;
}
};
}
#endif
<commit_msg>Adding parent in astar node properties<commit_after>#ifndef GRAPH_LIB_PROPERTIES_HPP
#define GRAPH_LIB_PROPERTIES_HPP
#include <string>
namespace graph {
struct WeightedProperty {
int weight;
bool operator==(WeightedProperty other) const {
return weight == other.weight;
}
};
struct AstarNodeProperty {
int gScore;
int hScore;
std::string parent;
bool operator==(AstarNodeProperty other) const {
return (gScore == other.gScore) && (hScore == other.hScore) &&
(parent == other.parent);
}
};
struct NoProperty {
bool operator==(NoProperty) const {
return true;
}
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017 Rhys Ulerich
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef DESCENDU_SEXP_HPP
#define DESCENDU_SEXP_HPP
#include <cctype>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
namespace descendu {
namespace sexp {
// TODO Track line/column as input processed
// TODO Record line/column within each node
enum struct node_type { list=1, symbol, string };
// switch (node.type) {
// case node_type::list: /* Use list-like methods */ break;
// case node_type::symbol: /* Use node.string */ break;
// case node_type::string: /* Use node.string */ break;
// }
class node : std::vector<node>
{
typedef std::vector<node> base_type;
public:
// Discern which type of data is contained.
node_type type;
// For string node access
std::string string;
// For list node access
using base_type::back;
using base_type::begin;
using base_type::cbegin;
using base_type::cend;
using base_type::emplace_back;
using base_type::end;
using base_type::front;
using base_type::operator[];
using base_type::pop_back;
using base_type::size;
// Construct a string node
explicit node(const std::string& s, const bool is_symbol = true)
: base_type(0)
, type(is_symbol ? node_type::symbol : node_type::string)
, string(s)
{};
// Move into a string node
explicit node(std::string&& s, const bool is_symbol = true)
: base_type(0)
, type(is_symbol ? node_type::symbol : node_type::string)
, string(s)
{};
// Construct an empty list node
node()
: base_type()
, type(node_type::list)
, string()
{};
};
namespace impl {
// Helper to process C99 and S-expression escapes for parse(...) just below
template<typename InputIt>
std::string& append_maybe_escaped(
const char c,
std::string &acc, // Reference!
InputIt& next, // Reference!
InputIt end,
const bool quoted)
{
if (c != '\'') return acc += c;
if (next == end) throw std::invalid_argument("backslash precedes EOF");
const char q = *next++;
switch (q) {
case 'a': return acc += '\a';
case 'b': return acc += '\b';
case 'f': return acc += '\f';
case 'n': return acc += '\n';
case 'r': return acc += '\r';
case 't': return acc += '\t';
case 'v': return acc += '\v';
case '\'':
case '"':
case '?': return acc += q;
case 'x':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
throw new std::logic_error("Escaping via numeric codes unimplemented");
case '(': case ')': if (quoted) return acc += q; // Possibly fall through
}
throw new std::invalid_argument(std::string("Improper escape \\" + q));
}
} // namespace impl
// Parse zero or more S-expressions in the input returning a list.
// Notice parsed input is wrapped in one additional list. That is,
// 1) "(foo)(bar)" returned as ((foo)(bar))
// 2) "(foo)" returned as ((foo))
// 3) "foo" returned as (foo)
// 4) "" returned as ()
// as otherwise non-list or trivial inputs problematic.
// Based upon https://en.wikipedia.org/wiki/S-expression#Parsing
// and grotesquely extended to handle different input with checking.
template<typename InputIt>
node parse(InputIt next, InputIt end) {
node sexp;
sexp.emplace_back();
std::string word;
int level = 0;
bool in_string = 0;
while (next != end) {
const char c = *next++;
if (std::isspace(c)) {
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
} else if (c == '(') {
++level;
sexp.emplace_back();
} else if (c == ')') {
if (level == 0) {
throw std::invalid_argument("unopened right parenthesis");
}
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
node temp(std::move(sexp.back()));
sexp.pop_back();
sexp.back().emplace_back(std::move(temp));
--level;
} else if (c == '"') {
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
for (;;) {
if (next == end) throw std::invalid_argument("unclosed quote");
const char q = *next++;
if (q == '"') break;
impl::append_maybe_escaped(q, word, next, end, /*quoted*/true);
}
sexp.back().emplace_back(std::move(word), /*string*/false);
word.clear();
} else {
impl::append_maybe_escaped(c, word, next, end, /*quoted*/false);
in_string = true;
}
}
if (level != 0) {
throw std::invalid_argument("unclosed left parenthesis");
}
if (in_string) { // Required for final top-level string
sexp.back().emplace_back(word);
}
if (!sexp.size()) {
throw std::logic_error("sanity failure on size");
}
if (sexp.front().type != node_type::list) {
throw std::logic_error("sanity failure on type");
}
return sexp.front();
}
node parse(const std::string& in) {
return parse(in.cbegin(), in.cend());
}
node parse(std::istream& is) {
return parse(
std::istream_iterator<char>(is),
std::istream_iterator<char>());
}
template<typename OutputIterator>
void copy(const node& sexp, OutputIterator out) {
switch (sexp.type) {
case node_type::list:
{
*out++ = '(';
std::size_t count = 0;
for (const auto& term : sexp) {
if (count++) {
*out++ = ' ';
}
copy(term, out);
}
*out++ = ')';
}
break;
case node_type::symbol:
for (const char c : sexp.string) {
switch (c) {
case '\a': *out++ = '\\'; *out++ = 'a'; break;
case '\b': *out++ = '\\'; *out++ = 'b'; break;
case '\f': *out++ = '\\'; *out++ = 'f'; break;
case '\n': *out++ = '\\'; *out++ = 'n'; break;
case '\r': *out++ = '\\'; *out++ = 'r'; break;
case '\t': *out++ = '\\'; *out++ = 't'; break;
case '\v': *out++ = '\\'; *out++ = 'v'; break;
case '\'': *out++ = '\\'; *out++ = '\''; break;
case '"': *out++ = '\\'; *out++ = '"'; break;
case '?': *out++ = '\\'; *out++ = '?'; break;
case ' ': *out++ = '\\'; *out++ = ' '; break;
case '(': *out++ = '\\'; *out++ = '('; break;
case ')': *out++ = '\\'; *out++ = ')'; break;
default:
*out++ = c;
}
}
break;
case node_type::string:
*out++ = '"';
for (const char c : sexp.string) {
switch (c) {
case '\a': *out++ = '\\'; *out++ = 'a'; break;
case '\b': *out++ = '\\'; *out++ = 'b'; break;
case '\f': *out++ = '\\'; *out++ = 'f'; break;
case '"': *out++ = '\\'; *out++ = '"'; break;
default:
*out++ = c;
}
}
*out++ = '"';
break;
default:
throw std::logic_error("Unimplemented case");
}
}
void copy(const node& sexp, std::ostream& os) {
return copy(sexp, std::ostream_iterator<char>(os));
}
std::string to_string(const node& sexp) {
std::ostringstream oss;
std::ostream_iterator<char> it(oss);
copy(sexp, it);
return oss.str();
}
} // namespace
} // namespace
#endif
<commit_msg>Correct boolean condition<commit_after>/*
* Copyright (C) 2017 Rhys Ulerich
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef DESCENDU_SEXP_HPP
#define DESCENDU_SEXP_HPP
#include <cctype>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
namespace descendu {
namespace sexp {
// TODO Track line/column as input processed
// TODO Record line/column within each node
enum struct node_type { list=1, symbol, string };
// switch (node.type) {
// case node_type::list: /* Use list-like methods */ break;
// case node_type::symbol: /* Use node.string */ break;
// case node_type::string: /* Use node.string */ break;
// }
class node : std::vector<node>
{
typedef std::vector<node> base_type;
public:
// Discern which type of data is contained.
node_type type;
// For string node access
std::string string;
// For list node access
using base_type::back;
using base_type::begin;
using base_type::cbegin;
using base_type::cend;
using base_type::emplace_back;
using base_type::end;
using base_type::front;
using base_type::operator[];
using base_type::pop_back;
using base_type::size;
// Construct a string node
explicit node(const std::string& s, const bool is_symbol = true)
: base_type(0)
, type(is_symbol ? node_type::symbol : node_type::string)
, string(s)
{};
// Move into a string node
explicit node(std::string&& s, const bool is_symbol = true)
: base_type(0)
, type(is_symbol ? node_type::symbol : node_type::string)
, string(s)
{};
// Construct an empty list node
node()
: base_type()
, type(node_type::list)
, string()
{};
};
namespace impl {
// Helper to process C99 and S-expression escapes for parse(...) just below
template<typename InputIt>
std::string& append_maybe_escaped(
const char c,
std::string &acc, // Reference!
InputIt& next, // Reference!
InputIt end,
const bool quoted)
{
if (c != '\'') return acc += c;
if (next == end) throw std::invalid_argument("backslash precedes EOF");
const char q = *next++;
switch (q) {
case 'a': return acc += '\a';
case 'b': return acc += '\b';
case 'f': return acc += '\f';
case 'n': return acc += '\n';
case 'r': return acc += '\r';
case 't': return acc += '\t';
case 'v': return acc += '\v';
case '\'':
case '"':
case '?': return acc += q;
case 'x':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
throw new std::logic_error("Escaping via numeric codes unimplemented");
case '(': case ')': if (!quoted) return acc += q; // Possibly fall through
}
throw new std::invalid_argument(std::string("Improper escape \\" + q));
}
} // namespace impl
// Parse zero or more S-expressions in the input returning a list.
// Notice parsed input is wrapped in one additional list. That is,
// 1) "(foo)(bar)" returned as ((foo)(bar))
// 2) "(foo)" returned as ((foo))
// 3) "foo" returned as (foo)
// 4) "" returned as ()
// as otherwise non-list or trivial inputs problematic.
// Based upon https://en.wikipedia.org/wiki/S-expression#Parsing
// and grotesquely extended to handle different input with checking.
template<typename InputIt>
node parse(InputIt next, InputIt end) {
node sexp;
sexp.emplace_back();
std::string word;
int level = 0;
bool in_string = 0;
while (next != end) {
const char c = *next++;
if (std::isspace(c)) {
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
} else if (c == '(') {
++level;
sexp.emplace_back();
} else if (c == ')') {
if (level == 0) {
throw std::invalid_argument("unopened right parenthesis");
}
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
node temp(std::move(sexp.back()));
sexp.pop_back();
sexp.back().emplace_back(std::move(temp));
--level;
} else if (c == '"') {
if (in_string) {
sexp.back().emplace_back(std::move(word));
word.clear();
}
in_string = false;
for (;;) {
if (next == end) throw std::invalid_argument("unclosed quote");
const char q = *next++;
if (q == '"') break;
impl::append_maybe_escaped(q, word, next, end, /*quoted*/true);
}
sexp.back().emplace_back(std::move(word), /*string*/false);
word.clear();
} else {
impl::append_maybe_escaped(c, word, next, end, /*quoted*/false);
in_string = true;
}
}
if (level != 0) {
throw std::invalid_argument("unclosed left parenthesis");
}
if (in_string) { // Required for final top-level string
sexp.back().emplace_back(word);
}
if (!sexp.size()) {
throw std::logic_error("sanity failure on size");
}
if (sexp.front().type != node_type::list) {
throw std::logic_error("sanity failure on type");
}
return sexp.front();
}
node parse(const std::string& in) {
return parse(in.cbegin(), in.cend());
}
node parse(std::istream& is) {
return parse(
std::istream_iterator<char>(is),
std::istream_iterator<char>());
}
template<typename OutputIterator>
void copy(const node& sexp, OutputIterator out) {
switch (sexp.type) {
case node_type::list:
{
*out++ = '(';
std::size_t count = 0;
for (const auto& term : sexp) {
if (count++) {
*out++ = ' ';
}
copy(term, out);
}
*out++ = ')';
}
break;
case node_type::symbol:
for (const char c : sexp.string) {
switch (c) {
case '\a': *out++ = '\\'; *out++ = 'a'; break;
case '\b': *out++ = '\\'; *out++ = 'b'; break;
case '\f': *out++ = '\\'; *out++ = 'f'; break;
case '\n': *out++ = '\\'; *out++ = 'n'; break;
case '\r': *out++ = '\\'; *out++ = 'r'; break;
case '\t': *out++ = '\\'; *out++ = 't'; break;
case '\v': *out++ = '\\'; *out++ = 'v'; break;
case '\'': *out++ = '\\'; *out++ = '\''; break;
case '"': *out++ = '\\'; *out++ = '"'; break;
case '?': *out++ = '\\'; *out++ = '?'; break;
case ' ': *out++ = '\\'; *out++ = ' '; break;
case '(': *out++ = '\\'; *out++ = '('; break;
case ')': *out++ = '\\'; *out++ = ')'; break;
default:
*out++ = c;
}
}
break;
case node_type::string:
*out++ = '"';
for (const char c : sexp.string) {
switch (c) {
case '\a': *out++ = '\\'; *out++ = 'a'; break;
case '\b': *out++ = '\\'; *out++ = 'b'; break;
case '\f': *out++ = '\\'; *out++ = 'f'; break;
case '"': *out++ = '\\'; *out++ = '"'; break;
default:
*out++ = c;
}
}
*out++ = '"';
break;
default:
throw std::logic_error("Unimplemented case");
}
}
void copy(const node& sexp, std::ostream& os) {
return copy(sexp, std::ostream_iterator<char>(os));
}
std::string to_string(const node& sexp) {
std::ostringstream oss;
std::ostream_iterator<char> it(oss);
copy(sexp, it);
return oss.str();
}
} // namespace
} // namespace
#endif
<|endoftext|>
|
<commit_before>#ifndef BLUETOE_LINK_LAYER_RING_BUFFER_HPP
#define BLUETOE_LINK_LAYER_RING_BUFFER_HPP
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <bluetoe/link_layer/buffer.hpp>
namespace bluetoe {
namespace link_layer {
/**
* @brief structure, able to store variable sized link layer PDUs in a fixed size ring.
*
* The buffer uses the size field of the stored PDUs as pointers
* to the next PDU stored in the buffer.
*
* Elements are inserted at the front and removed from the end. When the ring buffer is empty
* it is quarantied that the buffer can store one elemente of at least ( Size / 2 ) - 1 in size.
*/
template < std::size_t Size >
class pdu_ring_buffer
{
public:
static constexpr std::size_t size = Size;
/**
* @brief sets up the ring to be empty
* @pre next_end().size == 0
* @pre buffer must point to an array of at least Size bytes
*/
explicit pdu_ring_buffer( std::uint8_t* buffer );
/**
* @brief resets the ring to be empty
* @pre next_end().size == 0
* @pre buffer must point to an array of at least Size bytes
*/
void reset( std::uint8_t* buffer );
/**
* @brief return a writeable PDU buffer of at least size bytes at the front of the ring
*
* The function is idempotent and will yield the same results as long as the state of the
* buffer is not changed and the parameters are the same.
*
* If there is not enough room for size bytes in the ring buffer, the function will return an
* empty read_buffer.
*
* @pre size > 2
* @pre buffer must point to an array of at least Size bytes
*/
read_buffer alloc_front( std::uint8_t* buffer, std::size_t size ) const;
/**
* @brief stores the allocated PDU in the ring.
*
* The length field of the PDU must contain the actual size of the PDU - 2.
* Now the stored PDU can be read through the ring.
*
* @pre pdu.size >= pdu.buffer[ 1 ] + 2
* @pre pdu.buffer[ 1 ] != 0
* @post next_end().size != 0
*/
void push_front( std::uint8_t* buffer, const read_buffer& pdu );
/**
* @brief returns the next PDU from the ring.
*
* If no PDU is stored in the ring, the function will return an empty write_buffer.
*/
write_buffer next_end() const;
/**
* @brief frees the last PDU at the end of the ring
*
* @pre next_end().size == 0
*/
void pop_end( std::uint8_t* buffer );
private:
static constexpr std::size_t ll_header_size = 2;
static constexpr std::uint8_t wrap_mark = 0;
template < class P >
static std::uint8_t pdu_length( const P& pdu );
// 1) if end_ == front_, the ring is empty
// end_ and front_ can point to everywhere into the buffer
// 2) if front_ > end_, the all elements are between front_ and end_
// 3) if end_ > front_, -> buffer splited
// there are elements from front_ to the end of the buffer
// and there are elements from the beginning of the buffer till end_
std::uint8_t* end_;
std::uint8_t* front_;
};
template < std::size_t Size >
pdu_ring_buffer< Size >::pdu_ring_buffer( std::uint8_t* buffer )
{
reset( buffer );
}
template < std::size_t Size >
void pdu_ring_buffer< Size >::reset( std::uint8_t* buffer )
{
assert( buffer );
front_ = buffer;
front_[ 1 ] = wrap_mark;
end_ = buffer;
}
template < std::size_t Size >
read_buffer pdu_ring_buffer< Size >::alloc_front( std::uint8_t* buffer, std::size_t size ) const
{
assert( buffer );
assert( size > ll_header_size );
// buffer splited? There must be one byte left to not overflow the ring.
if ( end_ > front_ && size < end_ - front_ )
{
return read_buffer{ front_, size };
}
if ( front_ >= end_ )
{
const std::uint8_t* end_of_buffer = buffer + Size;
// allocate at the end?
if ( size <= end_of_buffer - front_ )
{
return read_buffer{ front_, size };
}
// allocate at the begining? Again, there must be one byte left between the end front_ and the end_
if ( size < end_ - buffer )
{
return read_buffer{ buffer, size };
}
}
return read_buffer{ 0, 0 };
}
template < std::size_t Size >
void pdu_ring_buffer< Size >::push_front( std::uint8_t* buffer, const read_buffer& pdu )
{
assert( pdu.size >= pdu_length( pdu ) );
assert( pdu_length( pdu ) != 0 );
const std::uint8_t* end_of_buffer = buffer + Size;
// set size to 0 to mark force the end_ pointer to wrap here
if ( front_ != pdu.buffer && front_ + 1 < end_of_buffer )
front_[ 1 ] = wrap_mark;
const bool was_empty = front_ == end_;
front_ = pdu.buffer + pdu_length( pdu );
// if the ring was empty, the end_ ptr have to wrap too now
if ( was_empty )
end_ = pdu.buffer;
}
template < std::size_t Size >
write_buffer pdu_ring_buffer< Size >::next_end() const
{
return front_ == end_
? write_buffer{ 0, 0 }
: write_buffer{ end_, end_[ 1 ] + ll_header_size };
}
template < std::size_t Size >
void pdu_ring_buffer< Size >::pop_end( std::uint8_t* buffer )
{
end_ += end_[ 1 ] + ll_header_size;
const std::uint8_t* end_of_buffer = buffer + Size;
// wrap the end_ pointer to the beginning, if the buffer is not empty
if ( end_ != front_ && ( end_ + 1 >= end_of_buffer || end_[ 1 ] == wrap_mark ) )
end_ = buffer;
}
template < std::size_t Size >
template < class P >
std::uint8_t pdu_ring_buffer< Size >::pdu_length( const P& pdu )
{
return pdu.buffer[ 1 ] + ll_header_size;
}
}
}
#endif
<commit_msg>ring can be used for receiving and transmitting<commit_after>#ifndef BLUETOE_LINK_LAYER_RING_BUFFER_HPP
#define BLUETOE_LINK_LAYER_RING_BUFFER_HPP
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <bluetoe/link_layer/buffer.hpp>
namespace bluetoe {
namespace link_layer {
/**
* @brief structure, able to store variable sized link layer PDUs in a fixed size ring.
*
* The buffer uses the size field of the stored PDUs as pointers
* to the next PDU stored in the buffer.
*
* Elements are inserted at the front and removed from the end. When the ring buffer is empty
* it is quarantied that the buffer can store one elemente of at least ( Size / 2 ) - 1 in size.
*/
template < std::size_t Size, typename Buffer = read_buffer >
class pdu_ring_buffer
{
public:
static constexpr std::size_t size = Size;
/**
* @brief sets up the ring to be empty
* @pre next_end().size == 0
* @pre buffer must point to an array of at least Size bytes
*/
explicit pdu_ring_buffer( std::uint8_t* buffer );
/**
* @brief resets the ring to be empty
* @pre next_end().size == 0
* @pre buffer must point to an array of at least Size bytes
*/
void reset( std::uint8_t* buffer );
/**
* @brief return a writeable PDU buffer of at least size bytes at the front of the ring
*
* The function is idempotent and will yield the same results as long as the state of the
* buffer is not changed and the parameters are the same.
*
* If there is not enough room for size bytes in the ring buffer, the function will return an
* empty read_buffer.
*
* @pre size > 2
* @pre buffer must point to an array of at least Size bytes
*/
Buffer alloc_front( std::uint8_t* buffer, std::size_t size ) const;
/**
* @brief stores the allocated PDU in the ring.
*
* The length field of the PDU must contain the actual size of the PDU - 2.
* Now the stored PDU can be read through the ring.
*
* @pre pdu.size >= pdu.buffer[ 1 ] + 2
* @pre pdu.buffer[ 1 ] != 0
* @post next_end().size != 0
*/
void push_front( std::uint8_t* buffer, const Buffer& pdu );
/**
* @brief returns the next PDU from the ring.
*
* If no PDU is stored in the ring, the function will return an empty write_buffer.
*/
Buffer next_end() const;
/**
* @brief frees the last PDU at the end of the ring
*
* @pre next_end().size == 0
*/
void pop_end( std::uint8_t* buffer );
private:
static constexpr std::size_t ll_header_size = 2;
static constexpr std::uint8_t wrap_mark = 0;
template < class P >
static std::uint8_t pdu_length( const P& pdu );
// 1) if end_ == front_, the ring is empty
// end_ and front_ can point to everywhere into the buffer
// 2) if front_ > end_, the all elements are between front_ and end_
// 3) if end_ > front_, -> buffer splited
// there are elements from front_ to the end of the buffer
// and there are elements from the beginning of the buffer till end_
std::uint8_t* end_;
std::uint8_t* front_;
};
template < std::size_t Size, typename Buffer >
pdu_ring_buffer< Size, Buffer >::pdu_ring_buffer( std::uint8_t* buffer )
{
reset( buffer );
}
template < std::size_t Size, typename Buffer >
void pdu_ring_buffer< Size, Buffer >::reset( std::uint8_t* buffer )
{
assert( buffer );
front_ = buffer;
front_[ 1 ] = wrap_mark;
end_ = buffer;
}
template < std::size_t Size, typename Buffer >
Buffer pdu_ring_buffer< Size, Buffer >::alloc_front( std::uint8_t* buffer, std::size_t size ) const
{
assert( buffer );
assert( size > ll_header_size );
// buffer splited? There must be one byte left to not overflow the ring.
if ( end_ > front_ && size < end_ - front_ )
{
return Buffer{ front_, size };
}
if ( front_ >= end_ )
{
const std::uint8_t* end_of_buffer = buffer + Size;
// allocate at the end?
if ( size <= end_of_buffer - front_ )
{
return Buffer{ front_, size };
}
// allocate at the begining? Again, there must be one byte left between the end front_ and the end_
if ( size < end_ - buffer )
{
return Buffer{ buffer, size };
}
}
return Buffer{ 0, 0 };
}
template < std::size_t Size, typename Buffer >
void pdu_ring_buffer< Size, Buffer >::push_front( std::uint8_t* buffer, const Buffer& pdu )
{
assert( pdu.size >= pdu_length( pdu ) );
assert( pdu_length( pdu ) != 0 );
const std::uint8_t* end_of_buffer = buffer + Size;
// set size to 0 to mark force the end_ pointer to wrap here
if ( front_ != pdu.buffer && front_ + 1 < end_of_buffer )
front_[ 1 ] = wrap_mark;
const bool was_empty = front_ == end_;
front_ = pdu.buffer + pdu_length( pdu );
// if the ring was empty, the end_ ptr have to wrap too now
if ( was_empty )
end_ = pdu.buffer;
}
template < std::size_t Size, typename Buffer >
Buffer pdu_ring_buffer< Size, Buffer >::next_end() const
{
return front_ == end_
? Buffer{ 0, 0 }
: Buffer{ end_, end_[ 1 ] + ll_header_size };
}
template < std::size_t Size, typename Buffer >
void pdu_ring_buffer< Size, Buffer >::pop_end( std::uint8_t* buffer )
{
end_ += end_[ 1 ] + ll_header_size;
const std::uint8_t* end_of_buffer = buffer + Size;
// wrap the end_ pointer to the beginning, if the buffer is not empty
if ( end_ != front_ && ( end_ + 1 >= end_of_buffer || end_[ 1 ] == wrap_mark ) )
end_ = buffer;
}
template < std::size_t Size, typename Buffer >
template < class P >
std::uint8_t pdu_ring_buffer< Size, Buffer >::pdu_length( const P& pdu )
{
return pdu.buffer[ 1 ] + ll_header_size;
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include <engine/engine.h>
#include <engine/resource_manager.h>
#include <foundation/array.h>
#include <foundation/malloc_allocator.h>
#include <foundation/memory.h>
#include <opengl_renderer/opengl_context_windows.h>
#include <opengl_renderer/opengl_renderer.h>
#include <os/windows/callstack_capturer.h>
#include <os/windows/window.h>
#include <renderer/renderer.h>
using namespace bowtie;
namespace
{
Engine* s_engine;
Renderer* s_renderer;
OpenGLContextWindows* s_context;
Allocator* s_allocator;
}
void create_render_context_callback(HWND hwnd, const Vector2u& resolution)
{
s_context->create(hwnd);
renderer::run(*s_renderer, s_context, resolution);
}
void window_resized_callback(const Vector2u& resolution)
{
engine::resize(*s_engine, resolution);
}
void key_down_callback(keyboard::Key key)
{
engine::key_pressed(*s_engine, key);
}
void key_up_callback(keyboard::Key key)
{
engine::key_released(*s_engine, key);
}
int WINAPI WinMain(__in HINSTANCE instance, __in_opt HINSTANCE, __in_opt LPSTR, __in int)
{
auto callstack_capturer = callstack_capturer::create();
auto& allocator = *(new MallocAllocator());
memory::init_allocator(allocator, "default allocator", &callstack_capturer);
s_allocator = &allocator;
auto& renderer_allocator = *(new MallocAllocator());
memory::init_allocator(renderer_allocator, "renederer allocator", &callstack_capturer);
{
ConcreteRenderer opengl_renderer = opengl_renderer::create();
Renderer renderer;
renderer::init(renderer, opengl_renderer, renderer_allocator, allocator);
s_renderer = &renderer;
OpenGLContextWindows context;
s_context = &context;
auto& render_interface = renderer.render_interface;
{
Engine engine;
engine::init(engine, allocator, render_interface);
s_engine = &engine;
auto resolution = Vector2u(1280, 720);
Window window;
window::init(window, instance, resolution, &create_render_context_callback, &window_resized_callback, &key_down_callback, &key_up_callback);
while(window.is_open)
{
window::dispatch_messages(window);
engine::update(engine);
renderer::deallocate_processed_commands(renderer, allocator);
}
engine::deinit(engine);
}
renderer::stop(renderer, allocator);
renderer::deinit(renderer);
}
memory::deinit_allocator(renderer_allocator);
memory::deinit_allocator(allocator);
}
<commit_msg>Proper zeroing.<commit_after>#include <engine/engine.h>
#include <engine/resource_manager.h>
#include <foundation/array.h>
#include <foundation/malloc_allocator.h>
#include <foundation/memory.h>
#include <opengl_renderer/opengl_context_windows.h>
#include <opengl_renderer/opengl_renderer.h>
#include <os/windows/callstack_capturer.h>
#include <os/windows/window.h>
#include <renderer/renderer.h>
using namespace bowtie;
namespace
{
Engine* s_engine;
Renderer* s_renderer;
OpenGLContextWindows* s_context;
Allocator* s_allocator;
}
void create_render_context_callback(HWND hwnd, const Vector2u& resolution)
{
s_context->create(hwnd);
renderer::run(*s_renderer, s_context, resolution);
}
void window_resized_callback(const Vector2u& resolution)
{
engine::resize(*s_engine, resolution);
}
void key_down_callback(keyboard::Key key)
{
engine::key_pressed(*s_engine, key);
}
void key_up_callback(keyboard::Key key)
{
engine::key_released(*s_engine, key);
}
int WINAPI WinMain(__in HINSTANCE instance, __in_opt HINSTANCE, __in_opt LPSTR, __in int)
{
auto callstack_capturer = callstack_capturer::create();
auto& allocator = *(new MallocAllocator());
memory::init_allocator(allocator, "default allocator", &callstack_capturer);
s_allocator = &allocator;
auto& renderer_allocator = *(new MallocAllocator());
memory::init_allocator(renderer_allocator, "renederer allocator", &callstack_capturer);
{
ConcreteRenderer opengl_renderer = opengl_renderer::create();
Renderer renderer;
renderer::init(renderer, opengl_renderer, renderer_allocator, allocator);
s_renderer = &renderer;
OpenGLContextWindows context;
s_context = &context;
auto& render_interface = renderer.render_interface;
{
Engine engine = {0};
engine::init(engine, allocator, render_interface);
s_engine = &engine;
auto resolution = Vector2u(1280, 720);
Window window = {0};
window::init(window, instance, resolution, &create_render_context_callback, &window_resized_callback, &key_down_callback, &key_up_callback);
while(window.is_open)
{
window::dispatch_messages(window);
engine::update(engine);
renderer::deallocate_processed_commands(renderer, allocator);
}
engine::deinit(engine);
}
renderer::stop(renderer, allocator);
renderer::deinit(renderer);
}
memory::deinit_allocator(renderer_allocator);
memory::deinit_allocator(allocator);
}
<|endoftext|>
|
<commit_before>//
// Created by Seth on 8/2/17.
//
#include <iostream>
#include "yanda.hpp"
//// Simplify with typedefs as needed ////
using Array4D = yanda::NDimensionalArray<int, 4>;
using Array3D = yanda::NDimensionalArray<int, 3>;
using Array2D = yanda::NDimensionalArray<int, 2>;
using Idx = Array4D::Index;
int main()
{
//// 4D Array ////
// Equal to int[4][3][2][1]
Array4D::Extent size4{5, 4, 3, 2};
Array4D array4(size4);
// Assignment
array4({4, 3, 2, 1}) = 18;
// Retrieval
int val = array4({4, 3, 2, 1});
//// 3D array ////
// Initialize the Extents with a list
Array3D array3({4, 3, 2});
// Expand the array
array3.setExtents({4, 4, 4});
// Fill the array
for (Idx z = 0; z < array3.extents()[0]; z++) {
for (Idx y = 0; y < array3.extents()[1]; y++) {
for (Idx x = 0; x < array3.extents()[2]; x++) {
array3({z, y, x}) = val++;
}
}
}
yanda::Print(array3);
//// 2D array ////
// Get 2D array by slicing the 3D array
Array2D array2 = array3.slice(2);
yanda::Print(array2);
// Get raw data
std::vector<int> data = array2.data();
// Make new array from raw data
Array2D array2_2({8, 2}, data.begin(), data.end());
yanda::Print(array2_2);
// Try to make bad array
try {
Array2D array2_3({5, 3}, data.begin(), data.end());
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
}<commit_msg>Update Usage.cpp<commit_after>//
// Created by Seth on 8/2/17.
//
#include <iostream>
#include "yanda.hpp"
//// Simplify with typedefs as needed ////
using Array4D = yanda::NDimensionalArray<int, 4>;
using Array3D = yanda::NDimensionalArray<int, 3>;
using Array2D = yanda::NDimensionalArray<int, 2>;
using Idx = Array4D::Index;
int main()
{
//// 4D Array ////
// Equal to int[5][4][3][2]
Array4D::Extent size4{5, 4, 3, 2};
Array4D array4(size4);
// Assignment
array4({4, 3, 2, 1}) = 18;
// Retrieval
int val = array4({4, 3, 2, 1});
//// 3D array ////
// Initialize the Extents with a list
Array3D array3({4, 3, 2});
// Expand the array
array3.setExtents({4, 4, 4});
// Fill the array
for (Idx z = 0; z < array3.extents()[0]; z++) {
for (Idx y = 0; y < array3.extents()[1]; y++) {
for (Idx x = 0; x < array3.extents()[2]; x++) {
array3({z, y, x}) = val++;
}
}
}
yanda::Print(array3);
// Be careful to include all of dimensions when accessing an element
// This results in a compiler error
// val = array3({3,3,3,3});
// Does not result in compiler error. Returns array3({3,3,0})
val = array3({3,3});
//// 2D array ////
// Get 2D array by slicing the 3D array
Array2D array2 = array3.slice(2);
yanda::Print(array2);
// Get raw data
std::vector<int> data = array2.data();
// Make new array from raw data
Array2D array2_2({8, 2}, data.begin(), data.end());
yanda::Print(array2_2);
// Try to make bad array
try {
Array2D array2_3({5, 3}, data.begin(), data.end());
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "./fuzztest/internal/runtime.h"
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <csignal>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "./fuzztest/internal/io.h"
#include "./fuzztest/internal/logging.h"
#include "./fuzztest/internal/type_support.h"
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif
namespace fuzztest::internal {
RunMode run_mode = RunMode::kUnitTest;
ABSL_CONST_INIT absl::Duration fuzz_time_limit = absl::InfiniteDuration();
std::atomic<bool> external_failure_was_detected;
std::atomic<bool> termination_requested;
OnFailure on_failure;
void (*crash_handler_hook)();
void OnFailure::DumpReproducer(std::string_view outdir) const {
const std::string filename =
WriteDataToDir(current_args_.Visit(ArgumentSerializeVisitor{}), outdir);
if (filename.empty()) {
absl::FPrintF(GetStderr(), "[!] Failed to write reproducer file.\n");
} else {
absl::FPrintF(GetStderr(), "[*] Reproducer file written to: %s\n",
filename);
}
}
void OnFailure::PrintFinalStats(absl::FormatRawSink out) const {
const std::string separator = '\n' + std::string(65, '=') + '\n';
absl::Format(out, "%s=== Fuzzing stats\n\n", separator);
const absl::Duration fuzzing_time = clock_fn_() - stats_->start_time;
absl::Format(out, "Elapsed seconds (ns): %d\n",
absl::ToInt64Nanoseconds(fuzzing_time));
absl::Format(out, "Total runs: %d\n", stats_->runs);
absl::Format(out, "Edges covered: %d\n", stats_->edges_covered);
absl::Format(out, "Total edges: %d\n", stats_->total_edges);
absl::Format(out, "Corpus size: %d\n", stats_->useful_inputs);
}
void OnFailure::PrintReport(absl::FormatRawSink out) const {
// We don't want to try and print a fuzz report when we are not running a fuzz
// test, even if we got a crash.
if (!enabled_) return;
if (crash_handler_hook) crash_handler_hook();
// First, lets try to dump the reproducer if requested.
if (current_args_.has_value()) {
const char* outdir = getenv("FUZZTEST_REPRODUCERS_OUT_DIR");
if (outdir != nullptr && outdir[0]) {
DumpReproducer(outdir);
}
}
if (run_mode != RunMode::kUnitTest) {
PrintFinalStats(out);
}
const std::string separator = '\n' + std::string(65, '=') + '\n';
if (current_args_.has_value()) {
absl::Format(out, "%s=== BUG FOUND!\n\n", separator);
absl::Format(out, "%s:%d: Counterexample found for %s.%s.\n", test_->file(),
test_->line(), test_->suite_name(), test_->test_name());
absl::Format(out, "The test fails with input:\n");
for (size_t i = 0; i < num_args_; ++i) {
absl::Format(out, "argument %d: ", i);
current_args_.Visit(ArgumentPrintVisitor{}, out, i,
PrintMode::kHumanReadable);
absl::Format(out, "\n");
}
// There doesn't seem to be a good way to generate a reproducer test when
// the test uses a fixture (see b/241271658).
if (!test_->uses_fixture()) {
absl::Format(out, "%s=== Reproducer test\n\n", separator);
absl::Format(out, "TEST(%1$s, %2$sRegression) {\n %2$s(\n",
test_->suite_name(), test_->test_name());
for (size_t i = 0; i < num_args_; ++i) {
if (i != 0) absl::Format(out, ",\n");
absl::Format(out, " ");
current_args_.Visit(ArgumentPrintVisitor{}, out, i,
PrintMode::kSourceCode);
}
absl::Format(out, "\n );\n");
absl::Format(out, "}\n");
}
} else {
absl::Format(out, "%s=== SETUP FAILURE!\n\n", separator);
absl::Format(out, "%s:%d: There was a problem with %s.%s.", test_->file(),
test_->line(), test_->suite_name(), test_->test_name());
if (test_abort_message != nullptr) {
absl::Format(out, "%s", *test_abort_message);
}
}
absl::Format(out, "%s", separator);
}
#if defined(__linux__)
struct OldSignalHandler {
int signum;
struct sigaction action;
};
static FILE* signal_out;
struct FILESink {
friend void AbslFormatFlush(FILESink*, absl::string_view v) {
fprintf(signal_out, "%.*s", static_cast<int>(v.size()), v.data());
fflush(signal_out);
}
};
static FILESink signal_out_sink;
static OldSignalHandler crash_handlers[] = {{SIGILL}, {SIGFPE}, {SIGSEGV},
{SIGBUS}, {SIGTRAP}, {SIGABRT}};
static OldSignalHandler termination_handlers[] = {
{SIGHUP}, {SIGINT}, {SIGTERM}};
static void HandleCrash(int signum, siginfo_t* info, void* ucontext) {
// Dump our info first.
on_failure.PrintReport(&signal_out_sink);
// The old signal handler might print important messages (e.g., strack trace)
// to the original file descriptors,
// therefore we restore them before calling them.
if (IsSilenceTargetEnabled()) RestoreTargetStdoutAndStderr();
// Find the old signal handler, if available, and call it.
auto it =
std::find_if(std::begin(crash_handlers), std::end(crash_handlers),
[signum](const auto& h) { return h.signum == signum; });
if (it != std::end(crash_handlers) && it->action.sa_sigaction != nullptr) {
it->action.sa_sigaction(signum, info, ucontext);
}
}
static void HandleTermination(int, siginfo_t*, void*) {
termination_requested.store(true, std::memory_order_relaxed);
}
static void SetNewSigAction(int signum, void (*handler)(int, siginfo_t*, void*),
struct sigaction* old_sigact) {
struct sigaction new_sigact = {};
sigemptyset(&new_sigact.sa_mask);
new_sigact.sa_sigaction = handler;
new_sigact.sa_flags = SA_SIGINFO;
if (sigaction(signum, &new_sigact, old_sigact) == -1) {
fprintf(GetStderr(), "Error installing signal handler: %s\n",
strerror(errno));
exit(1);
}
}
void InstallSignalHandlers(FILE* out) {
if (signal_out != nullptr) {
// Already installed. Noop.
return;
}
signal_out = out;
#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER)
// An ASan failure might come without a signal.
// Eg a divide by zero is intercepted by ASan and it terminates the process
// after printing its output. This handler helps us print our output
// afterwards.
__sanitizer_set_death_callback(
[](auto...) { on_failure.PrintReport(&signal_out_sink); });
#endif
for (OldSignalHandler& h : crash_handlers) {
SetNewSigAction(h.signum, &HandleCrash, &h.action);
}
for (OldSignalHandler& h : termination_handlers) {
SetNewSigAction(h.signum, &HandleTermination, nullptr);
}
}
void OnFailure::PrintFinalStatsOnDefaultSink() const {
PrintFinalStats(&signal_out_sink);
}
void OnFailure::PrintReportOnDefaultSink() const {
PrintReport(&signal_out_sink);
}
#else // __linux__
// TODO(sbenzaquen): We should still install signal handlers in other systems.
void InstallSignalHandlers(FILE* out) {}
void OnFailure::PrintFinalStatsOnDefaultSink() const {}
void OnFailure::PrintReportOnDefaultSink() const {}
#endif // __linux__
} // namespace fuzztest::internal
<commit_msg>FuzzTest: make use of SA_ONSTACK flag for signal handlers<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "./fuzztest/internal/runtime.h"
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <csignal>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "./fuzztest/internal/io.h"
#include "./fuzztest/internal/logging.h"
#include "./fuzztest/internal/type_support.h"
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif
namespace fuzztest::internal {
RunMode run_mode = RunMode::kUnitTest;
ABSL_CONST_INIT absl::Duration fuzz_time_limit = absl::InfiniteDuration();
std::atomic<bool> external_failure_was_detected;
std::atomic<bool> termination_requested;
OnFailure on_failure;
void (*crash_handler_hook)();
void OnFailure::DumpReproducer(std::string_view outdir) const {
const std::string filename =
WriteDataToDir(current_args_.Visit(ArgumentSerializeVisitor{}), outdir);
if (filename.empty()) {
absl::FPrintF(GetStderr(), "[!] Failed to write reproducer file.\n");
} else {
absl::FPrintF(GetStderr(), "[*] Reproducer file written to: %s\n",
filename);
}
}
void OnFailure::PrintFinalStats(absl::FormatRawSink out) const {
const std::string separator = '\n' + std::string(65, '=') + '\n';
absl::Format(out, "%s=== Fuzzing stats\n\n", separator);
const absl::Duration fuzzing_time = clock_fn_() - stats_->start_time;
absl::Format(out, "Elapsed seconds (ns): %d\n",
absl::ToInt64Nanoseconds(fuzzing_time));
absl::Format(out, "Total runs: %d\n", stats_->runs);
absl::Format(out, "Edges covered: %d\n", stats_->edges_covered);
absl::Format(out, "Total edges: %d\n", stats_->total_edges);
absl::Format(out, "Corpus size: %d\n", stats_->useful_inputs);
}
void OnFailure::PrintReport(absl::FormatRawSink out) const {
// We don't want to try and print a fuzz report when we are not running a fuzz
// test, even if we got a crash.
if (!enabled_) return;
if (crash_handler_hook) crash_handler_hook();
// First, lets try to dump the reproducer if requested.
if (current_args_.has_value()) {
const char* outdir = getenv("FUZZTEST_REPRODUCERS_OUT_DIR");
if (outdir != nullptr && outdir[0]) {
DumpReproducer(outdir);
}
}
if (run_mode != RunMode::kUnitTest) {
PrintFinalStats(out);
}
const std::string separator = '\n' + std::string(65, '=') + '\n';
if (current_args_.has_value()) {
absl::Format(out, "%s=== BUG FOUND!\n\n", separator);
absl::Format(out, "%s:%d: Counterexample found for %s.%s.\n", test_->file(),
test_->line(), test_->suite_name(), test_->test_name());
absl::Format(out, "The test fails with input:\n");
for (size_t i = 0; i < num_args_; ++i) {
absl::Format(out, "argument %d: ", i);
current_args_.Visit(ArgumentPrintVisitor{}, out, i,
PrintMode::kHumanReadable);
absl::Format(out, "\n");
}
// There doesn't seem to be a good way to generate a reproducer test when
// the test uses a fixture (see b/241271658).
if (!test_->uses_fixture()) {
absl::Format(out, "%s=== Reproducer test\n\n", separator);
absl::Format(out, "TEST(%1$s, %2$sRegression) {\n %2$s(\n",
test_->suite_name(), test_->test_name());
for (size_t i = 0; i < num_args_; ++i) {
if (i != 0) absl::Format(out, ",\n");
absl::Format(out, " ");
current_args_.Visit(ArgumentPrintVisitor{}, out, i,
PrintMode::kSourceCode);
}
absl::Format(out, "\n );\n");
absl::Format(out, "}\n");
}
} else {
absl::Format(out, "%s=== SETUP FAILURE!\n\n", separator);
absl::Format(out, "%s:%d: There was a problem with %s.%s.", test_->file(),
test_->line(), test_->suite_name(), test_->test_name());
if (test_abort_message != nullptr) {
absl::Format(out, "%s", *test_abort_message);
}
}
absl::Format(out, "%s", separator);
}
#if defined(__linux__)
struct OldSignalHandler {
int signum;
struct sigaction action;
};
static FILE* signal_out;
struct FILESink {
friend void AbslFormatFlush(FILESink*, absl::string_view v) {
fprintf(signal_out, "%.*s", static_cast<int>(v.size()), v.data());
fflush(signal_out);
}
};
static FILESink signal_out_sink;
static OldSignalHandler crash_handlers[] = {{SIGILL}, {SIGFPE}, {SIGSEGV},
{SIGBUS}, {SIGTRAP}, {SIGABRT}};
static OldSignalHandler termination_handlers[] = {
{SIGHUP}, {SIGINT}, {SIGTERM}};
static void HandleCrash(int signum, siginfo_t* info, void* ucontext) {
// Dump our info first.
on_failure.PrintReport(&signal_out_sink);
// The old signal handler might print important messages (e.g., strack trace)
// to the original file descriptors,
// therefore we restore them before calling them.
if (IsSilenceTargetEnabled()) RestoreTargetStdoutAndStderr();
// Find the old signal handler, if available, and call it.
auto it =
std::find_if(std::begin(crash_handlers), std::end(crash_handlers),
[signum](const auto& h) { return h.signum == signum; });
if (it != std::end(crash_handlers) && it->action.sa_sigaction != nullptr) {
it->action.sa_sigaction(signum, info, ucontext);
}
}
static void HandleTermination(int, siginfo_t*, void*) {
termination_requested.store(true, std::memory_order_relaxed);
}
static void SetNewSigAction(int signum, void (*handler)(int, siginfo_t*, void*),
struct sigaction* old_sigact) {
struct sigaction new_sigact = {};
sigemptyset(&new_sigact.sa_mask);
new_sigact.sa_sigaction = handler;
// We make use of the SA_ONSTACK flag so that signal handlers are executed on
// a separate stack. This is needed to properly handle cases where stack space
// is limited and the delivery of a signal needs to be properly handled.
new_sigact.sa_flags = SA_SIGINFO | SA_ONSTACK;
if (sigaction(signum, &new_sigact, old_sigact) == -1) {
fprintf(GetStderr(), "Error installing signal handler: %s\n",
strerror(errno));
exit(1);
}
}
void InstallSignalHandlers(FILE* out) {
if (signal_out != nullptr) {
// Already installed. Noop.
return;
}
signal_out = out;
#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER)
// An ASan failure might come without a signal.
// Eg a divide by zero is intercepted by ASan and it terminates the process
// after printing its output. This handler helps us print our output
// afterwards.
__sanitizer_set_death_callback(
[](auto...) { on_failure.PrintReport(&signal_out_sink); });
#endif
for (OldSignalHandler& h : crash_handlers) {
SetNewSigAction(h.signum, &HandleCrash, &h.action);
}
for (OldSignalHandler& h : termination_handlers) {
SetNewSigAction(h.signum, &HandleTermination, nullptr);
}
}
void OnFailure::PrintFinalStatsOnDefaultSink() const {
PrintFinalStats(&signal_out_sink);
}
void OnFailure::PrintReportOnDefaultSink() const {
PrintReport(&signal_out_sink);
}
#else // __linux__
// TODO(sbenzaquen): We should still install signal handlers in other systems.
void InstallSignalHandlers(FILE* out) {}
void OnFailure::PrintFinalStatsOnDefaultSink() const {}
void OnFailure::PrintReportOnDefaultSink() const {}
#endif // __linux__
} // namespace fuzztest::internal
<|endoftext|>
|
<commit_before>// Copyright Hugh Perkins 2016
// 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 "handle_branching.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
using namespace llvm;
namespace cocl {
// a Block has one or more links to child blocks
// a Block can be linked to by one or more blocks
// we probably need a root block, which holds the others
static int nextId = 0;
class Block {
public:
int id;
Block() {
this->id = nextId;
nextId++;
}
virtual string blockType() const {
return "Block";
}
virtual void dump(set<const Block *> &seen, string indent = "") const = 0;
vector<Block *>incoming;
virtual void replaceChild(Block *oldChild, Block *newChild) = 0;
};
class RootBlock : public Block {
public:
Block *first = 0;
virtual string blockType() const {
return "RootBlock";
}
virtual void dump(set<const Block *> &seen, string indent = "") const {
seen.insert(this);
cout << indent << "RootBlock " << this->id << endl;
if(seen.find(first) == seen.end()) {
first->dump(seen, indent + " ");
}
}
void replaceChild(Block *oldChild, Block *newChild) {
assert(first == oldChild);
first = newChild;
}
};
class If : public Block {
public:
Value *condition = 0;
Block *trueBlock = 0;
Block *falseBlock = 0;
virtual string blockType() const {
return "If";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "If " << this->id << endl;
cout << indent << " True:" << endl;
if(seen.find(trueBlock) == seen.end()) {
trueBlock->dump(seen, indent + " ");
} else {
cout << indent << " (*" << trueBlock->id << endl;
}
if(falseBlock != 0) {
cout << indent << " False:" << endl;
if(seen.find(falseBlock) == seen.end()) {
falseBlock->dump(seen, indent + " ");
} else {
cout << indent << " (*" << falseBlock->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(trueBlock == oldChild) {
trueBlock = newChild;
return;
}
if(falseBlock == oldChild) {
falseBlock = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class ConditionalBranch : public Block {
public:
Value *condition = 0;
Block *trueNext = 0;
Block *falseNext = 0;
virtual string blockType() const {
return "ConditionalBranch";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "ConditionalBranch " << this->id << endl;
cout << indent << " True:" << endl;
if(seen.find(trueNext) == seen.end()) {
trueNext->dump(seen, indent + " ");
} else {
cout << indent << " (*" << trueNext->id << endl;
}
if(falseNext != 0) {
cout << indent << " False:" << endl;
if(seen.find(falseNext) == seen.end()) {
falseNext->dump(seen, indent + " ");
} else {
cout << indent << " (*" << falseNext->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(trueNext == oldChild) {
trueNext = newChild;
return;
}
if(falseNext == oldChild) {
falseNext = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class BasicBlockBlock : public Block {
public:
BasicBlock *basicBlock = 0;
vector<Value *> instructions;
Block *next; // initially will probalby point to a Branch block
virtual string blockType() const {
return "BasicBlockBlock";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "BasicBlockBlock " << this->id << endl;
if(next == 0) {
return;
}
if(seen.find(next) == seen.end()) {
next->dump(seen, indent);
} else {
cout << indent << " (*" << next->id << endl;
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(next == oldChild) {
next = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class Sequence : public Block {
public:
vector<Block *> children;
virtual string blockType() const {
return "Sequence";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "Sequence " << this->id << endl;
for(auto it = children.begin(); it != children.end(); it++) {
Block *child = *it;
if(seen.find(child) == seen.end()) {
child->dump(seen, indent + " ");
} else {
cout << indent << " (*" << child->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
int i = 0;
bool foundChild = false;
for(auto it = children.begin(); it != children.end(); it++) {
Block *child = *it;
if(child == oldChild) {
foundChild = true;
break;
}
i++;
}
if(foundChild) {
children[i] = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class ReturnBlock : public Block {
public:
virtual string blockType() const {
return "ReturnBlock";
}
virtual void dump(set<const Block *> &seen, string indent) const {
cout << indent << "ReturnBlock " << this->id << endl;
}
void replaceChild(Block *oldChild, Block *newChild) {
throw runtime_error("couldnt find old child");
}
};
vector<unique_ptr<Block> > blocks; // doesnt include the root. I guess. ???
map<BasicBlock *, Block *> blockByBasicBlock;
// void dumpBlock(Block *block) {
// cout << "dumping block" << endl;
// block->dump();
// }
void mergeSequences(Block *root) {
// basically we look for any block with one single incoming, and that incoming is a basicblockblock
bool didAMerge = true;
while(didAMerge) {
didAMerge = false;
for(auto it = blocks.begin(); it != blocks.end(); it++) {
Block *block = it->get();
if(block->incoming.size() == 1) {
// cout << "block " << block->id << " has only one incoming" << endl;
Block *parent = block->incoming[0];
if(BasicBlockBlock *parentBlockBlock = dynamic_cast<BasicBlockBlock*>(parent)) {
// cout << "its a blockblock" << endl;
if(BasicBlockBlock *thisBlockBlock = dynamic_cast<BasicBlockBlock*>(block)) {
// so merge...
cout << "merging ... " << block->id << ", " << parent->id << endl;
unique_ptr<Sequence> sequence(new Sequence());
sequence->children.push_back(parent);
sequence->children.push_back(block);
for(auto parentincit = parent->incoming.begin(); parentincit != parent->incoming.end(); parentincit++) {
Block *parentinc = *parentincit;
sequence->incoming.push_back(parentinc);
parentinc->replaceChild(parent, sequence.get());
}
parent->incoming.clear();
parent->incoming.push_back(sequence.get());
parentBlockBlock->next = 0;
block->incoming.clear();
block->incoming.push_back(sequence.get());
thisBlockBlock->next = 0;
blocks.push_back(std::move(sequence));
didAMerge = true;
}
} else {
// cout << "but not a basicblockblock" << endl;
}
}
}
}
}
void handle_branching_simplify(Function *F) {
cout << "simplify " << string(F->getName()) << endl;
unique_ptr<RootBlock> root(new RootBlock());
for(auto it=F->begin(); it != F->end(); it++) {
cout << "block" << endl;
BasicBlock *basicBlock = &*it;
unique_ptr<BasicBlockBlock> block(new BasicBlockBlock());
block->basicBlock = basicBlock;
for(auto instit=basicBlock->begin(); instit != basicBlock->end(); instit++) {
Instruction *inst = &*instit;
// skip branches, phis and so on, which we'll handle later, somehow...
if(isa<BranchInst>(inst)) {
continue;
}
if(isa<PHINode>(inst)) {
continue;
}
if(isa<ReturnInst>(inst)) {
continue;
}
block->instructions.push_back(inst);
}
blockByBasicBlock[basicBlock] = block.get();
blocks.push_back(std::move(block));
}
root->first = blockByBasicBlock[&F->getEntryBlock()];
root->first->incoming.push_back(root.get());
// go through, and start linking stuff togehter, now that we have a map from basic block to block
for(auto it=F->begin(); it != F->end(); it++) {
BasicBlock *basicBlock = &*it;
BasicBlockBlock *block = dynamic_cast<BasicBlockBlock *>(blockByBasicBlock[basicBlock]);
// I think that each block has to end initially either with a branch or a return?
Instruction *lastInst = basicBlock->getTerminator();
cout << "lastinst:" << endl;
lastInst->dump();
cout << endl;
if(isa<ReturnInst>(lastInst)) {
cout << "finishes in ret" << endl;
unique_ptr<ReturnBlock> retBlock(new ReturnBlock());
block->next = retBlock.get();
block->next->incoming.push_back(block);
blocks.push_back(std::move(retBlock));
} else if(BranchInst* branchInst = dyn_cast<BranchInst>(lastInst)) {
cout << "its a branch" << endl;
// if its unconditional, we just link directly to the next block
// otherwise we link to a ConditionalBranch block
if(branchInst->isUnconditional()) {
cout << "unconditonal branch" << endl;
BasicBlock *next = branchInst->getSuccessor(0);
Block *nextBlock = blockByBasicBlock[next];
block->next = nextBlock;
block->next->incoming.push_back(block);
} else {
// conditional
// create a ConditionalBranch block
cout << "conditonal branch" << endl;
unique_ptr<ConditionalBranch> conditionalBranch(new ConditionalBranch());
BasicBlock *trueBasicBlock = branchInst->getSuccessor(0);
Block *trueBlock = blockByBasicBlock[trueBasicBlock];
conditionalBranch->trueNext = trueBlock;
conditionalBranch->trueNext->incoming.push_back(conditionalBranch.get());
conditionalBranch->falseNext = 0;
if(branchInst->getNumSuccessors() == 2) {
BasicBlock *falseBasicBlock = branchInst->getSuccessor(1);
Block *falseBlock = blockByBasicBlock[falseBasicBlock];
conditionalBranch->falseNext = falseBlock;
conditionalBranch->falseNext->incoming.push_back(conditionalBranch.get());
}
block->next = conditionalBranch.get();
block->next->incoming.push_back(block);
blocks.push_back(std::move(conditionalBranch));
}
} else {
cout << "hmmm, how did we get here???" << endl;
cout << "lastinst:" << endl;
lastInst->dump();
cout << endl;
throw runtime_error("dont know how we got here...");
}
}
set<const Block *>seen;
root->dump(seen, "");
mergeSequences(root.get());
seen.clear();
root->dump(seen, "");
}
}
<commit_msg>sequence moderately more correct now<commit_after>// Copyright Hugh Perkins 2016
// 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 "handle_branching.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
using namespace llvm;
namespace cocl {
// a Block has one or more links to child blocks
// a Block can be linked to by one or more blocks
// we probably need a root block, which holds the others
static int nextId = 0;
class Block {
public:
int id;
Block() {
this->id = nextId;
nextId++;
}
virtual string blockType() const {
return "Block";
}
virtual void dump(set<const Block *> &seen, string indent = "") const = 0;
vector<Block *>incoming;
virtual void replaceChild(Block *oldChild, Block *newChild) = 0;
};
class RootBlock : public Block {
public:
Block *first = 0;
virtual string blockType() const {
return "RootBlock";
}
virtual void dump(set<const Block *> &seen, string indent = "") const {
seen.insert(this);
cout << indent << "RootBlock " << this->id << endl;
if(seen.find(first) == seen.end()) {
first->dump(seen, indent + " ");
}
}
void replaceChild(Block *oldChild, Block *newChild) {
assert(first == oldChild);
first = newChild;
}
};
class If : public Block {
public:
Value *condition = 0;
Block *trueBlock = 0;
Block *falseBlock = 0;
virtual string blockType() const {
return "If";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "If " << this->id << endl;
cout << indent << " True:" << endl;
if(seen.find(trueBlock) == seen.end()) {
trueBlock->dump(seen, indent + " ");
} else {
cout << indent << " (*" << trueBlock->id << endl;
}
if(falseBlock != 0) {
cout << indent << " False:" << endl;
if(seen.find(falseBlock) == seen.end()) {
falseBlock->dump(seen, indent + " ");
} else {
cout << indent << " (*" << falseBlock->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(trueBlock == oldChild) {
trueBlock = newChild;
return;
}
if(falseBlock == oldChild) {
falseBlock = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class ConditionalBranch : public Block {
public:
Value *condition = 0;
Block *trueNext = 0;
Block *falseNext = 0;
virtual string blockType() const {
return "ConditionalBranch";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "ConditionalBranch " << this->id << endl;
cout << indent << " True:" << endl;
if(seen.find(trueNext) == seen.end()) {
trueNext->dump(seen, indent + " ");
} else {
cout << indent << " (*" << trueNext->id << endl;
}
if(falseNext != 0) {
cout << indent << " False:" << endl;
if(seen.find(falseNext) == seen.end()) {
falseNext->dump(seen, indent + " ");
} else {
cout << indent << " (*" << falseNext->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(trueNext == oldChild) {
trueNext = newChild;
return;
}
if(falseNext == oldChild) {
falseNext = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class BasicBlockBlock : public Block {
public:
BasicBlock *basicBlock = 0;
vector<Value *> instructions;
Block *next; // initially will probalby point to a Branch block
virtual string blockType() const {
return "BasicBlockBlock";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "BasicBlockBlock " << this->id << endl;
if(next == 0) {
return;
}
if(seen.find(next) == seen.end()) {
next->dump(seen, indent);
} else {
cout << indent << "(*" << next->id << endl;
}
}
void replaceChild(Block *oldChild, Block *newChild) {
if(next == oldChild) {
next = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class Sequence : public Block {
public:
vector<Block *> children;
Block *next = 0;
virtual string blockType() const {
return "Sequence";
}
virtual void dump(set<const Block *> &seen, string indent) const {
seen.insert(this);
cout << indent << "Sequence " << this->id << endl;
for(auto it = children.begin(); it != children.end(); it++) {
Block *child = *it;
if(seen.find(child) == seen.end()) {
child->dump(seen, indent + " ");
} else {
cout << indent << " (*" << child->id << endl;
}
}
if(next != 0) {
if(seen.find(next) == seen.end()) {
next->dump(seen, indent + "");
} else {
cout << indent << "(*" << next->id << endl;
}
}
}
void replaceChild(Block *oldChild, Block *newChild) {
int i = 0;
bool foundChild = false;
for(auto it = children.begin(); it != children.end(); it++) {
Block *child = *it;
if(child == oldChild) {
foundChild = true;
break;
}
i++;
}
if(foundChild) {
children[i] = newChild;
return;
}
throw runtime_error("couldnt find old child");
}
};
class ReturnBlock : public Block {
public:
virtual string blockType() const {
return "ReturnBlock";
}
virtual void dump(set<const Block *> &seen, string indent) const {
cout << indent << "ReturnBlock " << this->id << endl;
}
void replaceChild(Block *oldChild, Block *newChild) {
throw runtime_error("couldnt find old child");
}
};
vector<unique_ptr<Block> > blocks; // doesnt include the root. I guess. ???
map<BasicBlock *, Block *> blockByBasicBlock;
// void dumpBlock(Block *block) {
// cout << "dumping block" << endl;
// block->dump();
// }
void mergeSequences(Block *root) {
// basically we look for any block with one single incoming, and that incoming is a basicblockblock
bool didAMerge = true;
while(didAMerge) {
didAMerge = false;
for(auto it = blocks.begin(); it != blocks.end(); it++) {
Block *block = it->get();
if(block->incoming.size() == 1) {
// cout << "block " << block->id << " has only one incoming" << endl;
Block *parent = block->incoming[0];
if(BasicBlockBlock *parentBlockBlock = dynamic_cast<BasicBlockBlock*>(parent)) {
// cout << "its a blockblock" << endl;
if(BasicBlockBlock *thisBlockBlock = dynamic_cast<BasicBlockBlock*>(block)) {
// so merge...
cout << "merging ... " << block->id << ", " << parent->id << endl;
unique_ptr<Sequence> sequence(new Sequence());
sequence->children.push_back(parent);
sequence->children.push_back(block);
for(auto parentincit = parent->incoming.begin(); parentincit != parent->incoming.end(); parentincit++) {
Block *parentinc = *parentincit;
sequence->incoming.push_back(parentinc);
parentinc->replaceChild(parent, sequence.get());
}
parent->incoming.clear();
parent->incoming.push_back(sequence.get());
parentBlockBlock->next = 0;
block->incoming.clear();
block->incoming.push_back(sequence.get());
sequence->next = thisBlockBlock->next;
thisBlockBlock->next = 0;
blocks.push_back(std::move(sequence));
didAMerge = true;
}
} else {
// cout << "but not a basicblockblock" << endl;
}
}
}
}
}
void handle_branching_simplify(Function *F) {
cout << "simplify " << string(F->getName()) << endl;
unique_ptr<RootBlock> root(new RootBlock());
for(auto it=F->begin(); it != F->end(); it++) {
cout << "block" << endl;
BasicBlock *basicBlock = &*it;
unique_ptr<BasicBlockBlock> block(new BasicBlockBlock());
block->basicBlock = basicBlock;
for(auto instit=basicBlock->begin(); instit != basicBlock->end(); instit++) {
Instruction *inst = &*instit;
// skip branches, phis and so on, which we'll handle later, somehow...
if(isa<BranchInst>(inst)) {
continue;
}
if(isa<PHINode>(inst)) {
continue;
}
if(isa<ReturnInst>(inst)) {
continue;
}
block->instructions.push_back(inst);
}
blockByBasicBlock[basicBlock] = block.get();
blocks.push_back(std::move(block));
}
root->first = blockByBasicBlock[&F->getEntryBlock()];
root->first->incoming.push_back(root.get());
// go through, and start linking stuff togehter, now that we have a map from basic block to block
for(auto it=F->begin(); it != F->end(); it++) {
BasicBlock *basicBlock = &*it;
BasicBlockBlock *block = dynamic_cast<BasicBlockBlock *>(blockByBasicBlock[basicBlock]);
// I think that each block has to end initially either with a branch or a return?
Instruction *lastInst = basicBlock->getTerminator();
cout << "lastinst:" << endl;
lastInst->dump();
cout << endl;
if(isa<ReturnInst>(lastInst)) {
cout << "finishes in ret" << endl;
unique_ptr<ReturnBlock> retBlock(new ReturnBlock());
block->next = retBlock.get();
block->next->incoming.push_back(block);
blocks.push_back(std::move(retBlock));
} else if(BranchInst* branchInst = dyn_cast<BranchInst>(lastInst)) {
cout << "its a branch" << endl;
// if its unconditional, we just link directly to the next block
// otherwise we link to a ConditionalBranch block
if(branchInst->isUnconditional()) {
cout << "unconditonal branch" << endl;
BasicBlock *next = branchInst->getSuccessor(0);
Block *nextBlock = blockByBasicBlock[next];
block->next = nextBlock;
block->next->incoming.push_back(block);
} else {
// conditional
// create a ConditionalBranch block
cout << "conditonal branch" << endl;
unique_ptr<ConditionalBranch> conditionalBranch(new ConditionalBranch());
BasicBlock *trueBasicBlock = branchInst->getSuccessor(0);
Block *trueBlock = blockByBasicBlock[trueBasicBlock];
conditionalBranch->trueNext = trueBlock;
conditionalBranch->trueNext->incoming.push_back(conditionalBranch.get());
conditionalBranch->falseNext = 0;
if(branchInst->getNumSuccessors() == 2) {
BasicBlock *falseBasicBlock = branchInst->getSuccessor(1);
Block *falseBlock = blockByBasicBlock[falseBasicBlock];
conditionalBranch->falseNext = falseBlock;
conditionalBranch->falseNext->incoming.push_back(conditionalBranch.get());
}
block->next = conditionalBranch.get();
block->next->incoming.push_back(block);
blocks.push_back(std::move(conditionalBranch));
}
} else {
cout << "hmmm, how did we get here???" << endl;
cout << "lastinst:" << endl;
lastInst->dump();
cout << endl;
throw runtime_error("dont know how we got here...");
}
}
set<const Block *>seen;
root->dump(seen, "");
mergeSequences(root.get());
seen.clear();
root->dump(seen, "");
}
}
<|endoftext|>
|
<commit_before>// ECE556 - Copyright 2014 University of Wisconsin-Madison. All Rights Reserved.
#include "ece556.h"
int
main(int argc, char **argv)
{
signal(SIGSEGV, handler);
if(argc!=5){
fprintf(stderr, "Usage : ./ROUTE.exe -d=<num> -n=<num> <input_benchmark_name> <output_file_name> \n");
return 1;
}
int status;
int netDecomp = argv[1];
int netOrdering = argv[2];
char *inputFileName = argv[3];
char *outputFileName = argv[4];
/// create a new routing instance
routingInst *rst = new routingInst;
/// read benchmark
status = readBenchmark(inputFileName, rst);
if(status==0){
fprintf(stderr, "ERROR: reading input file \n");
return 1;
}
/// run actual routing
status = solveRouting(rst);
if(status==0){
fprintf(stderr, "ERROR: running routing \n");
release(rst);
return 1;
}
if (netOrdering == 1){
status = RRR(rst);
if(status==0){
fprintf(stderr, "ERROR: running rip-up and re-route\n");
release(rst);
return 1;
}
}
/// write the result
status = writeOutput(outputFileName, rst);
if(status==0){
fprintf(stderr, "ERROR: writing the result \n");
release(rst);
return 1;
}
release(rst);
printf("\nDONE!\n\n");
return 0;
}
<commit_msg>fixed bug<commit_after>// ECE556 - Copyright 2014 University of Wisconsin-Madison. All Rights Reserved.
#include "ece556.h"
int
main(int argc, char **argv)
{
signal(SIGSEGV, handler);
if(argc!=5){
fprintf(stderr, "Usage : ./ROUTE.exe -d=<num> -n=<num> <input_benchmark_name> <output_file_name> \n");
return 1;
}
int status;
int netDecomp = atoi(argv[1]);
int netOrdering = atoi(argv[2]);
char *inputFileName = argv[3];
char *outputFileName = argv[4];
/// create a new routing instance
routingInst *rst = new routingInst;
/// read benchmark
status = readBenchmark(inputFileName, rst);
if(status==0){
fprintf(stderr, "ERROR: reading input file \n");
return 1;
}
/// run actual routing
status = solveRouting(rst);
if(status==0){
fprintf(stderr, "ERROR: running routing \n");
release(rst);
return 1;
}
if (netOrdering == 1){
status = RRR(rst);
if(status==0){
fprintf(stderr, "ERROR: running rip-up and re-route\n");
release(rst);
return 1;
}
}
/// write the result
status = writeOutput(outputFileName, rst);
if(status==0){
fprintf(stderr, "ERROR: writing the result \n");
release(rst);
return 1;
}
release(rst);
printf("\nDONE!\n\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include "itemdetailswidget.hpp"
#include "ui_itemdetailswidget.h"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QMapIterator>
#include <QSqlQuery>
#include <QTableWidget>
#include <QTabWidget>
#include <QTextEdit>
#include <QVBoxLayout>
#include "attribute_set.hpp"
#include "global.hpp"
#include "attributetree.h"
#include "skillrequirementtree.hpp"
ItemDetailsWidget::ItemDetailsWidget(int typeId, QWidget* parent)
: QWidget(parent) {
this->typeId = typeId;
as = AttributeSet::fromPrototype(typeId);
init();
}
ItemDetailsWidget::ItemDetailsWidget(const AttributeSet& as, QWidget* parent)
: QWidget(parent) {
this->as = as;
this->typeId = as.prototypeId;
init();
}
ItemDetailsWidget::~ItemDetailsWidget() {
delete ui;
}
void ItemDetailsWidget::init() {
ui = new Ui::ItemDetailsWidget;
ui->setupUi(this);
setWindowFlags(Qt::Dialog);
setAttribute(Qt::WA_DeleteOnClose);
setWindowTitle(tr("Item Details - %1").arg(as.name));
ui->typePixmapLabel->setPixmap(*getTypePixmap64(typeId));
ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(as.name));
ui->horizontalLayout->setAlignment(ui->verticalLayout_2, Qt::AlignTop);
initDescriptionTab();
initAttributeTree();
initSkillRequirementTree();
fillTabs();
}
void ItemDetailsWidget::initDescriptionTab()
{
descriptionTab = new QTextEdit();
descriptionTab->setText(as.description);
}
void ItemDetailsWidget::initAttributeTree()
{
at = new AttributeTree();
at->init(as);
}
void ItemDetailsWidget::initSkillRequirementTree() {
srt = new SkillRequirementTree(typeId);
}
void ItemDetailsWidget::fillTabs() {
ui->tabs->addTab(descriptionTab, tr("Description"));
ui->tabs->addTab(at, tr("Attributes"));
ui->tabs->addTab(srt, tr("Skill Requirement"));
}
<commit_msg>Description tab in ItemDetailsWidget can properly display html now.<commit_after>#include "itemdetailswidget.hpp"
#include "ui_itemdetailswidget.h"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QMapIterator>
#include <QSqlQuery>
#include <QTableWidget>
#include <QTabWidget>
#include <QTextEdit>
#include <QVBoxLayout>
#include "attribute_set.hpp"
#include "global.hpp"
#include "attributetree.h"
#include "skillrequirementtree.hpp"
ItemDetailsWidget::ItemDetailsWidget(int typeId, QWidget* parent)
: QWidget(parent) {
this->typeId = typeId;
as = AttributeSet::fromPrototype(typeId);
init();
}
ItemDetailsWidget::ItemDetailsWidget(const AttributeSet& as, QWidget* parent)
: QWidget(parent) {
this->as = as;
this->typeId = as.prototypeId;
init();
}
ItemDetailsWidget::~ItemDetailsWidget() {
delete ui;
}
void ItemDetailsWidget::init() {
ui = new Ui::ItemDetailsWidget;
ui->setupUi(this);
setWindowFlags(Qt::Dialog);
setAttribute(Qt::WA_DeleteOnClose);
setWindowTitle(tr("Item Details - %1").arg(as.name));
ui->typePixmapLabel->setPixmap(*getTypePixmap64(typeId));
ui->typeNameLabel->setText(QString("<h2>%1</h2>").arg(as.name));
ui->horizontalLayout->setAlignment(ui->verticalLayout_2, Qt::AlignTop);
initDescriptionTab();
initAttributeTree();
initSkillRequirementTree();
fillTabs();
}
void ItemDetailsWidget::initDescriptionTab()
{
descriptionTab = new QTextEdit();
QString description = as.description;
description.replace("\n", "<br>");
descriptionTab->setHtml(description);
}
void ItemDetailsWidget::initAttributeTree()
{
at = new AttributeTree();
at->init(as);
}
void ItemDetailsWidget::initSkillRequirementTree() {
srt = new SkillRequirementTree(typeId);
}
void ItemDetailsWidget::fillTabs() {
ui->tabs->addTab(descriptionTab, tr("Description"));
ui->tabs->addTab(at, tr("Attributes"));
ui->tabs->addTab(srt, tr("Skill Requirement"));
}
<|endoftext|>
|
<commit_before>/*
* ngtcp2
*
* Copyright (c) 2017 ngtcp2 contributors
*
* 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 "crypto.h"
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif /* HAVE_ARPA_INET_H */
#include <algorithm>
#include "template.h"
namespace ngtcp2 {
namespace crypto {
int export_secret(uint8_t *dest, size_t destlen, SSL *ssl, const uint8_t *label,
size_t labellen) {
int rv;
rv = SSL_export_keying_material(
ssl, dest, destlen, reinterpret_cast<const char *>(label), labellen,
reinterpret_cast<const uint8_t *>(""), 0, 1);
if (rv != 1) {
return -1;
}
return 0;
}
int export_client_secret(uint8_t *dest, size_t destlen, SSL *ssl) {
static constexpr uint8_t label[] = "EXPORTER-QUIC client 1-RTT Secret";
return export_secret(dest, destlen, ssl, label, str_size(label));
}
int export_server_secret(uint8_t *dest, size_t destlen, SSL *ssl) {
static constexpr uint8_t label[] = "EXPORTER-QUIC server 1-RTT Secret";
return export_secret(dest, destlen, ssl, label, str_size(label));
}
#ifdef WORDS_BIGENDIAN
#define bswap64(N) (N)
#else /* !WORDS_BIGENDIAN */
#define bswap64(N) \
((uint64_t)(ntohl((uint32_t)(N))) << 32 | ntohl((uint32_t)((N) >> 32)))
#endif /* !WORDS_BIGENDIAN */
int derive_cleartext_secret(uint8_t *dest, size_t destlen, uint64_t secret,
const uint8_t *salt, size_t saltlen) {
Context ctx;
prf_sha256(ctx);
secret = bswap64(secret);
return hkdf_extract(dest, destlen, reinterpret_cast<uint8_t *>(&secret),
sizeof(secret), salt, saltlen, ctx);
}
int derive_client_cleartext_secret(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen) {
static constexpr uint8_t LABEL[] = "QUIC client cleartext Secret";
Context ctx;
prf_sha256(ctx);
return crypto::hkdf_expand_label(dest, destlen, secret, secretlen, LABEL,
str_size(LABEL), ctx);
}
int derive_server_cleartext_secret(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen) {
static constexpr uint8_t LABEL[] = "QUIC server cleartext Secret";
Context ctx;
prf_sha256(ctx);
return crypto::hkdf_expand_label(dest, destlen, secret, secretlen, LABEL,
str_size(LABEL), ctx);
}
ssize_t derive_packet_protection_key(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen,
const Context &ctx) {
int rv;
static constexpr uint8_t LABEL_KEY[] = "key";
auto keylen = aead_key_length(ctx);
if (keylen > destlen) {
return -1;
}
rv = crypto::hkdf_expand_label(dest, keylen, secret, secretlen, LABEL_KEY,
str_size(LABEL_KEY), ctx);
if (rv != 0) {
return -1;
}
return keylen;
}
ssize_t derive_packet_protection_iv(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen,
const Context &ctx) {
int rv;
static constexpr uint8_t LABEL_IV[] = "iv";
auto ivlen = std::max(static_cast<size_t>(8), aead_nonce_length(ctx));
if (ivlen > destlen) {
return -1;
}
rv = crypto::hkdf_expand_label(dest, ivlen, secret, secretlen, LABEL_IV,
str_size(LABEL_IV), ctx);
if (rv != 0) {
return -1;
}
return ivlen;
}
int hkdf_expand_label(uint8_t *dest, size_t destlen, const uint8_t *secret,
size_t secretlen, const uint8_t *qlabel, size_t qlabellen,
const Context &ctx) {
std::array<uint8_t, 256> info;
static constexpr const uint8_t LABEL[] = "tls13 ";
auto p = std::begin(info);
*p++ = destlen / 256;
*p++ = destlen % 256;
*p++ = str_size(LABEL) + qlabellen;
p = std::copy_n(LABEL, str_size(LABEL), p);
p = std::copy_n(qlabel, qlabellen, p);
*p++ = 0;
return hkdf_expand(dest, destlen, secret, secretlen, info.data(),
p - std::begin(info), ctx);
}
} // namespace crypto
} // namespace ngtcp2
<commit_msg>Update HDKF label for handshake packets<commit_after>/*
* ngtcp2
*
* Copyright (c) 2017 ngtcp2 contributors
*
* 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 "crypto.h"
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif /* HAVE_ARPA_INET_H */
#include <algorithm>
#include "template.h"
namespace ngtcp2 {
namespace crypto {
int export_secret(uint8_t *dest, size_t destlen, SSL *ssl, const uint8_t *label,
size_t labellen) {
int rv;
rv = SSL_export_keying_material(
ssl, dest, destlen, reinterpret_cast<const char *>(label), labellen,
reinterpret_cast<const uint8_t *>(""), 0, 1);
if (rv != 1) {
return -1;
}
return 0;
}
int export_client_secret(uint8_t *dest, size_t destlen, SSL *ssl) {
static constexpr uint8_t label[] = "EXPORTER-QUIC client 1-RTT Secret";
return export_secret(dest, destlen, ssl, label, str_size(label));
}
int export_server_secret(uint8_t *dest, size_t destlen, SSL *ssl) {
static constexpr uint8_t label[] = "EXPORTER-QUIC server 1-RTT Secret";
return export_secret(dest, destlen, ssl, label, str_size(label));
}
#ifdef WORDS_BIGENDIAN
#define bswap64(N) (N)
#else /* !WORDS_BIGENDIAN */
#define bswap64(N) \
((uint64_t)(ntohl((uint32_t)(N))) << 32 | ntohl((uint32_t)((N) >> 32)))
#endif /* !WORDS_BIGENDIAN */
int derive_cleartext_secret(uint8_t *dest, size_t destlen, uint64_t secret,
const uint8_t *salt, size_t saltlen) {
Context ctx;
prf_sha256(ctx);
secret = bswap64(secret);
return hkdf_extract(dest, destlen, reinterpret_cast<uint8_t *>(&secret),
sizeof(secret), salt, saltlen, ctx);
}
int derive_client_cleartext_secret(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen) {
static constexpr uint8_t LABEL[] = "QUIC client handshake Secret";
Context ctx;
prf_sha256(ctx);
return crypto::hkdf_expand_label(dest, destlen, secret, secretlen, LABEL,
str_size(LABEL), ctx);
}
int derive_server_cleartext_secret(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen) {
static constexpr uint8_t LABEL[] = "QUIC server handshake Secret";
Context ctx;
prf_sha256(ctx);
return crypto::hkdf_expand_label(dest, destlen, secret, secretlen, LABEL,
str_size(LABEL), ctx);
}
ssize_t derive_packet_protection_key(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen,
const Context &ctx) {
int rv;
static constexpr uint8_t LABEL_KEY[] = "key";
auto keylen = aead_key_length(ctx);
if (keylen > destlen) {
return -1;
}
rv = crypto::hkdf_expand_label(dest, keylen, secret, secretlen, LABEL_KEY,
str_size(LABEL_KEY), ctx);
if (rv != 0) {
return -1;
}
return keylen;
}
ssize_t derive_packet_protection_iv(uint8_t *dest, size_t destlen,
const uint8_t *secret, size_t secretlen,
const Context &ctx) {
int rv;
static constexpr uint8_t LABEL_IV[] = "iv";
auto ivlen = std::max(static_cast<size_t>(8), aead_nonce_length(ctx));
if (ivlen > destlen) {
return -1;
}
rv = crypto::hkdf_expand_label(dest, ivlen, secret, secretlen, LABEL_IV,
str_size(LABEL_IV), ctx);
if (rv != 0) {
return -1;
}
return ivlen;
}
int hkdf_expand_label(uint8_t *dest, size_t destlen, const uint8_t *secret,
size_t secretlen, const uint8_t *qlabel, size_t qlabellen,
const Context &ctx) {
std::array<uint8_t, 256> info;
static constexpr const uint8_t LABEL[] = "tls13 ";
auto p = std::begin(info);
*p++ = destlen / 256;
*p++ = destlen % 256;
*p++ = str_size(LABEL) + qlabellen;
p = std::copy_n(LABEL, str_size(LABEL), p);
p = std::copy_n(qlabel, qlabellen, p);
*p++ = 0;
return hkdf_expand(dest, destlen, secret, secretlen, info.data(),
p - std::begin(info), ctx);
}
} // namespace crypto
} // namespace ngtcp2
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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: chartspacefragment.cxx,v $
*
* $Revision: 1.3 $
*
* 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.
*
************************************************************************/
#include "oox/drawingml/chart/chartspacefragment.hxx"
#include "oox/drawingml/shapepropertiescontext.hxx"
#include "oox/drawingml/textbodycontext.hxx"
#include "oox/drawingml/chart/chartspacemodel.hxx"
#include "oox/drawingml/chart/plotareacontext.hxx"
#include "oox/drawingml/chart/titlecontext.hxx"
using ::rtl::OUString;
using ::oox::core::ContextWrapper;
using ::oox::core::XmlFilterBase;
namespace oox {
namespace drawingml {
namespace chart {
// ============================================================================
ChartSpaceFragment::ChartSpaceFragment( XmlFilterBase& rFilter, const OUString& rFragmentPath, ChartSpaceModel& rModel ) :
FragmentBase< ChartSpaceModel >( rFilter, rFragmentPath, rModel )
{
}
ChartSpaceFragment::~ChartSpaceFragment()
{
}
ContextWrapper ChartSpaceFragment::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
switch( getCurrentElement() )
{
case XML_ROOT_CONTEXT:
return (nElement == C_TOKEN( chartSpace ));
case C_TOKEN( chartSpace ):
switch( nElement )
{
case C_TOKEN( chart ):
return true;
case C_TOKEN( spPr ):
return new ShapePropertiesContext( *this, mrModel.mxShapeProp.create() );
case C_TOKEN( style ):
mrModel.mnStyle = rAttribs.getInteger( XML_val, 2 );
return false;
case C_TOKEN( txPr ):
return new TextBodyContext( *this, mrModel.mxTextProp.create() );
}
break;
case C_TOKEN( chart ):
switch( nElement )
{
case C_TOKEN( autoTitleDeleted ):
// default is 'false', not 'true' as specified
mrModel.mbAutoTitleDel = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( dispBlanksAs ):
mrModel.mnDispBlanksAs = rAttribs.getToken( XML_val, XML_zero );
return false;
case C_TOKEN( legend ):
return new LegendContext( *this, mrModel.mxLegend.create() );
case C_TOKEN( plotArea ):
return new PlotAreaContext( *this, mrModel.mxPlotArea.create() );
case C_TOKEN( plotVisOnly ):
// default is 'false', not 'true' as specified
mrModel.mbPlotVisOnly = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( showDLblsOverMax ):
// default is 'false', not 'true' as specified
mrModel.mbShowLabelsOverMax = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( title ):
return new TitleContext( *this, mrModel.mxTitle.create() );
case C_TOKEN( view3D ):
return new View3DContext( *this, mrModel.mxView3D.create() );
}
break;
}
return false;
}
// ============================================================================
} // namespace chart
} // namespace drawingml
} // namespace oox
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.6); FILE MERGED 2008/06/06 16:27:53 dr 1.2.6.2: chart formatting: builtin line/fill/effect styles, manual line formatting 2008/05/27 10:40:38 dr 1.2.6.1: joined changes from CWS xmlfilter05<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: chartspacefragment.cxx,v $
*
* $Revision: 1.4 $
*
* 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.
*
************************************************************************/
#include "oox/drawingml/chart/chartspacefragment.hxx"
#include "oox/drawingml/shapepropertiescontext.hxx"
#include "oox/drawingml/textbodycontext.hxx"
#include "oox/drawingml/chart/chartspacemodel.hxx"
#include "oox/drawingml/chart/plotareacontext.hxx"
#include "oox/drawingml/chart/titlecontext.hxx"
using ::rtl::OUString;
using ::oox::core::ContextWrapper;
using ::oox::core::XmlFilterBase;
namespace oox {
namespace drawingml {
namespace chart {
// ============================================================================
ChartSpaceFragment::ChartSpaceFragment( XmlFilterBase& rFilter, const OUString& rFragmentPath, ChartSpaceModel& rModel ) :
FragmentBase< ChartSpaceModel >( rFilter, rFragmentPath, rModel )
{
}
ChartSpaceFragment::~ChartSpaceFragment()
{
}
ContextWrapper ChartSpaceFragment::onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs )
{
switch( getCurrentElement() )
{
case XML_ROOT_CONTEXT:
return (nElement == C_TOKEN( chartSpace ));
case C_TOKEN( chartSpace ):
switch( nElement )
{
case C_TOKEN( chart ):
return true;
case C_TOKEN( spPr ):
return new ShapePropertiesContext( *this, mrModel.mxShapeProp.create() );
case C_TOKEN( style ):
mrModel.mnStyle = rAttribs.getInteger( XML_val, 2 );
return false;
case C_TOKEN( txPr ):
return new TextBodyContext( *this, mrModel.mxTextProp.create() );
}
break;
case C_TOKEN( chart ):
switch( nElement )
{
case C_TOKEN( autoTitleDeleted ):
// default is 'false', not 'true' as specified
mrModel.mbAutoTitleDel = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( backWall ):
return new WallFloorContext( *this, mrModel.mxBackWall.create() );
case C_TOKEN( dispBlanksAs ):
mrModel.mnDispBlanksAs = rAttribs.getToken( XML_val, XML_zero );
return false;
case C_TOKEN( floor ):
return new WallFloorContext( *this, mrModel.mxFloor.create() );
case C_TOKEN( legend ):
return new LegendContext( *this, mrModel.mxLegend.create() );
case C_TOKEN( plotArea ):
return new PlotAreaContext( *this, mrModel.mxPlotArea.create() );
case C_TOKEN( plotVisOnly ):
// default is 'false', not 'true' as specified
mrModel.mbPlotVisOnly = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( showDLblsOverMax ):
// default is 'false', not 'true' as specified
mrModel.mbShowLabelsOverMax = rAttribs.getBool( XML_val, false );
return false;
case C_TOKEN( sideWall ):
return new WallFloorContext( *this, mrModel.mxSideWall.create() );
case C_TOKEN( title ):
return new TitleContext( *this, mrModel.mxTitle.create() );
case C_TOKEN( view3D ):
return new View3DContext( *this, mrModel.mxView3D.create() );
}
break;
}
return false;
}
// ============================================================================
} // namespace chart
} // namespace drawingml
} // namespace oox
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "OptionsGroupBox.hpp"
using namespace pkmnsim;
using namespace std;
OptionsGroupBox::OptionsGroupBox(QWidget* parent): QGroupBox(parent)
{
//Initialize private variables
type1 = "Normal";
type2 = "Any";
evolved = false;
setTitle(QString("Options"));
QHBoxLayout* mainLayout = new QHBoxLayout(this);
QVBoxLayout* choicesLayout = new QVBoxLayout();
QHBoxLayout* typesLayout = new QHBoxLayout();
QHBoxLayout* checkBoxesLayout = new QHBoxLayout();
QVBoxLayout* buttonLayout = new QVBoxLayout();
//typesLayout
QLabel* typesLabel = new QLabel(tr("Input type(s):"),this);
TypesComboBox* type1ComboBox = new TypesComboBox(this,5);
TypesComboBox* type2ComboBox = new TypesComboBox(this,5);
type2ComboBox->insertItem(0,QString("Any"));
type2ComboBox->insertItem(1,QString("None"));
type2ComboBox->setCurrentIndex(0);
typesLayout->addWidget(typesLabel);
typesLayout->addWidget(type1ComboBox);
typesLayout->addWidget(type2ComboBox);
//checkBoxesLayout
QCheckBox* evolvedCheckBox = new QCheckBox(tr("Only fully evolved Pokemon?"),this);
checkBoxesLayout->addWidget(evolvedCheckBox);
//Separator and calculate button
QFrame* vertLine = new QFrame(this);
vertLine->setFrameShape(QFrame::VLine);
QPushButton* calculateButton = new QPushButton(tr("Calculate"),this);
//Setting layer hierarchy
choicesLayout->addLayout(typesLayout);
choicesLayout->addLayout(checkBoxesLayout);
mainLayout->addLayout(choicesLayout);
mainLayout->addWidget(vertLine);
mainLayout->addWidget(calculateButton);
//Connections
connect(type1ComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setTypeOne(QString)));
connect(type2ComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setTypeTwo(QString)));
connect(evolvedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setEvolved(int)));
connect(calculateButton, SIGNAL(released()), this, SLOT(calculateResults()));
setLayout(mainLayout);
setFixedSize(800,100);
}
//Private slots to set private variables
void OptionsGroupBox::setTypeOne(QString typeOneQString) {type1 = typeOneQString.toStdString();}
void OptionsGroupBox::setTypeTwo(QString typeTwoQString) {type2 = typeTwoQString.toStdString();}
void OptionsGroupBox::setEvolved(int state) {evolved = state;}
void OptionsGroupBox::calculateResults()
{
vector<vector<stat_st> > highest_stats_vecs, lowest_stats_vecs;
vector<int> errcodes;
for(int i = 1; i <= 5; i++)
{
vector<stat_st> high_vec, low_vec;
errcodes.push_back(sort_pokemon_by_stats(type1, type2, high_vec, low_vec, i, (type2 == "Any"), evolved));
highest_stats_vecs.push_back(high_vec);
lowest_stats_vecs.push_back(low_vec);
}
emit resultsCalculated(highest_stats_vecs, lowest_stats_vecs, errcodes, type1, type2);
}
<commit_msg>get_type_stats_gui: idiot-proofing app so it doesn't segfault if a user asks for duplicate types<commit_after>/*
* Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include "OptionsGroupBox.hpp"
using namespace pkmnsim;
using namespace std;
OptionsGroupBox::OptionsGroupBox(QWidget* parent): QGroupBox(parent)
{
//Initialize private variables
type1 = "Normal";
type2 = "Any";
evolved = false;
setTitle(QString("Options"));
QHBoxLayout* mainLayout = new QHBoxLayout(this);
QVBoxLayout* choicesLayout = new QVBoxLayout();
QHBoxLayout* typesLayout = new QHBoxLayout();
QHBoxLayout* checkBoxesLayout = new QHBoxLayout();
QVBoxLayout* buttonLayout = new QVBoxLayout();
//typesLayout
QLabel* typesLabel = new QLabel(tr("Input type(s):"),this);
TypesComboBox* type1ComboBox = new TypesComboBox(this,5);
TypesComboBox* type2ComboBox = new TypesComboBox(this,5);
type2ComboBox->insertItem(0,QString("Any"));
type2ComboBox->insertItem(1,QString("None"));
type2ComboBox->setCurrentIndex(0);
typesLayout->addWidget(typesLabel);
typesLayout->addWidget(type1ComboBox);
typesLayout->addWidget(type2ComboBox);
//checkBoxesLayout
QCheckBox* evolvedCheckBox = new QCheckBox(tr("Only fully evolved Pokemon?"),this);
checkBoxesLayout->addWidget(evolvedCheckBox);
//Separator and calculate button
QFrame* vertLine = new QFrame(this);
vertLine->setFrameShape(QFrame::VLine);
QPushButton* calculateButton = new QPushButton(tr("Calculate"),this);
//Setting layer hierarchy
choicesLayout->addLayout(typesLayout);
choicesLayout->addLayout(checkBoxesLayout);
mainLayout->addLayout(choicesLayout);
mainLayout->addWidget(vertLine);
mainLayout->addWidget(calculateButton);
//Connections
connect(type1ComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setTypeOne(QString)));
connect(type2ComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setTypeTwo(QString)));
connect(evolvedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setEvolved(int)));
connect(calculateButton, SIGNAL(released()), this, SLOT(calculateResults()));
setLayout(mainLayout);
setFixedSize(800,100);
}
//Private slots to set private variables
void OptionsGroupBox::setTypeOne(QString typeOneQString) {type1 = typeOneQString.toStdString();}
void OptionsGroupBox::setTypeTwo(QString typeTwoQString) {type2 = typeTwoQString.toStdString();}
void OptionsGroupBox::setEvolved(int state) {evolved = state;}
void OptionsGroupBox::calculateResults()
{
vector<vector<stat_st> > highest_stats_vecs, lowest_stats_vecs;
vector<int> errcodes;
//Prevent app from segfaulting by looking for duplicate types
if(type1 == type2) type2 = "None";
for(int i = 1; i <= 5; i++)
{
vector<stat_st> high_vec, low_vec;
errcodes.push_back(sort_pokemon_by_stats(type1, type2, high_vec, low_vec, i, (type2 == "Any"), evolved));
highest_stats_vecs.push_back(high_vec);
lowest_stats_vecs.push_back(low_vec);
}
emit resultsCalculated(highest_stats_vecs, lowest_stats_vecs, errcodes, type1, type2);
}
<|endoftext|>
|
<commit_before>/* ****************************************************************************
*
* FILE main_samsonKiller.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Feb 25 2011
*
*/
#include "parseArgs/parseArgs.h" // parseArgs
#include "parseArgs/paUsage.h" // paUsage
#include "logMsg/traceLevels.h" // Trace levels
#include "samson/network/Endpoint.h" // Endpoint
#include "samson/common/ports.h" // SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT
#include "samson/network/iomConnect.h" // iomConnect
#include "samson/network/iomMsgSend.h" // iomMsgSend
/* ****************************************************************************
*
* Option variables
*/
char name[80];
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
{ " ", name, "NAME", PaString, PaOpt, (long) "all", PaNL, PaNL, "name of prcess to kill" },
PA_END_OF_ARGS
};
/* ****************************************************************************
*
* sysKill -
*/
static void sysKill(const char* name)
{
char com[256];
snprintf(com, sizeof(com), "killall -9 %s > /dev/null 2>&1", name);
if (system(com) == 0)
printf("Killed %s\n", name);
}
/* ****************************************************************************
*
* killProcess -
*/
static int killProcess(const char* name, unsigned short port)
{
samson::Endpoint ep;
samson::Endpoint me;
int s;
ep.name = name;
ep.wFd = iomConnect("localhost", port);
me.name = "samsonKiller";
if ((ep.wFd == -1) || ((s = iomMsgSend(&ep, &me, samson::Message::Die, samson::Message::Msg)) != 0))
sysKill(name);
else
{
int fd = iomConnect("localhost", port);
if (fd != -1)
sysKill(name);
else
printf("killed '%s'\n", name);
}
return 0;
}
/* ****************************************************************************
*
* main -
*/
int main(int argC, const char *argV[])
{
name[0] = 0;
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
if (name[0] != 0)
{
if ((strcasecmp(name, "worker") == 0) || (strcasecmp(name, "samsonWorker") == 0))
return killProcess("samsonWorker", WORKER_PORT);
else if ((strcasecmp(name, "controller") == 0) || (strcasecmp(name, "samsonController") == 0))
return killProcess("samsonController", CONTROLLER_PORT);
else if ((strcasecmp(name, "spawner") == 0) || (strcasecmp(name, "samsonSpawner") == 0))
return killProcess("samsonSpawner", SPAWNER_PORT);
else if (strcasecmp(name, "all") == 0)
{
killProcess("samsonWorker", WORKER_PORT);
killProcess("samsonController", CONTROLLER_PORT);
killProcess("samsonSpawner", SPAWNER_PORT);
return 0;
}
else
{
printf("non-familiar process '%s'\n", name);
exit(1);
}
}
return 0;
}
<commit_msg>Now killing spawner first ...<commit_after>/* ****************************************************************************
*
* FILE main_samsonKiller.cpp
*
* AUTHOR Ken Zangelin
*
* CREATION DATE Feb 25 2011
*
*/
#include "parseArgs/parseArgs.h" // parseArgs
#include "parseArgs/paUsage.h" // paUsage
#include "logMsg/traceLevels.h" // Trace levels
#include "samson/network/Endpoint.h" // Endpoint
#include "samson/common/ports.h" // SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT
#include "samson/network/iomConnect.h" // iomConnect
#include "samson/network/iomMsgSend.h" // iomMsgSend
/* ****************************************************************************
*
* Option variables
*/
char name[80];
/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
{ " ", name, "NAME", PaString, PaOpt, (long) "all", PaNL, PaNL, "name of prcess to kill" },
PA_END_OF_ARGS
};
/* ****************************************************************************
*
* sysKill -
*/
static void sysKill(const char* name)
{
char com[256];
snprintf(com, sizeof(com), "killall -9 %s > /dev/null 2>&1", name);
if (system(com) == 0)
printf("Killed %s\n", name);
}
/* ****************************************************************************
*
* killProcess -
*/
static int killProcess(const char* name, unsigned short port)
{
samson::Endpoint ep;
samson::Endpoint me;
int s;
ep.name = name;
ep.wFd = iomConnect("localhost", port);
me.name = "samsonKiller";
if ((ep.wFd == -1) || ((s = iomMsgSend(&ep, &me, samson::Message::Die, samson::Message::Msg)) != 0))
sysKill(name);
else
{
int fd = iomConnect("localhost", port);
if (fd != -1)
sysKill(name);
else
printf("killed '%s'\n", name);
}
return 0;
}
/* ****************************************************************************
*
* main -
*/
int main(int argC, const char *argV[])
{
name[0] = 0;
paConfig("log to file", (void*) true);
paParse(paArgs, argC, (char**) argV, 1, false);
if (name[0] != 0)
{
if ((strcasecmp(name, "worker") == 0) || (strcasecmp(name, "samsonWorker") == 0))
return killProcess("samsonWorker", WORKER_PORT);
else if ((strcasecmp(name, "controller") == 0) || (strcasecmp(name, "samsonController") == 0))
return killProcess("samsonController", CONTROLLER_PORT);
else if ((strcasecmp(name, "spawner") == 0) || (strcasecmp(name, "samsonSpawner") == 0))
return killProcess("samsonSpawner", SPAWNER_PORT);
else if (strcasecmp(name, "all") == 0)
{
killProcess("samsonSpawner", SPAWNER_PORT);
killProcess("samsonWorker", WORKER_PORT);
killProcess("samsonController", CONTROLLER_PORT);
return 0;
}
else
{
printf("non-familiar process '%s'\n", name);
exit(1);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010-2013 OTClient <https://github.com/edubart/otclient>
*
* 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 "thingtype.h"
#include "spritemanager.h"
#include "game.h"
#include "lightview.h"
#include <framework/graphics/graphics.h>
#include <framework/graphics/texture.h>
#include <framework/graphics/image.h>
#include <framework/graphics/texturemanager.h>
#include <framework/core/filestream.h>
#include <framework/otml/otml.h>
ThingType::ThingType()
{
m_category = ThingInvalidCategory;
m_id = 0;
m_null = true;
m_exactSize = 0;
m_numPatternX = m_numPatternY = m_numPatternZ = 0;
m_animationPhases = 0;
m_layers = 0;
m_elevation = 0;
m_opacity = 1.0f;
}
void ThingType::unserialize(uint16 clientId, ThingCategory category, const FileStreamPtr& fin)
{
m_null = false;
m_id = clientId;
m_category = category;
bool done = false;
for(int i = 0 ; i < ThingLastAttr;++i) {
int attr = fin->getU8();
if(attr == ThingLastAttr) {
done = true;
break;
}
if(g_game.getFeature(Otc::GameChargeableItems)) {
if(attr == ThingAttrWritable) {
m_attribs.set(ThingAttrChargeable, true);
continue;
} else if(attr > ThingAttrWritable)
attr -= 1;
}
switch(attr) {
case ThingAttrDisplacement: {
m_displacement.x = fin->getU16();
m_displacement.y = fin->getU16();
m_attribs.set(attr, true);
break;
}
case ThingAttrLight: {
Light light;
light.intensity = fin->getU16();
light.color = fin->getU16();
m_attribs.set(attr, light);
break;
}
case ThingAttrMarket: {
MarketData market;
market.category = fin->getU16();
market.tradeAs = fin->getU16();
market.showAs = fin->getU16();
market.name = fin->getString();
market.restrictVocation = fin->getU16();
market.requiredLevel = fin->getU16();
m_attribs.set(attr, market);
break;
}
case ThingAttrElevation: {
m_elevation = fin->getU16();
m_attribs.set(attr, m_elevation);
break;
}
case ThingAttrGround:
case ThingAttrWritable:
case ThingAttrWritableOnce:
case ThingAttrMinimapColor:
case ThingAttrCloth:
case ThingAttrLensHelp:
m_attribs.set(attr, fin->getU16());
break;
default:
m_attribs.set(attr, true);
break;
};
}
if(!done)
stdext::throw_exception("corrupt data");
uint8 width = fin->getU8();
uint8 height = fin->getU8();
m_size = Size(width, height);
m_exactSize = (width > 1 || height > 1) ? std::min((int)fin->getU8(), std::max(width * 32, height * 32)) : 32;
m_layers = fin->getU8();
m_numPatternX = fin->getU8();
m_numPatternY = fin->getU8();
m_numPatternZ = fin->getU8();
m_animationPhases = fin->getU8();
int totalSprites = m_size.area() * m_layers * m_numPatternX * m_numPatternY * m_numPatternZ * m_animationPhases;
if(totalSprites == 0)
stdext::throw_exception("a thing type has no sprites");
if(totalSprites > 4096)
stdext::throw_exception("a thing type has more than 4096 sprites");
m_spritesIndex.resize(totalSprites);
for(int i = 0; i < totalSprites; i++)
m_spritesIndex[i] = g_game.getFeature(Otc::GameSpritesU32) ? fin->getU32() : fin->getU16();
m_textures.resize(m_animationPhases);
m_texturesFramesRects.resize(m_animationPhases);
m_texturesFramesOriginRects.resize(m_animationPhases);
m_texturesFramesOffsets.resize(m_animationPhases);
}
void ThingType::unserializeOtml(const OTMLNodePtr& node)
{
for(const OTMLNodePtr& node2 : node->children()) {
if(node2->tag() == "opacity")
m_opacity = node2->value<float>();
else if(node2->tag() == "notprewalkable")
m_attribs.set(ThingAttrNotPreWalkable, node2->value<bool>());
else if(node2->tag() == "image")
m_customImage = node2->value();
}
}
void ThingType::draw(const Point& dest, float scaleFactor, int layer, int xPattern, int yPattern, int zPattern, int animationPhase, LightView *lightView)
{
if(m_null)
return;
const TexturePtr& texture = getTexture(animationPhase); // texture might not exists, neither its rects.
int frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern);
Point textureOffset;
Rect textureRect;
if(scaleFactor != 1.0f) {
textureRect = m_texturesFramesOriginRects[animationPhase][frameIndex];
} else {
textureOffset = m_texturesFramesOffsets[animationPhase][frameIndex];
textureRect = m_texturesFramesRects[animationPhase][frameIndex];
}
Rect screenRect(dest + (textureOffset - m_displacement - (m_size.toPoint() - Point(1, 1)) * 32) * scaleFactor,
textureRect.size() * scaleFactor);
bool useOpacity = m_opacity < 1.0f;
if(useOpacity)
g_painter->setColor(Color(1.0f,1.0f,1.0f,m_opacity));
g_painter->drawTexturedRect(screenRect, texture, textureRect);
if(useOpacity)
g_painter->setColor(Color::white);
if(lightView && hasLight()) {
Light light = getLight();
if(light.intensity > 0)
lightView->addLightSource(screenRect.center(), scaleFactor, light);
}
}
const TexturePtr& ThingType::getTexture(int animationPhase)
{
TexturePtr& animationPhaseTexture = m_textures[animationPhase];
if(!animationPhaseTexture) {
bool useCustomImage = false;
if(animationPhase == 0 && !m_customImage.empty())
useCustomImage = true;
// we don't need layers in common items, they will be pre-drawn
int textureLayers = 1;
int numLayers = m_layers;
if(m_category == ThingCategoryCreature && numLayers >= 2) {
// 5 layers: outfit base, red mask, green mask, blue mask, yellow mask
textureLayers = 5;
numLayers = 5;
}
int indexSize = textureLayers * m_numPatternX * m_numPatternY * m_numPatternZ;
Size textureSize = getBestTextureDimension(m_size.width(), m_size.height(), indexSize);
ImagePtr fullImage;
if(useCustomImage)
fullImage = Image::load(m_customImage);
else
fullImage = ImagePtr(new Image(textureSize * Otc::TILE_PIXELS));
m_texturesFramesRects[animationPhase].resize(indexSize);
m_texturesFramesOriginRects[animationPhase].resize(indexSize);
m_texturesFramesOffsets[animationPhase].resize(indexSize);
for(int z = 0; z < m_numPatternZ; ++z) {
for(int y = 0; y < m_numPatternY; ++y) {
for(int x = 0; x < m_numPatternX; ++x) {
for(int l = 0; l < numLayers; ++l) {
bool spriteMask = (m_category == ThingCategoryCreature && l > 0);
int frameIndex = getTextureIndex(l % textureLayers, x, y, z);
Point framePos = Point(frameIndex % (textureSize.width() / m_size.width()) * m_size.width(),
frameIndex / (textureSize.width() / m_size.width()) * m_size.height()) * Otc::TILE_PIXELS;
if(!useCustomImage) {
for(int h = 0; h < m_size.height(); ++h) {
for(int w = 0; w < m_size.width(); ++w) {
uint spriteIndex = getSpriteIndex(w, h, spriteMask ? 1 : l, x, y, z, animationPhase);
ImagePtr spriteImage = g_sprites.getSpriteImage(m_spritesIndex[spriteIndex]);
if(spriteImage) {
if(spriteMask) {
static Color maskColors[] = { Color::red, Color::green, Color::blue, Color::yellow };
spriteImage->overwriteMask(maskColors[l - 1]);
}
Point spritePos = Point(m_size.width() - w - 1,
m_size.height() - h - 1) * Otc::TILE_PIXELS;
fullImage->blit(framePos + spritePos, spriteImage);
}
}
}
}
Rect drawRect(framePos + Point(m_size.width(), m_size.height()) * Otc::TILE_PIXELS - Point(1,1), framePos);
for(int x = framePos.x; x < framePos.x + m_size.width() * Otc::TILE_PIXELS; ++x) {
for(int y = framePos.y; y < framePos.y + m_size.height() * Otc::TILE_PIXELS; ++y) {
uint8 *p = fullImage->getPixel(x,y);
if(p[3] != 0x00) {
drawRect.setTop (std::min(y, (int)drawRect.top()));
drawRect.setLeft (std::min(x, (int)drawRect.left()));
drawRect.setBottom(std::max(y, (int)drawRect.bottom()));
drawRect.setRight (std::max(x, (int)drawRect.right()));
}
}
}
m_texturesFramesRects[animationPhase][frameIndex] = drawRect;
m_texturesFramesOriginRects[animationPhase][frameIndex] = Rect(framePos, Size(m_size.width(), m_size.height()) * Otc::TILE_PIXELS);
m_texturesFramesOffsets[animationPhase][frameIndex] = drawRect.topLeft() - framePos;
}
}
}
}
animationPhaseTexture = TexturePtr(new Texture(fullImage, true));
animationPhaseTexture->setSmooth(true);
}
return animationPhaseTexture;
}
Size ThingType::getBestTextureDimension(int w, int h, int count)
{
const int MAX = 32;
int k = 1;
while(k < w)
k<<=1;
w = k;
k = 1;
while(k < h)
k<<=1;
h = k;
int numSprites = w*h*count;
assert(numSprites <= MAX*MAX);
assert(w <= MAX);
assert(h <= MAX);
Size bestDimension = Size(MAX, MAX);
for(int i=w;i<=MAX;i<<=1) {
for(int j=h;j<=MAX;j<<=1) {
Size candidateDimension = Size(i, j);
if(candidateDimension.area() < numSprites)
continue;
if((candidateDimension.area() < bestDimension.area()) ||
(candidateDimension.area() == bestDimension.area() && candidateDimension.width() + candidateDimension.height() < bestDimension.width() + bestDimension.height()))
bestDimension = candidateDimension;
}
}
return bestDimension;
}
uint ThingType::getSpriteIndex(int w, int h, int l, int x, int y, int z, int a) {
uint index =
((((((a % m_animationPhases)
* m_numPatternZ + z)
* m_numPatternY + y)
* m_numPatternX + x)
* m_layers + l)
* m_size.height() + h)
* m_size.width() + w;
assert(index < m_spritesIndex.size());
return index;
}
uint ThingType::getTextureIndex(int l, int x, int y, int z) {
return ((l * m_numPatternZ + z)
* m_numPatternY + y)
* m_numPatternX + x;
}
int ThingType::getExactSize(int layer, int xPattern, int yPattern, int zPattern, int animationPhase)
{
getTexture(animationPhase); // we must calculate it anyway.
int frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern);
Size size = m_texturesFramesOriginRects[animationPhase][frameIndex].size() - m_texturesFramesOffsets[animationPhase][frameIndex].toSize();
return std::max(size.width(), size.height());
}
<commit_msg>Full ground option in otml<commit_after>/*
* Copyright (c) 2010-2013 OTClient <https://github.com/edubart/otclient>
*
* 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 "thingtype.h"
#include "spritemanager.h"
#include "game.h"
#include "lightview.h"
#include <framework/graphics/graphics.h>
#include <framework/graphics/texture.h>
#include <framework/graphics/image.h>
#include <framework/graphics/texturemanager.h>
#include <framework/core/filestream.h>
#include <framework/otml/otml.h>
ThingType::ThingType()
{
m_category = ThingInvalidCategory;
m_id = 0;
m_null = true;
m_exactSize = 0;
m_numPatternX = m_numPatternY = m_numPatternZ = 0;
m_animationPhases = 0;
m_layers = 0;
m_elevation = 0;
m_opacity = 1.0f;
}
void ThingType::unserialize(uint16 clientId, ThingCategory category, const FileStreamPtr& fin)
{
m_null = false;
m_id = clientId;
m_category = category;
bool done = false;
for(int i = 0 ; i < ThingLastAttr;++i) {
int attr = fin->getU8();
if(attr == ThingLastAttr) {
done = true;
break;
}
if(g_game.getFeature(Otc::GameChargeableItems)) {
if(attr == ThingAttrWritable) {
m_attribs.set(ThingAttrChargeable, true);
continue;
} else if(attr > ThingAttrWritable)
attr -= 1;
}
switch(attr) {
case ThingAttrDisplacement: {
m_displacement.x = fin->getU16();
m_displacement.y = fin->getU16();
m_attribs.set(attr, true);
break;
}
case ThingAttrLight: {
Light light;
light.intensity = fin->getU16();
light.color = fin->getU16();
m_attribs.set(attr, light);
break;
}
case ThingAttrMarket: {
MarketData market;
market.category = fin->getU16();
market.tradeAs = fin->getU16();
market.showAs = fin->getU16();
market.name = fin->getString();
market.restrictVocation = fin->getU16();
market.requiredLevel = fin->getU16();
m_attribs.set(attr, market);
break;
}
case ThingAttrElevation: {
m_elevation = fin->getU16();
m_attribs.set(attr, m_elevation);
break;
}
case ThingAttrGround:
case ThingAttrWritable:
case ThingAttrWritableOnce:
case ThingAttrMinimapColor:
case ThingAttrCloth:
case ThingAttrLensHelp:
m_attribs.set(attr, fin->getU16());
break;
default:
m_attribs.set(attr, true);
break;
};
}
if(!done)
stdext::throw_exception("corrupt data");
uint8 width = fin->getU8();
uint8 height = fin->getU8();
m_size = Size(width, height);
m_exactSize = (width > 1 || height > 1) ? std::min((int)fin->getU8(), std::max(width * 32, height * 32)) : 32;
m_layers = fin->getU8();
m_numPatternX = fin->getU8();
m_numPatternY = fin->getU8();
m_numPatternZ = fin->getU8();
m_animationPhases = fin->getU8();
int totalSprites = m_size.area() * m_layers * m_numPatternX * m_numPatternY * m_numPatternZ * m_animationPhases;
if(totalSprites == 0)
stdext::throw_exception("a thing type has no sprites");
if(totalSprites > 4096)
stdext::throw_exception("a thing type has more than 4096 sprites");
m_spritesIndex.resize(totalSprites);
for(int i = 0; i < totalSprites; i++)
m_spritesIndex[i] = g_game.getFeature(Otc::GameSpritesU32) ? fin->getU32() : fin->getU16();
m_textures.resize(m_animationPhases);
m_texturesFramesRects.resize(m_animationPhases);
m_texturesFramesOriginRects.resize(m_animationPhases);
m_texturesFramesOffsets.resize(m_animationPhases);
}
void ThingType::unserializeOtml(const OTMLNodePtr& node)
{
for(const OTMLNodePtr& node2 : node->children()) {
if(node2->tag() == "opacity")
m_opacity = node2->value<float>();
else if(node2->tag() == "notprewalkable")
m_attribs.set(ThingAttrNotPreWalkable, node2->value<bool>());
else if(node2->tag() == "image")
m_customImage = node2->value();
else if(node2->tag() == "full-ground") {
if(node2->value<bool>())
m_attribs.set(ThingAttrFullGround, true);
else
m_attribs.remove(ThingAttrFullGround);
}
}
}
void ThingType::draw(const Point& dest, float scaleFactor, int layer, int xPattern, int yPattern, int zPattern, int animationPhase, LightView *lightView)
{
if(m_null)
return;
const TexturePtr& texture = getTexture(animationPhase); // texture might not exists, neither its rects.
int frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern);
Point textureOffset;
Rect textureRect;
if(scaleFactor != 1.0f) {
textureRect = m_texturesFramesOriginRects[animationPhase][frameIndex];
} else {
textureOffset = m_texturesFramesOffsets[animationPhase][frameIndex];
textureRect = m_texturesFramesRects[animationPhase][frameIndex];
}
Rect screenRect(dest + (textureOffset - m_displacement - (m_size.toPoint() - Point(1, 1)) * 32) * scaleFactor,
textureRect.size() * scaleFactor);
bool useOpacity = m_opacity < 1.0f;
if(useOpacity)
g_painter->setColor(Color(1.0f,1.0f,1.0f,m_opacity));
g_painter->drawTexturedRect(screenRect, texture, textureRect);
if(useOpacity)
g_painter->setColor(Color::white);
if(lightView && hasLight()) {
Light light = getLight();
if(light.intensity > 0)
lightView->addLightSource(screenRect.center(), scaleFactor, light);
}
}
const TexturePtr& ThingType::getTexture(int animationPhase)
{
TexturePtr& animationPhaseTexture = m_textures[animationPhase];
if(!animationPhaseTexture) {
bool useCustomImage = false;
if(animationPhase == 0 && !m_customImage.empty())
useCustomImage = true;
// we don't need layers in common items, they will be pre-drawn
int textureLayers = 1;
int numLayers = m_layers;
if(m_category == ThingCategoryCreature && numLayers >= 2) {
// 5 layers: outfit base, red mask, green mask, blue mask, yellow mask
textureLayers = 5;
numLayers = 5;
}
int indexSize = textureLayers * m_numPatternX * m_numPatternY * m_numPatternZ;
Size textureSize = getBestTextureDimension(m_size.width(), m_size.height(), indexSize);
ImagePtr fullImage;
if(useCustomImage)
fullImage = Image::load(m_customImage);
else
fullImage = ImagePtr(new Image(textureSize * Otc::TILE_PIXELS));
m_texturesFramesRects[animationPhase].resize(indexSize);
m_texturesFramesOriginRects[animationPhase].resize(indexSize);
m_texturesFramesOffsets[animationPhase].resize(indexSize);
for(int z = 0; z < m_numPatternZ; ++z) {
for(int y = 0; y < m_numPatternY; ++y) {
for(int x = 0; x < m_numPatternX; ++x) {
for(int l = 0; l < numLayers; ++l) {
bool spriteMask = (m_category == ThingCategoryCreature && l > 0);
int frameIndex = getTextureIndex(l % textureLayers, x, y, z);
Point framePos = Point(frameIndex % (textureSize.width() / m_size.width()) * m_size.width(),
frameIndex / (textureSize.width() / m_size.width()) * m_size.height()) * Otc::TILE_PIXELS;
if(!useCustomImage) {
for(int h = 0; h < m_size.height(); ++h) {
for(int w = 0; w < m_size.width(); ++w) {
uint spriteIndex = getSpriteIndex(w, h, spriteMask ? 1 : l, x, y, z, animationPhase);
ImagePtr spriteImage = g_sprites.getSpriteImage(m_spritesIndex[spriteIndex]);
if(spriteImage) {
if(spriteMask) {
static Color maskColors[] = { Color::red, Color::green, Color::blue, Color::yellow };
spriteImage->overwriteMask(maskColors[l - 1]);
}
Point spritePos = Point(m_size.width() - w - 1,
m_size.height() - h - 1) * Otc::TILE_PIXELS;
fullImage->blit(framePos + spritePos, spriteImage);
}
}
}
}
Rect drawRect(framePos + Point(m_size.width(), m_size.height()) * Otc::TILE_PIXELS - Point(1,1), framePos);
for(int x = framePos.x; x < framePos.x + m_size.width() * Otc::TILE_PIXELS; ++x) {
for(int y = framePos.y; y < framePos.y + m_size.height() * Otc::TILE_PIXELS; ++y) {
uint8 *p = fullImage->getPixel(x,y);
if(p[3] != 0x00) {
drawRect.setTop (std::min(y, (int)drawRect.top()));
drawRect.setLeft (std::min(x, (int)drawRect.left()));
drawRect.setBottom(std::max(y, (int)drawRect.bottom()));
drawRect.setRight (std::max(x, (int)drawRect.right()));
}
}
}
m_texturesFramesRects[animationPhase][frameIndex] = drawRect;
m_texturesFramesOriginRects[animationPhase][frameIndex] = Rect(framePos, Size(m_size.width(), m_size.height()) * Otc::TILE_PIXELS);
m_texturesFramesOffsets[animationPhase][frameIndex] = drawRect.topLeft() - framePos;
}
}
}
}
animationPhaseTexture = TexturePtr(new Texture(fullImage, true));
animationPhaseTexture->setSmooth(true);
}
return animationPhaseTexture;
}
Size ThingType::getBestTextureDimension(int w, int h, int count)
{
const int MAX = 32;
int k = 1;
while(k < w)
k<<=1;
w = k;
k = 1;
while(k < h)
k<<=1;
h = k;
int numSprites = w*h*count;
assert(numSprites <= MAX*MAX);
assert(w <= MAX);
assert(h <= MAX);
Size bestDimension = Size(MAX, MAX);
for(int i=w;i<=MAX;i<<=1) {
for(int j=h;j<=MAX;j<<=1) {
Size candidateDimension = Size(i, j);
if(candidateDimension.area() < numSprites)
continue;
if((candidateDimension.area() < bestDimension.area()) ||
(candidateDimension.area() == bestDimension.area() && candidateDimension.width() + candidateDimension.height() < bestDimension.width() + bestDimension.height()))
bestDimension = candidateDimension;
}
}
return bestDimension;
}
uint ThingType::getSpriteIndex(int w, int h, int l, int x, int y, int z, int a) {
uint index =
((((((a % m_animationPhases)
* m_numPatternZ + z)
* m_numPatternY + y)
* m_numPatternX + x)
* m_layers + l)
* m_size.height() + h)
* m_size.width() + w;
assert(index < m_spritesIndex.size());
return index;
}
uint ThingType::getTextureIndex(int l, int x, int y, int z) {
return ((l * m_numPatternZ + z)
* m_numPatternY + y)
* m_numPatternX + x;
}
int ThingType::getExactSize(int layer, int xPattern, int yPattern, int zPattern, int animationPhase)
{
getTexture(animationPhase); // we must calculate it anyway.
int frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern);
Size size = m_texturesFramesOriginRects[animationPhase][frameIndex].size() - m_texturesFramesOffsets[animationPhase][frameIndex].toSize();
return std::max(size.width(), size.height());
}
<|endoftext|>
|
<commit_before>//
// Originally written by BjÃrn Fahller (bjorn@fahller.se)
// Modified by Jeff Bush
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//
#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>
#include <vector>
#include <algorithm>
namespace basic {
struct stack_frame { jmp_buf buf; };
std::forward_list<stack_frame> stack;
#define GOSUB \
if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
&& (basic::stack.pop_front(),true))) \
goto
#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)
template <typename T, typename U>
struct separator
{
static char const *str() { return ""; }
};
template <typename T>
struct separator<T,T>
{
static char const *str() { return ","; }
};
inline void type_mismatch() {
std::cout << "Type mismatch error\n";
exit(1);
}
inline void array_out_of_bounds() {
std::cout << "Array out of bounds error\n";
exit(1);
}
inline void dimension_error() {
std::cout << "Array Dimension error\n";
exit(1);
}
inline void illegal_quantity_error() {
std::cout << "Illegal quantity error\n";
exit(1);
}
class variant
{
public:
variant()
: isnum(true),
numval(0)
{}
variant(double _numval)
: isnum(true),
numval(_numval)
{}
variant(int _numval)
: isnum(true),
numval(_numval)
{}
variant(const std::string _strval)
: isnum(false),
strval(_strval)
{}
variant(const char *_strval)
: isnum(false),
strval(_strval)
{}
double numeric() const {
if (!isnum)
type_mismatch();
return numval;
}
std::string string() const {
if (isnum)
type_mismatch();
return strval;
}
variant toString() const {
if (isnum)
return variant(std::to_string(numval));
else
return *this;
}
variant toNum() const {
if (!isnum)
return variant(stod(strval));
else
return *this;
}
variant &operator=(const variant ©from) {
isnum = copyfrom.isnum;
numval = copyfrom.numval;
strval = copyfrom.strval;
return *this;
}
// Note that strings in BASIC are 1 based, so subtract 1 from the left
// index
variant midStr(const variant &left, const variant &right) const {
if (isnum || !left.isnum || !right.isnum)
type_mismatch();
return variant(strval.substr(int(left.numval) - 1, (int(right.numval) - int(left.numval) + 1)));
}
variant leftStr(const variant &count) const {
if (isnum)
type_mismatch();
return variant(strval.substr(0, int(count.numval)));
}
variant rightStr(const variant &count) const {
if (isnum)
type_mismatch();
return variant(strval.substr(strval.length() - int(count.numval) - 1, int(count.numval)));
}
variant strlen() const {
if (isnum)
type_mismatch();
return variant((int)strval.length());
}
variant operator+(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return variant(numval + op.numval);
else
return variant(strval + op.strval);
}
variant operator-(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval - op.numval);
}
variant operator*(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval * op.numval);
}
variant operator/(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval / op.numval);
}
bool operator>(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval > op.numval;
else
return strval > op.strval;
}
bool operator>=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval >= op.numval;
else
return strval >= op.strval;
}
bool operator<(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval < op.numval;
else
return strval < op.strval;
}
bool operator<=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval <= op.numval;
else
return strval <= op.strval;
}
bool operator!=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval != op.numval;
else
return strval != op.strval;
}
bool operator==(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval == op.numval;
else
return strval == op.strval;
}
bool isnum;
double numval;
std::string strval;
};
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator+(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) + p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator-(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) - p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator*(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) * p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator/(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) / p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, bool>::type
operator==(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) == p;
}
template <typename T>
struct is_dimmable
{
using DT = typename std::decay<T>::type;
static constexpr bool value = std::is_integral<DT>::value || std::is_same<DT, variant>::value;
};
template <template <typename> class pred, typename ... T>
struct all_are
{
static constexpr bool value = true;
};
template <template <typename> class pred, typename H, typename ... T>
struct all_are<pred, H, T...>
{
static constexpr bool value = pred<H>::value && all_are<pred, T...>::value;
};
template <typename T>
T numeric_value(T t) { return t; }
inline
long numeric_value(const variant& v) { return long(v.numeric()); }
class array
{
public:
template <typename ... T, typename = typename std::enable_if<all_are<is_dimmable, T...>::value>::type>
array(T const & ... t)
: dimensions{1LU+numeric_value(t)..., 1LU},
elements(std::accumulate(std::begin(dimensions),
std::end(dimensions),
1U,
[](std::size_t i, std::size_t j){ return i*j;}))
{}
template <typename ... T>
typename std::enable_if<all_are<is_dimmable, T...>::value, variant&>::type
operator()(T const& ... t) {
if (sizeof...(t) != dimensions.size() - 1)
dimension_error();
long indexes[] { long(numeric_value(t))... };
auto i = sizeof...(t);
size_t mul = 1U;
size_t idx = 0U;
while (i--)
{
if (indexes[i] < 0 || indexes[i] >= dimensions[i])
array_out_of_bounds();
idx += indexes[i]*mul;
mul = dimensions[i];
}
return elements[idx];
}
private:
std::vector<std::size_t> dimensions;
std::vector<variant> elements;
};
class printer
{
public:
printer &operator,(const char *s) {
std::cout << s;
return *this;
}
printer &operator,(const variant &v) {
if (v.isnum)
std::cout << v.numval;
else
std::cout << v.strval;
return *this;
}
~printer() { std::cout << std::endl; }
};
class input
{
public:
input& operator,(char const *s) {
std::cout << s << std::flush;
return *this;
}
input& operator,(variant& v) {
if (v.isnum)
std::cin >> v.numval;
else
std::cin >> v.strval;
return *this;
}
};
template <typename T>
variant to_char_str(T const& t)
{
auto n = numeric_value(t);
char a[] = { char(n), '\0' };
return variant{a};
}
template <std::size_t N>
inline variant to_asc_val(char const (&a)[N])
{
if (N < 2) illegal_quantity_error();
return variant(double(a[0]));
}
inline variant to_asc_val(variant const& v)
{
auto s = v.string();
if (s.empty()) illegal_quantity_error();
return variant(double(s[0]));
}
#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET basic::variant
#define GOTO goto
#define FOR { basic::variant& for_loop_variable =
#define TO ; \
{ \
jmp_buf for_loop_top; \
bool for_loop_exit = false; \
while (!for_loop_exit) \
{ \
if (setjmp(for_loop_top) == 0) \
{ \
basic::variant for_loop_step=1; \
basic::variant const for_loop_endval=
#define STEP ; \
for_loop_step=
#define NEXT for_loop_variable=for_loop_variable+for_loop_step; \
for_loop_exit=( ( for_loop_step > 0 \
&& for_loop_variable > for_loop_endval) \
||( for_loop_step < 0 \
&& for_loop_variable < for_loop_endval)); \
longjmp(for_loop_top, 1); \
} \
} \
} \
}
#define END exit(0)
#define VAL(x) x.toNum()
#define STR(x) x.toString()
#define MID$(str, left, right) str.midStr(left, right)
#define LEFT$(str, count) str.leftStr(count)
#define RIGHT$(str, count) str.rightStr(count)
#define LEN(str) str.strlen()
#define DIM basic::array
#define RND(x) ((rand() & 0xffff)/65535.0)
#define INT(x) static_cast<int>(basic::numeric_value(x))
#define CHR$(num) basic::to_char_str(num)
#define ASC(str) basic::to_asc_val(str)
} // namespace basic
<commit_msg>Fixed UTF8 issue<commit_after>//
// Originally written by Björn Fahller (bjorn@fahller.se)
// Modified by Jeff Bush
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//
#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>
#include <vector>
#include <algorithm>
#include <numeric>
namespace basic {
struct stack_frame { jmp_buf buf; };
std::forward_list<stack_frame> stack;
#define GOSUB \
if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
&& (basic::stack.pop_front(),true))) \
goto
#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)
template <typename T, typename U>
struct separator
{
static char const *str() { return ""; }
};
template <typename T>
struct separator<T,T>
{
static char const *str() { return ","; }
};
inline void type_mismatch() {
std::cout << "Type mismatch error\n";
exit(1);
}
inline void array_out_of_bounds() {
std::cout << "Array out of bounds error\n";
exit(1);
}
inline void dimension_error() {
std::cout << "Array Dimension error\n";
exit(1);
}
inline void illegal_quantity_error() {
std::cout << "Illegal quantity error\n";
exit(1);
}
class variant
{
public:
variant()
: isnum(true),
numval(0)
{}
variant(double _numval)
: isnum(true),
numval(_numval)
{}
variant(int _numval)
: isnum(true),
numval(_numval)
{}
variant(const std::string _strval)
: isnum(false),
strval(_strval)
{}
variant(const char *_strval)
: isnum(false),
strval(_strval)
{}
double numeric() const {
if (!isnum)
type_mismatch();
return numval;
}
std::string string() const {
if (isnum)
type_mismatch();
return strval;
}
variant toString() const {
if (isnum)
return variant(std::to_string(numval));
else
return *this;
}
variant toNum() const {
if (!isnum)
return variant(stod(strval));
else
return *this;
}
variant &operator=(const variant ©from) {
isnum = copyfrom.isnum;
numval = copyfrom.numval;
strval = copyfrom.strval;
return *this;
}
// Note that strings in BASIC are 1 based, so subtract 1 from the left
// index
variant midStr(const variant &left, const variant &right) const {
if (isnum || !left.isnum || !right.isnum)
type_mismatch();
return variant(strval.substr(int(left.numval) - 1, (int(right.numval) - int(left.numval) + 1)));
}
variant leftStr(const variant &count) const {
if (isnum)
type_mismatch();
return variant(strval.substr(0, int(count.numval)));
}
variant rightStr(const variant &count) const {
if (isnum)
type_mismatch();
return variant(strval.substr(strval.length() - int(count.numval) - 1, int(count.numval)));
}
variant strlen() const {
if (isnum)
type_mismatch();
return variant((int)strval.length());
}
variant operator+(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return variant(numval + op.numval);
else
return variant(strval + op.strval);
}
variant operator-(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval - op.numval);
}
variant operator*(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval * op.numval);
}
variant operator/(const variant op) const {
if (!isnum || !op.isnum)
type_mismatch();
return variant(numval / op.numval);
}
bool operator>(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval > op.numval;
else
return strval > op.strval;
}
bool operator>=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval >= op.numval;
else
return strval >= op.strval;
}
bool operator<(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval < op.numval;
else
return strval < op.strval;
}
bool operator<=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval <= op.numval;
else
return strval <= op.strval;
}
bool operator!=(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval != op.numval;
else
return strval != op.strval;
}
bool operator==(const variant op) const {
if (isnum != op.isnum)
type_mismatch();
if (isnum)
return numval == op.numval;
else
return strval == op.strval;
}
bool isnum;
double numval;
std::string strval;
};
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator+(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) + p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator-(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) - p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator*(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) * p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, variant>::type
operator/(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) / p;
}
template <typename T>
typename std::enable_if<std::is_constructible<variant, T>::value && !std::is_same<typename std::decay<T>::type, variant>::value, bool>::type
operator==(T&& t, variant const& p)
{
return variant(std::forward<T>(t)) == p;
}
template <typename T>
struct is_dimmable
{
using DT = typename std::decay<T>::type;
static constexpr bool value = std::is_integral<DT>::value || std::is_same<DT, variant>::value;
};
template <template <typename> class pred, typename ... T>
struct all_are
{
static constexpr bool value = true;
};
template <template <typename> class pred, typename H, typename ... T>
struct all_are<pred, H, T...>
{
static constexpr bool value = pred<H>::value && all_are<pred, T...>::value;
};
template <typename T>
T numeric_value(T t) { return t; }
inline
long numeric_value(const variant& v) { return long(v.numeric()); }
class array
{
public:
template <typename ... T, typename = typename std::enable_if<all_are<is_dimmable, T...>::value>::type>
array(T const & ... t)
: dimensions{1LU+numeric_value(t)..., 1LU},
elements(std::accumulate(std::begin(dimensions),
std::end(dimensions),
1U,
[](std::size_t i, std::size_t j){ return i*j;}))
{}
template <typename ... T>
typename std::enable_if<all_are<is_dimmable, T...>::value, variant&>::type
operator()(T const& ... t) {
if (sizeof...(t) != dimensions.size() - 1)
dimension_error();
long indexes[] { long(numeric_value(t))... };
auto i = sizeof...(t);
size_t mul = 1U;
size_t idx = 0U;
while (i--)
{
if (indexes[i] < 0 || indexes[i] >= dimensions[i])
array_out_of_bounds();
idx += indexes[i]*mul;
mul = dimensions[i];
}
return elements[idx];
}
private:
std::vector<std::size_t> dimensions;
std::vector<variant> elements;
};
class printer
{
public:
printer &operator,(const char *s) {
std::cout << s;
return *this;
}
printer &operator,(const variant &v) {
if (v.isnum)
std::cout << v.numval;
else
std::cout << v.strval;
return *this;
}
~printer() { std::cout << std::endl; }
};
class input
{
public:
input& operator,(char const *s) {
std::cout << s << std::flush;
return *this;
}
input& operator,(variant& v) {
if (v.isnum)
std::cin >> v.numval;
else
std::cin >> v.strval;
return *this;
}
};
template <typename T>
variant to_char_str(T const& t)
{
auto n = numeric_value(t);
char a[] = { char(n), '\0' };
return variant{a};
}
template <std::size_t N>
inline variant to_asc_val(char const (&a)[N])
{
if (N < 2) illegal_quantity_error();
return variant(double(a[0]));
}
inline variant to_asc_val(variant const& v)
{
auto s = v.string();
if (s.empty()) illegal_quantity_error();
return variant(double(s[0]));
}
#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET basic::variant
#define GOTO goto
#define FOR { basic::variant& for_loop_variable =
#define TO ; \
{ \
jmp_buf for_loop_top; \
bool for_loop_exit = false; \
while (!for_loop_exit) \
{ \
if (setjmp(for_loop_top) == 0) \
{ \
basic::variant for_loop_step=1; \
basic::variant const for_loop_endval=
#define STEP ; \
for_loop_step=
#define NEXT for_loop_variable=for_loop_variable+for_loop_step; \
for_loop_exit=( ( for_loop_step > 0 \
&& for_loop_variable > for_loop_endval) \
||( for_loop_step < 0 \
&& for_loop_variable < for_loop_endval)); \
longjmp(for_loop_top, 1); \
} \
} \
} \
}
#define END exit(0)
#define VAL(x) x.toNum()
#define STR(x) x.toString()
#define MID$(str, left, right) str.midStr(left, right)
#define LEFT$(str, count) str.leftStr(count)
#define RIGHT$(str, count) str.rightStr(count)
#define LEN(str) str.strlen()
#define DIM basic::array
#define RND(x) ((rand() & 0xffff)/65535.0)
#define INT(x) static_cast<int>(basic::numeric_value(x))
#define CHR$(num) basic::to_char_str(num)
#define ASC(str) basic::to_asc_val(str)
} // namespace basic
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
#include <iostream>
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
// ignore the "Global" namespace, which contains the QtMsgType enum
if (meta_class->name().startsWith("Global")) return false;
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
if (type->isEnum() && (options & ProtectedEnumAsInts)) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)te);
if (enumType && enumType->wasProtected()) {
s << "int";
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName)) {
if (option & UseIndexedName) {
s << " " << arg->indexedName();
}
else {
s << " " << arg->argumentName();
}
}
if ((option & IncludeDefaultExpression) && !arg->defaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->defaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "py_set_";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "py_get_";
s << name_prefix << function_name;
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
if (!meta_function->exception().isEmpty())
s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);
bool ShellGenerator::functionHasNonConstReferences(const AbstractMetaFunction* function)
{
foreach(const AbstractMetaArgument* arg, function->arguments())
{
if (!arg->type()->isConstant() && arg->type()->isReference()) {
QString s;
QTextStream t(&s);
t << function->implementingClass()->qualifiedCppName() << "::";
writeFunctionSignature(t, function, 0, "",
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
std::cout << s.toLatin1().constData() << std::endl;
return true;
}
}
return false;
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
bool hasPromoter = meta_class->typeEntry()->shouldCreatePromoter();
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
if (hasPromoter || func->wasPublic()) {
resultFunctions << func;
}
}
}
qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
// | AbstractMetaClass::NotRemovedFromTargetLang
);
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (func->wasProtected() || func->isVirtual()) {
functions << func;
}
}
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QByteArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<commit_msg>remove virtual functions that are removed from the target language (why was this commented?)<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
#include <iostream>
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
// ignore the "Global" namespace, which contains the QtMsgType enum
if (meta_class->name().startsWith("Global")) return false;
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
if (type->isEnum() && (options & ProtectedEnumAsInts)) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)te);
if (enumType && enumType->wasProtected()) {
s << "int";
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName)) {
if (option & UseIndexedName) {
s << " " << arg->indexedName();
}
else {
s << " " << arg->argumentName();
}
}
if ((option & IncludeDefaultExpression) && !arg->defaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->defaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "py_set_";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "py_get_";
s << name_prefix << function_name;
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
if (!meta_function->exception().isEmpty())
s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);
bool ShellGenerator::functionHasNonConstReferences(const AbstractMetaFunction* function)
{
foreach(const AbstractMetaArgument* arg, function->arguments())
{
if (!arg->type()->isConstant() && arg->type()->isReference()) {
QString s;
QTextStream t(&s);
t << function->implementingClass()->qualifiedCppName() << "::";
writeFunctionSignature(t, function, 0, "",
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
std::cout << s.toLatin1().constData() << std::endl;
return true;
}
}
return false;
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
bool hasPromoter = meta_class->typeEntry()->shouldCreatePromoter();
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
if (hasPromoter || func->wasPublic()) {
resultFunctions << func;
}
}
}
qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang
);
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (func->wasProtected() || func->isVirtual()) {
functions << func;
}
}
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QByteArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<|endoftext|>
|
<commit_before>#include "Application.hpp"
#include "InputHandlers.hpp"
#include "renderer/RenderContext.hpp"
#include "renderer/ShaderManager.hpp"
#include "renderer/OculusVR.hpp"
#include "renderer/CameraDirector.hpp"
// application globals
extern CameraDirector g_cameraDirector;
RenderContext g_renderContext;
Application g_application;
OculusVR g_oculusVR;
int main(int argc, char **argv)
{
// initialize everything
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 )
{
return 1;
}
if (!g_oculusVR.InitVR())
{
SDL_Quit();
return 1;
}
ovrSizei hmdResolution = g_oculusVR.GetResolution();
ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 };
g_renderContext.Init("Oculus Rift Minimum OpenGL", 100, 100, windowSize.w, windowSize.h);
SDL_ShowCursor(SDL_DISABLE);
if (glewInit() != GLEW_OK)
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitNonDistortMirror(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
ShaderManager::GetInstance()->LoadShaders();
g_application.OnStart();
while (g_application.Running())
{
// handle key presses
processEvents();
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_oculusVR.OnRenderStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex);
// update MVP in quad shader
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
g_application.OnRender();
g_oculusVR.OnEyeRenderFinish(eyeIndex);
}
g_oculusVR.SubmitFrame();
Application::VRMirrorMode mirrorMode = g_application.CurrMirrorMode();
if (mirrorMode == Application::Mirror_Regular)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Count, 0);
}
if (mirrorMode == Application::Mirror_RegularLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Left, windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
if (mirrorMode == Application::Mirror_RegularRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Right, windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
if (mirrorMode == Application::Mirror_NonDistort)
{
// non distorted, dual view
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(eyeIndex);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(eyeIndex == 0 ? 0 : windowSize.w / 2);
}
// non distort end
}
if (mirrorMode == Application::Mirror_NonDistortLeftEye)
{
// non distorted, centered
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Left);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
// non distorted end
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
if (mirrorMode == Application::Mirror_NonDistortRightEye)
{
// non distorted, centered
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Right);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
// non distorted end
}
SDL_GL_SwapWindow(g_renderContext.window);
}
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 0;
}<commit_msg>added extra comments<commit_after>#include "Application.hpp"
#include "InputHandlers.hpp"
#include "renderer/RenderContext.hpp"
#include "renderer/ShaderManager.hpp"
#include "renderer/OculusVR.hpp"
#include "renderer/CameraDirector.hpp"
// application globals
extern CameraDirector g_cameraDirector;
RenderContext g_renderContext;
Application g_application;
OculusVR g_oculusVR;
int main(int argc, char **argv)
{
// initialize everything
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 )
{
return 1;
}
if (!g_oculusVR.InitVR())
{
SDL_Quit();
return 1;
}
ovrSizei hmdResolution = g_oculusVR.GetResolution();
ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 };
g_renderContext.Init("Oculus Rift Minimum OpenGL", 100, 100, windowSize.w, windowSize.h);
SDL_ShowCursor(SDL_DISABLE);
if (glewInit() != GLEW_OK)
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitNonDistortMirror(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
ShaderManager::GetInstance()->LoadShaders();
g_application.OnStart();
while (g_application.Running())
{
// handle key presses
processEvents();
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_oculusVR.OnRenderStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex);
// update MVP in quad shader
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
g_application.OnRender();
g_oculusVR.OnEyeRenderFinish(eyeIndex);
}
g_oculusVR.SubmitFrame();
Application::VRMirrorMode mirrorMode = g_application.CurrMirrorMode();
/*
* Standard mirror blit (both eyes, distorted)
*/
if (mirrorMode == Application::Mirror_Regular)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Count, 0);
}
/*
* Standard mirror blit (single eye, left)
*/
if (mirrorMode == Application::Mirror_RegularLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Left, windowSize.w / 4);
// rectangle indicating we're rendering left eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
/*
* Standard mirror blit (single eye, right)
*/
if (mirrorMode == Application::Mirror_RegularRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Right, windowSize.w / 4);
// rectangle indicating we're rendering right eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
/*
* Both eye mirror - no distortion (requires 2 extra renders!)
*/
if (mirrorMode == Application::Mirror_NonDistort)
{
g_oculusVR.OnNonDistortMirrorStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(eyeIndex);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(eyeIndex == 0 ? 0 : windowSize.w / 2);
}
}
/*
* Left eye - no distortion (1 extra render)
*/
if (mirrorMode == Application::Mirror_NonDistortLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Left);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
/*
* Right eye - no distortion (1 extra render)
*/
if (mirrorMode == Application::Mirror_NonDistortRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Right);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
SDL_GL_SwapWindow(g_renderContext.window);
}
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 0;
}<|endoftext|>
|
<commit_before>/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.net/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseClient.hpp *
* *
* hprose client class for Cpp. *
* *
* LastModified: Mar 2, 2014 *
* Author: Chen fei <cf@hprose.com> *
* *
\**********************************************************/
#ifndef HPROSE_CLIENT_HPROSE_CLIENT_HPP
#define HPROSE_CLIENT_HPROSE_CLIENT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <hprose/io.hpp>
#include <boost/thread.hpp>
namespace hprose {
namespace HproseTags {
const char ResultTags[4] = { TagResult, TagArgument, TagError, TagEnd }; // Todo: Remove
} // namespace HproseTags
class HproseClient {
protected: // structors
HproseClient() {
}
HproseClient(const std::string & uri) {
UseService(uri);
}
virtual ~HproseClient() {
}
protected:
virtual void * GetInvokeContext() = 0;
virtual void SendData(void * context) = 0;
virtual void EndInvoke(void * context) = 0;
virtual std::ostream & GetOutputStream(void * context) = 0;
virtual std::istream & GetInputStream(void * context) = 0;
public:
virtual void UseService(const std::string & uri) {
this->uri = uri;
}
template<typename ReturnType>
inline ReturnType Invoke(const std::string & name) {
std::vector<Any> args;
return Invoke<ReturnType>(name, args);
}
template<typename ReturnType>
inline void Invoke(ReturnType & ret, const std::string & name) {
std::vector<Any> args;
Invoke(ret, name, args);
}
#ifndef BOOST_NO_INITIALIZER_LISTS
template<typename ReturnType, typename ArgType>
inline ReturnType Invoke(const std::string & name, const std::initializer_list<ArgType> & args) {
return Invoke<ReturnType>(name, args, false);
}
template<typename ReturnType, typename ArgType>
inline void Invoke(ReturnType & ret, const std::string & name, const std::initializer_list<ArgType> & args) {
Invoke(ret, name, args, false);
}
#endif
template<typename ReturnType, typename ArgsType>
inline ReturnType Invoke(const std::string & name, ArgsType & args, bool ref = false) {
ReturnType ret = ReturnType();
Invoke(ret, name, args, ref);
return ret;
}
template<typename ReturnType, typename ArgsType>
void Invoke(ReturnType & ret, const std::string & name, ArgsType & args, bool ref = false) {
std::string error;
void * context = 0;
context = GetInvokeContext();
try {
DoOutput(name, args, ref, GetOutputStream(context));
SendData(context);
DoInput(ret, args, error, GetInputStream(context));
}
catch (...) {
}
EndInvoke(context);
if (!error.empty()) {
HPROSE_THROW_EXCEPTION(error);
}
}
template<typename ReturnType, typename Functor>
inline void AsyncInvoke(const std::string & name, Functor func) {
static std::vector<Any> args;
AsyncInvoke<ReturnType>(name, args, func, false);
}
template<typename ReturnType, typename ArgsType, typename Functor>
inline void AsyncInvoke(const std::string & name, ArgsType & args, Functor func, bool ref = false) {
boost::thread thread(Async<ReturnType, ArgsType, Functor>(*this, name, args, func, ref));
}
private:
template<typename ReturnType, typename ArgsType, typename Functor>
class Async {
public:
Async(HproseClient & client, const std::string & name, ArgsType & args, Functor func, bool ref)
: client(client), name(name), args(args), func(func), ref(ref) {
}
public:
inline void operator()() {
ReturnType ret = ReturnType();
client.Invoke(ret, name, args, ref);
func(ret, args);
}
private:
HproseClient & client;
std::string name;
ArgsType & args;
Functor func;
bool ref;
}; // class Async
private:
template<typename ReturnType, typename ArgsType>
void DoInput(ReturnType & ret, ArgsType & args, std::string & error, std::istream & stream) {
HproseReader reader(stream);
while (true) {
switch (reader.CheckTags(HproseTags::ResultTags)) {
case HproseTags::TagResult:
ret = reader.Unserialize<ReturnType>();
break;
case HproseTags::TagArgument:
//args = reader.ReadList<ArgsType>();
break;
case HproseTags::TagError:
error = reader.ReadString();
return;
case HproseTags::TagEnd:
return;
}
}
}
template<typename ArgsType>
void DoOutput(const std::string & name, ArgsType & args, bool ref, std::ostream & stream) {
HproseWriter writer(stream);
stream << HproseTags::TagCall;
writer.WriteString(name, false);
writer.WriteList(args, false);
if (ref) {
writer.WriteBool(true);
}
stream << HproseTags::TagEnd;
}
template<typename ArgsType, size_t ArraySize>
void DoOutput(const std::string & name, ArgsType (&args)[ArraySize], bool ref, std::ostream & stream) {
HproseWriter writer(stream);
stream << HproseTags::TagCall;
writer.WriteString(name, false);
writer.WriteList(args, false);
if (ref) {
writer.WriteBool(true);
}
stream << HproseTags::TagEnd;
}
protected:
std::string uri;
}; // class HproseClient
} // namespace hprose
#endif // HPROSE_CLIENT_HPROSE_CLIENT_HPP
<commit_msg>fix Async invoke args destroy early issue.<commit_after>/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.net/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseClient.hpp *
* *
* hprose client class for Cpp. *
* *
* LastModified: Mar 2, 2014 *
* Author: Chen fei <cf@hprose.com> *
* *
\**********************************************************/
#ifndef HPROSE_CLIENT_HPROSE_CLIENT_HPP
#define HPROSE_CLIENT_HPROSE_CLIENT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <hprose/io.hpp>
#include <boost/thread.hpp>
namespace hprose {
namespace HproseTags {
const char ResultTags[4] = { TagResult, TagArgument, TagError, TagEnd }; // Todo: Remove
} // namespace HproseTags
class HproseClient {
protected: // structors
HproseClient() {
}
HproseClient(const std::string & uri) {
UseService(uri);
}
virtual ~HproseClient() {
}
protected:
virtual void * GetInvokeContext() = 0;
virtual void SendData(void * context) = 0;
virtual void EndInvoke(void * context) = 0;
virtual std::ostream & GetOutputStream(void * context) = 0;
virtual std::istream & GetInputStream(void * context) = 0;
public:
virtual void UseService(const std::string & uri) {
this->uri = uri;
}
template<typename ReturnType>
inline ReturnType Invoke(const std::string & name) {
std::vector<Any> args;
return Invoke<ReturnType>(name, args);
}
template<typename ReturnType>
inline void Invoke(ReturnType & ret, const std::string & name) {
std::vector<Any> args;
Invoke(ret, name, args);
}
#ifndef BOOST_NO_INITIALIZER_LISTS
template<typename ReturnType, typename ArgType>
inline ReturnType Invoke(const std::string & name, const std::initializer_list<ArgType> & args) {
return Invoke<ReturnType>(name, args, false);
}
template<typename ReturnType, typename ArgType>
inline void Invoke(ReturnType & ret, const std::string & name, const std::initializer_list<ArgType> & args) {
Invoke(ret, name, args, false);
}
#endif
template<typename ReturnType, typename ArgsType>
inline ReturnType Invoke(const std::string & name, ArgsType & args, bool ref = false) {
ReturnType ret = ReturnType();
Invoke(ret, name, args, ref);
return ret;
}
template<typename ReturnType, typename ArgsType>
void Invoke(ReturnType & ret, const std::string & name, ArgsType & args, bool ref = false) {
std::string error;
void * context = 0;
context = GetInvokeContext();
try {
DoOutput(name, args, ref, GetOutputStream(context));
SendData(context);
DoInput(ret, args, error, GetInputStream(context));
}
catch (...) {
}
EndInvoke(context);
if (!error.empty()) {
HPROSE_THROW_EXCEPTION(error);
}
}
template<typename ReturnType, typename Functor>
inline void AsyncInvoke(const std::string & name, Functor func) {
static std::vector<Any> args;
AsyncInvoke<ReturnType>(name, args, func, false);
}
template<typename ReturnType, typename ArgsType, typename Functor>
inline void AsyncInvoke(const std::string & name, const ArgsType & args, Functor func, bool ref = false) {
boost::thread thread(Async<ReturnType, ArgsType, Functor>(*this, name, args, func, ref));
}
template<typename ReturnType, typename ArgsType, typename Functor, size_t ArraySize>
inline void AsyncInvoke(const std::string & name, const ArgsType (&args)[ArraySize], Functor func, bool ref = false) {
std::vector<ArgsType> newArgs(ArraySize);
for (int i = 0; i < ArraySize; ++i) {
newArgs[i] = args[i];
}
AsyncInvoke<ReturnType>(name, newArgs, func, ref);
}
private:
template<typename ReturnType, typename ArgsType, typename Functor>
class Async {
public:
Async(HproseClient & client, const std::string & name, ArgsType args, Functor func, bool ref)
: client(client), name(name), args(args), func(func), ref(ref) {
}
public:
inline void operator()() {
ReturnType ret = ReturnType();
client.Invoke(ret, name, args, ref);
func(ret, args);
}
private:
HproseClient & client;
std::string name;
ArgsType args;
Functor func;
bool ref;
}; // class Async
private:
template<typename ReturnType, typename ArgsType>
void DoInput(ReturnType & ret, ArgsType & args, std::string & error, std::istream & stream) {
HproseReader reader(stream);
while (true) {
switch (reader.CheckTags(HproseTags::ResultTags)) {
case HproseTags::TagResult:
ret = reader.Unserialize<ReturnType>();
break;
case HproseTags::TagArgument:
//args = reader.ReadList<ArgsType>();
break;
case HproseTags::TagError:
error = reader.ReadString();
return;
case HproseTags::TagEnd:
return;
}
}
}
template<typename ArgsType>
void DoOutput(const std::string & name, ArgsType & args, bool ref, std::ostream & stream) {
HproseWriter writer(stream);
stream << HproseTags::TagCall;
writer.WriteString(name, false);
writer.WriteList(args, false);
if (ref) {
writer.WriteBool(true);
}
stream << HproseTags::TagEnd;
}
template<typename ArgsType, size_t ArraySize>
void DoOutput(const std::string & name, ArgsType (&args)[ArraySize], bool ref, std::ostream & stream) {
HproseWriter writer(stream);
stream << HproseTags::TagCall;
writer.WriteString(name, false);
writer.WriteList(args, false);
if (ref) {
writer.WriteBool(true);
}
stream << HproseTags::TagEnd;
}
protected:
std::string uri;
}; // class HproseClient
} // namespace hprose
#endif // HPROSE_CLIENT_HPROSE_CLIENT_HPP
<|endoftext|>
|
<commit_before>#ifndef HAND_ROLLED_INCLUDED__
#define HAND_ROLLED_INCLUDED__
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
// Variation 1: Accept std::reference_wrapper<>.
#ifndef ACCEPT_REFERENCE_WRAPPER
#define ACCEPT_REFERENCE_WRAPPER 1
#endif
#ifndef INSTRUMENT_COPIES
#define INSTRUMENT_COPIES 1
#endif
#if INSTRUMENT_COPIES
std::size_t& allocations ()
{
static std::size_t allocations_ = 0;
return allocations_;
}
void reset_allocations ()
{ allocations() = 0; }
#endif
class any_printable
{
public:
// Contructors
any_printable () = default;
template <typename T>
any_printable (T value) :
handle_ (
new handle<typename std::remove_reference<T>::type>(
std::forward<T>(value)
)
)
{
#if INSTRUMENT_COPIES
++allocations();
#endif
}
any_printable (const any_printable & rhs) :
handle_ (rhs.handle_->clone())
{}
any_printable (any_printable && rhs) noexcept = default;
// Assignment
template <typename T>
any_printable& operator= (T value)
{
any_printable temp(std::forward<T>(value));
std::swap(temp, *this);
return *this;
}
any_printable & operator= (const any_printable & rhs)
{
any_printable temp(rhs);
std::swap(temp, *this);
return *this;
}
any_printable & operator= (any_printable && rhs) noexcept = default;
// Public interface
void print () const
{
assert(handle_);
handle_->print();
}
private:
struct handle_base
{
virtual ~handle_base () {}
virtual handle_base* clone () const = 0;
// Public interface
virtual void print () const = 0;
};
template <typename T>
struct handle :
handle_base
{
#if ACCEPT_REFERENCE_WRAPPER
template <typename U = T>
handle (T value,
typename std::enable_if<
std::is_reference<U>::value
>::type* = 0) :
value_ (value)
{}
template <typename U = T>
handle (T value,
typename std::enable_if<
!std::is_reference<U>::value,
int
>::type* = 0) noexcept :
value_ (std::move(value))
{}
#else
handle (T value) :
value_ (value)
{}
handle (T && value) noexcept :
value_ (std::move(value))
{}
#endif
virtual handle_base* clone () const
{
#if INSTRUMENT_COPIES
++allocations();
#endif
return new handle(value_);
}
// Public interface
virtual void print () const
{ value_.print(); }
T value_;
};
#if ACCEPT_REFERENCE_WRAPPER
template <typename T>
struct handle<std::reference_wrapper<T>> :
handle<T &>
{
handle (std::reference_wrapper<T> ref) :
handle<T &> (ref.get())
{}
};
#endif
std::unique_ptr<handle_base> handle_;
};
struct hi_printable
{
void print () const
{ std::cout << "Hello, world!\n"; }
};
struct bye_printable
{
void print () const
{ std::cout << "Bye, now!\n"; }
};
struct large_printable :
std::vector<std::string>
{
large_printable () :
std::vector<std::string> (1000, std::string(1000, ' '))
{ ++allocations(); }
large_printable (const large_printable & rhs) :
std::vector<std::string> (rhs)
{ ++allocations(); }
large_printable & operator= (const large_printable & rhs)
{
++allocations();
static_cast<std::vector<std::string> &>(*this) = rhs;
return *this;
}
large_printable (large_printable && rhs) = default;
large_printable & operator= (large_printable && rhs) = default;
void print () const
{ std::cout << "I'm expensive to copy.\n"; }
};
/* Limitations:
1 - Each member functions must be repeated in 3 places.
2 - Macros, which could be used to address this, are evil.
3 - How do you define an any_fooable type, where foo() is a free function?
4 - How do you define an any_barable type, where bar is an operator?
5 - How do you apply the small buffer optimization to handle small types without making allocations?
*/
#endif
<commit_msg>Get rid of troublesome handle<T> move ctor.<commit_after>#ifndef HAND_ROLLED_INCLUDED__
#define HAND_ROLLED_INCLUDED__
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
// Variation 1: Accept std::reference_wrapper<>.
#ifndef ACCEPT_REFERENCE_WRAPPER
#define ACCEPT_REFERENCE_WRAPPER 1
#endif
#ifndef INSTRUMENT_COPIES
#define INSTRUMENT_COPIES 1
#endif
#if INSTRUMENT_COPIES
std::size_t& allocations ()
{
static std::size_t allocations_ = 0;
return allocations_;
}
void reset_allocations ()
{ allocations() = 0; }
#endif
class any_printable
{
public:
// Contructors
any_printable () = default;
template <typename T>
any_printable (T value) :
handle_ (
new handle<typename std::remove_reference<T>::type>(
std::forward<T>(value)
)
)
{
#if INSTRUMENT_COPIES
++allocations();
#endif
}
any_printable (const any_printable & rhs) :
handle_ (rhs.handle_->clone())
{}
any_printable (any_printable && rhs) noexcept = default;
// Assignment
template <typename T>
any_printable& operator= (T value)
{
any_printable temp(std::forward<T>(value));
std::swap(temp, *this);
return *this;
}
any_printable & operator= (const any_printable & rhs)
{
any_printable temp(rhs);
std::swap(temp, *this);
return *this;
}
any_printable & operator= (any_printable && rhs) noexcept = default;
// Public interface
void print () const
{
assert(handle_);
handle_->print();
}
private:
struct handle_base
{
virtual ~handle_base () {}
virtual handle_base* clone () const = 0;
// Public interface
virtual void print () const = 0;
};
template <typename T>
struct handle :
handle_base
{
#if ACCEPT_REFERENCE_WRAPPER
template <typename U = T>
handle (T value,
typename std::enable_if<
std::is_reference<U>::value
>::type* = 0) :
value_ (value)
{}
template <typename U = T>
handle (T value,
typename std::enable_if<
!std::is_reference<U>::value,
int
>::type* = 0) noexcept :
value_ (std::move(value))
{}
#else
handle (T value) :
value_ (std::move(value))
{}
#endif
virtual handle_base* clone () const
{
#if INSTRUMENT_COPIES
++allocations();
#endif
return new handle(value_);
}
// Public interface
virtual void print () const
{ value_.print(); }
T value_;
};
#if ACCEPT_REFERENCE_WRAPPER
template <typename T>
struct handle<std::reference_wrapper<T>> :
handle<T &>
{
handle (std::reference_wrapper<T> ref) :
handle<T &> (ref.get())
{}
};
#endif
std::unique_ptr<handle_base> handle_;
};
struct hi_printable
{
void print () const
{ std::cout << "Hello, world!\n"; }
};
struct bye_printable
{
void print () const
{ std::cout << "Bye, now!\n"; }
};
struct large_printable :
std::vector<std::string>
{
large_printable () :
std::vector<std::string> (1000, std::string(1000, ' '))
{ ++allocations(); }
large_printable (const large_printable & rhs) :
std::vector<std::string> (rhs)
{ ++allocations(); }
large_printable & operator= (const large_printable & rhs)
{
++allocations();
static_cast<std::vector<std::string> &>(*this) = rhs;
return *this;
}
large_printable (large_printable && rhs) = default;
large_printable & operator= (large_printable && rhs) = default;
void print () const
{ std::cout << "I'm expensive to copy.\n"; }
};
/* Limitations:
1 - Each member functions must be repeated in 3 places.
2 - Macros, which could be used to address this, are evil.
3 - How do you define an any_fooable type, where foo() is a free function?
4 - How do you define an any_barable type, where bar is an operator?
5 - How do you apply the small buffer optimization to handle small types without making allocations?
*/
#endif
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// 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.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <CmdHelp.h>
#include <ViewText.h>
#include <Context.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdHelp::CmdHelp ()
{
_keyword = "help";
_usage = "task help";
_description = "Displays this usage help text";
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdHelp::execute (const std::string& command_line, std::string& output)
{
ViewText view;
view.width (context.getWidth ());
view.add (Column::factory ("string.left", ""));
view.add (Column::factory ("string.left", ""));
view.add (Column::factory ("string.left", ""));
// Static first row.
int row = view.addRow ();
view.set (row, 0, "Usage:");
view.set (row, 1, "task");
// Obsolete method of getting a list of all commands.
std::vector <std::string> all;
std::map <std::string, Command*>::iterator i;
for (i = context.commands.begin (); i != context.commands.end (); ++i)
all.push_back (i->first);
// Sort alphabetically by usage.
std::sort (all.begin (), all.end ());
std::vector <std::string>::iterator name;
for (name = all.begin (); name != all.end (); ++name)
{
row = view.addRow ();
view.set (row, 1, context.commands[*name]->usage ());
view.set (row, 2, context.commands[*name]->description ());
}
/*
row = view.addRow ();
view.set (row, 1, "task add [tags] [attrs] desc...");
view.set (row, 2, "Adds a new task.");
row = view.addRow ();
view.set (row, 1, "task log [tags] [attrs] desc...");
view.set (row, 2, "Adds a new task that is already completed.");
row = view.addRow ();
view.set (row, 1, "task append ID [tags] [attrs] desc...");
view.set (row, 2, "Appends more description to an existing task.");
row = view.addRow ();
view.set (row, 1, "task prepend ID [tags] [attrs] desc...");
view.set (row, 2, "Prepends more description to an existing task.");
row = view.addRow ();
view.set (row, 1, "task annotate ID desc...");
view.set (row, 2, "Adds an annotation to an existing task.");
row = view.addRow ();
view.set (row, 1, "task denotate ID desc...");
view.set (row, 2, "Deletes an annotation of an existing task.");
row = view.addRow ();
view.set (row, 1, "task ID [tags] [attrs] [desc...]");
view.set (row, 2, "Modifies the existing task with provided arguments.");
row = view.addRow ();
view.set (row, 1, "task ID /from/to/g");
view.set (row, 2, "Performs substitution on the task description and "
"annotations. The 'g' is optional, and causes "
"substitutions for all matching text, not just the "
"first occurrence.");
row = view.addRow ();
view.set (row, 1, "task ID");
view.set (row, 2, "Specifying an ID without a command invokes the 'info' command.");
row = view.addRow ();
view.set (row, 1, "task undo");
view.set (row, 2, "Reverts the most recent action.");
row = view.addRow ();
view.set (row, 1, "task shell");
view.set (row, 2, "Launches an interactive shell.");
row = view.addRow ();
view.set (row, 1, "task duplicate ID [tags] [attrs] [desc...]");
view.set (row, 2, "Duplicates the specified task, and allows modifications.");
row = view.addRow ();
view.set (row, 1, "task delete ID");
view.set (row, 2, "Deletes the specified task.");
row = view.addRow ();
view.set (row, 1, "task start ID");
view.set (row, 2, "Marks specified task as started.");
row = view.addRow ();
view.set (row, 1, "task stop ID");
view.set (row, 2, "Removes the 'start' time from a task.");
row = view.addRow ();
view.set (row, 1, "task done ID [tags] [attrs] [desc...]");
view.set (row, 2, "Marks the specified task as completed.");
row = view.addRow ();
view.set (row, 1, "task projects");
view.set (row, 2, "Shows a list of all project names used, and how many tasks are in each.");
row = view.addRow ();
view.set (row, 1, "task summary");
view.set (row, 2, "Shows a report of task status by project.");
row = view.addRow ();
view.set (row, 1, "task timesheet [weeks]");
view.set (row, 2, "Shows a weekly report of tasks completed and started.");
row = view.addRow ();
view.set (row, 1, "task history");
view.set (row, 2, "Shows a report of task history, by month. Alias to history.monthly.");
row = view.addRow ();
view.set (row, 1, "task history.annual");
view.set (row, 2, "Shows a report of task history, by year.");
row = view.addRow ();
view.set (row, 1, "task ghistory");
view.set (row, 2, "Shows a graphical report of task history, by month. Alias to ghistory.monthly.");
row = view.addRow ();
view.set (row, 1, "task ghistory.annual");
view.set (row, 2, "Shows a graphical report of task history, by year.");
row = view.addRow ();
view.set (row, 1, "task burndown.daily");
view.set (row, 2, "Shows a graphical burndown chart, by day.");
row = view.addRow ();
view.set (row, 1, "task burndown.weekly");
view.set (row, 2, "Shows a graphical burndown chart, by week.");
row = view.addRow ();
view.set (row, 1, "task burndown.monthly");
view.set (row, 2, "Shows a graphical burndown chart, by month.");
row = view.addRow ();
view.set (row, 1, "task calendar [due|month year|year]");
view.set (row, 2, "Shows a calendar, with due tasks marked.");
row = view.addRow ();
view.set (row, 1, "task stats");
view.set (row, 2, "Shows task database statistics.");
row = view.addRow ();
view.set (row, 1, "task import");
view.set (row, 2, "Imports tasks from a variety of formats.");
row = view.addRow ();
view.set (row, 1, "task export");
view.set (row, 2, "Lists all tasks in CSV format. Alias to export.csv");
row = view.addRow ();
view.set (row, 1, "task export.csv");
view.set (row, 2, "Lists all tasks in CSV format.");
row = view.addRow ();
view.set (row, 1, "task export.ical");
view.set (row, 2, "Lists all tasks in iCalendar format.");
row = view.addRow ();
view.set (row, 1, "task export.yaml");
view.set (row, 2, "Lists all tasks in YAML format.");
row = view.addRow ();
view.set (row, 1, "task merge URL");
view.set (row, 2, "Merges the specified undo.data file with the local data files.");
row = view.addRow ();
view.set (row, 1, "task push URL");
view.set (row, 2, "Pushes the local *.data files to the URL.");
row = view.addRow ();
view.set (row, 1, "task pull URL");
view.set (row, 2, "Overwrites the local *.data files with those found at the URL.");
row = view.addRow ();
view.set (row, 1, "task color [sample | legend]");
view.set (row, 2, "Displays all possible colors, a named sample, or a "
"legend containing all currently defined colors.");
row = view.addRow ();
view.set (row, 1, "task count [filter]");
view.set (row, 2, "Shows only the number of matching tasks.");
row = view.addRow ();
view.set (row, 1, "task ids [filter]");
view.set (row, 2, "Shows only the IDs of matching tasks, in the form of a range.");
row = view.addRow ();
view.set (row, 1, "task config [name [value | '']]");
view.set (row, 2, "Add, modify and remove settings in the task configuration.");
*/
output = "\n"
+ view.render ()
+ "\n"
+ "Documentation for taskwarrior can be found using 'man task', "
"'man taskrc', 'man task-tutorial', 'man task-color', 'man task-faq' "
"or at http://taskwarrior.org"
+ "\n"
+ "\n"
+ "ID is the numeric identifier displayed by the 'task list' command. "
"You can specify multiple IDs for task commands, and multiple tasks "
"will be affected. To specify multiple IDs make sure you use one "
"of these forms:\n"
" task delete 1,2,3\n"
" task info 1-3\n"
" task pri:H 1,2-5,19\n"
"\n"
"Tags are arbitrary words, any quantity:\n"
" +tag The + means add the tag\n"
" -tag The - means remove the tag\n"
"\n"
"Attributes are:\n"
" project: Project name\n"
" priority: Priority\n"
" due: Due date\n"
" recur: Recurrence frequency\n"
" until: Recurrence end date\n"
" fg: Foreground color\n"
" bg: Background color\n"
" limit: Desired number of rows in report, or 'page'\n"
" wait: Date until task becomes pending\n"
"\n"
"Attribute modifiers improve filters. Supported modifiers are:\n"
" before (synonyms under, below)\n"
" after (synonyms over, above)\n"
" none\n"
" any\n"
" is (synonym equals)\n"
" isnt (synonym not)\n"
" has (synonym contains)\n"
" hasnt\n"
" startswith (synonym left)\n"
" endswith (synonym right)\n"
" word\n"
" noword\n"
"\n"
" For example:\n"
" task list due.before:eom priority.not:L\n"
"\n"
" Modifiers can be inverted with the ~ character:\n"
" project.~is is equivalent to project.isnt\n"
"\n"
"The default .taskrc file can be overridden with:\n"
" task rc:<alternate file> ...\n"
"\n"
"The values in .taskrc (or alternate) can be overridden with:\n"
" task ... rc.<name>:<value>\n"
"\n"
"Any command or attribute name may be abbreviated if still unique:\n"
" task list project:Home\n"
" task li pro:Home\n"
"\n"
"Some task descriptions need to be escaped because of the shell:\n"
" task add \"quoted ' quote\"\n"
" task add escaped \\' quote\n"
"\n"
"The argument -- tells taskwarrior to treat all other args as description.\n"
" task add -- project:Home needs scheduling\n"
"\n"
"Many characters have special meaning to the shell, including:\n"
" $ ! ' \" ( ) ; \\ ` * ? { } [ ] < > | & % # ~\n"
"\n";
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Commands - help<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// 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.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <CmdHelp.h>
#include <ViewText.h>
#include <Context.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdHelp::CmdHelp ()
{
_keyword = "help";
_usage = "task help";
_description = "Displays this usage help text";
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdHelp::execute (const std::string& command_line, std::string& output)
{
ViewText view;
view.width (context.getWidth ());
view.add (Column::factory ("string.left", ""));
view.add (Column::factory ("string.left", ""));
view.add (Column::factory ("string.left", ""));
// Static first row.
int row = view.addRow ();
view.set (row, 0, "Usage:");
view.set (row, 1, "task");
// Obsolete method of getting a list of all commands.
std::vector <std::string> all;
std::map <std::string, Command*>::iterator i;
for (i = context.commands.begin (); i != context.commands.end (); ++i)
all.push_back (i->first);
// Sort alphabetically by usage.
std::sort (all.begin (), all.end ());
std::vector <std::string>::iterator name;
for (name = all.begin (); name != all.end (); ++name)
{
if ((*name)[0] != '_')
{
row = view.addRow ();
view.set (row, 1, context.commands[*name]->usage ());
view.set (row, 2, context.commands[*name]->description ());
}
}
for (name = all.begin (); name != all.end (); ++name)
{
if ((*name)[0] == '_')
{
row = view.addRow ();
view.set (row, 1, context.commands[*name]->usage ());
view.set (row, 2, context.commands[*name]->description ());
}
}
/*
row = view.addRow ();
view.set (row, 1, "task add [tags] [attrs] desc...");
view.set (row, 2, "Adds a new task.");
row = view.addRow ();
view.set (row, 1, "task log [tags] [attrs] desc...");
view.set (row, 2, "Adds a new task that is already completed.");
row = view.addRow ();
view.set (row, 1, "task append ID [tags] [attrs] desc...");
view.set (row, 2, "Appends more description to an existing task.");
row = view.addRow ();
view.set (row, 1, "task prepend ID [tags] [attrs] desc...");
view.set (row, 2, "Prepends more description to an existing task.");
row = view.addRow ();
view.set (row, 1, "task annotate ID desc...");
view.set (row, 2, "Adds an annotation to an existing task.");
row = view.addRow ();
view.set (row, 1, "task denotate ID desc...");
view.set (row, 2, "Deletes an annotation of an existing task.");
row = view.addRow ();
view.set (row, 1, "task ID [tags] [attrs] [desc...]");
view.set (row, 2, "Modifies the existing task with provided arguments.");
row = view.addRow ();
view.set (row, 1, "task ID /from/to/g");
view.set (row, 2, "Performs substitution on the task description and "
"annotations. The 'g' is optional, and causes "
"substitutions for all matching text, not just the "
"first occurrence.");
row = view.addRow ();
view.set (row, 1, "task ID");
view.set (row, 2, "Specifying an ID without a command invokes the 'info' command.");
row = view.addRow ();
view.set (row, 1, "task undo");
view.set (row, 2, "Reverts the most recent action.");
row = view.addRow ();
view.set (row, 1, "task shell");
view.set (row, 2, "Launches an interactive shell.");
row = view.addRow ();
view.set (row, 1, "task duplicate ID [tags] [attrs] [desc...]");
view.set (row, 2, "Duplicates the specified task, and allows modifications.");
row = view.addRow ();
view.set (row, 1, "task delete ID");
view.set (row, 2, "Deletes the specified task.");
row = view.addRow ();
view.set (row, 1, "task start ID");
view.set (row, 2, "Marks specified task as started.");
row = view.addRow ();
view.set (row, 1, "task stop ID");
view.set (row, 2, "Removes the 'start' time from a task.");
row = view.addRow ();
view.set (row, 1, "task done ID [tags] [attrs] [desc...]");
view.set (row, 2, "Marks the specified task as completed.");
row = view.addRow ();
view.set (row, 1, "task projects");
view.set (row, 2, "Shows a list of all project names used, and how many tasks are in each.");
row = view.addRow ();
view.set (row, 1, "task summary");
view.set (row, 2, "Shows a report of task status by project.");
row = view.addRow ();
view.set (row, 1, "task timesheet [weeks]");
view.set (row, 2, "Shows a weekly report of tasks completed and started.");
row = view.addRow ();
view.set (row, 1, "task history");
view.set (row, 2, "Shows a report of task history, by month. Alias to history.monthly.");
row = view.addRow ();
view.set (row, 1, "task history.annual");
view.set (row, 2, "Shows a report of task history, by year.");
row = view.addRow ();
view.set (row, 1, "task ghistory");
view.set (row, 2, "Shows a graphical report of task history, by month. Alias to ghistory.monthly.");
row = view.addRow ();
view.set (row, 1, "task ghistory.annual");
view.set (row, 2, "Shows a graphical report of task history, by year.");
row = view.addRow ();
view.set (row, 1, "task burndown.daily");
view.set (row, 2, "Shows a graphical burndown chart, by day.");
row = view.addRow ();
view.set (row, 1, "task burndown.weekly");
view.set (row, 2, "Shows a graphical burndown chart, by week.");
row = view.addRow ();
view.set (row, 1, "task burndown.monthly");
view.set (row, 2, "Shows a graphical burndown chart, by month.");
row = view.addRow ();
view.set (row, 1, "task calendar [due|month year|year]");
view.set (row, 2, "Shows a calendar, with due tasks marked.");
row = view.addRow ();
view.set (row, 1, "task stats");
view.set (row, 2, "Shows task database statistics.");
row = view.addRow ();
view.set (row, 1, "task import");
view.set (row, 2, "Imports tasks from a variety of formats.");
row = view.addRow ();
view.set (row, 1, "task export");
view.set (row, 2, "Lists all tasks in CSV format. Alias to export.csv");
row = view.addRow ();
view.set (row, 1, "task export.csv");
view.set (row, 2, "Lists all tasks in CSV format.");
row = view.addRow ();
view.set (row, 1, "task export.ical");
view.set (row, 2, "Lists all tasks in iCalendar format.");
row = view.addRow ();
view.set (row, 1, "task export.yaml");
view.set (row, 2, "Lists all tasks in YAML format.");
row = view.addRow ();
view.set (row, 1, "task merge URL");
view.set (row, 2, "Merges the specified undo.data file with the local data files.");
row = view.addRow ();
view.set (row, 1, "task push URL");
view.set (row, 2, "Pushes the local *.data files to the URL.");
row = view.addRow ();
view.set (row, 1, "task pull URL");
view.set (row, 2, "Overwrites the local *.data files with those found at the URL.");
row = view.addRow ();
view.set (row, 1, "task color [sample | legend]");
view.set (row, 2, "Displays all possible colors, a named sample, or a "
"legend containing all currently defined colors.");
row = view.addRow ();
view.set (row, 1, "task count [filter]");
view.set (row, 2, "Shows only the number of matching tasks.");
row = view.addRow ();
view.set (row, 1, "task ids [filter]");
view.set (row, 2, "Shows only the IDs of matching tasks, in the form of a range.");
row = view.addRow ();
view.set (row, 1, "task config [name [value | '']]");
view.set (row, 2, "Add, modify and remove settings in the task configuration.");
*/
output = "\n"
+ view.render ()
+ "\n"
+ "Documentation for taskwarrior can be found using 'man task', "
"'man taskrc', 'man task-tutorial', 'man task-color', 'man task-faq' "
"or at http://taskwarrior.org"
+ "\n"
+ "\n"
+ "ID is the numeric identifier displayed by the 'task list' command. "
"You can specify multiple IDs for task commands, and multiple tasks "
"will be affected. To specify multiple IDs make sure you use one "
"of these forms:\n"
" task delete 1,2,3\n"
" task info 1-3\n"
" task pri:H 1,2-5,19\n"
"\n"
"Tags are arbitrary words, any quantity:\n"
" +tag The + means add the tag\n"
" -tag The - means remove the tag\n"
"\n"
"Attributes are:\n"
" project: Project name\n"
" priority: Priority\n"
" due: Due date\n"
" recur: Recurrence frequency\n"
" until: Recurrence end date\n"
" fg: Foreground color\n"
" bg: Background color\n"
" limit: Desired number of rows in report, or 'page'\n"
" wait: Date until task becomes pending\n"
"\n"
"Attribute modifiers improve filters. Supported modifiers are:\n"
" before (synonyms under, below)\n"
" after (synonyms over, above)\n"
" none\n"
" any\n"
" is (synonym equals)\n"
" isnt (synonym not)\n"
" has (synonym contains)\n"
" hasnt\n"
" startswith (synonym left)\n"
" endswith (synonym right)\n"
" word\n"
" noword\n"
"\n"
" For example:\n"
" task list due.before:eom priority.not:L\n"
"\n"
" Modifiers can be inverted with the ~ character:\n"
" project.~is is equivalent to project.isnt\n"
"\n"
"The default .taskrc file can be overridden with:\n"
" task rc:<alternate file> ...\n"
"\n"
"The values in .taskrc (or alternate) can be overridden with:\n"
" task ... rc.<name>:<value>\n"
"\n"
"Any command or attribute name may be abbreviated if still unique:\n"
" task list project:Home\n"
" task li pro:Home\n"
"\n"
"Some task descriptions need to be escaped because of the shell:\n"
" task add \"quoted ' quote\"\n"
" task add escaped \\' quote\n"
"\n"
"The argument -- tells taskwarrior to treat all other args as description.\n"
" task add -- project:Home needs scheduling\n"
"\n"
"Many characters have special meaning to the shell, including:\n"
" $ ! ' \" ( ) ; \\ ` * ? { } [ ] < > | & % # ~\n"
"\n";
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pngwrite.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 18:03:05 $
*
* 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_PNGWRITE_HXX
#define _SV_PNGWRITE_HXX
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
#include <vector>
// -------------
// - PNGWriter -
// -------------
namespace vcl
{
class PNGWriterImpl;
class VCL_DLLPUBLIC PNGWriter
{
PNGWriterImpl* mpImpl;
public:
PNGWriter( const BitmapEx& BmpEx,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >* pFilterData = NULL );
~PNGWriter();
sal_Bool Write( SvStream& rStm );
// additional method to be able to modify all chunk before they are stored
struct ChunkData
{
sal_uInt32 nType;
std::vector< sal_uInt8 > aData;
};
std::vector< vcl::PNGWriter::ChunkData >& GetChunks();
};
}
#endif // _SV_PNGWRITE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.320); FILE MERGED 2008/04/01 16:05:20 thb 1.2.320.3: #i85898# Stripping all external header guards 2008/04/01 13:01:13 thb 1.2.320.2: #i85898# Stripping all external header guards 2008/03/28 15:44:15 rt 1.2.320.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: pngwrite.hxx,v $
* $Revision: 1.3 $
*
* 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_PNGWRITE_HXX
#define _SV_PNGWRITE_HXX
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <vcl/dllapi.h>
#include <vcl/bitmapex.hxx>
#include <vector>
// -------------
// - PNGWriter -
// -------------
namespace vcl
{
class PNGWriterImpl;
class VCL_DLLPUBLIC PNGWriter
{
PNGWriterImpl* mpImpl;
public:
PNGWriter( const BitmapEx& BmpEx,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >* pFilterData = NULL );
~PNGWriter();
sal_Bool Write( SvStream& rStm );
// additional method to be able to modify all chunk before they are stored
struct ChunkData
{
sal_uInt32 nType;
std::vector< sal_uInt8 > aData;
};
std::vector< vcl::PNGWriter::ChunkData >& GetChunks();
};
}
#endif // _SV_PNGWRITE_HXX
<|endoftext|>
|
<commit_before>//----------------------------------*-C++-*----------------------------------//
/*!
* \file AdjointMcParallelFor.cc
* \author Steven Hamilton
* \brief Perform single history of adjoint MC
*/
//---------------------------------------------------------------------------//
#ifndef mc_solver_AdjointMcParallelFor_i_hh
#define mc_solver_AdjointMcParallelFor_i_hh
#include <iterator>
#include <random>
#include <cmath>
#include "AdjointMcParallelFor.hh"
#include "MC_Components.hh"
#include "utils/String_Functions.hh"
#include "harness/Warnings.hh"
namespace alea
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor
*
* \param P Views into entries of probability matrix
* \param W Views into entries of weight matrix
* \param inds Views into nonzeros indices
* \param offsets Starting indices for each matrix row
* \param coeffs Polynomial coefficients
* \param pl Problem parameters
*/
//---------------------------------------------------------------------------//
AdjointMcParallelFor::AdjointMcParallelFor(
const MC_Data_View &mc_data,
const const_scalar_view coeffs,
Teuchos::RCP<Teuchos::ParameterList> pl)
: d_N(mc_data.offsets.size()-1)
, d_mc_data(mc_data)
, d_coeffs(coeffs)
, d_start_cdf("start_cdf",d_N)
, d_start_wt("start_wt",d_N)
, d_rand_pool(pl->get("random_seed",31891))
, d_max_history_length(d_coeffs.size()-1)
{
d_num_histories = pl->get("num_histories",1000);
// Determine type of tally
std::string estimator = pl->get<std::string>("estimator",
"expected_value");
VALIDATE(estimator == "collision" ||
estimator == "expected_value",
"Only collision and expected_value estimators are available.");
d_use_expected_value = (estimator == "expected_value");
// Power factor for initial probability distribution
d_start_wt_factor = pl->get<SCALAR>("start_weight_factor",1.0);
// Should we print anything to screen
std::string verb = profugus::to_lower(pl->get("verbosity","low"));
d_print = (verb == "high");
}
//---------------------------------------------------------------------------//
// Solve problem using Monte Carlo
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::solve(const MV &x, MV &y)
{
range_policy policy(0,d_num_histories);
// Build initial probability and weight distributions
build_initial_distribution(x);
// Need to get Kokkos view directly, this is silly
Teuchos::ArrayRCP<SCALAR> y_data = y.getDataNonConst(0);
const scalar_view y_device("result",d_N);
const scalar_host_mirror y_mirror =
Kokkos::create_mirror_view(y_device);
d_y = y_device;
// Execute functor
Kokkos::parallel_for(policy,*this);
// Copy data back to host
Kokkos::deep_copy(y_mirror,y_device);
DEVICE::fence();
// Apply scale factor
SCALAR scale_factor = 1.0 / static_cast<SCALAR>(d_num_histories);
for( LO i=0; i<d_N; ++i )
{
y_data[i] = scale_factor*y_mirror(i);
}
// Add rhs for expected value
if( d_use_expected_value )
{
scalar_host_mirror coeffs_mirror =
Kokkos::create_mirror_view(d_coeffs);
Kokkos::deep_copy(coeffs_mirror,d_coeffs);
y.update(coeffs_mirror(0),x,1.0);
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform adjoint Monte Carlo process
*/
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::operator()(const policy_member &member) const
{
LO new_ind;
LO state;
int row_length;
generator_type rand_gen = d_rand_pool.get_state();
// Get starting position and weight
state = getNewState(d_start_cdf,0,d_N,rand_gen);
if( state == -1 )
{
d_rand_pool.free_state(rand_gen);
return;
}
if( std::abs(d_start_wt(state)) == 0.0 )
{
d_rand_pool.free_state(rand_gen);
return;
}
SCALAR weight = d_start_wt(state);
SCALAR initial_weight = weight;
if( d_print )
{
printf("Thread %i starting history in state %i with initial weight %6.2e\n",
member,state,initial_weight);
}
// Collision estimator starts tallying on zeroth order term
// Expected value estimator gets this added explicitly at the end
int stage = 0;
if( d_use_expected_value )
stage++;
// Transport particle until done
while(true)
{
// Get data and add to tally
tallyContribution(state,d_coeffs(stage)*weight);
if( stage >= d_max_history_length )
{
d_rand_pool.free_state(rand_gen);
return;
}
// Get new state index
int start = d_mc_data.offsets(state);
row_length = d_mc_data.offsets(state+1)-start;
new_ind = getNewState(d_mc_data.P,d_mc_data.offsets(state),
row_length,rand_gen);
if( new_ind== -1 )
{
d_rand_pool.free_state(rand_gen);
return;
}
// Modify weight and update state
state = d_mc_data.inds(new_ind);
weight *= d_mc_data.W(new_ind);
stage++;
if( d_print )
{
printf("Thread %i transitioning to state %i with new weight %6.2e\n",
member,state,weight);
}
} // while
d_rand_pool.free_state(rand_gen);
}
//---------------------------------------------------------------------------//
// PRIVATE FUNCTIONS
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
/*!
* \brief Tally contribution into vector
*/
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::tallyContribution(
const LO state,
const SCALAR wt ) const
{
if( d_use_expected_value )
{
int start = d_mc_data.offsets(state);
int row_length = d_mc_data.offsets(state+1)-start;
if( row_length > 0 )
{
for( LO i=0; i<row_length; ++i )
{
// P is cdf, we want value of pdf
//y[inds[i]] += wt*H[i];
Kokkos::atomic_add(&d_y(d_mc_data.inds[start+i]),
wt*d_mc_data.H[start+i]);
}
}
}
else
{
//y[state] += wt;
Kokkos::atomic_add(&d_y(state),wt);
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Get new state by sampling from cdf
*/
//---------------------------------------------------------------------------//
template <class view_type>
LO AdjointMcParallelFor::getNewState(const view_type &cdf,
LO first,
LO cdf_length,
generator_type &gen) const
{
// Generate random number
SCALAR rand = Kokkos::rand<generator_type,SCALAR>::draw(gen);
// Sample cdf to get new state
// Use local lower_bound implementation, not std library version
// This allows calling from device
LO elem = lower_bound(cdf,first,cdf_length,rand);
if( elem == first+cdf_length )
return -1;
return elem;
}
//---------------------------------------------------------------------------//
// Build initial cdf and weights
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::build_initial_distribution(const MV &x)
{
// Build data on host, then explicitly copy to device
// In future, convert this to a new Kernel to allow building
// distributions directly on device if x is allocated there
scalar_host_mirror start_cdf_host = Kokkos::create_mirror_view(d_start_cdf);
scalar_host_mirror start_wt_host = Kokkos::create_mirror_view(d_start_wt);
Teuchos::ArrayRCP<const SCALAR> x_data = x.getData(0);
for( LO i=0; i<d_N; ++i )
{
start_cdf_host(i) =
SCALAR_TRAITS::pow(SCALAR_TRAITS::magnitude(x_data[i]),
d_start_wt_factor);
}
SCALAR pdf_sum = std::accumulate(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,0.0);
ENSURE( pdf_sum > 0.0 );
std::transform(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0),
[pdf_sum](SCALAR x){return x/pdf_sum;});
std::transform(x_data.begin(),x_data.end(),&start_cdf_host(0),
&start_wt_host(0),
[](SCALAR x, SCALAR y){return y==0.0 ? 0.0 : x/y;});
std::partial_sum(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0));
Kokkos::deep_copy(d_start_cdf,start_cdf_host);
Kokkos::deep_copy(d_start_wt, start_wt_host);
}
} // namespace alea
#endif // mc_solver_AdjointMcParallelFor_i_hh
<commit_msg>Cleaning up loop over history length.<commit_after>//----------------------------------*-C++-*----------------------------------//
/*!
* \file AdjointMcParallelFor.cc
* \author Steven Hamilton
* \brief Perform single history of adjoint MC
*/
//---------------------------------------------------------------------------//
#ifndef mc_solver_AdjointMcParallelFor_i_hh
#define mc_solver_AdjointMcParallelFor_i_hh
#include <iterator>
#include <random>
#include <cmath>
#include "AdjointMcParallelFor.hh"
#include "MC_Components.hh"
#include "utils/String_Functions.hh"
#include "harness/Warnings.hh"
namespace alea
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor
*
* \param P Views into entries of probability matrix
* \param W Views into entries of weight matrix
* \param inds Views into nonzeros indices
* \param offsets Starting indices for each matrix row
* \param coeffs Polynomial coefficients
* \param pl Problem parameters
*/
//---------------------------------------------------------------------------//
AdjointMcParallelFor::AdjointMcParallelFor(
const MC_Data_View &mc_data,
const const_scalar_view coeffs,
Teuchos::RCP<Teuchos::ParameterList> pl)
: d_N(mc_data.offsets.size()-1)
, d_mc_data(mc_data)
, d_coeffs(coeffs)
, d_start_cdf("start_cdf",d_N)
, d_start_wt("start_wt",d_N)
, d_rand_pool(pl->get("random_seed",31891))
, d_max_history_length(d_coeffs.size()-1)
{
d_num_histories = pl->get("num_histories",1000);
// Determine type of tally
std::string estimator = pl->get<std::string>("estimator",
"expected_value");
VALIDATE(estimator == "collision" ||
estimator == "expected_value",
"Only collision and expected_value estimators are available.");
d_use_expected_value = (estimator == "expected_value");
// Power factor for initial probability distribution
d_start_wt_factor = pl->get<SCALAR>("start_weight_factor",1.0);
// Should we print anything to screen
std::string verb = profugus::to_lower(pl->get("verbosity","low"));
d_print = (verb == "high");
}
//---------------------------------------------------------------------------//
// Solve problem using Monte Carlo
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::solve(const MV &x, MV &y)
{
range_policy policy(0,d_num_histories);
// Build initial probability and weight distributions
build_initial_distribution(x);
// Need to get Kokkos view directly, this is silly
Teuchos::ArrayRCP<SCALAR> y_data = y.getDataNonConst(0);
const scalar_view y_device("result",d_N);
const scalar_host_mirror y_mirror =
Kokkos::create_mirror_view(y_device);
d_y = y_device;
// Execute functor
Kokkos::parallel_for(policy,*this);
// Copy data back to host
Kokkos::deep_copy(y_mirror,y_device);
DEVICE::fence();
// Apply scale factor
SCALAR scale_factor = 1.0 / static_cast<SCALAR>(d_num_histories);
for( LO i=0; i<d_N; ++i )
{
y_data[i] = scale_factor*y_mirror(i);
}
// Add rhs for expected value
if( d_use_expected_value )
{
scalar_host_mirror coeffs_mirror =
Kokkos::create_mirror_view(d_coeffs);
Kokkos::deep_copy(coeffs_mirror,d_coeffs);
y.update(coeffs_mirror(0),x,1.0);
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform adjoint Monte Carlo process
*/
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::operator()(const policy_member &member) const
{
LO new_ind;
LO state;
int row_length;
generator_type rand_gen = d_rand_pool.get_state();
// Get starting position and weight
state = getNewState(d_start_cdf,0,d_N,rand_gen);
if( state == -1 )
{
d_rand_pool.free_state(rand_gen);
return;
}
if( std::abs(d_start_wt(state)) == 0.0 )
{
d_rand_pool.free_state(rand_gen);
return;
}
SCALAR weight = d_start_wt(state);
SCALAR initial_weight = weight;
if( d_print )
{
printf("Thread %i starting history in state %i with initial weight %6.2e\n",
member,state,initial_weight);
}
// Collision estimator starts tallying on zeroth order term
// Expected value estimator gets this added explicitly at the end
int stage = 0;
if( d_use_expected_value )
stage++;
// Get data and add to tally
tallyContribution(state,d_coeffs(stage)*weight);
// Transport particle until done
for( ; stage<d_max_history_length; ++stage )
{
// Get new state index
int start = d_mc_data.offsets(state);
row_length = d_mc_data.offsets(state+1)-start;
new_ind = getNewState(d_mc_data.P,d_mc_data.offsets(state),
row_length,rand_gen);
if( new_ind== -1 )
{
d_rand_pool.free_state(rand_gen);
return;
}
// Modify weight and update state
state = d_mc_data.inds(new_ind);
weight *= d_mc_data.W(new_ind);
if( d_print )
{
printf("Thread %i transitioning to state %i with new weight %6.2e\n",
member,state,weight);
}
// Get data and add to tally
tallyContribution(state,d_coeffs(stage)*weight);
} // while
d_rand_pool.free_state(rand_gen);
}
//---------------------------------------------------------------------------//
// PRIVATE FUNCTIONS
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
/*!
* \brief Tally contribution into vector
*/
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::tallyContribution(
const LO state,
const SCALAR wt ) const
{
if( d_use_expected_value )
{
int start = d_mc_data.offsets(state);
int row_length = d_mc_data.offsets(state+1)-start;
if( row_length > 0 )
{
for( LO i=0; i<row_length; ++i )
{
// P is cdf, we want value of pdf
//y[inds[i]] += wt*H[i];
Kokkos::atomic_add(&d_y(d_mc_data.inds[start+i]),
wt*d_mc_data.H[start+i]);
}
}
}
else
{
//y[state] += wt;
Kokkos::atomic_add(&d_y(state),wt);
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Get new state by sampling from cdf
*/
//---------------------------------------------------------------------------//
template <class view_type>
LO AdjointMcParallelFor::getNewState(const view_type &cdf,
LO first,
LO cdf_length,
generator_type &gen) const
{
// Generate random number
SCALAR rand = Kokkos::rand<generator_type,SCALAR>::draw(gen);
// Sample cdf to get new state
// Use local lower_bound implementation, not std library version
// This allows calling from device
LO elem = lower_bound(cdf,first,cdf_length,rand);
if( elem == first+cdf_length )
return -1;
return elem;
}
//---------------------------------------------------------------------------//
// Build initial cdf and weights
//---------------------------------------------------------------------------//
void AdjointMcParallelFor::build_initial_distribution(const MV &x)
{
// Build data on host, then explicitly copy to device
// In future, convert this to a new Kernel to allow building
// distributions directly on device if x is allocated there
scalar_host_mirror start_cdf_host = Kokkos::create_mirror_view(d_start_cdf);
scalar_host_mirror start_wt_host = Kokkos::create_mirror_view(d_start_wt);
Teuchos::ArrayRCP<const SCALAR> x_data = x.getData(0);
for( LO i=0; i<d_N; ++i )
{
start_cdf_host(i) =
SCALAR_TRAITS::pow(SCALAR_TRAITS::magnitude(x_data[i]),
d_start_wt_factor);
}
SCALAR pdf_sum = std::accumulate(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,0.0);
ENSURE( pdf_sum > 0.0 );
std::transform(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0),
[pdf_sum](SCALAR x){return x/pdf_sum;});
std::transform(x_data.begin(),x_data.end(),&start_cdf_host(0),
&start_wt_host(0),
[](SCALAR x, SCALAR y){return y==0.0 ? 0.0 : x/y;});
std::partial_sum(&start_cdf_host(0),&start_cdf_host(d_N-1)+1,&start_cdf_host(0));
Kokkos::deep_copy(d_start_cdf,start_cdf_host);
Kokkos::deep_copy(d_start_wt, start_wt_host);
}
} // namespace alea
#endif // mc_solver_AdjointMcParallelFor_i_hh
<|endoftext|>
|
<commit_before>// implementation for sampled_mapping.h
namespace MathTL
{
SampledMapping<1>::SampledMapping()
: Grid<1>(), values_()
{
}
SampledMapping<1>::SampledMapping(const SampledMapping<1>& sm)
: Grid<1>(sm), values_(sm.values_)
{
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid)
: Grid<1>(grid), values_(grid.size())
{
for (unsigned int i = 0; i < grid.size(); i++)
values_[i] = 0;
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid, const Array1D<double>& values)
: Grid<1>(grid), values_(values)
{
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid, const Function<1>& f)
: Grid<1>(grid), values_(grid.size())
{
for (unsigned int n(0); n < grid.size(); n++)
values_[n] = f.value(Point<1>(grid_[n]));
}
SampledMapping<1>::SampledMapping(const MultiIndex<int,1>& a,
const MultiIndex<int,1>& b,
const InfiniteVector<double, MultiIndex<int,1> >& values,
const int resolution)
: Grid<1>(a[0], b[0], (1<<resolution)*(b[0]-a[0]))
{
values_.resize(Grid<1>::size());
for (int k(a[0]<<resolution), n(0); k <= (b[0]<<resolution); k++, n++)
values_[n] = values.get_coefficient(MultiIndex<int,1>(k));
}
SampledMapping<1>::SampledMapping(const Point<1>& a,
const Point<1>& b,
const FixedArray1D<Array1D<double>,1>& values)
: Grid<1>(a[0], b[0], values[0].size()-1), values_(values[0])
{
}
SampledMapping<1>::SampledMapping(const Chart<1>& ch,
const FixedArray1D<Array1D<double>,1>& values,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<1> x;
Point<1> x_patch;
grid_.resize(n_points);
values_.resize(n_points);
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
ch.map_point(x,x_patch);
grid_[i] = x_patch[0];
values_[i] = values[0][i] / ch.Gram_factor(x);
}
}
SampledMapping<1>::SampledMapping(const Chart<1>& ch,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<1> x;
Point<1> x_patch;
grid_.resize(n_points);
values_.resize(n_points);
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
ch.map_point(x,x_patch);
grid_[i] = x_patch[0];
values_[i] = 0;
}
}
SampledMapping<1>&
SampledMapping<1>::operator = (const SampledMapping<1>& sm)
{
Grid<1>::operator = (sm);
values_ = sm.values_;
return *this;
}
void
SampledMapping<1>::add(const SampledMapping<1>& s)
{
assert(values_.size() == s.values_.size());
for (unsigned int i = 0; i < values_.size(); i++)
values_[i] += s.values_[i];
}
void
SampledMapping<1>::add(const double alpha, const SampledMapping<1>& s)
{
assert(values_.size() == s.values_.size());
for (unsigned int i = 0; i < values_.size(); i++)
values_[i] += alpha * s.values_[i];
}
void
SampledMapping<1>::matlab_output(std::ostream& os) const
{
Grid<1>::matlab_output(os);
os << "y = " // here we can take y
<< values_
<< ";"
<< std::endl;
}
SampledMapping<2>::SampledMapping()
: Grid<2>(), values_()
{
}
SampledMapping<2>::SampledMapping(const SampledMapping<2>& sm)
: Grid<2>(sm), values_(sm.values_)
{
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid)
: Grid<2>(grid)
{
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid, const Matrix<double>& values)
: Grid<2>(grid), values_(values)
{
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid, const Function<2>& f)
: Grid<2>(grid), values_()
{
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) = f.value(Point<2>(gridx_(m,n), gridy_(m,n)));
}
SampledMapping<2>::SampledMapping(const MultiIndex<int,2>& a,
const MultiIndex<int,2>& b,
const InfiniteVector<double, MultiIndex<int,2> >& values,
const int resolution)
{
// TODO: implement this
}
SampledMapping<2>::SampledMapping(const Point<2>& a,
const Point<2>& b,
const FixedArray1D<Array1D<double>,2>& values)
: Grid<2>(a, b, values[0].size()-1, values[1].size()-1),
values_(values[0].size(), values[1].size())
{
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) = values[0][m] * values[1][n];
}
SampledMapping<2>::SampledMapping(const Chart<2>& ch,
const FixedArray1D<Array1D<double>,2>& values,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<2> x;
Point<2> x_patch;
gridx_.resize(n_points,n_points);
gridy_.resize(n_points,n_points);
values_.resize(n_points,n_points);
// setup grid
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
for (unsigned int j = 0; j < n_points; j++) {
x[1] = h*j;
ch.map_point(x,x_patch);
gridx_.set_entry(i,j,x_patch[0]);
gridy_.set_entry(i,j,x_patch[1]);
values_.set_entry(i,j,(values[0][i] * values[1][j]) / ch.Gram_factor(x));
}
}
// values_.resize(n_points,n_points);
// // setup values
// for (unsigned int i = 0; i < n_points; i++) {
// x[0] = h*i;
// for (unsigned int j = 0; j < n_points; j++) {
// x[1] = h*j;
// values_.set_entry(i,j,(values[0][i] * values[1][j]) / ch.Gram_factor(x));
// }
// }
}
SampledMapping<2>::SampledMapping(const Chart<2>& ch,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<2> x;
Point<2> x_patch;
gridx_.resize(n_points,n_points);
gridy_.resize(n_points,n_points);
// setup grid
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
for (unsigned int j = 0; j < n_points; j++) {
x[1] = h*j;
ch.map_point(x,x_patch);
//cout << "i=" << x_patch[0] << " j= " << x_patch[1] << endl;
gridx_.set_entry(i,j,x_patch[0]);
gridy_.set_entry(i,j,x_patch[1]);
}
}
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
}
SampledMapping<2>&
SampledMapping<2>::operator = (const SampledMapping<2>& sm)
{
Grid<2>::operator = (sm);
values_ = sm.values_;
return *this;
}
void
SampledMapping<2>::add(const SampledMapping<2>& s)
{
assert(values_.row_dimension() == s.values_.row_dimension()
&& values_.column_dimension() == s.values_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) += s.values_(m,n); // Matrix does not (yet) have an add() method
}
void
SampledMapping<2>::add(const double alpha, const SampledMapping<2>& s)
{
assert(values_.row_dimension() == s.values_.row_dimension()
&& values_.column_dimension() == s.values_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) += alpha * s.values_(m,n); // Matrix does not (yet) have an add() method
}
void
SampledMapping<2>::matlab_output(std::ostream& os) const
{
Grid<2>::matlab_output(os);
os << "z = ";
print_matrix(values_, os);
os << ";"
<< std::endl;
}
template <unsigned int DIM>
void matlab_output(std::ostream& os,
const Array1D<SampledMapping<DIM> >& values)
{
switch (DIM) {
case 1: {
for (unsigned int i = 0; i < values.size(); i++) {
values[i].matlab_output(os);
os << "hold on" << std::endl
<< "plot(x,y)" << std::endl;
if (i == (values.size()-1))
os << "hold off" << std::endl;
}
break;
}
case 2: {
for (unsigned int i = 0; i < values.size(); i++) {
values[i].matlab_output(os);
os << "hold on" << std::endl
<< "surf(x,y,z)" << std::endl;
if (i == (values.size()-1))
os << "hold off" << std::endl;
}
break;
}
}// end switch
}
}
<commit_msg>fixed a bug in the SampledMapping<2> constructor from two 1D value vectors (confused the two dimensions)<commit_after>// implementation for sampled_mapping.h
namespace MathTL
{
SampledMapping<1>::SampledMapping()
: Grid<1>(), values_()
{
}
SampledMapping<1>::SampledMapping(const SampledMapping<1>& sm)
: Grid<1>(sm), values_(sm.values_)
{
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid)
: Grid<1>(grid), values_(grid.size())
{
for (unsigned int i = 0; i < grid.size(); i++)
values_[i] = 0;
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid, const Array1D<double>& values)
: Grid<1>(grid), values_(values)
{
}
SampledMapping<1>::SampledMapping(const Grid<1>& grid, const Function<1>& f)
: Grid<1>(grid), values_(grid.size())
{
for (unsigned int n(0); n < grid.size(); n++)
values_[n] = f.value(Point<1>(grid_[n]));
}
SampledMapping<1>::SampledMapping(const MultiIndex<int,1>& a,
const MultiIndex<int,1>& b,
const InfiniteVector<double, MultiIndex<int,1> >& values,
const int resolution)
: Grid<1>(a[0], b[0], (1<<resolution)*(b[0]-a[0]))
{
values_.resize(Grid<1>::size());
for (int k(a[0]<<resolution), n(0); k <= (b[0]<<resolution); k++, n++)
values_[n] = values.get_coefficient(MultiIndex<int,1>(k));
}
SampledMapping<1>::SampledMapping(const Point<1>& a,
const Point<1>& b,
const FixedArray1D<Array1D<double>,1>& values)
: Grid<1>(a[0], b[0], values[0].size()-1), values_(values[0])
{
}
SampledMapping<1>::SampledMapping(const Chart<1>& ch,
const FixedArray1D<Array1D<double>,1>& values,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<1> x;
Point<1> x_patch;
grid_.resize(n_points);
values_.resize(n_points);
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
ch.map_point(x,x_patch);
grid_[i] = x_patch[0];
values_[i] = values[0][i] / ch.Gram_factor(x);
}
}
SampledMapping<1>::SampledMapping(const Chart<1>& ch,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<1> x;
Point<1> x_patch;
grid_.resize(n_points);
values_.resize(n_points);
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
ch.map_point(x,x_patch);
grid_[i] = x_patch[0];
values_[i] = 0;
}
}
SampledMapping<1>&
SampledMapping<1>::operator = (const SampledMapping<1>& sm)
{
Grid<1>::operator = (sm);
values_ = sm.values_;
return *this;
}
void
SampledMapping<1>::add(const SampledMapping<1>& s)
{
assert(values_.size() == s.values_.size());
for (unsigned int i = 0; i < values_.size(); i++)
values_[i] += s.values_[i];
}
void
SampledMapping<1>::add(const double alpha, const SampledMapping<1>& s)
{
assert(values_.size() == s.values_.size());
for (unsigned int i = 0; i < values_.size(); i++)
values_[i] += alpha * s.values_[i];
}
void
SampledMapping<1>::matlab_output(std::ostream& os) const
{
Grid<1>::matlab_output(os);
os << "y = " // here we can take y
<< values_
<< ";"
<< std::endl;
}
SampledMapping<2>::SampledMapping()
: Grid<2>(), values_()
{
}
SampledMapping<2>::SampledMapping(const SampledMapping<2>& sm)
: Grid<2>(sm), values_(sm.values_)
{
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid)
: Grid<2>(grid)
{
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid, const Matrix<double>& values)
: Grid<2>(grid), values_(values)
{
}
SampledMapping<2>::SampledMapping(const Grid<2>& grid, const Function<2>& f)
: Grid<2>(grid), values_()
{
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) = f.value(Point<2>(gridx_(m,n), gridy_(m,n)));
}
SampledMapping<2>::SampledMapping(const MultiIndex<int,2>& a,
const MultiIndex<int,2>& b,
const InfiniteVector<double, MultiIndex<int,2> >& values,
const int resolution)
{
// TODO: implement this
}
SampledMapping<2>::SampledMapping(const Point<2>& a,
const Point<2>& b,
const FixedArray1D<Array1D<double>,2>& values)
: Grid<2>(a, b, values[0].size()-1, values[1].size()-1),
values_(values[1].size(), values[0].size())
{
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) = values[1][m] * values[0][n];
}
SampledMapping<2>::SampledMapping(const Chart<2>& ch,
const FixedArray1D<Array1D<double>,2>& values,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<2> x;
Point<2> x_patch;
gridx_.resize(n_points,n_points);
gridy_.resize(n_points,n_points);
values_.resize(n_points,n_points);
// setup grid
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
for (unsigned int j = 0; j < n_points; j++) {
x[1] = h*j;
ch.map_point(x,x_patch);
gridx_.set_entry(i,j,x_patch[0]);
gridy_.set_entry(i,j,x_patch[1]);
values_.set_entry(i,j,(values[0][i] * values[1][j]) / ch.Gram_factor(x));
}
}
// values_.resize(n_points,n_points);
// // setup values
// for (unsigned int i = 0; i < n_points; i++) {
// x[0] = h*i;
// for (unsigned int j = 0; j < n_points; j++) {
// x[1] = h*j;
// values_.set_entry(i,j,(values[0][i] * values[1][j]) / ch.Gram_factor(x));
// }
// }
}
SampledMapping<2>::SampledMapping(const Chart<2>& ch,
const unsigned int resolution)
{
const unsigned int n_points = (1 << resolution)+1;
const double h = 1.0 / (n_points-1);
Point<2> x;
Point<2> x_patch;
gridx_.resize(n_points,n_points);
gridy_.resize(n_points,n_points);
// setup grid
for (unsigned int i = 0; i < n_points; i++) {
x[0] = h*i;
for (unsigned int j = 0; j < n_points; j++) {
x[1] = h*j;
ch.map_point(x,x_patch);
//cout << "i=" << x_patch[0] << " j= " << x_patch[1] << endl;
gridx_.set_entry(i,j,x_patch[0]);
gridy_.set_entry(i,j,x_patch[1]);
}
}
values_.resize(gridx_.row_dimension(), gridx_.column_dimension());
}
SampledMapping<2>&
SampledMapping<2>::operator = (const SampledMapping<2>& sm)
{
Grid<2>::operator = (sm);
values_ = sm.values_;
return *this;
}
void
SampledMapping<2>::add(const SampledMapping<2>& s)
{
assert(values_.row_dimension() == s.values_.row_dimension()
&& values_.column_dimension() == s.values_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) += s.values_(m,n); // Matrix does not (yet) have an add() method
}
void
SampledMapping<2>::add(const double alpha, const SampledMapping<2>& s)
{
assert(values_.row_dimension() == s.values_.row_dimension()
&& values_.column_dimension() == s.values_.column_dimension());
for (unsigned int m(0); m < values_.row_dimension(); m++)
for (unsigned int n(0); n < values_.column_dimension(); n++)
values_(m,n) += alpha * s.values_(m,n); // Matrix does not (yet) have an add() method
}
void
SampledMapping<2>::matlab_output(std::ostream& os) const
{
Grid<2>::matlab_output(os);
os << "z = ";
print_matrix(values_, os);
os << ";"
<< std::endl;
}
template <unsigned int DIM>
void matlab_output(std::ostream& os,
const Array1D<SampledMapping<DIM> >& values)
{
switch (DIM) {
case 1: {
for (unsigned int i = 0; i < values.size(); i++) {
values[i].matlab_output(os);
os << "hold on" << std::endl
<< "plot(x,y)" << std::endl;
if (i == (values.size()-1))
os << "hold off" << std::endl;
}
break;
}
case 2: {
for (unsigned int i = 0; i < values.size(); i++) {
values[i].matlab_output(os);
os << "hold on" << std::endl
<< "surf(x,y,z)" << std::endl;
if (i == (values.size()-1))
os << "hold off" << std::endl;
}
break;
}
}// end switch
}
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* 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 <QTimer>
#include <nitroshare/application.h>
#include <nitroshare/logger.h>
#include <nitroshare/message.h>
#include <nitroshare/settingsregistry.h>
#include <qmdnsengine/resolver.h>
#include "mdnsenumerator.h"
const QString MessageTag = "mdns";
const QByteArray ServiceType = "_nitroshare._tcp.local.";
MdnsEnumerator::MdnsEnumerator(Application *application)
: mApplication(application),
mHostname(&mServer),
mProvider(&mServer, &mHostname),
mBrowser(&mServer, ServiceType, &mCache)
{
connect(&mHostname, &QMdnsEngine::Hostname::hostnameChanged, this, &MdnsEnumerator::onHostnameChanged);
connect(&mBrowser, &QMdnsEngine::Browser::serviceAdded, this, &MdnsEnumerator::onServiceUpdated);
connect(&mBrowser, &QMdnsEngine::Browser::serviceUpdated, this, &MdnsEnumerator::onServiceUpdated);
connect(&mBrowser, &QMdnsEngine::Browser::serviceRemoved, this, &MdnsEnumerator::onServiceRemoved);
connect(application->settingsRegistry(), &SettingsRegistry::settingsChanged, this, &MdnsEnumerator::onSettingsChanged);
// Initialize the service
mService.setType(ServiceType);
mService.setAttributes({{ "uuid", mApplication->deviceUuid().toUtf8() }});
// Trigger loading the initial settings
onSettingsChanged({ Application::DeviceName });
}
void MdnsEnumerator::onHostnameChanged(const QByteArray &hostname) {
mApplication->logger()->log(new Message(
Message::Info,
MessageTag,
QString("hostname set to %1").arg(QString(hostname))
));
}
void MdnsEnumerator::onServiceUpdated(const QMdnsEngine::Service &service)
{
mApplication->logger()->log(new Message(
Message::Debug,
MessageTag,
QString("%1 updated").arg(QString(service.name()))
));
// Send an update for the attributes currently known
QString uuid = findUuid(service);
QVariantMap properties = {
{ DeviceEnumerator::UuidKey, uuid },
{ DeviceEnumerator::NameKey, service.name() },
{ DeviceEnumerator::PortKey, service.port() }
};
emit deviceUpdated(uuid, properties);
// Send an update every time an address is resolved
QMdnsEngine::Resolver *resolver = new QMdnsEngine::Resolver(&mServer, service.name(), &mCache, this);
connect(resolver, &QMdnsEngine::Resolver::resolved, [this, uuid](const QHostAddress &address) {
emit deviceUpdated(uuid, {{ DeviceEnumerator::AddressesKey, address.toString() }});
});
// Delete the resolver after 2 seconds
QTimer::singleShot(2000, resolver, &QMdnsEngine::Resolver::deleteLater);
}
void MdnsEnumerator::onServiceRemoved(const QMdnsEngine::Service &service)
{
mApplication->logger()->log(new Message(
Message::Debug,
MessageTag,
QString("%1 removed").arg(QString(service.name()))
));
emit deviceRemoved(findUuid(service));
}
void MdnsEnumerator::onSettingsChanged(const QStringList &keys)
{
if (keys.contains(Application::DeviceName)) {
mService.setName(mApplication->deviceName().toUtf8());
mService.setPort(0);
mProvider.update(mService);
}
}
QString MdnsEnumerator::findUuid(const QMdnsEngine::Service &service)
{
QString uuid = service.attributes().value("uuid");
if (uuid.isNull()) {
uuid = service.name();
}
return uuid;
}
<commit_msg>Ensure mdns plugin sends correct port for listening locally.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* 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 <QTimer>
#include <nitroshare/application.h>
#include <nitroshare/logger.h>
#include <nitroshare/message.h>
#include <nitroshare/settingsregistry.h>
#include <qmdnsengine/resolver.h>
#include "mdnsenumerator.h"
const QString MessageTag = "mdns";
const QString TransferPort = "TransferPort";
const QByteArray ServiceType = "_nitroshare._tcp.local.";
MdnsEnumerator::MdnsEnumerator(Application *application)
: mApplication(application),
mHostname(&mServer),
mProvider(&mServer, &mHostname),
mBrowser(&mServer, ServiceType, &mCache)
{
connect(&mHostname, &QMdnsEngine::Hostname::hostnameChanged, this, &MdnsEnumerator::onHostnameChanged);
connect(&mBrowser, &QMdnsEngine::Browser::serviceAdded, this, &MdnsEnumerator::onServiceUpdated);
connect(&mBrowser, &QMdnsEngine::Browser::serviceUpdated, this, &MdnsEnumerator::onServiceUpdated);
connect(&mBrowser, &QMdnsEngine::Browser::serviceRemoved, this, &MdnsEnumerator::onServiceRemoved);
connect(application->settingsRegistry(), &SettingsRegistry::settingsChanged, this, &MdnsEnumerator::onSettingsChanged);
// Initialize the service
mService.setType(ServiceType);
mService.setAttributes({{ "uuid", mApplication->deviceUuid().toUtf8() }});
// Trigger loading the initial settings
onSettingsChanged({ Application::DeviceName });
}
void MdnsEnumerator::onHostnameChanged(const QByteArray &hostname) {
mApplication->logger()->log(new Message(
Message::Info,
MessageTag,
QString("hostname set to %1").arg(QString(hostname))
));
}
void MdnsEnumerator::onServiceUpdated(const QMdnsEngine::Service &service)
{
mApplication->logger()->log(new Message(
Message::Debug,
MessageTag,
QString("%1 updated").arg(QString(service.name()))
));
// Send an update for the attributes currently known
QString uuid = findUuid(service);
QVariantMap properties = {
{ DeviceEnumerator::UuidKey, uuid },
{ DeviceEnumerator::NameKey, service.name() },
{ DeviceEnumerator::PortKey, service.port() }
};
emit deviceUpdated(uuid, properties);
// Send an update every time an address is resolved
QMdnsEngine::Resolver *resolver = new QMdnsEngine::Resolver(&mServer, service.name(), &mCache, this);
connect(resolver, &QMdnsEngine::Resolver::resolved, [this, uuid](const QHostAddress &address) {
emit deviceUpdated(uuid, {{ DeviceEnumerator::AddressesKey, address.toString() }});
});
// Delete the resolver after 2 seconds
QTimer::singleShot(2000, resolver, &QMdnsEngine::Resolver::deleteLater);
}
void MdnsEnumerator::onServiceRemoved(const QMdnsEngine::Service &service)
{
mApplication->logger()->log(new Message(
Message::Debug,
MessageTag,
QString("%1 removed").arg(QString(service.name()))
));
emit deviceRemoved(findUuid(service));
}
void MdnsEnumerator::onSettingsChanged(const QStringList &keys)
{
if (keys.contains(Application::DeviceName)) {
mService.setName(mApplication->deviceName().toUtf8());
mService.setPort(mApplication->settingsRegistry()->value(TransferPort).toInt());
mProvider.update(mService);
}
}
QString MdnsEnumerator::findUuid(const QMdnsEngine::Service &service)
{
QString uuid = service.attributes().value("uuid");
if (uuid.isNull()) {
uuid = service.name();
}
return uuid;
}
<|endoftext|>
|
<commit_before>#ifndef VIENNAFVM_PDE_SOLVER_HPP
#define VIENNAFVM_PDE_SOLVER_HPP
/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(add your name here)
license: see file LICENSE in the ViennaFVM base directory
======================================================================= */
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/operation_sparse.hpp>
#ifdef VIENNAFVM_VERBOSE
#include "viennafvm/timer.hpp"
#endif
#include "viennafvm/forwards.h"
#include "viennafvm/quantity.hpp"
#include "viennafvm/linear_assembler.hpp"
#include "viennafvm/linear_solvers/viennacl.hpp"
namespace viennafvm
{
template <typename PDESystemType, typename DomainType, typename QuantityContainer, typename VectorType>
double apply_update(PDESystemType const & pde_system, std::size_t pde_index,
DomainType const & domain,
QuantityContainer & quantities,
VectorType const & update, numeric_type alpha = 0.3)
{
typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTag;
typedef typename viennagrid::result_of::const_element_range<DomainType, CellTag>::type CellContainer;
typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typedef typename QuantityContainer::value_type QuantityType;
long quantity_id = pde_system.unknown(pde_index)[0].id();
numeric_type l2_update_norm = 0;
QuantityType & quan = quantities.at(quantity_id);
CellContainer cells(domain);
// get damping term
numeric_type A_n = 0.0;
if (pde_system.option(pde_index).geometric_update())
{
for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit)
{
double current_value = quan.get_value(*cit);
double update_value = quan.get_value(*cit);
if (quan.get_unknown_index(*cit) >= 0)
update_value = update(quan.get_unknown_index(*cit));
else
update_value = quan.get_boundary_value(*cit) - current_value;
if (current_value != 0)
A_n = std::max(A_n, std::abs(update_value / current_value));
}
}
// apply update:
for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit)
{
double current_value = quan.get_value(*cit);
double update_value = quan.get_value(*cit);
if (quan.get_unknown_index(*cit) >= 0)
update_value = update(quan.get_unknown_index(*cit));
else
update_value = quan.get_boundary_value(*cit) - current_value;
numeric_type new_value = current_value + alpha * update_value;
if (pde_system.option(pde_index).geometric_update())
{
if (update_value < 0)
new_value = current_value + alpha * ( update_value / (1.0 - A_n * ( update_value / current_value ) ));
else
new_value = std::pow(current_value, 1.0 - alpha) * std::pow( current_value + update_value, alpha);
}
else
{
new_value = current_value + alpha * update_value;
}
l2_update_norm += (new_value - current_value) * (new_value - current_value);
quan.set_value(*cit, new_value);
}
// std::cout << "* Update norm for quantity " << pde_index << ": " << std::sqrt(l2_update_norm) << std::endl;
return std::sqrt(l2_update_norm);
}
class pde_solver
{
typedef boost::numeric::ublas::compressed_matrix<viennafvm::numeric_type> MatrixType;
typedef boost::numeric::ublas::vector<viennafvm::numeric_type> VectorType;
public:
typedef viennafvm::numeric_type numeric_type;
pde_solver()
{
nonlinear_iterations = 100;
nonlinear_breaktol = 1.0e-3;
damping = 1.0;
}
template<typename ProblemDescriptionT, typename PDESystemT, typename LinearSolverT>
bool operator()(ProblemDescriptionT & problem_description,
PDESystemT const & pde_system,
LinearSolverT& linear_solver,
std::size_t break_pde = 0)
{
#ifdef VIENNAFVM_VERBOSE
std::streamsize cout_precision = std::cout.precision();
#endif
bool is_linear = pde_system.is_linear(); //TODO: Replace with an automatic detection
if (is_linear)
{
for (std::size_t pde_index = 0; pde_index < pde_system.size(); ++pde_index)
{
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer timer;
timer.start();
std::cout << " * Quantity " << pde_index << " : " << std::endl;
std::cout << " ------------------------------------------" << std::endl;
#endif
MatrixType system_matrix;
VectorType load_vector;
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer subtimer;
subtimer.start();
#endif
viennafvm::linear_assembler fvm_assembler;
fvm_assembler(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), system_matrix, load_vector);
#ifdef VIENNAFVM_VERBOSE
std::cout.precision(3);
subtimer.get();
std::cout << " Assembly time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
VectorType update;
linear_solver(system_matrix, load_vector, update);
#ifdef VIENNAFVM_VERBOSE
std::cout << " Precond time : " << std::fixed << linear_solver.last_pc_time() << " s" << std::endl;
std::cout << " Solver time : " << std::fixed << linear_solver.last_solver_time() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.start();
numeric_type update_norm = apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, damping);
#else
apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, 1.0); //this is linear, so there's no need for any damping
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.get();
std::cout << " Update time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
timer.get();
std::cout << " Total time : " << std::fixed << timer.get() << " s" << std::endl;
std::cout.precision(cout_precision);
std::cout.unsetf(std::ios_base::floatfield);
std::cout << " Solver iters : " << linear_solver.last_iterations();
if(linear_solver.last_iterations() == linear_solver.max_iterations())
std::cout << " ( not converged ) " << std::endl;
else std::cout << std::endl;
std::cout << " Solver error : " << linear_solver.last_error() << std::endl;
std::cout << " Update norm : " << update_norm << std::endl;
std::cout << std::endl;
#endif
if(linear_solver.last_iterations() == linear_solver.max_iterations())
return false;
else return true;
}
}
else // nonlinear
{
picard_iteration_ = true;
#ifdef VIENNAFVM_VERBOSE
std::vector<double> previous_update_norms(pde_system.size());
#endif
bool converged = false;
std::size_t required_nonlinear_iterations = 0;
for (std::size_t iter=0; iter < nonlinear_iterations; ++iter)
{
required_nonlinear_iterations++;
#ifdef VIENNAFVM_VERBOSE
std::cout << " --- Nonlinear iteration " << iter << " --- " << std::endl;
#endif
if (picard_iteration_)
{
for (std::size_t pde_index = 0; pde_index < pde_system.size(); ++pde_index)
{
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer timer;
timer.start();
std::cout << " * Quantity " << pde_index << " : " << std::endl;
std::cout << " ------------------------------------" << std::endl;
#endif
MatrixType system_matrix;
VectorType load_vector;
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer subtimer;
subtimer.start();
#endif
// assemble linearized systems
viennafvm::linear_assembler fvm_assembler;
fvm_assembler(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), system_matrix, load_vector);
#ifdef VIENNAFVM_VERBOSE
std::cout.precision(3);
subtimer.get();
std::cout << " Assembly time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
VectorType update;
linear_solver(system_matrix, load_vector, update);
#ifdef VIENNAFVM_VERBOSE
std::cout << " Precond time : " << std::fixed << linear_solver.last_pc_time() << " s" << std::endl;
std::cout << " Solver time : " << std::fixed << linear_solver.last_solver_time() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.start();
#endif
numeric_type update_norm = apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, damping);
#ifdef VIENNAFVM_VERBOSE
subtimer.get();
std::cout << " Update time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
timer.get();
std::cout << " Total time : " << std::fixed << timer.get() << " s" << std::endl;
std::cout.precision(cout_precision);
std::cout.unsetf(std::ios_base::floatfield);
std::cout << " Solver iters : " << linear_solver.last_iterations();
if(linear_solver.last_iterations() == linear_solver.max_iterations())
std::cout << " ( not converged ) " << std::endl;
else std::cout << std::endl;
std::cout << " Solver error : " << linear_solver.last_error() << std::endl;
std::string norm_tendency_indicator;
if(iter == 0)
{
previous_update_norms[pde_index] = update_norm;
norm_tendency_indicator = "";
}
else
{
if(update_norm > previous_update_norms[pde_index])
norm_tendency_indicator = "<up>";
else
if(update_norm < previous_update_norms[pde_index])
norm_tendency_indicator = "<down>";
else
norm_tendency_indicator = "<=>";
previous_update_norms[pde_index] = update_norm;
}
std::cout << " Update norm : " << update_norm << " " << norm_tendency_indicator;
if(pde_index == break_pde)
std::cout << " ( **** )" << std::endl;
else
std::cout << std::endl;
std::cout << std::endl;
#endif
if(pde_index == break_pde) // check if the potential update has converged ..
{
if(update_norm <= nonlinear_breaktol) converged = true;
}
}
}
else
{
throw "not implemented!";
}
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
#endif
if(converged) break; // .. the nonlinear for-loop
} // nonlinear for-loop
if(converged)
{
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
std::cout << "--------" << std::endl;
std::cout << "Success: Simulation converged successfully!" << std::endl;
std::cout << " Update norm of observed variable reached the break-tolerance of " << nonlinear_breaktol
<< " in " << required_nonlinear_iterations << " iterations" << std::endl;
std::cout << "--------" << std::endl;
#endif
return true;
}
else
{
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
std::cout << "--------" << std::endl;
std::cout << "Warning: Simulation did not converge!" << std::endl;
std::cout << " Update norm of observed variable did not reach the break-tolerance of " << nonlinear_breaktol
<< " in " << nonlinear_iterations << " iterations" << std::endl;
std::cout << "--------" << std::endl;
#endif
return false;
}
}
return true; // should be never the case: TODO Design flow, restructure if/else conditions appropriatly
}
std::size_t get_nonlinear_iterations() { return nonlinear_iterations; }
void set_nonlinear_iterations(std::size_t max_iters) { nonlinear_iterations = max_iters; }
numeric_type get_nonlinear_breaktol() { return nonlinear_iterations; }
void set_nonlinear_breaktol(numeric_type value) { nonlinear_breaktol = value; }
numeric_type get_damping() { return damping; }
void set_damping(numeric_type value) { damping = value; }
private:
bool picard_iteration_;
std::size_t nonlinear_iterations;
numeric_type nonlinear_breaktol;
numeric_type damping;
};
}
#endif // VIENNAFVM_PDE_SOLVER_HPP
<commit_msg>PDE solver: Set damping from 1.0 to 0.5 in order to fix issues with MOSFET results.<commit_after>#ifndef VIENNAFVM_PDE_SOLVER_HPP
#define VIENNAFVM_PDE_SOLVER_HPP
/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(add your name here)
license: see file LICENSE in the ViennaFVM base directory
======================================================================= */
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/operation_sparse.hpp>
#ifdef VIENNAFVM_VERBOSE
#include "viennafvm/timer.hpp"
#endif
#include "viennafvm/forwards.h"
#include "viennafvm/quantity.hpp"
#include "viennafvm/linear_assembler.hpp"
#include "viennafvm/linear_solvers/viennacl.hpp"
namespace viennafvm
{
template <typename PDESystemType, typename DomainType, typename QuantityContainer, typename VectorType>
double apply_update(PDESystemType const & pde_system, std::size_t pde_index,
DomainType const & domain,
QuantityContainer & quantities,
VectorType const & update, numeric_type alpha = 0.3)
{
typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTag;
typedef typename viennagrid::result_of::const_element_range<DomainType, CellTag>::type CellContainer;
typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typedef typename QuantityContainer::value_type QuantityType;
long quantity_id = pde_system.unknown(pde_index)[0].id();
numeric_type l2_update_norm = 0;
QuantityType & quan = quantities.at(quantity_id);
CellContainer cells(domain);
// get damping term
numeric_type A_n = 0.0;
if (pde_system.option(pde_index).geometric_update())
{
for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit)
{
double current_value = quan.get_value(*cit);
double update_value = quan.get_value(*cit);
if (quan.get_unknown_index(*cit) >= 0)
update_value = update(quan.get_unknown_index(*cit));
else
update_value = quan.get_boundary_value(*cit) - current_value;
if (current_value != 0)
A_n = std::max(A_n, std::abs(update_value / current_value));
}
}
// apply update:
for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit)
{
double current_value = quan.get_value(*cit);
double update_value = quan.get_value(*cit);
if (quan.get_unknown_index(*cit) >= 0)
update_value = update(quan.get_unknown_index(*cit));
else
update_value = quan.get_boundary_value(*cit) - current_value;
numeric_type new_value = current_value + alpha * update_value;
if (pde_system.option(pde_index).geometric_update())
{
//if (update_value < 0)
// new_value = current_value + alpha * ( update_value / (1.0 - A_n * ( update_value / current_value ) ));
//else
new_value = std::pow(current_value, 1.0 - alpha) * std::pow( current_value + update_value, alpha);
}
else
{
new_value = current_value + alpha * update_value;
}
l2_update_norm += (new_value - current_value) * (new_value - current_value);
quan.set_value(*cit, new_value);
}
// std::cout << "* Update norm for quantity " << pde_index << ": " << std::sqrt(l2_update_norm) << std::endl;
return std::sqrt(l2_update_norm);
}
class pde_solver
{
typedef boost::numeric::ublas::compressed_matrix<viennafvm::numeric_type> MatrixType;
typedef boost::numeric::ublas::vector<viennafvm::numeric_type> VectorType;
public:
typedef viennafvm::numeric_type numeric_type;
pde_solver()
{
nonlinear_iterations = 100;
nonlinear_breaktol = 1.0e-3;
damping = 0.5;
}
template<typename ProblemDescriptionT, typename PDESystemT, typename LinearSolverT>
bool operator()(ProblemDescriptionT & problem_description,
PDESystemT const & pde_system,
LinearSolverT& linear_solver,
std::size_t break_pde = 0)
{
#ifdef VIENNAFVM_VERBOSE
std::streamsize cout_precision = std::cout.precision();
#endif
bool is_linear = pde_system.is_linear(); //TODO: Replace with an automatic detection
if (is_linear)
{
for (std::size_t pde_index = 0; pde_index < pde_system.size(); ++pde_index)
{
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer timer;
timer.start();
std::cout << " * Quantity " << pde_index << " : " << std::endl;
std::cout << " ------------------------------------------" << std::endl;
#endif
MatrixType system_matrix;
VectorType load_vector;
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer subtimer;
subtimer.start();
#endif
viennafvm::linear_assembler fvm_assembler;
fvm_assembler(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), system_matrix, load_vector);
#ifdef VIENNAFVM_VERBOSE
std::cout.precision(3);
subtimer.get();
std::cout << " Assembly time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
VectorType update;
linear_solver(system_matrix, load_vector, update);
#ifdef VIENNAFVM_VERBOSE
std::cout << " Precond time : " << std::fixed << linear_solver.last_pc_time() << " s" << std::endl;
std::cout << " Solver time : " << std::fixed << linear_solver.last_solver_time() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.start();
numeric_type update_norm = apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, damping);
#else
apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, 1.0); //this is linear, so there's no need for any damping
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.get();
std::cout << " Update time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
timer.get();
std::cout << " Total time : " << std::fixed << timer.get() << " s" << std::endl;
std::cout.precision(cout_precision);
std::cout.unsetf(std::ios_base::floatfield);
std::cout << " Solver iters : " << linear_solver.last_iterations();
if(linear_solver.last_iterations() == linear_solver.max_iterations())
std::cout << " ( not converged ) " << std::endl;
else std::cout << std::endl;
std::cout << " Solver error : " << linear_solver.last_error() << std::endl;
std::cout << " Update norm : " << update_norm << std::endl;
std::cout << std::endl;
#endif
if(linear_solver.last_iterations() == linear_solver.max_iterations())
return false;
else return true;
}
}
else // nonlinear
{
picard_iteration_ = true;
#ifdef VIENNAFVM_VERBOSE
std::vector<double> previous_update_norms(pde_system.size());
#endif
bool converged = false;
std::size_t required_nonlinear_iterations = 0;
for (std::size_t iter=0; iter < nonlinear_iterations; ++iter)
{
required_nonlinear_iterations++;
#ifdef VIENNAFVM_VERBOSE
std::cout << " --- Nonlinear iteration " << iter << " --- " << std::endl;
#endif
if (picard_iteration_)
{
for (std::size_t pde_index = 0; pde_index < pde_system.size(); ++pde_index)
{
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer timer;
timer.start();
std::cout << " * Quantity " << pde_index << " : " << std::endl;
std::cout << " ------------------------------------" << std::endl;
#endif
MatrixType system_matrix;
VectorType load_vector;
#ifdef VIENNAFVM_VERBOSE
viennafvm::Timer subtimer;
subtimer.start();
#endif
// assemble linearized systems
viennafvm::linear_assembler fvm_assembler;
fvm_assembler(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), system_matrix, load_vector);
#ifdef VIENNAFVM_VERBOSE
std::cout.precision(3);
subtimer.get();
std::cout << " Assembly time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
VectorType update;
linear_solver(system_matrix, load_vector, update);
#ifdef VIENNAFVM_VERBOSE
std::cout << " Precond time : " << std::fixed << linear_solver.last_pc_time() << " s" << std::endl;
std::cout << " Solver time : " << std::fixed << linear_solver.last_solver_time() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
subtimer.start();
#endif
numeric_type update_norm = apply_update(pde_system, pde_index, problem_description.mesh(), problem_description.quantities(), update, damping);
#ifdef VIENNAFVM_VERBOSE
subtimer.get();
std::cout << " Update time : " << std::fixed << subtimer.get() << " s" << std::endl;
#endif
#ifdef VIENNAFVM_VERBOSE
timer.get();
std::cout << " Total time : " << std::fixed << timer.get() << " s" << std::endl;
std::cout.precision(cout_precision);
std::cout.unsetf(std::ios_base::floatfield);
std::cout << " Solver iters : " << linear_solver.last_iterations();
if(linear_solver.last_iterations() == linear_solver.max_iterations())
std::cout << " ( not converged ) " << std::endl;
else std::cout << std::endl;
std::cout << " Solver error : " << linear_solver.last_error() << std::endl;
std::string norm_tendency_indicator;
if(iter == 0)
{
previous_update_norms[pde_index] = update_norm;
norm_tendency_indicator = "";
}
else
{
if(update_norm > previous_update_norms[pde_index])
norm_tendency_indicator = "<up>";
else
if(update_norm < previous_update_norms[pde_index])
norm_tendency_indicator = "<down>";
else
norm_tendency_indicator = "<=>";
previous_update_norms[pde_index] = update_norm;
}
std::cout << " Update norm : " << update_norm << " " << norm_tendency_indicator;
if(pde_index == break_pde)
std::cout << " ( **** )" << std::endl;
else
std::cout << std::endl;
std::cout << std::endl;
#endif
if(pde_index == break_pde) // check if the potential update has converged ..
{
if(update_norm <= nonlinear_breaktol) converged = true;
}
}
}
else
{
throw "not implemented!";
}
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
#endif
if(converged) break; // .. the nonlinear for-loop
} // nonlinear for-loop
if(converged)
{
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
std::cout << "--------" << std::endl;
std::cout << "Success: Simulation converged successfully!" << std::endl;
std::cout << " Update norm of observed variable reached the break-tolerance of " << nonlinear_breaktol
<< " in " << required_nonlinear_iterations << " iterations" << std::endl;
std::cout << "--------" << std::endl;
#endif
return true;
}
else
{
#ifdef VIENNAFVM_VERBOSE
std::cout << std::endl;
std::cout << "--------" << std::endl;
std::cout << "Warning: Simulation did not converge!" << std::endl;
std::cout << " Update norm of observed variable did not reach the break-tolerance of " << nonlinear_breaktol
<< " in " << nonlinear_iterations << " iterations" << std::endl;
std::cout << "--------" << std::endl;
#endif
return false;
}
}
return true; // should be never the case: TODO Design flow, restructure if/else conditions appropriatly
}
std::size_t get_nonlinear_iterations() { return nonlinear_iterations; }
void set_nonlinear_iterations(std::size_t max_iters) { nonlinear_iterations = max_iters; }
numeric_type get_nonlinear_breaktol() { return nonlinear_iterations; }
void set_nonlinear_breaktol(numeric_type value) { nonlinear_breaktol = value; }
numeric_type get_damping() { return damping; }
void set_damping(numeric_type value) { damping = value; }
private:
bool picard_iteration_;
std::size_t nonlinear_iterations;
numeric_type nonlinear_breaktol;
numeric_type damping;
};
}
#endif // VIENNAFVM_PDE_SOLVER_HPP
<|endoftext|>
|
<commit_before>#include <math.h>
#include <vector>
#include <string>
#include "io.hh"
#include "conf.hh"
#include "Recipe.hh"
#include "FeatureGenerator.hh"
#include "SpeakerConfig.hh"
const char *recipe_file;
const char *out_file;
conf::Config config;
FeatureGenerator gen;
SpeakerConfig m_speaker_config(gen); // Speaker configuration handler
int
main(int argc, char *argv[])
{
NormalizationModule *norm_mod = NULL;
FeatureModule *norm_mod_src = NULL;
std::vector<double> block_mean_acc, global_mean_acc;
std::vector<double> block_var_acc, global_var_acc;
std::vector<double> block_cov_acc, global_cov_acc;
double global_acc_count;
std::vector<float> mean, scale;
bool raw_flag;
bool cov_flag;
int info;
int block_size;
int cur_block_size;
int start_frame, end_frame;
int dim;
try {
config("usage: feanorm [OPTION...]\n")
('h', "help", "", "", "display help")
('r', "recipe=FILE", "arg must", "", "recipe file")
('c', "config=FILE", "arg must", "", "read feature configuration")
('w', "write-config=FILE", "arg", "", "write feature configuration")
('R', "raw-input", "", "", "raw audio input")
('M', "module=NAME", "arg", "", "normalization module name")
('b', "block=INT", "arg", "1000", "block size (for reducing round-off errors)")
('P', "print", "", "", "print mean and variance to stdout")
('\0', "cov", "", "", "estimate and print covariance matrix")
('S', "speakers=FILE", "arg", "", "speaker configuration file")
('i', "info=INT", "arg", "0", "info level")
;
config.default_parse(argc, argv);
info = config["info"].get_int();
raw_flag = config["raw-input"].specified;
gen.load_configuration(io::Stream(config["config"].get_str()));
dim = gen.dim();
if (config["module"].specified)
{
norm_mod = dynamic_cast< NormalizationModule* >
(gen.module(config["module"].get_str()));
if (norm_mod == NULL)
throw std::string("Module ") + config["module"].get_str() +
std::string(" is not a normalization module");
dim = norm_mod->dim();
std::vector<FeatureModule*> sources = norm_mod->sources();
assert( sources.front()->dim() == dim );
norm_mod_src = sources.front();
}
else if (config["write-config"].specified)
{
fprintf(stderr, "Warning: No --module given, configuration will be written unaltered\n");
}
block_size = config["block"].get_int();
cov_flag = config["cov"].specified;
if (config["speakers"].specified)
m_speaker_config.read_speaker_file(
io::Stream(config["speakers"].get_str()));
// Initialize accumulators
block_mean_acc.resize(dim);
block_var_acc.resize(dim);
global_mean_acc.resize(dim, 0);
global_var_acc.resize(dim, 0);
global_acc_count = 0;
if (cov_flag)
{
block_cov_acc.resize(dim*dim);
global_cov_acc.resize(dim*dim, 0);
}
// Read recipe file
Recipe recipe;
recipe.read(io::Stream(config["recipe"].get_str()),
0, 0, false);
// Handle each file in the recipe
for (int recipe_index = 0; recipe_index < (int)recipe.infos.size();
recipe_index++)
{
if (info > 0)
{
fprintf(stderr, "Processing file: %s\n",
recipe.infos[recipe_index].audio_path.c_str());
}
gen.open(recipe.infos[recipe_index].audio_path, raw_flag);
if (config["speakers"].specified)
{
m_speaker_config.set_speaker(recipe.infos[recipe_index].speaker_id);
if (recipe.infos[recipe_index].utterance_id.size() > 0)
m_speaker_config.set_utterance(
recipe.infos[recipe_index].utterance_id);
}
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] = 0;
block_var_acc[d] = 0;
}
if (cov_flag)
{
for (int d = 0; d < dim*dim; d++)
block_cov_acc[d] = 0;
}
cur_block_size = 0;
start_frame = (int)(recipe.infos[recipe_index].start_time *
gen.frame_rate());
end_frame = (int)(recipe.infos[recipe_index].end_time *
gen.frame_rate());
if (end_frame == 0)
end_frame = INT_MAX;
for (int f = start_frame; f < end_frame; f++)
{
const FeatureVec temp_fvec = gen.generate(f);
if (gen.eof())
{
// Accumulate to global variables
if (cur_block_size > 0)
{
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] += block_mean_acc[d]/(double)block_size;
global_var_acc[d] += block_var_acc[d]/(double)block_size;
}
if (cov_flag)
{
for (int d = 0; d < dim*dim; d++)
global_cov_acc[d] += block_cov_acc[d]/(double)block_size;
}
global_acc_count += (double)cur_block_size/(double)block_size;
}
break;
}
const FeatureVec vec = (norm_mod_src == NULL? temp_fvec :
norm_mod_src->at(f));
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] += vec[d];
block_var_acc[d] += vec[d]*vec[d];
}
if (cov_flag)
{
for (int d1 = 0; d1 < dim; d1++)
for (int d2 = 0; d2 < dim; d2++)
block_cov_acc[d1*dim+d2] += vec[d1]*vec[d2];
}
cur_block_size++;
if (cur_block_size == block_size)
{
// Accumulate to global variables
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] += block_mean_acc[d]/(double)block_size;
global_var_acc[d] += block_var_acc[d]/(double)block_size;
}
if (cov_flag)
{
for (int d = 0; d < dim*dim; d++)
global_cov_acc[d] += block_cov_acc[d]/(double)block_size;
}
global_acc_count++;
// Reset the block accumulators
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] = 0;
block_var_acc[d] = 0;
}
if (cov_flag)
{
for (int d = 0; d < dim*dim; d++)
block_cov_acc[d] = 0;
}
cur_block_size = 0;
}
}
gen.close();
}
mean.resize(dim);
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] /= global_acc_count;
mean[d] = global_mean_acc[d];
}
scale.resize(dim);
for (int d = 0; d < dim; d++)
{
scale[d] = 1/sqrtf(global_var_acc[d] / global_acc_count -
global_mean_acc[d]*global_mean_acc[d]);
}
if (config["print"].specified)
{
printf("mean:\n");
for (int d = 0; d < dim; d++)
printf("%f ", mean[d]);
printf("\n");
printf("variance:\n");
for (int d = 0; d < dim; d++)
printf("%f ", 1/(scale[d]*scale[d]));
printf("\n");
}
if (cov_flag)
{
for (int d1 = 0; d1 < dim; d1++)
{
for (int d2 = 0; d2 < dim; d2++)
{
double t = global_cov_acc[d1*dim+d2] / global_acc_count -
global_mean_acc[d1]*global_mean_acc[d2];
printf("%f ", t);
}
printf("\n");
}
}
if (norm_mod != NULL)
norm_mod->set_normalization(mean, scale);
if (config["write-config"].specified)
gen.write_configuration(io::Stream(config["write-config"].get_str(),
"w"));
}
catch (std::exception &e) {
fprintf(stderr, "exception: %s\n", e.what());
abort();
}
catch (std::string &str) {
fprintf(stderr, "exception: %s\n", str.c_str());
abort();
}
}
<commit_msg>pca functionality<commit_after>#include <math.h>
#include <vector>
#include <string>
#include "io.hh"
#include "conf.hh"
#include "Recipe.hh"
#include "FeatureGenerator.hh"
#include "SpeakerConfig.hh"
const char *recipe_file;
const char *out_file;
conf::Config config;
FeatureGenerator gen;
SpeakerConfig m_speaker_config(gen); // Speaker configuration handler
int
main(int argc, char *argv[])
{
NormalizationModule *norm_mod = NULL;
FeatureModule *norm_mod_src = NULL;
LinTransformModule *pca_mod = NULL;
FeatureModule *pca_mod_src = NULL;
std::vector<double> block_mean_acc, global_mean_acc;
std::vector<double> block_var_acc, global_var_acc;
std::vector<double> block_cov_acc, global_cov_acc;
double global_acc_count;
std::vector<float> mean, scale;
bool raw_flag;
bool cov_flag;
bool pca_flag;
int info;
int block_size;
int cur_block_size;
int start_frame, end_frame;
int dim;
try {
config("usage: feanorm [OPTION...]\n")
('h', "help", "", "", "display help")
('r', "recipe=FILE", "arg must", "", "recipe file")
('c', "config=FILE", "arg must", "", "read feature configuration")
('w', "write-config=FILE", "arg", "", "write feature configuration")
('R', "raw-input", "", "", "raw audio input")
('M', "module=NAME", "arg", "", "normalization module name")
('P', "pca=NAME", "arg", "", "pca module name")
('u', "unit-determinant", "", "", "unit determinant for pca transform, by default unit variance for data")
('b', "block=INT", "arg", "1000", "block size (for reducing round-off errors)")
('p', "print", "", "", "print mean and variance to stdout")
('\0', "cov", "", "", "estimate and print covariance matrix")
('S', "speakers=FILE", "arg", "", "speaker configuration file")
('i', "info=INT", "arg", "0", "info level")
;
config.default_parse(argc, argv);
info = config["info"].get_int();
raw_flag = config["raw-input"].specified;
gen.load_configuration(io::Stream(config["config"].get_str()));
dim = gen.dim();
if (config["module"].specified)
{
norm_mod = dynamic_cast< NormalizationModule* >
(gen.module(config["module"].get_str()));
if (norm_mod == NULL)
throw std::string("Module ") + config["module"].get_str() +
std::string(" is not a normalization module");
dim = norm_mod->dim();
std::vector<FeatureModule*> sources = norm_mod->sources();
assert( sources.front()->dim() == dim );
norm_mod_src = sources.front();
}
else if (config["write-config"].specified)
{
fprintf(stderr, "Warning: No --module given, configuration will be written unaltered\n");
}
if (config["pca"].specified)
{
pca_mod = dynamic_cast< LinTransformModule* >
(gen.module(config["pca"].get_str()));
if (pca_mod == NULL)
throw std::string("Module ") + config["pca"].get_str() +
std::string(" is not a linear transformation module");
std::vector<FeatureModule*> sources = pca_mod->sources();
assert( sources.front()->dim() == dim );
pca_mod_src = sources.front();
}
block_size = config["block"].get_int();
cov_flag = config["cov"].specified;
pca_flag = config["pca"].specified;
if (config["speakers"].specified)
m_speaker_config.read_speaker_file(
io::Stream(config["speakers"].get_str()));
// Initialize accumulators
block_mean_acc.resize(dim);
block_var_acc.resize(dim);
global_mean_acc.resize(dim, 0);
global_var_acc.resize(dim, 0);
global_acc_count = 0;
if (cov_flag || pca_flag)
{
block_cov_acc.resize(dim*dim);
global_cov_acc.resize(dim*dim, 0);
}
// Read recipe file
Recipe recipe;
recipe.read(io::Stream(config["recipe"].get_str()),
0, 0, false);
// Handle each file in the recipe
for (int recipe_index = 0; recipe_index < (int)recipe.infos.size();
recipe_index++)
{
if (info > 0)
{
fprintf(stderr, "Processing file: %s\n",
recipe.infos[recipe_index].audio_path.c_str());
}
gen.open(recipe.infos[recipe_index].audio_path, raw_flag);
if (config["speakers"].specified)
{
m_speaker_config.set_speaker(recipe.infos[recipe_index].speaker_id);
if (recipe.infos[recipe_index].utterance_id.size() > 0)
m_speaker_config.set_utterance(
recipe.infos[recipe_index].utterance_id);
}
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] = 0;
block_var_acc[d] = 0;
}
if (cov_flag || pca_flag)
{
for (int d = 0; d < dim*dim; d++)
block_cov_acc[d] = 0;
}
cur_block_size = 0;
start_frame = (int)(recipe.infos[recipe_index].start_time *
gen.frame_rate());
end_frame = (int)(recipe.infos[recipe_index].end_time *
gen.frame_rate());
if (end_frame == 0)
end_frame = INT_MAX;
for (int f = start_frame; f < end_frame; f++)
{
const FeatureVec temp_fvec = gen.generate(f);
if (gen.eof())
{
// Accumulate to global variables
if (cur_block_size > 0)
{
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] += block_mean_acc[d]/(double)block_size;
global_var_acc[d] += block_var_acc[d]/(double)block_size;
}
if (cov_flag || pca_flag)
{
for (int d = 0; d < dim*dim; d++)
global_cov_acc[d] += block_cov_acc[d]/(double)block_size;
}
global_acc_count += (double)cur_block_size/(double)block_size;
}
break;
}
const FeatureVec vec = (norm_mod_src == NULL? temp_fvec :
norm_mod_src->at(f));
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] += vec[d];
block_var_acc[d] += vec[d]*vec[d];
}
if (cov_flag || pca_flag)
{
for (int d1 = 0; d1 < dim; d1++)
for (int d2 = 0; d2 < dim; d2++)
block_cov_acc[d1*dim+d2] += vec[d1]*vec[d2];
}
cur_block_size++;
if (cur_block_size == block_size)
{
// Accumulate to global variables
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] += block_mean_acc[d]/(double)block_size;
global_var_acc[d] += block_var_acc[d]/(double)block_size;
}
if (cov_flag || pca_flag)
{
for (int d = 0; d < dim*dim; d++)
global_cov_acc[d] += block_cov_acc[d]/(double)block_size;
}
global_acc_count++;
// Reset the block accumulators
for (int d = 0; d < dim; d++)
{
block_mean_acc[d] = 0;
block_var_acc[d] = 0;
}
if (cov_flag || pca_flag)
{
for (int d = 0; d < dim*dim; d++)
block_cov_acc[d] = 0;
}
cur_block_size = 0;
}
}
gen.close();
}
mean.resize(dim);
for (int d = 0; d < dim; d++)
{
global_mean_acc[d] /= global_acc_count;
mean[d] = global_mean_acc[d];
}
scale.resize(dim);
for (int d = 0; d < dim; d++)
{
scale[d] = 1/sqrtf(global_var_acc[d] / global_acc_count -
global_mean_acc[d]*global_mean_acc[d]);
}
Matrix tr_matrix(dim, dim);
if (pca_flag) {
Matrix eigvecs(dim, dim);
Vector eigvals(dim);
for (int d1 = 0; d1 < dim; d1++)
for (int d2 = 0; d2 < dim; d2++)
eigvecs(d1, d2) = global_cov_acc[d1*dim+d2] / global_acc_count -
global_mean_acc[d1]*global_mean_acc[d2];
LaEigSolveSymmetricVecIP(eigvecs, eigvals);
tr_matrix.copy(eigvecs);
LaVectorLongInt pivots(dim,1);
LUFactorizeIP(tr_matrix, pivots);
LaLUInverseIP(tr_matrix, pivots);
// Normalize pca to have unit determinant, mainly for seeding mllt
if (config["unit-determinant"].specified) {
// Remove the effect of variance scaling first
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
tr_matrix(i,j) /= scale[j];
// Scale after that
Matrix temp_m(tr_matrix);
LUFactorizeIP(temp_m, pivots);
double det=1;
for (int i=0; i<dim; i++)
det *= temp_m(i,i);
det = std::fabs(det);
double sc = pow(det, 1/(double)dim);
Blas_Scale(1/sc, tr_matrix);
}
// Normal case, normalize the data to have unit variance
else {
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
tr_matrix(i,j) /= sqrt(eigvals(i));
// Remove the effect of variance scaling
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
tr_matrix(i,j) /= scale[j];
}
}
if (config["print"].specified)
{
printf("mean:\n");
for (int d = 0; d < dim; d++)
printf("%f ", mean[d]);
printf("\n");
printf("variance:\n");
for (int d = 0; d < dim; d++)
printf("%f ", 1/(scale[d]*scale[d]));
printf("\n");
}
if (cov_flag)
{
for (int d1 = 0; d1 < dim; d1++)
{
for (int d2 = 0; d2 < dim; d2++)
{
double t = global_cov_acc[d1*dim+d2] / global_acc_count -
global_mean_acc[d1]*global_mean_acc[d2];
printf("%f ", t);
}
printf("\n");
}
}
if (norm_mod != NULL)
norm_mod->set_normalization(mean, scale);
if (pca_mod != NULL) {
std::vector<float> tr;
tr.resize(dim*dim);
for (int i=0; i<dim; i++)
for (int j=0; j<dim; j++)
tr[i*dim + j] = tr_matrix(i, j);
pca_mod->set_transformation_matrix(tr);
}
if (config["write-config"].specified)
gen.write_configuration(io::Stream(config["write-config"].get_str(),
"w"));
}
catch (std::exception &e) {
fprintf(stderr, "exception: %s\n", e.what());
abort();
}
catch (std::string &str) {
fprintf(stderr, "exception: %s\n", str.c_str());
abort();
}
}
<|endoftext|>
|
<commit_before>/* ozmtool_main.cpp
Copyright (c) 2014, tuxuser. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include "ozmtool.h"
QString version = "v0.1";
QString appname = "OZMTool";
void usageDsdt2Bios()
{
printf("dsdt2bios command\n"
" usage:\n"
"\t%s --dsdt2bios -i AmiBoardInfo.bin -d DSDT.aml -o patchedAmiBoardInfo.bin\n\n"
" parameters:\n" \
"\t-i, --input [file]\t\tInput file (AmiBoardInfo)\n"
"\t-d, --dsdt [file]\t\tDSDT.aml file\n"
"\t-o, --out [file]\t\tOutput file (patched AmiBoardInfo)\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageFfsConvert()
{
printf("ffsconvert command\n"
" usage:\n"
"\t%s --ffsconvert -o outputdir -i kextsdir\n\n"
" parameters:\n"
"\t-i, --input [dir]\t\tInput kexts directory\n"
"\t-o, --out [dir]\t\tOutput ffs directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmUpdate()
{
printf("ozmupdate command\n" \
" usage:\n"
"\t%s --ozmupdate -a 1 -o BIOS_RECENT.OZM -i BIOS.OZM -r BIOS.CLEAN\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tInput \"old\" Ozmosis BIOSFile\n"
"\t-r, --recent [file]\t\tInput \"recent\" clean BIOSFile\n"
"\t-a, --aggressivity\t\tAggressivity level (see README)\n"
"\t-o, --out [file]\t\tOutput BIOSFile\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmCreate()
{
printf("ozmcreate command\n" \
" usage:\n"
"\t%s --ozmcreate -a -k kextdir -f ffsdir -d DSDT.aml -o outputfile -i BIOS.ROM\n\n"
" parameters:\n"
"\t-f, --ffs [dir]\t\tFFS directory (extracted OZM files)\n"
"\t-d, --dsdt [file]\t\t (optional) DSDT.aml file\n"
"\t-k, --kext [dir]\t\t (optional) KEXT directory\n"
"\t-i, --input [file]\t\tInput CLEAN Bios\n"
"\t-a, --aggressivity\t\tAggressivity level (see README)\n"
"\t-o, --out [file]\t\tOutput OZM Bios\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmExtract()
{
printf("ozmextract command\n"
" usage:\n"
"\t%s --ozmextract -o outputdir -i OZM.ROM\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tInput stock OZM Bios\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageDSDTExtract()
{
printf("dsdtextract command\n"
" usage:\n"
"\t%s --dsdtextract -o outputdir -i OZMBIOS_or_BIOS.ROM\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tBIOS file\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageDSDTInject()
{
printf("dsdtinject command\n"
" usage:\n"
"\t%s --dsdtinject -i BIOS.ROM -d DSDT.aml -o outputfile\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tBIOS file\n"
"\n-d, --dsdt [file]\t\tDSDT.aml\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageGeneral()
{
printf("Usage:\n" \
"\t%s [COMMAND] [PARAMETERS...]\n\n"
"Available commands:\n"
"\t--dsdtextract\t\tExtracts DSDT from BIOS\n"
"\t--dsdtinject\t\tInjects DSDT into BIOS\n"
"\t--ozmupdate\t\tUpdates clean BIOS with files from old OZM-flavoured one\n"
"\t--ozmextract\t\tExtracts Ozmosis files (ffs) from BIOS\n"
"\t--ozmcreate\t\tPatches Original BIOS with Ozmosis\n"
"\t--ffsconvert\t\tConverts kext-directories to FFS\n"
"\t--dsdt2bios\t\tInjects (bigger) DSDT into AmiBoardInfo\n"
"\t--help, -h\t\tPrint this\n\n",qPrintable(appname));
}
void versionInfo()
{
printf("%s - %s\n",qPrintable(appname), qPrintable(version));
}
void usageAll()
{
usageGeneral();
usageDSDTExtract();
usageDSDTInject();
usageOzmUpdate();
usageOzmExtract();
usageOzmCreate();
usageFfsConvert();
usageDsdt2Bios();
}
int main(int argc, char *argv[])
{
bool help = false;
bool dsdtextract = false;
bool dsdtinject = false;
bool ozmupdate = false;
bool ozmextract = false;
bool ozmcreate = false;
bool ffsconvert = false;
bool dsdt2bios = false;
QString inputpath = "";
QString output = "";
QString ffsdir = "";
QString kextdir = "";
QString dsdtfile = "";
QString recent = "";
int aggressivity = 0;
QCoreApplication a(argc, argv);
a.setOrganizationName("tuxuser");
a.setOrganizationDomain("tuxuser.org");
a.setApplicationName("OZMTool");
OZMTool w;
UINT8 result = ERR_SUCCESS;
if (argc == 1) {
usageGeneral();
printf("ERROR: No options supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
//
// Parse command line
//
argc --;
argv ++;
if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
usageAll();
return ERR_SUCCESS;
}
if (strcasecmp(argv[0], "--version") == 0) {
versionInfo();
return ERR_SUCCESS;
}
while (argc > 0) {
if (strcasecmp(argv[0], "--dsdtextract") == 0) {
dsdtextract = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--dsdtinject") == 0) {
dsdtextract = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmupdate") == 0) {
ozmupdate = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmextract") == 0) {
ozmextract = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmcreate") == 0) {
ozmcreate = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ffsconvert") == 0) {
ffsconvert = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--dsdt2bios") == 0) {
dsdt2bios = true;
argc --;
argv ++;
continue;
}
if ((strcasecmp(argv[0], "-f") == 0) || (strcasecmp(argv[0], "--ffs") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input FFS directory is missing for -f option\n");
goto fail;
}
ffsdir = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-k") == 0) || (strcasecmp(argv[0], "--kext") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input KEXT directory is missing for -k option\n");
goto fail;
}
kextdir = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-d") == 0) || (strcasecmp(argv[0], "--dsdt") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input DSDT.aml file is missing for -d option\n");
goto fail;
}
dsdtfile = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-i") == 0) || (strcasecmp(argv[0], "--input") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input file/directory is missing for -i option\n");
goto fail;
}
inputpath = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-o") == 0) || (strcasecmp(argv[0], "--out") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Output file/directory is missing for -o option\n");
goto fail;
}
output = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-r") == 0) || (strcasecmp(argv[0], "--recent") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input file is missing for -r option\n");
goto fail;
}
recent = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-a") == 0) || (strcasecmp(argv[0], "--aggressivity") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Value is missing for -a option\n");
goto fail;
}
aggressivity = atoi(argv[1]);
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
help = true;
argc --;
argv ++;
continue;
}
printf("Unknown option: %s\n", argv[0]);
fail:
printf("Exiting!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
int cmds = dsdtextract + dsdtinject + ozmextract + ozmupdate + ozmcreate + ffsconvert + dsdt2bios;
if (help) {
if (cmds > 1)
usageAll();
else if (dsdtextract)
usageDSDTExtract();
else if (dsdtinject)
usageDSDTInject();
else if (ozmupdate)
usageOzmUpdate();
else if (ozmextract)
usageOzmExtract();
else if (ozmcreate)
usageOzmCreate();
else if (ffsconvert)
usageFfsConvert();
else if (dsdt2bios)
usageDsdt2Bios();
else
usageAll();
return ERR_SUCCESS;
}
versionInfo();
if (cmds == 0) {
usageGeneral();
printf("ERROR: No command supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
else if (cmds > 1) {
usageGeneral();
printf("ERROR: More than one command supplied, only one is allowed!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (inputpath.isEmpty()) {
printf("ERROR: No input file/dir specified!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (output.isEmpty()) {
printf("ERROR: No output file/dir specified!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (ozmcreate && ffsdir.isEmpty()) {
printf("ERROR: No FFS directory file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (ozmupdate && recent.isEmpty()) {
printf("ERROR: No \"recent/clean\" BIOS file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if ((dsdt2bios || dsdtinject) && dsdtfile.isEmpty()) {
printf("ERROR: No DSDT.aml file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (dsdtextract)
result = w.DSDTExtract(inputpath, output);
else if (dsdtinject)
result = w.DSDTInject(inputpath, dsdtfile, output);
else if (ozmupdate)
result = w.OZMUpdate(inputpath, recent, output, aggressivity);
else if (ozmextract)
result = w.OZMExtract(inputpath, output);
else if (ozmcreate)
result = w.OZMCreate(inputpath, output, ffsdir, kextdir, dsdtfile, aggressivity);
else if (ffsconvert)
result = w.FFSConvert(inputpath, output);
else if (dsdt2bios)
result = w.DSDT2Bios(inputpath, dsdtfile, output);
if(result) {
printf("! Program exited with errors !\n");
printf("\nStatus code: %i\n", result);
}
return result;
}
<commit_msg>Fixing typo<commit_after>/* ozmtool_main.cpp
Copyright (c) 2014, tuxuser. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include "ozmtool.h"
QString version = "v0.1";
QString appname = "OZMTool";
void usageDsdt2Bios()
{
printf("dsdt2bios command\n"
" usage:\n"
"\t%s --dsdt2bios -i AmiBoardInfo.bin -d DSDT.aml -o patchedAmiBoardInfo.bin\n\n"
" parameters:\n" \
"\t-i, --input [file]\t\tInput file (AmiBoardInfo)\n"
"\t-d, --dsdt [file]\t\tDSDT.aml file\n"
"\t-o, --out [file]\t\tOutput file (patched AmiBoardInfo)\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageFfsConvert()
{
printf("ffsconvert command\n"
" usage:\n"
"\t%s --ffsconvert -o outputdir -i kextsdir\n\n"
" parameters:\n"
"\t-i, --input [dir]\t\tInput kexts directory\n"
"\t-o, --out [dir]\t\tOutput ffs directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmUpdate()
{
printf("ozmupdate command\n" \
" usage:\n"
"\t%s --ozmupdate -a 1 -o BIOS_RECENT.OZM -i BIOS.OZM -r BIOS.CLEAN\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tInput \"old\" Ozmosis BIOSFile\n"
"\t-r, --recent [file]\t\tInput \"recent\" clean BIOSFile\n"
"\t-a, --aggressivity\t\tAggressivity level (see README)\n"
"\t-o, --out [file]\t\tOutput BIOSFile\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmCreate()
{
printf("ozmcreate command\n" \
" usage:\n"
"\t%s --ozmcreate -a -k kextdir -f ffsdir -d DSDT.aml -o outputfile -i BIOS.ROM\n\n"
" parameters:\n"
"\t-f, --ffs [dir]\t\tFFS directory (extracted OZM files)\n"
"\t-d, --dsdt [file]\t\t (optional) DSDT.aml file\n"
"\t-k, --kext [dir]\t\t (optional) KEXT directory\n"
"\t-i, --input [file]\t\tInput CLEAN Bios\n"
"\t-a, --aggressivity\t\tAggressivity level (see README)\n"
"\t-o, --out [file]\t\tOutput OZM Bios\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageOzmExtract()
{
printf("ozmextract command\n"
" usage:\n"
"\t%s --ozmextract -o outputdir -i OZM.ROM\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tInput stock OZM Bios\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageDSDTExtract()
{
printf("dsdtextract command\n"
" usage:\n"
"\t%s --dsdtextract -o outputdir -i OZMBIOS_or_BIOS.ROM\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tBIOS file\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageDSDTInject()
{
printf("dsdtinject command\n"
" usage:\n"
"\t%s --dsdtinject -i BIOS.ROM -d DSDT.aml -o outputfile\n\n"
" parameters:\n"
"\t-i, --input [file]\t\tBIOS file\n"
"\n-d, --dsdt [file]\t\tDSDT.aml\n"
"\t-o, --out [dir]\t\tOutput directory\n"
"\t-h, --help\t\tPrint this\n\n",qPrintable(appname));
}
void usageGeneral()
{
printf("Usage:\n" \
"\t%s [COMMAND] [PARAMETERS...]\n\n"
"Available commands:\n"
"\t--dsdtextract\t\tExtracts DSDT from BIOS\n"
"\t--dsdtinject\t\tInjects DSDT into BIOS\n"
"\t--ozmupdate\t\tUpdates clean BIOS with files from old OZM-flavoured one\n"
"\t--ozmextract\t\tExtracts Ozmosis files (ffs) from BIOS\n"
"\t--ozmcreate\t\tPatches Original BIOS with Ozmosis\n"
"\t--ffsconvert\t\tConverts kext-directories to FFS\n"
"\t--dsdt2bios\t\tInjects (bigger) DSDT into AmiBoardInfo\n"
"\t--help, -h\t\tPrint this\n\n",qPrintable(appname));
}
void versionInfo()
{
printf("%s - %s\n",qPrintable(appname), qPrintable(version));
}
void usageAll()
{
usageGeneral();
usageDSDTExtract();
usageDSDTInject();
usageOzmUpdate();
usageOzmExtract();
usageOzmCreate();
usageFfsConvert();
usageDsdt2Bios();
}
int main(int argc, char *argv[])
{
bool help = false;
bool dsdtextract = false;
bool dsdtinject = false;
bool ozmupdate = false;
bool ozmextract = false;
bool ozmcreate = false;
bool ffsconvert = false;
bool dsdt2bios = false;
QString inputpath = "";
QString output = "";
QString ffsdir = "";
QString kextdir = "";
QString dsdtfile = "";
QString recent = "";
int aggressivity = 0;
QCoreApplication a(argc, argv);
a.setOrganizationName("tuxuser");
a.setOrganizationDomain("tuxuser.org");
a.setApplicationName("OZMTool");
OZMTool w;
UINT8 result = ERR_SUCCESS;
if (argc == 1) {
usageGeneral();
printf("ERROR: No options supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
//
// Parse command line
//
argc --;
argv ++;
if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
usageAll();
return ERR_SUCCESS;
}
if (strcasecmp(argv[0], "--version") == 0) {
versionInfo();
return ERR_SUCCESS;
}
while (argc > 0) {
if (strcasecmp(argv[0], "--dsdtextract") == 0) {
dsdtextract = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--dsdtinject") == 0) {
dsdtinject = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmupdate") == 0) {
ozmupdate = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmextract") == 0) {
ozmextract = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ozmcreate") == 0) {
ozmcreate = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--ffsconvert") == 0) {
ffsconvert = true;
argc --;
argv ++;
continue;
}
if (strcasecmp(argv[0], "--dsdt2bios") == 0) {
dsdt2bios = true;
argc --;
argv ++;
continue;
}
if ((strcasecmp(argv[0], "-f") == 0) || (strcasecmp(argv[0], "--ffs") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input FFS directory is missing for -f option\n");
goto fail;
}
ffsdir = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-k") == 0) || (strcasecmp(argv[0], "--kext") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input KEXT directory is missing for -k option\n");
goto fail;
}
kextdir = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-d") == 0) || (strcasecmp(argv[0], "--dsdt") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input DSDT.aml file is missing for -d option\n");
goto fail;
}
dsdtfile = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-i") == 0) || (strcasecmp(argv[0], "--input") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input file/directory is missing for -i option\n");
goto fail;
}
inputpath = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-o") == 0) || (strcasecmp(argv[0], "--out") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Output file/directory is missing for -o option\n");
goto fail;
}
output = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-r") == 0) || (strcasecmp(argv[0], "--recent") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Input file is missing for -r option\n");
goto fail;
}
recent = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-a") == 0) || (strcasecmp(argv[0], "--aggressivity") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
printf("Invalid option value\n"
"Value is missing for -a option\n");
goto fail;
}
aggressivity = atoi(argv[1]);
argc -= 2;
argv += 2;
continue;
}
if ((strcasecmp(argv[0], "-h") == 0) || (strcasecmp(argv[0], "--help") == 0)) {
help = true;
argc --;
argv ++;
continue;
}
printf("Unknown option: %s\n", argv[0]);
fail:
printf("Exiting!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
int cmds = dsdtextract + dsdtinject + ozmextract + ozmupdate + ozmcreate + ffsconvert + dsdt2bios;
if (help) {
if (cmds > 1)
usageAll();
else if (dsdtextract)
usageDSDTExtract();
else if (dsdtinject)
usageDSDTInject();
else if (ozmupdate)
usageOzmUpdate();
else if (ozmextract)
usageOzmExtract();
else if (ozmcreate)
usageOzmCreate();
else if (ffsconvert)
usageFfsConvert();
else if (dsdt2bios)
usageDsdt2Bios();
else
usageAll();
return ERR_SUCCESS;
}
versionInfo();
if (cmds == 0) {
usageGeneral();
printf("ERROR: No command supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
else if (cmds > 1) {
usageGeneral();
printf("ERROR: More than one command supplied, only one is allowed!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (inputpath.isEmpty()) {
printf("ERROR: No input file/dir specified!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (output.isEmpty()) {
printf("ERROR: No output file/dir specified!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (ozmcreate && ffsdir.isEmpty()) {
printf("ERROR: No FFS directory file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (ozmupdate && recent.isEmpty()) {
printf("ERROR: No \"recent/clean\" BIOS file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if ((dsdt2bios || dsdtinject) && dsdtfile.isEmpty()) {
printf("ERROR: No DSDT.aml file supplied!\n");
return ERR_GENERIC_CALL_NOT_SUPPORTED;
}
if (dsdtextract)
result = w.DSDTExtract(inputpath, output);
else if (dsdtinject)
result = w.DSDTInject(inputpath, dsdtfile, output);
else if (ozmupdate)
result = w.OZMUpdate(inputpath, recent, output, aggressivity);
else if (ozmextract)
result = w.OZMExtract(inputpath, output);
else if (ozmcreate)
result = w.OZMCreate(inputpath, output, ffsdir, kextdir, dsdtfile, aggressivity);
else if (ffsconvert)
result = w.FFSConvert(inputpath, output);
else if (dsdt2bios)
result = w.DSDT2Bios(inputpath, dsdtfile, output);
if(result) {
printf("! Program exited with errors !\n");
printf("\nStatus code: %i\n", result);
}
return result;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/fluid/inference/api/paddle_pass_builder.h"
#ifdef PADDLE_WITH_CUDA
#include <cudnn.h>
#endif
#include <glog/logging.h>
#include <sstream>
namespace paddle {
void PaddlePassBuilder::AppendPass(const std::string &pass_type) {
passes_.push_back(pass_type);
}
void PaddlePassBuilder::TurnOnDebug() {
std::vector<std::string> passes;
auto it = std::begin(passes_);
while (it != std::end(passes_)) {
if (*it != "graph_viz_pass") {
it = passes_.insert(it + 1, "graph_viz_pass");
} else {
++it;
}
}
}
std::string PaddlePassBuilder::DebugString() {
std::stringstream ss;
ss << "Passes to apply:\n";
for (auto &pass : passes_) {
ss << " - " << pass << '\n';
}
return ss.str();
}
void PaddlePassBuilder::DeletePass(const std::string &pass_type) {
auto it = std::begin(passes_);
while (it != std::end(passes_)) {
if (*it == pass_type) {
it = passes_.erase(it);
} else {
++it;
}
}
}
void PaddlePassBuilder::InsertPass(size_t idx, const std::string &pass_type) {
passes_.insert(std::begin(passes_) + idx, pass_type);
}
void PaddlePassBuilder::DeletePass(size_t idx) {
passes_.erase(std::begin(passes_) + idx);
}
void PaddlePassBuilder::AppendAnalysisPass(const std::string &pass) {
analysis_passes_.push_back(pass);
}
void PaddlePassBuilder::ClearPasses() { passes_.clear(); }
const std::vector<std::string> kTRTSubgraphPasses({
"conv_affine_channel_fuse_pass", //
"adaptive_pool2d_convert_global_pass",
"conv_eltwiseadd_affine_channel_fuse_pass", //
"shuffle_channel_detect_pass", //
"quant_conv2d_dequant_fuse_pass", //
"delete_quant_dequant_op_pass", //
"delete_quant_dequant_filter_op_pass", //
// "fc_fuse_pass", //
"simplify_with_basic_ops_pass", //
"embedding_eltwise_layernorm_fuse_pass", //
"multihead_matmul_fuse_pass_v2", //
"skip_layernorm_fuse_pass", //
"conv_bn_fuse_pass", //
"unsqueeze2_eltwise_fuse_pass", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"conv_elementwise_add_fuse_pass", //
"tensorrt_subgraph_pass", //
"conv_bn_fuse_pass", //
#if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be
// guaranteed at least v7
"conv_elementwise_add_act_fuse_pass", //
"conv_elementwise_add2_act_fuse_pass", //
#endif //
"transpose_flatten_concat_fuse_pass",
});
const std::vector<std::string> kLiteSubgraphPasses({
#ifdef PADDLE_WITH_LITE
"lite_subgraph_pass",
#endif
});
GpuPassStrategy::GpuPassStrategy() : PassStrategy({}) {
passes_.assign({
// "identity_scale_op_clean_pass", //
"is_test_pass", //
"simplify_with_basic_ops_pass", //
"conv_affine_channel_fuse_pass", //
"conv_eltwiseadd_affine_channel_fuse_pass", //
"conv_bn_fuse_pass", //
"conv_eltwiseadd_bn_fuse_pass", //
"embedding_eltwise_layernorm_fuse_pass", //
"multihead_matmul_fuse_pass_v2", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"fc_elementwise_layernorm_fuse_pass", //
#if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be
// guaranteed at least v7
"conv_elementwise_add_act_fuse_pass", //
"conv_elementwise_add2_act_fuse_pass", //
"conv_elementwise_add_fuse_pass", //
#endif //
"transpose_flatten_concat_fuse_pass", //
// following pass should be located in the last, since it will
// work on all fused ops.
"runtime_context_cache_pass"
});
use_gpu_ = true;
}
void GpuPassStrategy::EnableCUDNN() {
if (!use_cudnn_) {
passes_.insert(passes_.begin(), "cudnn_placement_pass");
}
use_cudnn_ = true;
}
void GpuPassStrategy::EnableMKLDNN() {
LOG(ERROR) << "GPU not support MKLDNN yet";
}
void GpuPassStrategy::EnableMkldnnQuantizer() {
LOG(ERROR) << "GPU not support MKL-DNN quantization";
}
void GpuPassStrategy::EnableMkldnnBfloat16() {
LOG(ERROR) << "GPU not support MKL-DNN bfloat16";
}
CpuPassStrategy::CpuPassStrategy() : PassStrategy({}) {
// NOTE the large fusions should be located in the front, so that they will
// not be damaged by smaller ones.
passes_.assign({"simplify_with_basic_ops_pass", //
"layer_norm_fuse_pass",
"attention_lstm_fuse_pass", //
"seqconv_eltadd_relu_fuse_pass", //
// "seqpool_concat_fuse_pass", //
"seqpool_cvm_concat_fuse_pass", //
// "embedding_fc_lstm_fuse_pass", //
// TODO(wilber): fix correctness problem.
// "fc_lstm_fuse_pass", //
"mul_lstm_fuse_pass", //
"fc_gru_fuse_pass", //
"mul_gru_fuse_pass", //
"seq_concat_fc_fuse_pass", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"repeated_fc_relu_fuse_pass", //
"squared_mat_sub_fuse_pass", //
"conv_bn_fuse_pass", //
"conv_eltwiseadd_bn_fuse_pass", //
"conv_transpose_bn_fuse_pass", //
"conv_transpose_eltwiseadd_bn_fuse_pass", //
"is_test_pass", //
// following pass should be located in the last, since
// it will work on all fused ops.
"runtime_context_cache_pass"});
use_gpu_ = false;
}
void CpuPassStrategy::EnableCUDNN() { LOG(ERROR) << "CPU not support cuDNN"; }
void CpuPassStrategy::EnableMKLDNN() {
// TODO(Superjomn) Consider the way to mix CPU with GPU.
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_) {
passes_.insert(passes_.begin(), "mkldnn_placement_pass");
for (auto &pass : std::vector<std::string>({
"depthwise_conv_mkldnn_pass", //
"conv_bn_fuse_pass", // Execute BN passes again to
"conv_eltwiseadd_bn_fuse_pass", // preserve correct pass order
"conv_affine_channel_fuse_pass", //
"conv_eltwiseadd_affine_channel_fuse_pass", //
"conv_transpose_bn_fuse_pass", //
"conv_transpose_eltwiseadd_bn_fuse_pass", //
"conv_bias_mkldnn_fuse_pass", //
"conv_transpose_bias_mkldnn_fuse_pass",
"conv3d_bias_mkldnn_fuse_pass", //
"conv_elementwise_add_mkldnn_fuse_pass",
"conv_concat_relu_mkldnn_fuse_pass",
"conv_relu_mkldnn_fuse_pass", //
"conv_leaky_relu_mkldnn_fuse_pass", //
"conv_relu6_mkldnn_fuse_pass", //
"conv_swish_mkldnn_fuse_pass", //
"scale_matmul_fuse_pass", //
"reshape_transpose_matmul_mkldnn_fuse_pass", //
"matmul_transpose_reshape_fuse_pass", //
// Disabled due to topology-dependent speed-up
// "fc_mkldnn_pass",
// "fc_act_mkldnn_fuse_pass",
"batch_norm_act_fuse_pass",
// TODO(intel): Please fix the bug on windows.
// https://github.com/PaddlePaddle/Paddle/issues/29710
//"mkldnn_inplace_pass", // This pass should be activated after
// fuses. Disabled by default due to
// little gain and lots of problems
})) {
passes_.push_back(pass);
}
}
use_mkldnn_ = true;
#else
use_mkldnn_ = false;
#endif
}
void CpuPassStrategy::EnableMkldnnQuantizer() {
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_quantizer_) {
passes_.push_back("cpu_quantize_placement_pass");
}
use_mkldnn_quantizer_ = true;
#else
use_mkldnn_quantizer_ = false;
#endif
}
void CpuPassStrategy::EnableMkldnnBfloat16() {
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_bfloat16_) {
passes_.push_back("cpu_bfloat16_placement_pass");
passes_.push_back("cpu_bfloat16_pass");
}
use_mkldnn_bfloat16_ = true;
#else
use_mkldnn_bfloat16_ = false;
#endif
}
} // namespace paddle
<commit_msg>resolve memory leak in cudnn8.0 (#31029)<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/fluid/inference/api/paddle_pass_builder.h"
#ifdef PADDLE_WITH_CUDA
#include <cudnn.h>
#endif
#include <glog/logging.h>
#include <sstream>
namespace paddle {
void PaddlePassBuilder::AppendPass(const std::string &pass_type) {
passes_.push_back(pass_type);
}
void PaddlePassBuilder::TurnOnDebug() {
std::vector<std::string> passes;
auto it = std::begin(passes_);
while (it != std::end(passes_)) {
if (*it != "graph_viz_pass") {
it = passes_.insert(it + 1, "graph_viz_pass");
} else {
++it;
}
}
}
std::string PaddlePassBuilder::DebugString() {
std::stringstream ss;
ss << "Passes to apply:\n";
for (auto &pass : passes_) {
ss << " - " << pass << '\n';
}
return ss.str();
}
void PaddlePassBuilder::DeletePass(const std::string &pass_type) {
auto it = std::begin(passes_);
while (it != std::end(passes_)) {
if (*it == pass_type) {
it = passes_.erase(it);
} else {
++it;
}
}
}
void PaddlePassBuilder::InsertPass(size_t idx, const std::string &pass_type) {
passes_.insert(std::begin(passes_) + idx, pass_type);
}
void PaddlePassBuilder::DeletePass(size_t idx) {
passes_.erase(std::begin(passes_) + idx);
}
void PaddlePassBuilder::AppendAnalysisPass(const std::string &pass) {
analysis_passes_.push_back(pass);
}
void PaddlePassBuilder::ClearPasses() { passes_.clear(); }
const std::vector<std::string> kTRTSubgraphPasses({
"conv_affine_channel_fuse_pass", //
"adaptive_pool2d_convert_global_pass",
"conv_eltwiseadd_affine_channel_fuse_pass", //
"shuffle_channel_detect_pass", //
"quant_conv2d_dequant_fuse_pass", //
"delete_quant_dequant_op_pass", //
"delete_quant_dequant_filter_op_pass", //
// "fc_fuse_pass", //
"simplify_with_basic_ops_pass", //
"embedding_eltwise_layernorm_fuse_pass", //
"multihead_matmul_fuse_pass_v2", //
"skip_layernorm_fuse_pass", //
"conv_bn_fuse_pass", //
"unsqueeze2_eltwise_fuse_pass", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"conv_elementwise_add_fuse_pass", //
"tensorrt_subgraph_pass", //
"conv_bn_fuse_pass", //
#if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be
// guaranteed at least v7
// cudnn8.0 has memory leak problem in conv + eltwise + act, so we
// disable the pass.
#if !(CUDNN_VERSION >= 8000 && CUDNN_VERSION < 8100)
"conv_elementwise_add_act_fuse_pass", //
"conv_elementwise_add2_act_fuse_pass", //
#endif
#endif
"transpose_flatten_concat_fuse_pass",
});
const std::vector<std::string> kLiteSubgraphPasses({
#ifdef PADDLE_WITH_LITE
"lite_subgraph_pass",
#endif
});
GpuPassStrategy::GpuPassStrategy() : PassStrategy({}) {
passes_.assign({
// "identity_scale_op_clean_pass", //
"is_test_pass", //
"simplify_with_basic_ops_pass", //
"conv_affine_channel_fuse_pass", //
"conv_eltwiseadd_affine_channel_fuse_pass", //
"conv_bn_fuse_pass", //
"conv_eltwiseadd_bn_fuse_pass", //
"embedding_eltwise_layernorm_fuse_pass", //
"multihead_matmul_fuse_pass_v2", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"fc_elementwise_layernorm_fuse_pass", //
#if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be
// guaranteed at least v7
"conv_elementwise_add_act_fuse_pass", //
"conv_elementwise_add2_act_fuse_pass", //
"conv_elementwise_add_fuse_pass", //
#endif //
"transpose_flatten_concat_fuse_pass", //
// following pass should be located in the last, since it will
// work on all fused ops.
"runtime_context_cache_pass"
});
use_gpu_ = true;
}
void GpuPassStrategy::EnableCUDNN() {
if (!use_cudnn_) {
passes_.insert(passes_.begin(), "cudnn_placement_pass");
}
use_cudnn_ = true;
}
void GpuPassStrategy::EnableMKLDNN() {
LOG(ERROR) << "GPU not support MKLDNN yet";
}
void GpuPassStrategy::EnableMkldnnQuantizer() {
LOG(ERROR) << "GPU not support MKL-DNN quantization";
}
void GpuPassStrategy::EnableMkldnnBfloat16() {
LOG(ERROR) << "GPU not support MKL-DNN bfloat16";
}
CpuPassStrategy::CpuPassStrategy() : PassStrategy({}) {
// NOTE the large fusions should be located in the front, so that they will
// not be damaged by smaller ones.
passes_.assign({"simplify_with_basic_ops_pass", //
"layer_norm_fuse_pass",
"attention_lstm_fuse_pass", //
"seqconv_eltadd_relu_fuse_pass", //
// "seqpool_concat_fuse_pass", //
"seqpool_cvm_concat_fuse_pass", //
// "embedding_fc_lstm_fuse_pass", //
// TODO(wilber): fix correctness problem.
// "fc_lstm_fuse_pass", //
"mul_lstm_fuse_pass", //
"fc_gru_fuse_pass", //
"mul_gru_fuse_pass", //
"seq_concat_fc_fuse_pass", //
"squeeze2_matmul_fuse_pass", //
"reshape2_matmul_fuse_pass", //
"flatten2_matmul_fuse_pass", //
"map_matmul_to_mul_pass", //
"fc_fuse_pass", //
"repeated_fc_relu_fuse_pass", //
"squared_mat_sub_fuse_pass", //
"conv_bn_fuse_pass", //
"conv_eltwiseadd_bn_fuse_pass", //
"conv_transpose_bn_fuse_pass", //
"conv_transpose_eltwiseadd_bn_fuse_pass", //
"is_test_pass", //
// following pass should be located in the last, since
// it will work on all fused ops.
"runtime_context_cache_pass"});
use_gpu_ = false;
}
void CpuPassStrategy::EnableCUDNN() { LOG(ERROR) << "CPU not support cuDNN"; }
void CpuPassStrategy::EnableMKLDNN() {
// TODO(Superjomn) Consider the way to mix CPU with GPU.
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_) {
passes_.insert(passes_.begin(), "mkldnn_placement_pass");
for (auto &pass : std::vector<std::string>({
"depthwise_conv_mkldnn_pass", //
"conv_bn_fuse_pass", // Execute BN passes again to
"conv_eltwiseadd_bn_fuse_pass", // preserve correct pass order
"conv_affine_channel_fuse_pass", //
"conv_eltwiseadd_affine_channel_fuse_pass", //
"conv_transpose_bn_fuse_pass", //
"conv_transpose_eltwiseadd_bn_fuse_pass", //
"conv_bias_mkldnn_fuse_pass", //
"conv_transpose_bias_mkldnn_fuse_pass",
"conv3d_bias_mkldnn_fuse_pass", //
"conv_elementwise_add_mkldnn_fuse_pass",
"conv_concat_relu_mkldnn_fuse_pass",
"conv_relu_mkldnn_fuse_pass", //
"conv_leaky_relu_mkldnn_fuse_pass", //
"conv_relu6_mkldnn_fuse_pass", //
"conv_swish_mkldnn_fuse_pass", //
"scale_matmul_fuse_pass", //
"reshape_transpose_matmul_mkldnn_fuse_pass", //
"matmul_transpose_reshape_fuse_pass", //
// Disabled due to topology-dependent speed-up
// "fc_mkldnn_pass",
// "fc_act_mkldnn_fuse_pass",
"batch_norm_act_fuse_pass",
// TODO(intel): Please fix the bug on windows.
// https://github.com/PaddlePaddle/Paddle/issues/29710
// "mkldnn_inplace_pass", // This pass should be activated after
// fuses. Disabled by default due to
// little gain and lots of problems
})) {
passes_.push_back(pass);
}
}
use_mkldnn_ = true;
#else
use_mkldnn_ = false;
#endif
}
void CpuPassStrategy::EnableMkldnnQuantizer() {
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_quantizer_) {
passes_.push_back("cpu_quantize_placement_pass");
}
use_mkldnn_quantizer_ = true;
#else
use_mkldnn_quantizer_ = false;
#endif
}
void CpuPassStrategy::EnableMkldnnBfloat16() {
#ifdef PADDLE_WITH_MKLDNN
if (!use_mkldnn_bfloat16_) {
passes_.push_back("cpu_bfloat16_placement_pass");
passes_.push_back("cpu_bfloat16_pass");
}
use_mkldnn_bfloat16_ = true;
#else
use_mkldnn_bfloat16_ = false;
#endif
}
} // namespace paddle
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2008 Matthias Kretz <kretz@kde.org>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#define QT_GUI_LIB
#include "../abstractvideodataoutput.h"
#include "../videoframe2.h"
#include "../../mediaobject.h"
#include "../../tests/qtesthelper.h"
#include <QtCore/QMutexLocker>
#include <QtGui/QImageReader>
#include <QtGui/QLabel>
#include <QtGui/QPixmap>
#include <QtTest/QtTest>
class Output : public QObject, public Phonon::Experimental::AbstractVideoDataOutput
{
Q_OBJECT
public:
Output() : receivedEnd(0) {}
virtual QSet<Phonon::Experimental::VideoFrame2::Format> allowedFormats() const;
virtual void frameReady(const Phonon::Experimental::VideoFrame2 &);
virtual void endOfMedia();
QList<QImage> frames;
int receivedEnd;
QMutex mutex;
};
QSet<Phonon::Experimental::VideoFrame2::Format> Output::allowedFormats() const
{
return QSet<Phonon::Experimental::VideoFrame2::Format>() << Phonon::Experimental::VideoFrame2::Format_RGB888;
}
void Output::frameReady(const Phonon::Experimental::VideoFrame2 &frame)
{
qDebug() << Q_FUNC_INFO;
Q_ASSERT(frame.format == Phonon::Experimental::VideoFrame2::Format_RGB888);
QMutexLocker lock(&mutex);
frames << frame.qImage();
}
void Output::endOfMedia()
{
++receivedEnd;
}
class VideoDataOutputTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void testDelete();
void playMedia();
void cleanupTestCase();
private:
Phonon::MediaObject *m_media;
Output *m_output;
};
void VideoDataOutputTest::initTestCase()
{
m_media = new Phonon::MediaObject;
m_output = new Output;
Phonon::createPath(m_media, m_output);
}
void VideoDataOutputTest::testDelete()
{
delete m_output;
m_output = new Output;
m_output->start();
QVERIFY(m_output->isRunning());
Phonon::createPath(m_media, m_output);
sleep(1);
}
void VideoDataOutputTest::playMedia()
{
m_media->setCurrentSource(QString(":/test.mng"));
m_media->play();
QVERIFY(QTest::kWaitForSignal(m_media, SIGNAL(finished()), 4000));
QEXPECT_FAIL("", "endOfMedia not yet implemented for xine", Continue);
QCOMPARE(m_output->receivedEnd, 1);
QList<QImage> frames;
{
QImageReader movie(":/test.mng");
QImage frame;
while (movie.read(&frame)) {
frames << frame.convertToFormat(QImage::Format_RGB888);
}
}
qDebug() << frames.size();
QMutexLocker lock(&m_output->mutex);
QVERIFY(!m_output->frames.isEmpty());
QCOMPARE(m_output->frames.size(), frames.size());
for (int i = 0; i < frames.size(); ++i) {
QCOMPARE(m_output->frames[i], frames[i]);
}
}
void VideoDataOutputTest::cleanupTestCase()
{
delete m_output;
delete m_media;
}
QTEST_MAIN(VideoDataOutputTest)
#include "videodataoutputtest.moc"
<commit_msg>fix compilation on windows<commit_after>/* This file is part of the KDE project
Copyright (C) 2008 Matthias Kretz <kretz@kde.org>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#define QT_GUI_LIB
#include "../abstractvideodataoutput.h"
#include "../videoframe2.h"
#include "../../mediaobject.h"
#include "../../tests/qtesthelper.h"
#include <QtCore/QMutexLocker>
#include <QtGui/QImageReader>
#include <QtGui/QLabel>
#include <QtGui/QPixmap>
#include <QtTest/QtTest>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
class Output : public QObject, public Phonon::Experimental::AbstractVideoDataOutput
{
Q_OBJECT
public:
Output() : receivedEnd(0) {}
virtual QSet<Phonon::Experimental::VideoFrame2::Format> allowedFormats() const;
virtual void frameReady(const Phonon::Experimental::VideoFrame2 &);
virtual void endOfMedia();
QList<QImage> frames;
int receivedEnd;
QMutex mutex;
};
QSet<Phonon::Experimental::VideoFrame2::Format> Output::allowedFormats() const
{
return QSet<Phonon::Experimental::VideoFrame2::Format>() << Phonon::Experimental::VideoFrame2::Format_RGB888;
}
void Output::frameReady(const Phonon::Experimental::VideoFrame2 &frame)
{
qDebug() << Q_FUNC_INFO;
Q_ASSERT(frame.format == Phonon::Experimental::VideoFrame2::Format_RGB888);
QMutexLocker lock(&mutex);
frames << frame.qImage();
}
void Output::endOfMedia()
{
++receivedEnd;
}
class VideoDataOutputTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void testDelete();
void playMedia();
void cleanupTestCase();
private:
Phonon::MediaObject *m_media;
Output *m_output;
};
void VideoDataOutputTest::initTestCase()
{
m_media = new Phonon::MediaObject;
m_output = new Output;
Phonon::createPath(m_media, m_output);
}
void VideoDataOutputTest::testDelete()
{
delete m_output;
m_output = new Output;
m_output->start();
QVERIFY(m_output->isRunning());
Phonon::createPath(m_media, m_output);
#ifdef Q_OS_WIN
Sleep(1000);
#else
sleep(1);
#endif
}
void VideoDataOutputTest::playMedia()
{
m_media->setCurrentSource(QString(":/test.mng"));
m_media->play();
QVERIFY(QTest::kWaitForSignal(m_media, SIGNAL(finished()), 4000));
QEXPECT_FAIL("", "endOfMedia not yet implemented for xine", Continue);
QCOMPARE(m_output->receivedEnd, 1);
QList<QImage> frames;
{
QImageReader movie(":/test.mng");
QImage frame;
while (movie.read(&frame)) {
frames << frame.convertToFormat(QImage::Format_RGB888);
}
}
qDebug() << frames.size();
QMutexLocker lock(&m_output->mutex);
QVERIFY(!m_output->frames.isEmpty());
QCOMPARE(m_output->frames.size(), frames.size());
for (int i = 0; i < frames.size(); ++i) {
QCOMPARE(m_output->frames[i], frames[i]);
}
}
void VideoDataOutputTest::cleanupTestCase()
{
delete m_output;
delete m_media;
}
QTEST_MAIN(VideoDataOutputTest)
#include "videodataoutputtest.moc"
<|endoftext|>
|
<commit_before>#ifndef _http_UserBufferedMessage_hpp__
#define _http_UserBufferedMessage_hpp__
// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011-2012
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".
#include <string>
#include "Request.hpp"
#include "Response.hpp"
namespace http {
/*!
* @brief Default strategy for handling message bodies: buffer them.
* @tparam Message base class, must be @c Request or @c Response.
*/
template<class Base,class T>
class UserBufferedMessage
: public Base
{
/* nested types. */
private:
typedef UserBufferedMessage<Base, T> Self;
/* class methods. */
private:
static int on_body
( ::http_parser * parser, const char * data, size_t size )
{
static_cast<Self*>(parser->data)->myBody.append(data, size);
return (0);
}
static void extra_configuration ( ::http_parser_settings& settings )
{
settings.on_body = &Self::on_body;
}
/* construction. */
public:
UserBufferedMessage (T &userbuff)
: Base(&Self::extra_configuration), myBody(userbuff)
{
}
/* data. */
private:
T &myBody;
};
template<class T>
class UserBufferedRequest : public UserBufferedMessage<Request, T>
{
public:
UserBufferedRequest(T &userbuf)
: UserBufferedMessage<Request, T>(userbuf)
{
}
private:
UserBufferedRequest() {}
};
template<class T>
class UserBufferedResponse : public UserBufferedMessage<Response, T>
{
public:
UserBufferedResponse(T &userbuf)
: UserBufferedMessage<Response, T>(userbuf)
{
}
private:
UserBufferedResponse() {}
};
}
#endif /* _http_UserBufferedMessage_hpp__ */
<commit_msg>Update class comments<commit_after>#ifndef _http_UserBufferedMessage_hpp__
#define _http_UserBufferedMessage_hpp__
// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011-2012
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".
#include <string>
#include "Request.hpp"
#include "Response.hpp"
namespace http {
/*!
* @brief Using user specified storage for body to avoid memory copy.
* @tparam Base Message base class, must be @c Request or @c Response.
* @tparam T Type of storage which supports append(const char*, size_t).
*/
template<class Base,class T>
class UserBufferedMessage
: public Base
{
/* nested types. */
private:
typedef UserBufferedMessage<Base, T> Self;
/* class methods. */
private:
static int on_body
( ::http_parser * parser, const char * data, size_t size )
{
static_cast<Self*>(parser->data)->myBody.append(data, size);
return (0);
}
static void extra_configuration ( ::http_parser_settings& settings )
{
settings.on_body = &Self::on_body;
}
/* construction. */
public:
UserBufferedMessage (T &userbuff)
: Base(&Self::extra_configuration), myBody(userbuff)
{
}
/* data. */
private:
T &myBody;
};
template<class T>
class UserBufferedRequest : public UserBufferedMessage<Request, T>
{
public:
UserBufferedRequest(T &userbuf)
: UserBufferedMessage<Request, T>(userbuf)
{
}
private:
UserBufferedRequest() {}
};
template<class T>
class UserBufferedResponse : public UserBufferedMessage<Response, T>
{
public:
UserBufferedResponse(T &userbuf)
: UserBufferedMessage<Response, T>(userbuf)
{
}
private:
UserBufferedResponse() {}
};
}
#endif /* _http_UserBufferedMessage_hpp__ */
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.