text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "events.h"
#include "hook.h"
#include "callables.h"
#include "../globals.h"
#include "../ipc/ipc_event.h"
#include "../ipc/ipc_server_man.h"
#include "player.h"
#include <arpa/inet.h>
Hook* Events::hPlayerJoinRequest;
Hook* Events::hPlayerSay;
Hook* Events::hPlayerChangeName;
Hook* Events::hServerStatusRequest;
Events::Events() {}
Events::Events(const Events& orig) {}
Events::~Events() {}
void Events::InsertHooks()
{
Events::hPlayerJoinRequest = new Hook((void*) Events::locPlayerJoinRequest, 5, (void*) Events::HPlayerJoinRequest);
Events::hPlayerSay = new Hook((void*) Events::locPlayerSay, 5, (void*) Events::HPlayerSay);
Events::hPlayerChangeName = new Hook((void*) Events::locPlayerNameChange, 5, (void*) Events::HPlayerNameChange);
Events::hServerStatusRequest = new Hook((void*) Events::locRconStatus, 5, (void*) Events::HServerStatusRequest);
}
/*===============================================================*\
* EVENTS
\*===============================================================*/
bool Events::HPlayerJoinRequest(unsigned long a1, uint32_t ip, unsigned long a3, unsigned long a4, unsigned long a5)
{
// Predict slot ID
unsigned int slotID = 0;
unsigned long slotOffset = 0x090B4F8C;
unsigned int assignedSlot = 0;
unsigned int maxClients = Callables::GetMaxClients();
for(uint32_t i = 0x090B4F8C; ;i += 677436)
{
if(slotID > maxClients)
break;
slotID = 35580271 * ((i - 151736204) >> 2);
// If the slot's disconnected
if(*(uint32_t*) i == 0)
{
slotOffset = i;
printf("Slot [%i] is going to be used is currently in state: %i\n", slotID, *(uint32_t*) slotOffset);
break;
}
//bool r = ((Events::funcdefIsPlayerConnectedAtSlot)Events::locfuncIsPlayerConnectedAtSlot)
//(a1, ip, a3, a4, a5, *(uint32_t *)(i + 32), *(uint32_t *)(i + 36), *(uint32_t *)(i + 40));
// If the slot was free
//if(r == false)
//break;
}
// Get the string value out of the IP
struct in_addr ip_addr;
ip_addr.s_addr = ip;
char* addr = inet_ntoa(ip_addr);
// Copy the IP pointer into a character pointer, this is required because
// the char* 'addr' is actually a pointer to a space inside the in_addr
// object, so it will be cleaned once the ip_addr object goes out of scope.
char* ipAddress = new char[strlen(addr) + 1];
memcpy(ipAddress, addr, strlen(addr));
ipAddress[strlen(addr)] = '\0';
char* cmd = new char[9 + 1];
strcpy(cmd, "JOINREQ");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) ipAddress, IPCTypes::ch);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
// Execute the origional request to join the server
Events::hPlayerJoinRequest->UnHook();
bool rtn = ((Events::funcdefPlayerJoinRequest)Events::locPlayerJoinRequest)(a1, ip, a3, a4, a5);
Events::hPlayerJoinRequest->Rehook();
// After the request is executed, we will check if the connection was a success
// then fire another event.
Player player(slotID);
if(player.GetConnState() > 0)
{
char* ipAddress = new char[strlen(addr) + 1];
memcpy(ipAddress, addr, strlen(addr));
ipAddress[strlen(addr)] = '\0';
unsigned int playerNameLen = strlen(player.GetName());
char* playerName = new char[playerNameLen + 1];
memcpy(playerName, player.GetName(), playerNameLen);
playerName[playerNameLen] = '\0';
unsigned int guidLen = strlen(player.GetGuid());
char* guid = new char[guidLen + 1];
memcpy(guid, player.GetGuid(), guidLen);
guid[guidLen] = '\0';
char* cmd = new char[9 + 1];
strcpy(cmd, "JOIN");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) assignedSlot, IPCTypes::uint);
ipcEvent->AddArgument((void*) ipAddress, IPCTypes::ch);
ipcEvent->AddArgument((void*) guid, IPCTypes::ch);
ipcEvent->AddArgument((void*) playerName, IPCTypes::ch);
IPCServer::SetEventForBroadcast(ipcEvent);
}
return rtn;
}
/**
* Triggered when the player says something
* This function also bypasses the script if !login command is issued on the server
* @param a1 Pointer to the inet object
* @param a2
* @param a3 Sayteam produces 1 and say produces 0
* @param a4 Pointer to the character for message
* @return
*/
int Events::HPlayerSay(unsigned int* playerId, int a2, int teamSay, char* message)
{
// Prepare the arguments and types for the event
//int* argTeamSay = new int;
//*argTeamSay = teamSay;
Player player(*playerId);
unsigned int playerNameLen = strlen(player.GetName());
char* playerName = new char[playerNameLen + 1];
memcpy(playerName, player.GetName(), playerNameLen);
playerName[playerNameLen] = '\0';
unsigned int messageLen = strlen(message);
char* argMessage = new char[messageLen + 1];
memcpy(argMessage, message, messageLen);
argMessage[messageLen] = '\0';
// Collate the arguments and types
char* cmd = new char[4 + 1];
strcpy(cmd, "CHAT");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) *playerId, IPCTypes::uint);
ipcEvent->AddArgument((void*) playerName, IPCTypes::ch);
ipcEvent->AddArgument((void*) argMessage, IPCTypes::ch);
printf("%s: %s\n", playerName, message);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}
int Events::HPlayerNameChange(unsigned int playerOffset)
{
unsigned int playerId = Callables::GetPlayerIdByOffset(playerOffset);
char* newNameRtn = Callables::GetValueFromSlashString((char*)(0x0887C320 + 9), "name");
// Copy the name into a new char
unsigned int newNameLen = strlen(newNameRtn);
char* newName = new char[newNameLen + 1];
memcpy(newName, newNameRtn, newNameLen);
newName[newNameLen] = '\0';
char* cmd = new char[10 + 1];
strcpy(cmd, "CHANGENAME");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) playerId, IPCTypes::uint);
ipcEvent->AddArgument((void*) newName, IPCTypes::ch);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}
int Events::HServerStatusRequest()
{
char* cmd = new char[9 + 1];
strcpy(cmd, "STATUSREQ");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}<commit_msg>Fixed passing of slot ID bug<commit_after>#include "events.h"
#include "hook.h"
#include "callables.h"
#include "../globals.h"
#include "../ipc/ipc_event.h"
#include "../ipc/ipc_server_man.h"
#include "player.h"
#include <arpa/inet.h>
Hook* Events::hPlayerJoinRequest;
Hook* Events::hPlayerSay;
Hook* Events::hPlayerChangeName;
Hook* Events::hServerStatusRequest;
Events::Events() {}
Events::Events(const Events& orig) {}
Events::~Events() {}
void Events::InsertHooks()
{
Events::hPlayerJoinRequest = new Hook((void*) Events::locPlayerJoinRequest, 5, (void*) Events::HPlayerJoinRequest);
Events::hPlayerSay = new Hook((void*) Events::locPlayerSay, 5, (void*) Events::HPlayerSay);
Events::hPlayerChangeName = new Hook((void*) Events::locPlayerNameChange, 5, (void*) Events::HPlayerNameChange);
Events::hServerStatusRequest = new Hook((void*) Events::locRconStatus, 5, (void*) Events::HServerStatusRequest);
}
/*===============================================================*\
* EVENTS
\*===============================================================*/
bool Events::HPlayerJoinRequest(unsigned long a1, uint32_t ip, unsigned long a3, unsigned long a4, unsigned long a5)
{
// Predict slot ID
unsigned int slotID = 0;
unsigned long slotOffset = 0x090B4F8C;
unsigned int maxClients = Callables::GetMaxClients();
for(uint32_t i = 0x090B4F8C; ;i += 677436)
{
if(slotID > maxClients)
break;
// If the slot's disconnected
if(*(uint32_t*) i == 0)
{
slotOffset = i;
slotID = 35580271 * ((i - 151736204) >> 2);
break;
}
}
printf("Slot %i predicted to connect\n", slotID);
// Get the string value out of the IP
struct in_addr ip_addr;
ip_addr.s_addr = ip;
char* addr = inet_ntoa(ip_addr);
// Copy the IP pointer into a character pointer, this is required because
// the char* 'addr' is actually a pointer to a space inside the in_addr
// object, so it will be cleaned once the ip_addr object goes out of scope.
char* ipAddress = new char[strlen(addr) + 1];
memcpy(ipAddress, addr, strlen(addr));
ipAddress[strlen(addr)] = '\0';
char* cmd = new char[9 + 1];
strcpy(cmd, "JOINREQ");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) ipAddress, IPCTypes::ch);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
// Execute the origional request to join the server
Events::hPlayerJoinRequest->UnHook();
bool rtn = ((Events::funcdefPlayerJoinRequest)Events::locPlayerJoinRequest)(a1, ip, a3, a4, a5);
Events::hPlayerJoinRequest->Rehook();
// After the request is executed, we will check if the connection was a success
// then fire another event.
Player player(slotID);
if(player.GetConnState() > 0)
{
char* ipAddress = new char[strlen(addr) + 1];
memcpy(ipAddress, addr, strlen(addr));
ipAddress[strlen(addr)] = '\0';
unsigned int playerNameLen = strlen(player.GetName());
char* playerName = new char[playerNameLen + 1];
memcpy(playerName, player.GetName(), playerNameLen);
playerName[playerNameLen] = '\0';
unsigned int guidLen = strlen(player.GetGuid());
char* guid = new char[guidLen + 1];
memcpy(guid, player.GetGuid(), guidLen);
guid[guidLen] = '\0';
char* cmd = new char[9 + 1];
strcpy(cmd, "JOIN");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) slotID, IPCTypes::uint);
ipcEvent->AddArgument((void*) ipAddress, IPCTypes::ch);
ipcEvent->AddArgument((void*) guid, IPCTypes::ch);
ipcEvent->AddArgument((void*) playerName, IPCTypes::ch);
IPCServer::SetEventForBroadcast(ipcEvent);
}
return rtn;
}
/**
* Triggered when the player says something
* This function also bypasses the script if !login command is issued on the server
* @param a1 Pointer to the inet object
* @param a2
* @param a3 Sayteam produces 1 and say produces 0
* @param a4 Pointer to the character for message
* @return
*/
int Events::HPlayerSay(unsigned int* playerId, int a2, int teamSay, char* message)
{
// Prepare the arguments and types for the event
//int* argTeamSay = new int;
//*argTeamSay = teamSay;
Player player(*playerId);
unsigned int playerNameLen = strlen(player.GetName());
char* playerName = new char[playerNameLen + 1];
memcpy(playerName, player.GetName(), playerNameLen);
playerName[playerNameLen] = '\0';
unsigned int messageLen = strlen(message);
char* argMessage = new char[messageLen + 1];
memcpy(argMessage, message, messageLen);
argMessage[messageLen] = '\0';
// Collate the arguments and types
char* cmd = new char[4 + 1];
strcpy(cmd, "CHAT");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) *playerId, IPCTypes::uint);
ipcEvent->AddArgument((void*) playerName, IPCTypes::ch);
ipcEvent->AddArgument((void*) argMessage, IPCTypes::ch);
printf("%s: %s\n", playerName, message);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}
int Events::HPlayerNameChange(unsigned int playerOffset)
{
unsigned int playerId = Callables::GetPlayerIdByOffset(playerOffset);
char* newNameRtn = Callables::GetValueFromSlashString((char*)(0x0887C320 + 9), "name");
// Copy the name into a new char
unsigned int newNameLen = strlen(newNameRtn);
char* newName = new char[newNameLen + 1];
memcpy(newName, newNameRtn, newNameLen);
newName[newNameLen] = '\0';
char* cmd = new char[10 + 1];
strcpy(cmd, "CHANGENAME");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
ipcEvent->AddArgument((void*) playerId, IPCTypes::uint);
ipcEvent->AddArgument((void*) newName, IPCTypes::ch);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}
int Events::HServerStatusRequest()
{
char* cmd = new char[9 + 1];
strcpy(cmd, "STATUSREQ");
IPCCoD4Event* ipcEvent = new IPCCoD4Event(cmd);
// Broadcast the event
IPCServer::SetEventForBroadcast(ipcEvent);
return 0;
}<|endoftext|>
|
<commit_before>/*
* Physically Based Rendering
* Copyright (c) 2017-2018 Michał Siejak
*/
#include <cstdio>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/Importer.hpp>
#include <assimp/DefaultLogger.hpp>
#include <assimp/LogStream.hpp>
#include "mesh.hpp"
namespace {
const unsigned int ImportFlags =
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_SortByPType |
aiProcess_PreTransformVertices |
aiProcess_GenNormals |
aiProcess_GenUVCoords |
aiProcess_OptimizeMeshes |
aiProcess_OptimizeGraph |
aiProcess_Debone |
aiProcess_ValidateDataStructure;
}
struct LogStream : public Assimp::LogStream
{
static void initialize()
{
if(Assimp::DefaultLogger::isNullLogger()) {
Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE);
Assimp::DefaultLogger::get()->attachStream(new LogStream, Assimp::Logger::Err | Assimp::Logger::Warn);
}
}
void write(const char* message) override
{
std::fprintf(stderr, "Assimp: %s", message);
}
};
Mesh::Mesh(const aiMesh* mesh)
{
assert(mesh->HasPositions());
assert(mesh->HasNormals());
m_vertices.reserve(mesh->mNumVertices);
for(size_t i=0; i<m_vertices.capacity(); ++i) {
Vertex vertex;
vertex.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z};
vertex.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z};
if(mesh->HasTangentsAndBitangents()) {
vertex.tangent = {mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z};
vertex.bitangent = {mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z};
}
if(mesh->HasTextureCoords(0)) {
vertex.texcoord = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y};
}
m_vertices.push_back(vertex);
}
m_faces.reserve(mesh->mNumFaces);
for(size_t i=0; i<m_faces.capacity(); ++i) {
assert(mesh->mFaces[i].mNumIndices == 3);
m_faces.push_back({mesh->mFaces[i].mIndices[0], mesh->mFaces[i].mIndices[1], mesh->mFaces[i].mIndices[2]});
}
}
std::shared_ptr<Mesh> Mesh::fromFile(const std::string& filename)
{
LogStream::initialize();
std::printf("Loading mesh: %s\n", filename.c_str());
std::shared_ptr<Mesh> mesh;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename, ImportFlags);
if(scene && scene->HasMeshes()) {
mesh = std::shared_ptr<Mesh>(new Mesh{scene->mMeshes[0]});
}
else {
throw std::runtime_error("Failed to load mesh file: " + filename);
}
return mesh;
}
std::shared_ptr<Mesh> Mesh::fromString(const std::string& data)
{
LogStream::initialize();
std::shared_ptr<Mesh> mesh;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFileFromMemory(data.c_str(), data.length(), ImportFlags, "nff");
if(scene && scene->HasMeshes()) {
mesh = std::shared_ptr<Mesh>(new Mesh{scene->mMeshes[0]});
}
else {
throw std::runtime_error("Failed to create mesh from string: " + data);
}
return mesh;
}
<commit_msg>Removed redundant aiProcess_OptimizeGraph from assimp import flags<commit_after>/*
* Physically Based Rendering
* Copyright (c) 2017-2018 Michał Siejak
*/
#include <cstdio>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/Importer.hpp>
#include <assimp/DefaultLogger.hpp>
#include <assimp/LogStream.hpp>
#include "mesh.hpp"
namespace {
const unsigned int ImportFlags =
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_SortByPType |
aiProcess_PreTransformVertices |
aiProcess_GenNormals |
aiProcess_GenUVCoords |
aiProcess_OptimizeMeshes |
aiProcess_Debone |
aiProcess_ValidateDataStructure;
}
struct LogStream : public Assimp::LogStream
{
static void initialize()
{
if(Assimp::DefaultLogger::isNullLogger()) {
Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE);
Assimp::DefaultLogger::get()->attachStream(new LogStream, Assimp::Logger::Err | Assimp::Logger::Warn);
}
}
void write(const char* message) override
{
std::fprintf(stderr, "Assimp: %s", message);
}
};
Mesh::Mesh(const aiMesh* mesh)
{
assert(mesh->HasPositions());
assert(mesh->HasNormals());
m_vertices.reserve(mesh->mNumVertices);
for(size_t i=0; i<m_vertices.capacity(); ++i) {
Vertex vertex;
vertex.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z};
vertex.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z};
if(mesh->HasTangentsAndBitangents()) {
vertex.tangent = {mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z};
vertex.bitangent = {mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z};
}
if(mesh->HasTextureCoords(0)) {
vertex.texcoord = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y};
}
m_vertices.push_back(vertex);
}
m_faces.reserve(mesh->mNumFaces);
for(size_t i=0; i<m_faces.capacity(); ++i) {
assert(mesh->mFaces[i].mNumIndices == 3);
m_faces.push_back({mesh->mFaces[i].mIndices[0], mesh->mFaces[i].mIndices[1], mesh->mFaces[i].mIndices[2]});
}
}
std::shared_ptr<Mesh> Mesh::fromFile(const std::string& filename)
{
LogStream::initialize();
std::printf("Loading mesh: %s\n", filename.c_str());
std::shared_ptr<Mesh> mesh;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename, ImportFlags);
if(scene && scene->HasMeshes()) {
mesh = std::shared_ptr<Mesh>(new Mesh{scene->mMeshes[0]});
}
else {
throw std::runtime_error("Failed to load mesh file: " + filename);
}
return mesh;
}
std::shared_ptr<Mesh> Mesh::fromString(const std::string& data)
{
LogStream::initialize();
std::shared_ptr<Mesh> mesh;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFileFromMemory(data.c_str(), data.length(), ImportFlags, "nff");
if(scene && scene->HasMeshes()) {
mesh = std::shared_ptr<Mesh>(new Mesh{scene->mMeshes[0]});
}
else {
throw std::runtime_error("Failed to create mesh from string: " + data);
}
return mesh;
}
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstddef>
#include <visionaray/math/simd/type_traits.h>
#include <visionaray/math/array.h>
#include <visionaray/math/forward.h>
#include <visionaray/math/vector.h>
#include <visionaray/texture/texture_traits.h>
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Implement Visionaray's texturing interface for Ptex textures
//
namespace ptex
{
// tex2D
inline vector<4, unorm<8>> tex2D(PtexPtr<PtexTexture> const& tex, coordinate<float> const& coord)
{
// Older versions of Ptex have only non-const PtexPtr accessors
PtexPtr<Ptex::PtexTexture>& mutable_tex = const_cast<PtexPtr<PtexTexture>&>(tex);
if (mutable_tex == nullptr)
{
return vector<4, unorm<8>>(1.0f);
}
Ptex::PtexFilter::Options opts(Ptex::PtexFilter::FilterType::f_bspline);
PtexPtr<Ptex::PtexFilter> filter(Ptex::PtexFilter::getFilter(mutable_tex.get(), opts));
int face_id = coord.face_id >= 0 ? coord.face_id : ~coord.face_id;
auto face_data = mutable_tex->getData(face_id);
auto res = face_data->res();
vec3 rgb;
filter->eval(
rgb.data(),
0,
mutable_tex->numChannels(),
face_id,
coord.u,
coord.v,
1.0f / res.u(),
0.0f,
0.0f,
1.0f / res.v()
);
return vector<4, unorm<8>>(rgb.x, rgb.y, rgb.z, 1.0f);
}
} // ptex
namespace simd
{
template <
size_t N,
typename T = float_from_simd_width<N>
>
inline ptex::coordinate<T> pack(array<ptex::coordinate<float>, N> const& coords)
{
ptex::coordinate<T> result;
int* face_id = reinterpret_cast<int*>(&result.face_id);
float* u = reinterpret_cast<float*>(&result.u);
float* v = reinterpret_cast<float*>(&result.v);
float* du = reinterpret_cast<float*>(&result.du);
float* dv = reinterpret_cast<float*>(&result.dv);
for (size_t i = 0; i < N; ++i)
{
face_id[i] = coords[i].face_id;
u[i] = coords[i].u;
v[i] = coords[i].v;
du[i] = coords[i].du;
dv[i] = coords[i].dv;
}
return result;
}
} // simd
// get_tex_coord() non-simd
template <
typename HR,
typename T,
typename = typename std::enable_if<!simd::is_simd_vector<typename HR::scalar_type>::value>::type
>
inline auto get_tex_coord(
ptex::face_id_t const* face_ids,
HR const& hr,
basic_triangle<3, T> /* */
)
-> ptex::coordinate<typename HR::scalar_type>
{
ptex::coordinate<typename HR::scalar_type> result;
vec2 tc1(0.0f, 0.0f);
vec2 tc2(1.0f, 0.0f);
vec2 tc3(1.0f, 1.0f);
vec2 tc4(0.0f, 1.0f);
result.face_id = face_ids[hr.prim_id];
vec2 uv;
if (result.face_id >= 0)
{
uv = lerp(tc1, tc2, tc3, hr.u, hr.v);
}
else
{
result.face_id = ~result.face_id;
uv = lerp(tc1, tc3, tc4, hr.u, hr.v);
}
result.u = uv.x;
result.v = uv.y;
return result;
}
// get_tex_coord() simd
template <
typename HR,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<typename HR::scalar_type>::value>::type,
typename = void
>
inline auto get_tex_coord(
ptex::face_id_t const* face_ids,
HR const& hr,
basic_triangle<3, T> /* */
)
-> ptex::coordinate<typename HR::scalar_type>
{
using U = typename HR::scalar_type;
auto hrs = unpack(hr);
array<ptex::coordinate<float>, simd::num_elements<U>::value> coords;
for (int i = 0; i < simd::num_elements<U>::value; ++i)
{
coords[i].face_id = face_ids[hrs[i].prim_id];
coords[i].u = hrs[i].u;
coords[i].v = hrs[i].v;
}
return simd::pack(coords);
}
template <>
struct texture_dimensions<PtexPtr<PtexTexture>>
{
enum { value = 2 };
};
} // visionaray
<commit_msg>Revert "Don't forget to flip negative face ids"<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstddef>
#include <visionaray/math/simd/type_traits.h>
#include <visionaray/math/array.h>
#include <visionaray/math/forward.h>
#include <visionaray/math/vector.h>
#include <visionaray/texture/texture_traits.h>
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Implement Visionaray's texturing interface for Ptex textures
//
namespace ptex
{
// tex2D
inline vector<4, unorm<8>> tex2D(PtexPtr<PtexTexture> const& tex, coordinate<float> const& coord)
{
// Older versions of Ptex have only non-const PtexPtr accessors
PtexPtr<Ptex::PtexTexture>& mutable_tex = const_cast<PtexPtr<PtexTexture>&>(tex);
if (mutable_tex == nullptr)
{
return vector<4, unorm<8>>(1.0f);
}
Ptex::PtexFilter::Options opts(Ptex::PtexFilter::FilterType::f_bspline);
PtexPtr<Ptex::PtexFilter> filter(Ptex::PtexFilter::getFilter(mutable_tex.get(), opts));
auto face_data = mutable_tex->getData(coord.face_id);
auto res = face_data->res();
vec3 rgb;
filter->eval(
rgb.data(),
0,
mutable_tex->numChannels(),
coord.face_id,
coord.u,
coord.v,
1.0f / res.u(),
0.0f,
0.0f,
1.0f / res.v()
);
return vector<4, unorm<8>>(rgb.x, rgb.y, rgb.z, 1.0f);
}
} // ptex
namespace simd
{
template <
size_t N,
typename T = float_from_simd_width<N>
>
inline ptex::coordinate<T> pack(array<ptex::coordinate<float>, N> const& coords)
{
ptex::coordinate<T> result;
int* face_id = reinterpret_cast<int*>(&result.face_id);
float* u = reinterpret_cast<float*>(&result.u);
float* v = reinterpret_cast<float*>(&result.v);
float* du = reinterpret_cast<float*>(&result.du);
float* dv = reinterpret_cast<float*>(&result.dv);
for (size_t i = 0; i < N; ++i)
{
face_id[i] = coords[i].face_id;
u[i] = coords[i].u;
v[i] = coords[i].v;
du[i] = coords[i].du;
dv[i] = coords[i].dv;
}
return result;
}
} // simd
// get_tex_coord() non-simd
template <
typename HR,
typename T,
typename = typename std::enable_if<!simd::is_simd_vector<typename HR::scalar_type>::value>::type
>
inline auto get_tex_coord(
ptex::face_id_t const* face_ids,
HR const& hr,
basic_triangle<3, T> /* */
)
-> ptex::coordinate<typename HR::scalar_type>
{
ptex::coordinate<typename HR::scalar_type> result;
vec2 tc1(0.0f, 0.0f);
vec2 tc2(1.0f, 0.0f);
vec2 tc3(1.0f, 1.0f);
vec2 tc4(0.0f, 1.0f);
result.face_id = face_ids[hr.prim_id];
vec2 uv;
if (result.face_id >= 0)
{
uv = lerp(tc1, tc2, tc3, hr.u, hr.v);
}
else
{
result.face_id = ~result.face_id;
uv = lerp(tc1, tc3, tc4, hr.u, hr.v);
}
result.u = uv.x;
result.v = uv.y;
return result;
}
// get_tex_coord() simd
template <
typename HR,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<typename HR::scalar_type>::value>::type,
typename = void
>
inline auto get_tex_coord(
ptex::face_id_t const* face_ids,
HR const& hr,
basic_triangle<3, T> /* */
)
-> ptex::coordinate<typename HR::scalar_type>
{
using U = typename HR::scalar_type;
auto hrs = unpack(hr);
array<ptex::coordinate<float>, simd::num_elements<U>::value> coords;
for (int i = 0; i < simd::num_elements<U>::value; ++i)
{
coords[i].face_id = face_ids[hrs[i].prim_id];
coords[i].u = hrs[i].u;
coords[i].v = hrs[i].v;
}
return simd::pack(coords);
}
template <>
struct texture_dimensions<PtexPtr<PtexTexture>>
{
enum { value = 2 };
};
} // visionaray
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljscheck.h"
#include "qmljsbind.h"
#include "qmljsinterpreter.h"
#include "qmljsevaluate.h"
#include "parser/qmljsast_p.h"
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtGui/QColor>
#include <QtGui/QApplication>
namespace QmlJS {
namespace Messages {
static const char *invalid_property_name = QT_TRANSLATE_NOOP("QmlJS::Check", "'%1' is not a valid property name");
static const char *unknown_type = QT_TRANSLATE_NOOP("QmlJS::Check", "unknown type");
static const char *has_no_members = QT_TRANSLATE_NOOP("QmlJS::Check", "'%1' does not have members");
static const char *is_not_a_member = QT_TRANSLATE_NOOP("QmlJS::Check", "'%1' is not a member of '%2'");
static const char *easing_curve_not_a_string = QT_TRANSLATE_NOOP("QmlJS::Check", "easing-curve name is not a string");
static const char *unknown_easing_curve_name = QT_TRANSLATE_NOOP("QmlJS::Check", "unknown easing-curve name");
static const char *value_might_be_undefined = QT_TRANSLATE_NOOP("QmlJS::Check", "value might be 'undefined'");
} // namespace Messages
static inline QString tr(const char *msg)
{ return qApp->translate("QmlJS::Check", msg); }
} // namespace QmlJS
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJS::Interpreter;
namespace {
class AssignmentCheck : public ValueVisitor
{
public:
DiagnosticMessage operator()(
const SourceLocation &location,
const Interpreter::Value *lhsValue,
const Interpreter::Value *rhsValue,
ExpressionNode *ast)
{
_message = DiagnosticMessage(DiagnosticMessage::Error, location, QString());
_rhsValue = rhsValue;
_ast = ast;
if (lhsValue)
lhsValue->accept(this);
return _message;
}
virtual void visit(const NumberValue *)
{
// ### Consider enums: elide: "ElideLeft" is valid, but currently elide is a NumberValue.
if (/*cast<StringLiteral *>(_ast)
||*/ _ast->kind == Node::Kind_TrueLiteral
|| _ast->kind == Node::Kind_FalseLiteral) {
_message.message = QCoreApplication::translate("QmlJS::Check", "numerical value expected");
}
}
virtual void visit(const BooleanValue *)
{
UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);
if (cast<StringLiteral *>(_ast)
|| cast<NumericLiteral *>(_ast)
|| (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))) {
_message.message = QCoreApplication::translate("QmlJS::Check", "boolean value expected");
}
}
virtual void visit(const StringValue *)
{
UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);
if (cast<NumericLiteral *>(_ast)
|| (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))
|| _ast->kind == Node::Kind_TrueLiteral
|| _ast->kind == Node::Kind_FalseLiteral) {
_message.message = QCoreApplication::translate("QmlJS::Check", "string value expected");
}
}
virtual void visit(const EasingCurveNameValue *)
{
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString curveName = stringLiteral->value->asString();
if (!EasingCurveNameValue::curveNames().contains(curveName)) {
_message.message = tr(Messages::unknown_easing_curve_name);
}
} else if (_rhsValue->asUndefinedValue()) {
_message.kind = DiagnosticMessage::Warning;
_message.message = tr(Messages::value_might_be_undefined);
} else if (! _rhsValue->asStringValue()) {
_message.message = tr(Messages::easing_curve_not_a_string);
}
}
virtual void visit(const ColorValue *)
{
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString colorString = stringLiteral->value->asString();
bool ok = true;
if (colorString.size() == 9 && colorString.at(0) == QLatin1Char('#')) {
// #rgba
for (int i = 1; i < 9; ++i) {
const QChar c = colorString.at(i);
if ((c >= QLatin1Char('0') && c <= QLatin1Char('9'))
|| (c >= QLatin1Char('a') && c <= QLatin1Char('f'))
|| (c >= QLatin1Char('A') && c <= QLatin1Char('F')))
continue;
ok = false;
break;
}
} else {
ok = QColor::isValidColor(colorString);
}
if (!ok)
_message.message = QCoreApplication::translate("QmlJS::Check", "not a valid color");
} else {
visit((StringValue *)0);
}
}
virtual void visit(const AnchorLineValue *)
{
if (! (_rhsValue->asAnchorLineValue() || _rhsValue->asUndefinedValue()))
_message.message = QCoreApplication::translate("QmlJS::Check", "expected anchor line");
}
DiagnosticMessage _message;
const Value *_rhsValue;
ExpressionNode *_ast;
};
} // end of anonymous namespace
Check::Check(Document::Ptr doc, const Snapshot &snapshot, const QStringList &importPaths)
: _doc(doc)
, _snapshot(snapshot)
, _context(&_engine)
, _link(&_context, doc, snapshot, importPaths)
, _scopeBuilder(doc, &_context)
, _ignoreTypeErrors(_context.documentImportsPlugins(_doc.data()))
{
}
Check::~Check()
{
}
QList<DiagnosticMessage> Check::operator()()
{
_messages.clear();
Node::accept(_doc->ast(), this);
_messages.append(_link.diagnosticMessages());
return _messages;
}
bool Check::visit(UiProgram *)
{
return true;
}
bool Check::visit(UiObjectDefinition *ast)
{
visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
return false;
}
bool Check::visit(UiObjectBinding *ast)
{
checkScopeObjectMember(ast->qualifiedId);
visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
return false;
}
void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
UiObjectInitializer *initializer)
{
// If the 'typeId' starts with a lower-case letter, it doesn't define
// a new object instance. For instance: anchors { ... }
if (typeId->name->asString().at(0).isLower() && ! typeId->next) {
checkScopeObjectMember(typeId);
// ### don't give up!
return;
}
_scopeBuilder.push(ast);
if (! _context.lookupType(_doc.data(), typeId)) {
if (! _ignoreTypeErrors)
error(typeId->identifierToken, tr(Messages::unknown_type));
// suppress subsequent errors about scope object lookup by clearing
// the scope object list
// ### todo: better way?
_context.scopeChain().qmlScopeObjects.clear();
_context.scopeChain().update();
}
Node::accept(initializer, this);
_scopeBuilder.pop();
}
bool Check::visit(UiScriptBinding *ast)
{
// special case for id property
if (ast->qualifiedId->name->asString() == QLatin1String("id") && ! ast->qualifiedId->next) {
if (! ast->statement)
return false;
const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),
ast->statement->lastSourceLocation());
ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
error(loc, QCoreApplication::translate("QmlJS::Check", "expected id"));
return false;
}
QString id;
if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) {
id = idExp->name->asString();
} else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) {
id = strExp->value->asString();
warning(loc, QCoreApplication::translate("QmlJS::Check", "using string literals for ids is discouraged"));
} else {
error(loc, QCoreApplication::translate("QmlJS::Check", "expected id"));
return false;
}
if (id.isEmpty() || ! id[0].isLower()) {
error(loc, QCoreApplication::translate("QmlJS::Check", "ids must be lower case"));
return false;
}
}
const Value *lhsValue = checkScopeObjectMember(ast->qualifiedId);
if (lhsValue) {
// ### Fix the evaluator to accept statements!
if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement)) {
ExpressionNode *expr = expStmt->expression;
Evaluate evaluator(&_context);
const Value *rhsValue = evaluator(expr);
const SourceLocation loc = locationFromRange(expStmt->firstSourceLocation(),
expStmt->lastSourceLocation());
AssignmentCheck assignmentCheck;
DiagnosticMessage message = assignmentCheck(loc, lhsValue, rhsValue, expr);
if (! message.message.isEmpty())
_messages += message;
}
}
return true;
}
bool Check::visit(UiArrayBinding *ast)
{
checkScopeObjectMember(ast->qualifiedId);
return true;
}
/// When something is changed here, also change ReadingContext::lookupProperty in
/// texttomodelmerger.cpp
/// ### Maybe put this into the context as a helper method.
const Value *Check::checkScopeObjectMember(const UiQualifiedId *id)
{
QList<const ObjectValue *> scopeObjects = _context.scopeChain().qmlScopeObjects;
if (scopeObjects.isEmpty())
return 0;
if (! id)
return 0; // ### error?
if (! id->name) // possible after error recovery
return 0;
QString propertyName = id->name->asString();
if (propertyName == QLatin1String("id") && ! id->next)
return 0; // ### should probably be a special value
// attached properties
bool isAttachedProperty = false;
if (! propertyName.isEmpty() && propertyName[0].isUpper()) {
isAttachedProperty = true;
scopeObjects += _context.scopeChain().qmlTypes;
}
if (scopeObjects.isEmpty())
return 0;
// global lookup for first part of id
const Value *value = 0;
for (int i = scopeObjects.size() - 1; i >= 0; --i) {
value = scopeObjects[i]->lookupMember(propertyName, &_context);
if (value)
break;
}
if (!value) {
error(id->identifierToken,
tr(Messages::invalid_property_name).arg(propertyName));
}
// can't look up members for attached properties
if (isAttachedProperty)
return 0;
// member lookup
const UiQualifiedId *idPart = id;
while (idPart->next) {
const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);
if (! objectValue) {
error(idPart->identifierToken,
tr(Messages::has_no_members).arg(propertyName));
return 0;
}
if (! idPart->next->name) {
// somebody typed "id." and error recovery still gave us a valid tree,
// so just bail out here.
return 0;
}
idPart = idPart->next;
propertyName = idPart->name->asString();
value = objectValue->lookupMember(propertyName, &_context);
if (! value) {
error(idPart->identifierToken,
tr(Messages::is_not_a_member).arg(propertyName,
objectValue->className()));
return 0;
}
}
return value;
}
void Check::error(const AST::SourceLocation &loc, const QString &message)
{
_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc, message));
}
void Check::warning(const AST::SourceLocation &loc, const QString &message)
{
_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));
}
SourceLocation Check::locationFromRange(const SourceLocation &start,
const SourceLocation &end)
{
return SourceLocation(start.offset,
end.end() - start.begin(),
start.startLine,
start.startColumn);
}
<commit_msg>QmlJS: Change way to translate strings to nicer one.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljscheck.h"
#include "qmljsbind.h"
#include "qmljsinterpreter.h"
#include "qmljsevaluate.h"
#include "parser/qmljsast_p.h"
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
#include <QtGui/QColor>
#include <QtGui/QApplication>
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJS::Interpreter;
namespace {
class AssignmentCheck : public ValueVisitor
{
public:
DiagnosticMessage operator()(
const SourceLocation &location,
const Interpreter::Value *lhsValue,
const Interpreter::Value *rhsValue,
ExpressionNode *ast)
{
_message = DiagnosticMessage(DiagnosticMessage::Error, location, QString());
_rhsValue = rhsValue;
_ast = ast;
if (lhsValue)
lhsValue->accept(this);
return _message;
}
virtual void visit(const NumberValue *)
{
// ### Consider enums: elide: "ElideLeft" is valid, but currently elide is a NumberValue.
if (/*cast<StringLiteral *>(_ast)
||*/ _ast->kind == Node::Kind_TrueLiteral
|| _ast->kind == Node::Kind_FalseLiteral) {
_message.message = QCoreApplication::translate("QmlJS::Check", "numerical value expected");
}
}
virtual void visit(const BooleanValue *)
{
UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);
if (cast<StringLiteral *>(_ast)
|| cast<NumericLiteral *>(_ast)
|| (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))) {
_message.message = QCoreApplication::translate("QmlJS::Check", "boolean value expected");
}
}
virtual void visit(const StringValue *)
{
UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);
if (cast<NumericLiteral *>(_ast)
|| (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))
|| _ast->kind == Node::Kind_TrueLiteral
|| _ast->kind == Node::Kind_FalseLiteral) {
_message.message = QCoreApplication::translate("QmlJS::Check", "string value expected");
}
}
virtual void visit(const EasingCurveNameValue *)
{
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString curveName = stringLiteral->value->asString();
if (!EasingCurveNameValue::curveNames().contains(curveName)) {
_message.message = QCoreApplication::translate("QmlJS::Check", "unknown easing-curve name");
}
} else if (_rhsValue->asUndefinedValue()) {
_message.kind = DiagnosticMessage::Warning;
_message.message = QCoreApplication::translate("QmlJS::Check", "value might be 'undefined'");
} else if (! _rhsValue->asStringValue()) {
_message.message = QCoreApplication::translate("QmlJS::Check", "easing-curve name is not a string");
}
}
virtual void visit(const ColorValue *)
{
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString colorString = stringLiteral->value->asString();
bool ok = true;
if (colorString.size() == 9 && colorString.at(0) == QLatin1Char('#')) {
// #rgba
for (int i = 1; i < 9; ++i) {
const QChar c = colorString.at(i);
if ((c >= QLatin1Char('0') && c <= QLatin1Char('9'))
|| (c >= QLatin1Char('a') && c <= QLatin1Char('f'))
|| (c >= QLatin1Char('A') && c <= QLatin1Char('F')))
continue;
ok = false;
break;
}
} else {
ok = QColor::isValidColor(colorString);
}
if (!ok)
_message.message = QCoreApplication::translate("QmlJS::Check", "not a valid color");
} else {
visit((StringValue *)0);
}
}
virtual void visit(const AnchorLineValue *)
{
if (! (_rhsValue->asAnchorLineValue() || _rhsValue->asUndefinedValue()))
_message.message = QCoreApplication::translate("QmlJS::Check", "expected anchor line");
}
DiagnosticMessage _message;
const Value *_rhsValue;
ExpressionNode *_ast;
};
} // end of anonymous namespace
Check::Check(Document::Ptr doc, const Snapshot &snapshot, const QStringList &importPaths)
: _doc(doc)
, _snapshot(snapshot)
, _context(&_engine)
, _link(&_context, doc, snapshot, importPaths)
, _scopeBuilder(doc, &_context)
, _ignoreTypeErrors(_context.documentImportsPlugins(_doc.data()))
{
}
Check::~Check()
{
}
QList<DiagnosticMessage> Check::operator()()
{
_messages.clear();
Node::accept(_doc->ast(), this);
_messages.append(_link.diagnosticMessages());
return _messages;
}
bool Check::visit(UiProgram *)
{
return true;
}
bool Check::visit(UiObjectDefinition *ast)
{
visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
return false;
}
bool Check::visit(UiObjectBinding *ast)
{
checkScopeObjectMember(ast->qualifiedId);
visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
return false;
}
void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
UiObjectInitializer *initializer)
{
// If the 'typeId' starts with a lower-case letter, it doesn't define
// a new object instance. For instance: anchors { ... }
if (typeId->name->asString().at(0).isLower() && ! typeId->next) {
checkScopeObjectMember(typeId);
// ### don't give up!
return;
}
_scopeBuilder.push(ast);
if (! _context.lookupType(_doc.data(), typeId)) {
if (! _ignoreTypeErrors)
error(typeId->identifierToken,
QCoreApplication::translate("QmlJS::Check", "unknown type"));
// suppress subsequent errors about scope object lookup by clearing
// the scope object list
// ### todo: better way?
_context.scopeChain().qmlScopeObjects.clear();
_context.scopeChain().update();
}
Node::accept(initializer, this);
_scopeBuilder.pop();
}
bool Check::visit(UiScriptBinding *ast)
{
// special case for id property
if (ast->qualifiedId->name->asString() == QLatin1String("id") && ! ast->qualifiedId->next) {
if (! ast->statement)
return false;
const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),
ast->statement->lastSourceLocation());
ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
error(loc, QCoreApplication::translate("QmlJS::Check", "expected id"));
return false;
}
QString id;
if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) {
id = idExp->name->asString();
} else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) {
id = strExp->value->asString();
warning(loc, QCoreApplication::translate("QmlJS::Check", "using string literals for ids is discouraged"));
} else {
error(loc, QCoreApplication::translate("QmlJS::Check", "expected id"));
return false;
}
if (id.isEmpty() || ! id[0].isLower()) {
error(loc, QCoreApplication::translate("QmlJS::Check", "ids must be lower case"));
return false;
}
}
const Value *lhsValue = checkScopeObjectMember(ast->qualifiedId);
if (lhsValue) {
// ### Fix the evaluator to accept statements!
if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement)) {
ExpressionNode *expr = expStmt->expression;
Evaluate evaluator(&_context);
const Value *rhsValue = evaluator(expr);
const SourceLocation loc = locationFromRange(expStmt->firstSourceLocation(),
expStmt->lastSourceLocation());
AssignmentCheck assignmentCheck;
DiagnosticMessage message = assignmentCheck(loc, lhsValue, rhsValue, expr);
if (! message.message.isEmpty())
_messages += message;
}
}
return true;
}
bool Check::visit(UiArrayBinding *ast)
{
checkScopeObjectMember(ast->qualifiedId);
return true;
}
/// When something is changed here, also change ReadingContext::lookupProperty in
/// texttomodelmerger.cpp
/// ### Maybe put this into the context as a helper method.
const Value *Check::checkScopeObjectMember(const UiQualifiedId *id)
{
QList<const ObjectValue *> scopeObjects = _context.scopeChain().qmlScopeObjects;
if (scopeObjects.isEmpty())
return 0;
if (! id)
return 0; // ### error?
if (! id->name) // possible after error recovery
return 0;
QString propertyName = id->name->asString();
if (propertyName == QLatin1String("id") && ! id->next)
return 0; // ### should probably be a special value
// attached properties
bool isAttachedProperty = false;
if (! propertyName.isEmpty() && propertyName[0].isUpper()) {
isAttachedProperty = true;
scopeObjects += _context.scopeChain().qmlTypes;
}
if (scopeObjects.isEmpty())
return 0;
// global lookup for first part of id
const Value *value = 0;
for (int i = scopeObjects.size() - 1; i >= 0; --i) {
value = scopeObjects[i]->lookupMember(propertyName, &_context);
if (value)
break;
}
if (!value) {
error(id->identifierToken,
QCoreApplication::translate("QmlJS::Check", "'%1' is not a valid property name").arg(propertyName));
}
// can't look up members for attached properties
if (isAttachedProperty)
return 0;
// member lookup
const UiQualifiedId *idPart = id;
while (idPart->next) {
const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);
if (! objectValue) {
error(idPart->identifierToken,
QCoreApplication::translate("QmlJS::Check", "'%1' does not have members").arg(propertyName));
return 0;
}
if (! idPart->next->name) {
// somebody typed "id." and error recovery still gave us a valid tree,
// so just bail out here.
return 0;
}
idPart = idPart->next;
propertyName = idPart->name->asString();
value = objectValue->lookupMember(propertyName, &_context);
if (! value) {
error(idPart->identifierToken,
QCoreApplication::translate("QmlJS::Check", "'%1' is not a member of '%2'").arg(
propertyName, objectValue->className()));
return 0;
}
}
return value;
}
void Check::error(const AST::SourceLocation &loc, const QString &message)
{
_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc, message));
}
void Check::warning(const AST::SourceLocation &loc, const QString &message)
{
_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));
}
SourceLocation Check::locationFromRange(const SourceLocation &start,
const SourceLocation &end)
{
return SourceLocation(start.offset,
end.end() - start.begin(),
start.startLine,
start.startColumn);
}
<|endoftext|>
|
<commit_before>
#ifndef __CONFIG_ARGS_H__
#define __CONFIG_ARGS_H__
#define KILOBYTE 1024L
#define MEGABYTE (KILOBYTE*1024L)
#define GIGABYTE (MEGABYTE*1024L)
#define TERABYTE (GIGABYTE*1024L)
/*!
* Version strings
*/
#define SOFTWARE_NAME_STRING "RethinkDB"
#define VERSION_STRING "0.2"
/**
* Basic configuration parameters.
* TODO: Many of these should be runtime switches.
*/
// Max concurrent IO requests per event queue
#define MAX_CONCURRENT_IO_REQUESTS 64
// Don't send more IO requests to the system until the per-thread
// queue of IO requests is higher than this depth
#define TARGET_IO_QUEUE_DEPTH 64
// Defines the maximum size of the batch of IO events to process on
// each loop iteration. A larger number will increase throughput but
// decrease concurrency
#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE 50
// Currently, each cache uses two IO accounts:
// one account for writes, and one account for reads.
// By adjusting the priorities of these accounts, reads
// can be prioritized over writes or the other way around.
//
// This is a one-per-serializer/file priority.
// The per-cache priorities are dynamically derived by dividing these priorities
// by the number of slices on a specific file.
#define CACHE_READS_IO_PRIORITY 2048
#define CACHE_WRITES_IO_PRIORITY 128
// Garbage Colletion uses its own two IO accounts.
// There is one low-priority account that is meant to guarantee
// (performance-wise) unintrusive garbage collection.
// If the garbage ratio keeps growing,
// GC starts using the high priority account instead, which
// might have a negative influence on database performance
// under i/o heavy workloads but guarantees that the database
// doesn't grow indefinitely.
//
// This is a one-per-serializer/file priority.
#define GC_IO_PRIORITY_NICE 16
#define GC_IO_PRIORITY_HIGH (2 * CACHE_WRITES_IO_PRIORITY)
// Size of the buffer used to perform IO operations (in bytes).
#define IO_BUFFER_SIZE (4 * KILOBYTE)
// Size of the device block size (in bytes)
#define DEVICE_BLOCK_SIZE (4 * KILOBYTE)
// Size of each btree node (in bytes) on disk
#define DEFAULT_BTREE_BLOCK_SIZE (4 * KILOBYTE)
// Maximum number of data blocks
#define MAX_DATA_EXTENTS (TERABYTE / (16 * KILOBYTE))
// Size of each extent (in bytes)
#define DEFAULT_EXTENT_SIZE (8 * MEGABYTE)
// Max number of blocks which can be read ahead in one i/o transaction (if enabled)
#define MAX_READ_AHEAD_BLOCKS 32
// Max size of log file name
#define MAX_LOG_FILE_NAME 1024
// Max length of log message, including terminating \0
#define MAX_LOG_MSGLEN 1024
// Queue ID of logging worker
#define LOG_WORKER 0
// Ratio of free ram to use for the cache by default
#define DEFAULT_MAX_CACHE_RATIO 0.7f
// Maximum number of threads we support
// TODO: make this dynamic where possible
#define MAX_THREADS 128
// Maximum slices total
#define MAX_SLICES 128
// Maximum number of files we use
#define MAX_SERIALIZERS 32
// The number of ways we split a BTree (the most optimal is the number
// of cores, but we use a higher split factor to allow upgrading to
// more cores without migrating the database file).
#define DEFAULT_BTREE_SHARD_FACTOR 64
// If --diff-log-size is not specified, then the patch log size will default to the
// smaller of DEFAULT_PATCH_LOG_SIZE and (DEFAULT_PATCH_LOG_FRACTION * cache size).
#ifdef NDEBUG
#define DEFAULT_PATCH_LOG_SIZE (512 * MEGABYTE)
#else
#define DEFAULT_PATCH_LOG_SIZE (4 * MEGABYTE)
#endif
#define DEFAULT_PATCH_LOG_FRACTION 0.2
// Default port to listen on
#define DEFAULT_LISTEN_PORT 11211
// Default port to do replication on
#define DEFAULT_REPLICATION_PORT 11319
#define DEFAULT_TOTAL_DELETE_QUEUE_LIMIT GIGABYTE
// Heartbeat configuration...
// The interval at which heartbeats are sent (ms)
#define REPLICATION_HEARTBEAT_INTERVAL 800 // (so we can allow a timeout of 1000 if users like it risky)
// The default timeout. This is the time after which replication
// connections get terminated, if no activity has been observed.
#define DEFAULT_REPLICATION_HEARTBEAT_TIMEOUT 10000
// Default extension for the semantic file which is appended to the database name
#define DEFAULT_SEMANTIC_EXTENSION ".semantic"
// Ticks (in milliseconds) the internal timed tasks are performed at
#define TIMER_TICKS_IN_MS 5
// How many milliseconds to allow changes to sit in memory before flushing to disk
#define DEFAULT_FLUSH_TIMER_MS 1000
// flush_waiting_threshold is the maximal number of transactions which can wait
// for a sync before a flush gets triggered on any single slice. As transactions only wait for
// sync with wait_for_flush enabled, this option plays a role only then.
#define DEFAULT_FLUSH_WAITING_THRESHOLD 8
// If wait_for_flush is true, concurrent flushing can be used to reduce the latency
// of each single flush. max_concurrent_flushes controls how many flushes can be active
// on a specific slice at any given time.
#define DEFAULT_MAX_CONCURRENT_FLUSHES 1
// If the size of the data affected by the current set of patches in a block is larger than
// block size / MAX_PATCHES_SIZE_RATIO, we flush the block instead of waiting for
// more patches to come.
// Note: An average write transaction under canonical workload leads to patches of about 75
// bytes of affected data.
// The actual value is continuously adjusted between MAX_PATCHES_SIZE_RATIO_MIN and
// MAX_PATCHES_SIZE_RATIO_MAX depending on how much the system is i/o bound
#define MAX_PATCHES_SIZE_RATIO_MIN 100
#define MAX_PATCHES_SIZE_RATIO_MAX 2
#define MAX_PATCHES_SIZE_RATIO_DURABILITY 5
#define RAISE_PATCHES_RATIO_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.6
// If more than this many bytes of dirty data accumulate in the cache, then write
// transactions will be throttled.
// A value of 0 means that it will automatically be set to MAX_UNSAVED_DATA_LIMIT_FRACTION
// times the max cache size
#define DEFAULT_UNSAVED_DATA_LIMIT 4096 * MEGABYTE
// The unsaved data limit cannot exceed this fraction of the max cache size
#define MAX_UNSAVED_DATA_LIMIT_FRACTION 0.9
// We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit
#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.2
// How many times the page replacement algorithm tries to find an eligible page before giving up.
// Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the
// page replacement algorithm will succeed on a given try, and if that probability is less than 1/2
// then the page replacement algorithm will on average be unable to evict pages from the cache.
#define PAGE_REPL_NUM_TRIES 10
// How large can the key be, in bytes? This value needs to fit in a byte.
#define MAX_KEY_SIZE 250
// Any values of this size or less will be directly stored in btree leaf nodes.
// Values greater than this size will be stored in overflow blocks. This value
// needs to fit in a byte.
#define MAX_IN_NODE_VALUE_SIZE 250
// In addition to the value itself we could potentially store
// memcached flags, exptime, and a CAS value in the value contents, so
// we reserve space for that.
#define MAX_BTREE_VALUE_AUXILIARY_SIZE (sizeof(btree_value) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint64_t))
#define MAX_BTREE_VALUE_SIZE (MAX_BTREE_VALUE_AUXILIARY_SIZE + MAX_IN_NODE_VALUE_SIZE)
// memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher
#define MAX_VALUE_SIZE 10 * MEGABYTE
// Values larger than this will be streamed in a set operation.
#define MAX_BUFFERED_SET_SIZE MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely
// Values larger than this will be streamed in a get operation
#define MAX_BUFFERED_GET_SIZE MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely
// If a single connection sends this many 'noreply' commands, the next command will
// have to wait until the first one finishes
#define MAX_CONCURRENT_QUERIES_PER_CONNECTION 500
//
#define MAX_CONCURRENT_QUEURIES_ON_IMPORT 1000
// How many timestamps we store in a leaf node. We store the
// NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.
#define NUM_LEAF_NODE_EARLIER_TIMES 2
// Perform allocator GC every N milliseconds (the resolution is limited to TIMER_TICKS_IN_MS)
#define ALLOC_GC_INTERVAL_MS 3000
//filenames for the database
#define DEFAULT_DB_FILE_NAME "rethinkdb_data"
// We assume there will never be more than this many blocks. The value
// is computed by dividing 1 TB by the smallest reasonable block size.
// This value currently fits in 32 bits, and so block_id_t and
// ser_block_id_t is a uint32_t.
#define MAX_BLOCK_ID (TERABYTE / KILOBYTE)
// We assume that there will never be more than this many blocks held in memory by the cache at
// any one time. The value is computed by dividing 50 GB by the smallest reasonable block size.
#define MAX_BLOCKS_IN_MEMORY (50 * GIGABYTE / KILOBYTE)
// Special block IDs. These don't really belong here because they're
// more magic constants than tunable parameters.
// The btree superblock, which has a reference to the root node block
// id.
#define SUPERBLOCK_ID 0
// HEY: This is kind of fragile because some patch disk storage code
// expects this value to be 1 (since the free list returns 1 the first
// time a block id is generated, or something).
#define MC_CONFIGBLOCK_ID (SUPERBLOCK_ID + 1)
// The ratio at which we should start GCing. (HEY: What's the extra
// 0.000001 in MAX_GC_HIGH_RATIO for? Is it because we told the user
// that 0.99 was too high?)
#define DEFAULT_GC_HIGH_RATIO 0.65
#define MAX_GC_HIGH_RATIO 0.990001
// The ratio at which we don't want to keep GC'ing.
#define DEFAULT_GC_LOW_RATIO 0.5
#define MIN_GC_LOW_RATIO 0.099999
// What's the maximum number of "young" extents we can have?
#define GC_YOUNG_EXTENT_MAX_SIZE 50
// What's the definition of a "young" extent in microseconds?
#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS 50000
// If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the
// entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.
#define LBA_MIN_SIZE_FOR_GC (MEGABYTE * 20)
#define LBA_MIN_UNGARBAGE_FRACTION 0.15
// How many LBA structures to have for each file
#define LBA_SHARD_FACTOR 16
// How many bytes of buffering space we can use per disk when reading the LBA. If it's set
// too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc
// doesn't return memory to the OS. If it's set too low, startup will take a longer time.
#define LBA_READ_BUFFER_SIZE GIGABYTE
// How many different places in each file we should be writing to at once, not counting the
// metablock or LBA
#define MAX_ACTIVE_DATA_EXTENTS 64
#define DEFAULT_ACTIVE_DATA_EXTENTS 1
// How many zones the serializer will divide a block device into
#define DEFAULT_FILE_ZONE_SIZE GIGABYTE
#define MAX_FILE_ZONES (TERABYTE / DEFAULT_FILE_ZONE_SIZE)
// XXX: I increased this from 65536; make sure it's actually needed.
#define COROUTINE_STACK_SIZE 131072
#define MAX_COROS_PER_THREAD 10000
// TODO: It would be nice if we didn't need MAX_HOSTNAME_LEN and
// MAX_PATH_LEN.. just because we're storing stuff in the database.
// Maximum length of a hostname we communicate with
#define MAX_HOSTNAME_LEN 100
//max length of a path that we have to store during run time
#define MAX_PATH_LEN 200
// Size of a cache line (used in cache_line_padded_t).
#define CACHE_LINE_SIZE 64
#endif // __CONFIG_ARGS_H__
<commit_msg>Change of default parameter value: heartbeat timeout is now 30s<commit_after>
#ifndef __CONFIG_ARGS_H__
#define __CONFIG_ARGS_H__
#define KILOBYTE 1024L
#define MEGABYTE (KILOBYTE*1024L)
#define GIGABYTE (MEGABYTE*1024L)
#define TERABYTE (GIGABYTE*1024L)
/*!
* Version strings
*/
#define SOFTWARE_NAME_STRING "RethinkDB"
#define VERSION_STRING "0.2"
/**
* Basic configuration parameters.
* TODO: Many of these should be runtime switches.
*/
// Max concurrent IO requests per event queue
#define MAX_CONCURRENT_IO_REQUESTS 64
// Don't send more IO requests to the system until the per-thread
// queue of IO requests is higher than this depth
#define TARGET_IO_QUEUE_DEPTH 64
// Defines the maximum size of the batch of IO events to process on
// each loop iteration. A larger number will increase throughput but
// decrease concurrency
#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE 50
// Currently, each cache uses two IO accounts:
// one account for writes, and one account for reads.
// By adjusting the priorities of these accounts, reads
// can be prioritized over writes or the other way around.
//
// This is a one-per-serializer/file priority.
// The per-cache priorities are dynamically derived by dividing these priorities
// by the number of slices on a specific file.
#define CACHE_READS_IO_PRIORITY 2048
#define CACHE_WRITES_IO_PRIORITY 128
// Garbage Colletion uses its own two IO accounts.
// There is one low-priority account that is meant to guarantee
// (performance-wise) unintrusive garbage collection.
// If the garbage ratio keeps growing,
// GC starts using the high priority account instead, which
// might have a negative influence on database performance
// under i/o heavy workloads but guarantees that the database
// doesn't grow indefinitely.
//
// This is a one-per-serializer/file priority.
#define GC_IO_PRIORITY_NICE 16
#define GC_IO_PRIORITY_HIGH (2 * CACHE_WRITES_IO_PRIORITY)
// Size of the buffer used to perform IO operations (in bytes).
#define IO_BUFFER_SIZE (4 * KILOBYTE)
// Size of the device block size (in bytes)
#define DEVICE_BLOCK_SIZE (4 * KILOBYTE)
// Size of each btree node (in bytes) on disk
#define DEFAULT_BTREE_BLOCK_SIZE (4 * KILOBYTE)
// Maximum number of data blocks
#define MAX_DATA_EXTENTS (TERABYTE / (16 * KILOBYTE))
// Size of each extent (in bytes)
#define DEFAULT_EXTENT_SIZE (8 * MEGABYTE)
// Max number of blocks which can be read ahead in one i/o transaction (if enabled)
#define MAX_READ_AHEAD_BLOCKS 32
// Max size of log file name
#define MAX_LOG_FILE_NAME 1024
// Max length of log message, including terminating \0
#define MAX_LOG_MSGLEN 1024
// Queue ID of logging worker
#define LOG_WORKER 0
// Ratio of free ram to use for the cache by default
#define DEFAULT_MAX_CACHE_RATIO 0.7f
// Maximum number of threads we support
// TODO: make this dynamic where possible
#define MAX_THREADS 128
// Maximum slices total
#define MAX_SLICES 128
// Maximum number of files we use
#define MAX_SERIALIZERS 32
// The number of ways we split a BTree (the most optimal is the number
// of cores, but we use a higher split factor to allow upgrading to
// more cores without migrating the database file).
#define DEFAULT_BTREE_SHARD_FACTOR 64
// If --diff-log-size is not specified, then the patch log size will default to the
// smaller of DEFAULT_PATCH_LOG_SIZE and (DEFAULT_PATCH_LOG_FRACTION * cache size).
#ifdef NDEBUG
#define DEFAULT_PATCH_LOG_SIZE (512 * MEGABYTE)
#else
#define DEFAULT_PATCH_LOG_SIZE (4 * MEGABYTE)
#endif
#define DEFAULT_PATCH_LOG_FRACTION 0.2
// Default port to listen on
#define DEFAULT_LISTEN_PORT 11211
// Default port to do replication on
#define DEFAULT_REPLICATION_PORT 11319
#define DEFAULT_TOTAL_DELETE_QUEUE_LIMIT GIGABYTE
// Heartbeat configuration...
// The interval at which heartbeats are sent (ms)
#define REPLICATION_HEARTBEAT_INTERVAL 800 // (so we can allow a timeout of 1000 if users like it risky)
// The default timeout. This is the time after which replication
// connections get terminated, if no activity has been observed.
#define DEFAULT_REPLICATION_HEARTBEAT_TIMEOUT 30000
// Default extension for the semantic file which is appended to the database name
#define DEFAULT_SEMANTIC_EXTENSION ".semantic"
// Ticks (in milliseconds) the internal timed tasks are performed at
#define TIMER_TICKS_IN_MS 5
// How many milliseconds to allow changes to sit in memory before flushing to disk
#define DEFAULT_FLUSH_TIMER_MS 1000
// flush_waiting_threshold is the maximal number of transactions which can wait
// for a sync before a flush gets triggered on any single slice. As transactions only wait for
// sync with wait_for_flush enabled, this option plays a role only then.
#define DEFAULT_FLUSH_WAITING_THRESHOLD 8
// If wait_for_flush is true, concurrent flushing can be used to reduce the latency
// of each single flush. max_concurrent_flushes controls how many flushes can be active
// on a specific slice at any given time.
#define DEFAULT_MAX_CONCURRENT_FLUSHES 1
// If the size of the data affected by the current set of patches in a block is larger than
// block size / MAX_PATCHES_SIZE_RATIO, we flush the block instead of waiting for
// more patches to come.
// Note: An average write transaction under canonical workload leads to patches of about 75
// bytes of affected data.
// The actual value is continuously adjusted between MAX_PATCHES_SIZE_RATIO_MIN and
// MAX_PATCHES_SIZE_RATIO_MAX depending on how much the system is i/o bound
#define MAX_PATCHES_SIZE_RATIO_MIN 100
#define MAX_PATCHES_SIZE_RATIO_MAX 2
#define MAX_PATCHES_SIZE_RATIO_DURABILITY 5
#define RAISE_PATCHES_RATIO_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.6
// If more than this many bytes of dirty data accumulate in the cache, then write
// transactions will be throttled.
// A value of 0 means that it will automatically be set to MAX_UNSAVED_DATA_LIMIT_FRACTION
// times the max cache size
#define DEFAULT_UNSAVED_DATA_LIMIT 4096 * MEGABYTE
// The unsaved data limit cannot exceed this fraction of the max cache size
#define MAX_UNSAVED_DATA_LIMIT_FRACTION 0.9
// We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit
#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.2
// How many times the page replacement algorithm tries to find an eligible page before giving up.
// Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the
// page replacement algorithm will succeed on a given try, and if that probability is less than 1/2
// then the page replacement algorithm will on average be unable to evict pages from the cache.
#define PAGE_REPL_NUM_TRIES 10
// How large can the key be, in bytes? This value needs to fit in a byte.
#define MAX_KEY_SIZE 250
// Any values of this size or less will be directly stored in btree leaf nodes.
// Values greater than this size will be stored in overflow blocks. This value
// needs to fit in a byte.
#define MAX_IN_NODE_VALUE_SIZE 250
// In addition to the value itself we could potentially store
// memcached flags, exptime, and a CAS value in the value contents, so
// we reserve space for that.
#define MAX_BTREE_VALUE_AUXILIARY_SIZE (sizeof(btree_value) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint64_t))
#define MAX_BTREE_VALUE_SIZE (MAX_BTREE_VALUE_AUXILIARY_SIZE + MAX_IN_NODE_VALUE_SIZE)
// memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher
#define MAX_VALUE_SIZE 10 * MEGABYTE
// Values larger than this will be streamed in a set operation.
#define MAX_BUFFERED_SET_SIZE MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely
// Values larger than this will be streamed in a get operation
#define MAX_BUFFERED_GET_SIZE MAX_VALUE_SIZE // streaming is too slow for now, so we disable it completely
// If a single connection sends this many 'noreply' commands, the next command will
// have to wait until the first one finishes
#define MAX_CONCURRENT_QUERIES_PER_CONNECTION 500
//
#define MAX_CONCURRENT_QUEURIES_ON_IMPORT 1000
// How many timestamps we store in a leaf node. We store the
// NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.
#define NUM_LEAF_NODE_EARLIER_TIMES 2
// Perform allocator GC every N milliseconds (the resolution is limited to TIMER_TICKS_IN_MS)
#define ALLOC_GC_INTERVAL_MS 3000
//filenames for the database
#define DEFAULT_DB_FILE_NAME "rethinkdb_data"
// We assume there will never be more than this many blocks. The value
// is computed by dividing 1 TB by the smallest reasonable block size.
// This value currently fits in 32 bits, and so block_id_t and
// ser_block_id_t is a uint32_t.
#define MAX_BLOCK_ID (TERABYTE / KILOBYTE)
// We assume that there will never be more than this many blocks held in memory by the cache at
// any one time. The value is computed by dividing 50 GB by the smallest reasonable block size.
#define MAX_BLOCKS_IN_MEMORY (50 * GIGABYTE / KILOBYTE)
// Special block IDs. These don't really belong here because they're
// more magic constants than tunable parameters.
// The btree superblock, which has a reference to the root node block
// id.
#define SUPERBLOCK_ID 0
// HEY: This is kind of fragile because some patch disk storage code
// expects this value to be 1 (since the free list returns 1 the first
// time a block id is generated, or something).
#define MC_CONFIGBLOCK_ID (SUPERBLOCK_ID + 1)
// The ratio at which we should start GCing. (HEY: What's the extra
// 0.000001 in MAX_GC_HIGH_RATIO for? Is it because we told the user
// that 0.99 was too high?)
#define DEFAULT_GC_HIGH_RATIO 0.65
#define MAX_GC_HIGH_RATIO 0.990001
// The ratio at which we don't want to keep GC'ing.
#define DEFAULT_GC_LOW_RATIO 0.5
#define MIN_GC_LOW_RATIO 0.099999
// What's the maximum number of "young" extents we can have?
#define GC_YOUNG_EXTENT_MAX_SIZE 50
// What's the definition of a "young" extent in microseconds?
#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS 50000
// If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the
// entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.
#define LBA_MIN_SIZE_FOR_GC (MEGABYTE * 20)
#define LBA_MIN_UNGARBAGE_FRACTION 0.15
// How many LBA structures to have for each file
#define LBA_SHARD_FACTOR 16
// How many bytes of buffering space we can use per disk when reading the LBA. If it's set
// too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc
// doesn't return memory to the OS. If it's set too low, startup will take a longer time.
#define LBA_READ_BUFFER_SIZE GIGABYTE
// How many different places in each file we should be writing to at once, not counting the
// metablock or LBA
#define MAX_ACTIVE_DATA_EXTENTS 64
#define DEFAULT_ACTIVE_DATA_EXTENTS 1
// How many zones the serializer will divide a block device into
#define DEFAULT_FILE_ZONE_SIZE GIGABYTE
#define MAX_FILE_ZONES (TERABYTE / DEFAULT_FILE_ZONE_SIZE)
// XXX: I increased this from 65536; make sure it's actually needed.
#define COROUTINE_STACK_SIZE 131072
#define MAX_COROS_PER_THREAD 10000
// TODO: It would be nice if we didn't need MAX_HOSTNAME_LEN and
// MAX_PATH_LEN.. just because we're storing stuff in the database.
// Maximum length of a hostname we communicate with
#define MAX_HOSTNAME_LEN 100
//max length of a path that we have to store during run time
#define MAX_PATH_LEN 200
// Size of a cache line (used in cache_line_padded_t).
#define CACHE_LINE_SIZE 64
#endif // __CONFIG_ARGS_H__
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Andrei Pangin
*
* 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 <fstream>
#include <dlfcn.h>
#include "vmEntry.h"
#include "arguments.h"
#include "profiler.h"
#include "perfEvents.h"
#include "lockTracer.h"
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti = NULL;
AsyncGetCallTrace VM::_asyncGetCallTrace;
void VM::init(JavaVM* vm, bool attach) {
if (_jvmti != NULL) return;
_vm = vm;
_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
capabilities.can_generate_monitor_events = 1;
capabilities.can_tag_objects = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.VMDeath = Profiler::VMDeath;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.CompiledMethodLoad = Profiler::CompiledMethodLoad;
callbacks.CompiledMethodUnload = Profiler::CompiledMethodUnload;
callbacks.DynamicCodeGenerated = Profiler::DynamicCodeGenerated;
callbacks.ThreadStart = PerfEvents::ThreadStart;
callbacks.ThreadEnd = PerfEvents::ThreadEnd;
callbacks.MonitorContendedEnter = LockTracer::MonitorContendedEnter;
callbacks.MonitorContendedEntered = LockTracer::MonitorContendedEntered;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
PerfEvents::init();
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(RTLD_DEFAULT, "AsyncGetCallTrace");
if (_asyncGetCallTrace == NULL) {
void* libjvm_handle = dlopen("libjvm.so", RTLD_NOW);
if (!libjvm_handle) {
std::cerr << "Failed to load libjvm.so: " << dlerror() << std::endl;
}
// try loading AsyncGetCallTrace after opening libjvm.so
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(libjvm_handle, "AsyncGetCallTrace");
}
if (attach) {
loadAllMethodIDs(_jvmti);
_jvmti->GenerateEvents(JVMTI_EVENT_DYNAMIC_CODE_GENERATED);
_jvmti->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD);
}
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) {
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
VM::init(vm, false);
Arguments args(options);
if (args.error()) {
std::cerr << args.error().message() << std::endl;
return -1;
}
Profiler::_instance.run(args);
return 0;
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
VM::init(vm, true);
Arguments args(options);
if (args.error()) {
std::cerr << args.error().message() << std::endl;
return -1;
}
Profiler::_instance.run(args);
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
VM::init(vm, true);
return JNI_VERSION_1_6;
}
<commit_msg>Document why trying to AsyncGetCallTrace from libjvm.so is needed<commit_after>/*
* Copyright 2016 Andrei Pangin
*
* 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 <fstream>
#include <dlfcn.h>
#include "vmEntry.h"
#include "arguments.h"
#include "profiler.h"
#include "perfEvents.h"
#include "lockTracer.h"
JavaVM* VM::_vm;
jvmtiEnv* VM::_jvmti = NULL;
AsyncGetCallTrace VM::_asyncGetCallTrace;
void VM::init(JavaVM* vm, bool attach) {
if (_jvmti != NULL) return;
_vm = vm;
_vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_generate_all_class_hook_events = 1;
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
capabilities.can_get_source_file_name = 1;
capabilities.can_get_line_numbers = 1;
capabilities.can_generate_compiled_method_load_events = 1;
capabilities.can_generate_monitor_events = 1;
capabilities.can_tag_objects = 1;
_jvmti->AddCapabilities(&capabilities);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = VMInit;
callbacks.VMDeath = Profiler::VMDeath;
callbacks.ClassLoad = ClassLoad;
callbacks.ClassPrepare = ClassPrepare;
callbacks.CompiledMethodLoad = Profiler::CompiledMethodLoad;
callbacks.CompiledMethodUnload = Profiler::CompiledMethodUnload;
callbacks.DynamicCodeGenerated = Profiler::DynamicCodeGenerated;
callbacks.ThreadStart = PerfEvents::ThreadStart;
callbacks.ThreadEnd = PerfEvents::ThreadEnd;
callbacks.MonitorContendedEnter = LockTracer::MonitorContendedEnter;
callbacks.MonitorContendedEntered = LockTracer::MonitorContendedEntered;
_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL);
_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL);
PerfEvents::init();
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(RTLD_DEFAULT, "AsyncGetCallTrace");
if (_asyncGetCallTrace == NULL) {
// Unable to locate AsyncGetCallTrace, it is likely that JVM has been started
// by JNI_CreateJavaVM() via dynamically loaded libjvm.so from a C/C++ program
void* libjvm_handle = dlopen("libjvm.so", RTLD_NOW);
if (!libjvm_handle) {
std::cerr << "Failed to load libjvm.so: " << dlerror() << std::endl;
}
// Try loading AGCT after opening libjvm.so
_asyncGetCallTrace = (AsyncGetCallTrace)dlsym(libjvm_handle, "AsyncGetCallTrace");
}
if (attach) {
loadAllMethodIDs(_jvmti);
_jvmti->GenerateEvents(JVMTI_EVENT_DYNAMIC_CODE_GENERATED);
_jvmti->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD);
}
}
void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) {
jint method_count;
jmethodID* methods;
if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) {
jvmti->Deallocate((unsigned char*)methods);
}
}
void VM::loadAllMethodIDs(jvmtiEnv* jvmti) {
jint class_count;
jclass* classes;
if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) {
for (int i = 0; i < class_count; i++) {
loadMethodIDs(jvmti, classes[i]);
}
jvmti->Deallocate((unsigned char*)classes);
}
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
VM::init(vm, false);
Arguments args(options);
if (args.error()) {
std::cerr << args.error().message() << std::endl;
return -1;
}
Profiler::_instance.run(args);
return 0;
}
extern "C" JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
VM::init(vm, true);
Arguments args(options);
if (args.error()) {
std::cerr << args.error().message() << std::endl;
return -1;
}
Profiler::_instance.run(args);
return 0;
}
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
VM::init(vm, true);
return JNI_VERSION_1_6;
}
<|endoftext|>
|
<commit_before>/* Copyright (C) 2005-2008 Damien Stehle.
Copyright (C) 2007 David Cade.
Copyright (C) 2011 Xavier Pujol.
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include "util.h"
#include "lll.h"
#include "wrapper.h"
FPLLL_BEGIN_NAMESPACE
/* prec=53, eta=0.501, dim < dim_double_max [ (delta / 100.0) + 25 ] */
const double dim_double_max[75]=
{0,26,29.6,28.1,31.1,32.6,34.6,34,37.7,38.8,39.6,41.8,40.9,43.6,44.2,47,46.8,
50.6,49.1,51.5,52.5,54.8,54.6,57.4,57.6,59.9,61.8,62.3,64.5,67.1,68.8,68.3,
69.9,73.1,74,76.1,76.8,80.9,81.8,83,85.3,87.9,89,90.1,89,94.6,94.8,98.7,99,
101.6,104.9,106.8,108.2,107.4,110,112.7,114.6,118.1,119.7,121.8,122.9,126.6,
128.6,129,133.6,126.9,135.9,139.5,135.2,137.2,139.3,142.8,142.4,142.5,145.4};
const double eta_dep[10]=
{1.,//0.5
1.,//0.55
1.0521,//0.6
1.1254,//0.65
1.2535,//0.7
1.3957,//0.75
1.6231,//0.8
1.8189,//0.85
2.1025,//0.9
2.5117};//0.95
Wrapper::Wrapper(IntMatrix& b, IntMatrix& u, IntMatrix& uInv,
double delta, double eta, int flags) :
status(RED_SUCCESS), b(b), u(u), uInv(uInv), delta(delta), eta(eta),
useLong(false), lastEarlyRed(0)
{
n = b.getCols();
d = b.getRows();
this->flags = flags;
maxExponent = b.getMaxExp() + (int) ceil(0.5 * log2((double) d * n));
// Computes the parameters required for the proved version
goodPrec = l2MinPrec(d, delta, eta, LLL_DEF_EPSILON);
}
bool Wrapper::little(int kappa, int precision) {
/*one may add here dimension arguments with respect to eta and delta */
int dm=(int)(delta*100.-25.);
if (dm<0) dm=0;
if (dm>74) dm=74;
int em=(int) ((eta-0.5)*20);
if (em<0) em=0;
if (em>9) em=9;
double p = max(1.0, precision / 53.0);
p *= eta_dep[em]; /* eta dependance */
p *= dim_double_max[dm];
//cerr << kappa << " compared to " << p << endl;
return kappa < p;
}
template<class Z, class F>
int Wrapper::callLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz, ZZ_mat<Z>& uInvZ,
LLLMethod method, int precision, double delta, double eta) {
typedef Z_NR<Z> ZT;
typedef FP_NR<F> FT;
if (flags & LLL_VERBOSE) {
cerr << "====== Wrapper: calling " << LLL_METHOD_STR[method] << "<"
<< numTypeStr<Z>() << "," << numTypeStr<F>() << "> method";
if (precision > 0) {
cerr << " (precision=" << precision << ")";
}
cerr << " ======" << endl;
}
int gsoFlags = 0;
if (method == LM_PROVED) gsoFlags |= GSO_INT_GRAM;
if (method == LM_FAST) gsoFlags |= GSO_ROW_EXPO;
if (method != LM_PROVED && precision == 0) gsoFlags |= GSO_OP_FORCE_LONG;
int oldprec = Float::getprec();
if (precision > 0) {
Float::setprec(precision);
}
MatGSO<ZT, FT> mGSO(bz, uz, uInvZ, gsoFlags);
LLLReduction<ZT, FT> lllObj(mGSO, delta, eta, flags);
lllObj.lastEarlyRed = lastEarlyRed;
lllObj.lll();
status = lllObj.status;
lastEarlyRed = max(lastEarlyRed, lllObj.lastEarlyRed);
if (precision > 0) {
Float::setprec(oldprec);
}
if (flags & LLL_VERBOSE) {
cerr << "====== Wrapper: end of " << LLL_METHOD_STR[method]
<< " method ======\n" << endl;
}
if (lllObj.status == RED_SUCCESS)
return 0;
else if (lllObj.status == RED_GSO_FAILURE
|| lllObj.status == RED_BABAI_FAILURE)
return lllObj.finalKappa;
else
return -1;
}
template<class F>
int Wrapper::fastLLL(double delta, double eta) {
return callLLL<mpz_t, F>(b, u, uInv, LM_FAST, 0, delta, eta);
}
template<class Z, class F>
int Wrapper::heuristicLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz,
ZZ_mat<Z>& uInvZ, int precision,
double delta, double eta) {
return callLLL<Z, F>(bz, uz, uInvZ, LM_HEURISTIC, precision, delta, eta);
}
template<class Z, class F>
int Wrapper::provedLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz,
ZZ_mat<Z>& uInvZ, int precision,
double delta, double eta) {
return callLLL<Z, F>(bz, uz, uInvZ, LM_PROVED, precision, delta, eta);
}
int Wrapper::heuristicLoop(int precision) {
int kappa;
if (precision > numeric_limits<double>::digits)
kappa = heuristicLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
else {
#ifdef FPLLL_WITH_DPE
kappa = heuristicLLL<mpz_t, dpe_t>(b, u, uInv, 0, delta, eta);
#else
kappa = heuristicLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
#endif
}
if (kappa == 0)
return 0; // Success
else if (precision < goodPrec && !little(kappa, precision))
return heuristicLoop(increasePrec(precision));
else
return provedLoop(precision);
}
int Wrapper::provedLoop(int precision) {
int kappa;
if (precision > numeric_limits<double>::digits)
kappa = provedLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
else if (maxExponent * 2 > MAX_EXP_DOUBLE) {
#ifdef FPLLL_WITH_DPE
kappa = provedLLL<mpz_t, dpe_t>(b, u, uInv, 0, delta, eta);
#else
kappa = provedLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
#endif
}
else
kappa = provedLLL<mpz_t, double>(b, u, uInv, 0, delta, eta);
if (kappa == 0)
return 0; // Success
else if (precision < goodPrec)
return provedLoop(increasePrec(precision));
else
return -1; // This point should never be reached
}
int Wrapper::lastLLL() {
#ifdef FPLLL_WITH_ZLONG
if (useLong) {
int kappa;
if (goodPrec <= numeric_limits<double>::digits)
kappa = provedLLL<long, double>(bLong, uLong, uInvLong, goodPrec, delta, eta);
else
kappa = provedLLL<long, mpfr_t>(bLong, uLong, uInvLong, goodPrec, delta, eta);
return kappa;
}
#endif
#ifdef FPLLL_WITH_DPE
if (goodPrec <= numeric_limits<double>::digits) {
return provedLLL<mpz_t, dpe_t>(b, u, uInv, goodPrec, delta, eta);
}
#endif
return provedLLL<mpz_t, mpfr_t>(b, u, uInv, goodPrec, delta, eta);
}
bool Wrapper::lll() {
if (b.getRows() == 0 || b.getCols() == 0) return RED_SUCCESS;
#ifdef FPLLL_WITH_ZLONG
bool heuristicWithLong = maxExponent < numeric_limits<long>::digits - 2
&& u.empty() && uInv.empty();
bool provedWithLong = 2 * maxExponent < numeric_limits<long>::digits - 2
&& u.empty() && uInv.empty();
#else
bool heuristicWithLong = false, provedWithLong = false;
#endif
int kappa;
if (heuristicWithLong) {
#ifdef FPLLL_WITH_ZLONG
setUseLong(true);
heuristicLLL<long, double>(bLong, uLong, uInvLong, 0, delta, eta);
#endif
}
else {
kappa = fastLLL<double>(delta, eta);
bool lllFailure = (kappa != 0);
#ifdef FPLLL_WITH_LONG_DOUBLE
if (lllFailure) {
kappa = fastLLL<long double>(delta, eta);
lllFailure = kappa != 0;
}
int lastPrec = numeric_limits<long double>::digits;
#else
int lastPrec = numeric_limits<double>::digits;
#endif
if (lllFailure) {
int precD = numeric_limits<double>::digits;
if (little(kappa, lastPrec))
kappa = provedLoop(precD);
else
kappa = heuristicLoop(increasePrec(precD));
}
}
setUseLong(provedWithLong);
kappa = lastLLL();
setUseLong(false);
return kappa == 0;
}
void Wrapper::setUseLong(bool value) {
#ifdef FPLLL_WITH_ZLONG
if (!useLong && value) {
if (bLong.empty()) {
bLong.resize(d, n);
}
for (int i = 0; i < d; i++)
for (int j = 0; j < n; j++)
bLong(i, j) = b(i, j).get_si();
}
else if (useLong && !value) {
for (int i = 0; i < d; i++)
for (int j = 0; j < n; j++)
b(i, j) = bLong(i, j).get_si();
}
useLong = value;
#endif
}
int Wrapper::increasePrec(int precision) {
return min(precision * 2, goodPrec);
}
FPLLL_END_NAMESPACE
<commit_msg>documentation for wrapper.cpp<commit_after>/* Copyright (C) 2005-2008 Damien Stehle.
Copyright (C) 2007 David Cade.
Copyright (C) 2011 Xavier Pujol.
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include "util.h"
#include "lll.h"
#include "wrapper.h"
FPLLL_BEGIN_NAMESPACE
/* prec=53, eta=0.501, dim < dim_double_max [ (delta / 100.0) + 25 ] */
const double dim_double_max[75]=
{0,26,29.6,28.1,31.1,32.6,34.6,34,37.7,38.8,39.6,41.8,40.9,43.6,44.2,47,46.8,
50.6,49.1,51.5,52.5,54.8,54.6,57.4,57.6,59.9,61.8,62.3,64.5,67.1,68.8,68.3,
69.9,73.1,74,76.1,76.8,80.9,81.8,83,85.3,87.9,89,90.1,89,94.6,94.8,98.7,99,
101.6,104.9,106.8,108.2,107.4,110,112.7,114.6,118.1,119.7,121.8,122.9,126.6,
128.6,129,133.6,126.9,135.9,139.5,135.2,137.2,139.3,142.8,142.4,142.5,145.4};
const double eta_dep[10]=
{1.,//0.5
1.,//0.55
1.0521,//0.6
1.1254,//0.65
1.2535,//0.7
1.3957,//0.75
1.6231,//0.8
1.8189,//0.85
2.1025,//0.9
2.5117};//0.95
Wrapper::Wrapper(IntMatrix& b, IntMatrix& u, IntMatrix& uInv,
double delta, double eta, int flags) :
status(RED_SUCCESS), b(b), u(u), uInv(uInv), delta(delta), eta(eta),
useLong(false), lastEarlyRed(0)
{
n = b.getCols();
d = b.getRows();
this->flags = flags;
maxExponent = b.getMaxExp() + (int) ceil(0.5 * log2((double) d * n));
// Computes the parameters required for the proved version
goodPrec = l2MinPrec(d, delta, eta, LLL_DEF_EPSILON);
}
bool Wrapper::little(int kappa, int precision) {
/*one may add here dimension arguments with respect to eta and delta */
int dm=(int)(delta*100.-25.);
if (dm<0) dm=0;
if (dm>74) dm=74;
int em=(int) ((eta-0.5)*20);
if (em<0) em=0;
if (em>9) em=9;
double p = max(1.0, precision / 53.0);
p *= eta_dep[em]; /* eta dependance */
p *= dim_double_max[dm];
//cerr << kappa << " compared to " << p << endl;
return kappa < p;
}
/**
* main function. Method determines whether heuristic, fast or proved
*/
template<class Z, class F>
int Wrapper::callLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz, ZZ_mat<Z>& uInvZ,
LLLMethod method, int precision, double delta, double eta) {
typedef Z_NR<Z> ZT;
typedef FP_NR<F> FT;
if (flags & LLL_VERBOSE) {
cerr << "====== Wrapper: calling " << LLL_METHOD_STR[method] << "<"
<< numTypeStr<Z>() << "," << numTypeStr<F>() << "> method";
if (precision > 0) {
cerr << " (precision=" << precision << ")";
}
cerr << " ======" << endl;
}
int gsoFlags = 0;
if (method == LM_PROVED) gsoFlags |= GSO_INT_GRAM;
if (method == LM_FAST) gsoFlags |= GSO_ROW_EXPO;
if (method != LM_PROVED && precision == 0) gsoFlags |= GSO_OP_FORCE_LONG;
int oldprec = Float::getprec();
if (precision > 0) {
Float::setprec(precision);
}
MatGSO<ZT, FT> mGSO(bz, uz, uInvZ, gsoFlags);
LLLReduction<ZT, FT> lllObj(mGSO, delta, eta, flags);
lllObj.lastEarlyRed = lastEarlyRed;
lllObj.lll();
status = lllObj.status;
lastEarlyRed = max(lastEarlyRed, lllObj.lastEarlyRed);
if (precision > 0) {
Float::setprec(oldprec);
}
if (flags & LLL_VERBOSE) {
cerr << "====== Wrapper: end of " << LLL_METHOD_STR[method]
<< " method ======\n" << endl;
}
if (lllObj.status == RED_SUCCESS)
return 0;
else if (lllObj.status == RED_GSO_FAILURE
|| lllObj.status == RED_BABAI_FAILURE)
return lllObj.finalKappa;
else
return -1;
}
/**
* pass the method to callLLL()
*/
template<class F>
int Wrapper::fastLLL(double delta, double eta) {
return callLLL<mpz_t, F>(b, u, uInv, LM_FAST, 0, delta, eta);
}
template<class Z, class F>
int Wrapper::heuristicLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz,
ZZ_mat<Z>& uInvZ, int precision,
double delta, double eta) {
return callLLL<Z, F>(bz, uz, uInvZ, LM_HEURISTIC, precision, delta, eta);
}
template<class Z, class F>
int Wrapper::provedLLL(ZZ_mat<Z>& bz, ZZ_mat<Z>& uz,
ZZ_mat<Z>& uInvZ, int precision,
double delta, double eta) {
return callLLL<Z, F>(bz, uz, uInvZ, LM_PROVED, precision, delta, eta);
}
/**
* In heuristicLoop(), we only use double or dpe_t or mpfr_t.
*/
int Wrapper::heuristicLoop(int precision) {
int kappa;
if (precision > numeric_limits<double>::digits)
kappa = heuristicLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
else {
#ifdef FPLLL_WITH_DPE
kappa = heuristicLLL<mpz_t, dpe_t>(b, u, uInv, 0, delta, eta);
#else
kappa = heuristicLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
#endif
}
if (kappa == 0)
return 0; // Success
else if (precision < goodPrec && !little(kappa, precision))
return heuristicLoop(increasePrec(precision));
else
return provedLoop(precision);
}
int Wrapper::provedLoop(int precision) {
int kappa;
if (precision > numeric_limits<double>::digits)
kappa = provedLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
else if (maxExponent * 2 > MAX_EXP_DOUBLE) {
#ifdef FPLLL_WITH_DPE
kappa = provedLLL<mpz_t, dpe_t>(b, u, uInv, 0, delta, eta);
#else
kappa = provedLLL<mpz_t, mpfr_t>(b, u, uInv, precision, delta, eta);
#endif
}
else
kappa = provedLLL<mpz_t, double>(b, u, uInv, 0, delta, eta);
if (kappa == 0)
return 0; // Success
else if (precision < goodPrec)
return provedLoop(increasePrec(precision));
else
return -1; // This point should never be reached
}
/**
* last call to LLL. Need to be provedLLL.
*/
int Wrapper::lastLLL() {
/* <long, FT> */
#ifdef FPLLL_WITH_ZLONG
if (useLong) {
int kappa;
if (goodPrec <= numeric_limits<double>::digits)
kappa = provedLLL<long, double>(bLong, uLong, uInvLong, goodPrec, delta, eta);
else
kappa = provedLLL<long, mpfr_t>(bLong, uLong, uInvLong, goodPrec, delta, eta);
return kappa;
}
#endif
/* <mpfr, FT> */
#ifdef FPLLL_WITH_DPE
if (goodPrec <= numeric_limits<double>::digits) {
return provedLLL<mpz_t, dpe_t>(b, u, uInv, goodPrec, delta, eta);
}
#endif
return provedLLL<mpz_t, mpfr_t>(b, u, uInv, goodPrec, delta, eta);
}
/**
* Wrapper.lll() calls
* - heuristicLLL()
* - fastLLL()
* - provedLLL()
*/
bool Wrapper::lll() {
if (b.getRows() == 0 || b.getCols() == 0)
return RED_SUCCESS;
#ifdef FPLLL_WITH_ZLONG
bool heuristicWithLong = maxExponent < numeric_limits<long>::digits - 2
&& u.empty() && uInv.empty();
bool provedWithLong = 2 * maxExponent < numeric_limits<long>::digits - 2
&& u.empty() && uInv.empty();
#else
bool heuristicWithLong = false, provedWithLong = false;
#endif
int kappa;
/* small matrix */
if (heuristicWithLong) {
#ifdef FPLLL_WITH_ZLONG
setUseLong(true);
/* try heuristicLLL <long, double> */
heuristicLLL<long, double>(bLong, uLong, uInvLong, 0, delta, eta);
#endif
}
/* large matrix */
else {
/* try fastLLL<mpz_t, double> */
kappa = fastLLL<double>(delta, eta);
bool lllFailure = (kappa != 0);
/* try fastLLL<mpz_t, long double> */
#ifdef FPLLL_WITH_LONG_DOUBLE
if (lllFailure) {
kappa = fastLLL<long double>(delta, eta);
lllFailure = kappa != 0;
}
int lastPrec = numeric_limits<long double>::digits;
#else
int lastPrec = numeric_limits<double>::digits;
#endif
/* loop */
if (lllFailure) {
int precD = numeric_limits<double>::digits;
if (little(kappa, lastPrec))
kappa = provedLoop(precD);
else
kappa = heuristicLoop(increasePrec(precD));
}
}
setUseLong(provedWithLong);
/* final LLL */
kappa = lastLLL();
setUseLong(false);
return kappa == 0;
}
/**
* set blong <-- b
*/
void Wrapper::setUseLong(bool value) {
#ifdef FPLLL_WITH_ZLONG
if (!useLong && value) {
if (bLong.empty()) {
bLong.resize(d, n);
}
for (int i = 0; i < d; i++)
for (int j = 0; j < n; j++)
bLong(i, j) = b(i, j).get_si();
}
else if (useLong && !value) {
for (int i = 0; i < d; i++)
for (int j = 0; j < n; j++)
b(i, j) = bLong(i, j).get_si();
}
useLong = value;
#endif
}
int Wrapper::increasePrec(int precision) {
return min(precision * 2, goodPrec);
}
FPLLL_END_NAMESPACE
<|endoftext|>
|
<commit_before>/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* 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 "writerappender.h"
#include "layout.h"
#include "loggingevent.h"
#if QT_VERSION < 0x060000
#include <QTextCodec>
#endif
namespace Log4Qt
{
WriterAppender::WriterAppender(QObject *parent) :
AppenderSkeleton(false, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::Utf8),
#endif
mWriter(nullptr),
mImmediateFlush(true)
{
}
WriterAppender::WriterAppender(const LayoutSharedPtr &layout,
QObject *parent) :
AppenderSkeleton(false, layout, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mWriter(nullptr),
mImmediateFlush(true)
{
}
WriterAppender::WriterAppender(const LayoutSharedPtr &layout,
QTextStream *textStream,
QObject *parent) :
AppenderSkeleton(false, layout, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mWriter(textStream),
mImmediateFlush(true)
{
}
WriterAppender::~WriterAppender()
{
closeInternal();
}
#if QT_VERSION < 0x060000
void WriterAppender::setEncoding(QTextCodec *encoding)
{
QMutexLocker locker(&mObjectGuard);
if (mEncoding == encoding)
return;
mEncoding = encoding;
if (mWriter != nullptr)
{
if (mEncoding != nullptr)
mWriter->setCodec(mEncoding);
mWriter->setCodec(QTextCodec::codecForLocale());
}
}
#else
void WriterAppender::setEncoding(QStringConverter::Encoding encoding)
{
QMutexLocker locker(&mObjectGuard);
mEncoding = encoding;
if (mWriter != nullptr)
mWriter->setEncoding(mEncoding);
}
#endif
void WriterAppender::setWriter(QTextStream *textStream)
{
QMutexLocker locker(&mObjectGuard);
closeWriter();
mWriter = textStream;
#if QT_VERSION < 0x060000
if ((mEncoding != nullptr) && (mWriter != nullptr))
mWriter->setCodec(mEncoding);
#else
if (mWriter != nullptr)
mWriter->setEncoding(mEncoding);
#endif
writeHeader();
}
void WriterAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
if (writer() == nullptr)
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires writer and has no writer set"),
APPENDER_ACTIVATE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return;
}
AppenderSkeleton::activateOptions();
}
void WriterAppender::close()
{
closeInternal();
AppenderSkeleton::close();
}
void WriterAppender::closeInternal()
{
QMutexLocker locker(&mObjectGuard);
if (isClosed())
return;
closeWriter();
}
bool WriterAppender::requiresLayout() const
{
return true;
}
void WriterAppender::append(const LoggingEvent &event)
{
Q_ASSERT_X(layout(), "WriterAppender::append()", "Layout must not be null");
QString message(layout()->format(event));
*mWriter << message;
if (handleIoErrors())
return;
if (immediateFlush())
{
mWriter->flush();
if (handleIoErrors())
return;
}
}
bool WriterAppender::checkEntryConditions() const
{
if (writer() == nullptr)
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without a writer set"),
APPENDER_USE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return false;
}
return AppenderSkeleton::checkEntryConditions();
}
void WriterAppender::closeWriter()
{
if (mWriter == nullptr)
return;
writeFooter();
mWriter = nullptr;
}
bool WriterAppender::handleIoErrors() const
{
return false;
}
void WriterAppender::writeFooter() const
{
if (!layout() || (mWriter == nullptr))
return;
QString footer = layout()->footer();
if (footer.isEmpty())
return;
*mWriter << footer << Layout::endOfLine();
if (handleIoErrors())
return;
}
void WriterAppender::writeHeader() const
{
if (!layout() || (mWriter == nullptr))
return;
QString header = layout()->header();
if (header.isEmpty())
return;
*mWriter << header << Layout::endOfLine();
if (handleIoErrors())
return;
}
} // namespace Log4Qt
#include "moc_writerappender.cpp"
<commit_msg>Fix setEncoding in WriterAppender<commit_after>/******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* 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 "writerappender.h"
#include "layout.h"
#include "loggingevent.h"
#if QT_VERSION < 0x060000
#include <QTextCodec>
#endif
namespace Log4Qt
{
WriterAppender::WriterAppender(QObject *parent) :
AppenderSkeleton(false, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::Utf8),
#endif
mWriter(nullptr),
mImmediateFlush(true)
{
}
WriterAppender::WriterAppender(const LayoutSharedPtr &layout,
QObject *parent) :
AppenderSkeleton(false, layout, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mWriter(nullptr),
mImmediateFlush(true)
{
}
WriterAppender::WriterAppender(const LayoutSharedPtr &layout,
QTextStream *textStream,
QObject *parent) :
AppenderSkeleton(false, layout, parent),
#if QT_VERSION < 0x060000
mEncoding(nullptr),
#else
mEncoding(QStringConverter::Encoding::System),
#endif
mWriter(textStream),
mImmediateFlush(true)
{
}
WriterAppender::~WriterAppender()
{
closeInternal();
}
#if QT_VERSION < 0x060000
void WriterAppender::setEncoding(QTextCodec *encoding)
#else
void WriterAppender::setEncoding(QStringConverter::Encoding encoding)
#endif
{
QMutexLocker locker(&mObjectGuard);
if (mEncoding == encoding)
return;
mEncoding = encoding;
if (mWriter != nullptr)
{
#if QT_VERSION < 0x060000
if (mEncoding != nullptr)
mWriter->setCodec(mEncoding);
#else
mWriter->setEncoding(mEncoding);
#endif
}
}
void WriterAppender::setWriter(QTextStream *textStream)
{
QMutexLocker locker(&mObjectGuard);
closeWriter();
mWriter = textStream;
#if QT_VERSION < 0x060000
if ((mEncoding != nullptr) && (mWriter != nullptr))
mWriter->setCodec(mEncoding);
#else
if (mWriter != nullptr)
mWriter->setEncoding(mEncoding);
#endif
writeHeader();
}
void WriterAppender::activateOptions()
{
QMutexLocker locker(&mObjectGuard);
if (writer() == nullptr)
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires writer and has no writer set"),
APPENDER_ACTIVATE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return;
}
AppenderSkeleton::activateOptions();
}
void WriterAppender::close()
{
closeInternal();
AppenderSkeleton::close();
}
void WriterAppender::closeInternal()
{
QMutexLocker locker(&mObjectGuard);
if (isClosed())
return;
closeWriter();
}
bool WriterAppender::requiresLayout() const
{
return true;
}
void WriterAppender::append(const LoggingEvent &event)
{
Q_ASSERT_X(layout(), "WriterAppender::append()", "Layout must not be null");
QString message(layout()->format(event));
*mWriter << message;
if (handleIoErrors())
return;
if (immediateFlush())
{
mWriter->flush();
if (handleIoErrors())
return;
}
}
bool WriterAppender::checkEntryConditions() const
{
if (writer() == nullptr)
{
LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without a writer set"),
APPENDER_USE_MISSING_WRITER_ERROR);
e << name();
logger()->error(e);
return false;
}
return AppenderSkeleton::checkEntryConditions();
}
void WriterAppender::closeWriter()
{
if (mWriter == nullptr)
return;
writeFooter();
mWriter = nullptr;
}
bool WriterAppender::handleIoErrors() const
{
return false;
}
void WriterAppender::writeFooter() const
{
if (!layout() || (mWriter == nullptr))
return;
QString footer = layout()->footer();
if (footer.isEmpty())
return;
*mWriter << footer << Layout::endOfLine();
if (handleIoErrors())
return;
}
void WriterAppender::writeHeader() const
{
if (!layout() || (mWriter == nullptr))
return;
QString header = layout()->header();
if (header.isEmpty())
return;
*mWriter << header << Layout::endOfLine();
if (handleIoErrors())
return;
}
} // namespace Log4Qt
#include "moc_writerappender.cpp"
<|endoftext|>
|
<commit_before>/*=============================================================================
Program: Visualization Toolkit
Module: vtkGeoTerrain.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=============================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkObjectFactory.h"
#include "vtkGeoCamera.h"
#include "vtkGeoTerrainGlobeSource.h"
#include "vtkGeoTerrainNode.h"
#include "vtkGeoTerrainSource.h"
#include "vtkGeoTerrain.h"
#include "vtkPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkMutexLock.h"
// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>
vtkCxxRevisionMacro(vtkGeoTerrain, "1.3");
vtkStandardNewMacro(vtkGeoTerrain);
#if _WIN32
#include "windows.h"
#endif
#include "vtkTimerLog.h"
//-----------------------------------------------------------------------------
// Cross platform sleep
inline void vtkSleep(double duration)
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep((int)(1000*duration));
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = (int)duration;
sleep_time.tv_nsec = (int)(1000000000*(duration-sleep_time.tv_sec));
nanosleep(&sleep_time,&dummy);
#endif
}
//-----------------------------------------------------------------------------
VTK_THREAD_RETURN_TYPE vtkGeoTerrainThreadStart( void *arg )
{
// int threadId = ((vtkMultiThreader::ThreadInfo *)(arg))->ThreadID;
// int threadCount = ((vtkMultiThreader::ThreadInfo *)(arg))->NumberOfThreads;
vtkGeoTerrain* self;
self = (vtkGeoTerrain*)
(((vtkMultiThreader::ThreadInfo *)(arg))->UserData);
self->ThreadStart();
return VTK_THREAD_RETURN_VALUE;
}
//----------------------------------------------------------------------------
vtkGeoTerrain::vtkGeoTerrain()
{
// It is OK to have a default,
// but the use should be able to change the .
vtkSmartPointer<vtkGeoTerrainSource> source;
source = vtkSmartPointer<vtkGeoTerrainGlobeSource>::New();
this->SetTerrainSource(source);
this->Threader = vtkSmartPointer<vtkMultiThreader>::New();
this->WaitForRequestMutex1 = vtkSmartPointer<vtkMutexLock>::New();
this->WaitForRequestMutex1->Lock();
this->TreeMutex = vtkSmartPointer<vtkMutexLock>::New();
this->TreeLock = 0;
// Spawn a thread to update the tree.
this->ThreadId = this->Threader->SpawnThread( vtkGeoTerrainThreadStart, this);
}
//-----------------------------------------------------------------------------
vtkGeoTerrain::~vtkGeoTerrain()
{
this->RequestTerminate();
this->Threader->TerminateThread(this->ThreadId);
this->ThreadId = -1;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::StartEdit()
{
this->NewNodes.clear();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::AddNode(vtkGeoTerrainNode* node)
{
this->NewNodes.push_back(node);
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::FinishEdit()
{
this->Nodes = this->NewNodes;
this->NewNodes.clear();
}
//-----------------------------------------------------------------------------
int vtkGeoTerrain::GetNumberOfNodes()
{
return static_cast<int>(this->Nodes.size());
}
//-----------------------------------------------------------------------------
vtkGeoTerrainNode* vtkGeoTerrain::GetNode(int idx)
{
return this->Nodes[idx];
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::Update(vtkGeoCamera* camera)
{
bool returnValue = this->Update(this, camera);
// I am putting the request second so that it will not block the Update.
this->Request(camera);
return returnValue;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::SetTerrainSource(vtkGeoTerrainSource* source)
{
if ( !source )
{
return;
}
this->TerrainSource = source;
this->WesternHemisphere = vtkSmartPointer<vtkGeoTerrainNode>::New();
this->EasternHemisphere = vtkSmartPointer<vtkGeoTerrainNode>::New();
this->WesternHemisphere->SetId(0);
this->EasternHemisphere->SetId(1);
// Id is a bitmap representation of the branch trace.
this->WesternHemisphere->SetLongitudeRange(-180.0,0.0);
this->WesternHemisphere->SetLatitudeRange(-90.0,90.0);
source->GenerateTerrainForNode(this->WesternHemisphere);
this->EasternHemisphere->SetLongitudeRange(0.0,180.0);
this->EasternHemisphere->SetLatitudeRange(-90.0,90.0);
source->GenerateTerrainForNode(this->EasternHemisphere);
}
//-----------------------------------------------------------------------------
// This could be done in a separate thread.
int vtkGeoTerrain::RefineNode(vtkGeoTerrainNode* node)
{
// Create the four children.
if (node->GetChild(0))
{ // This node is already refined.
return VTK_OK;
}
if (node->CreateChildren() == VTK_ERROR)
{
return VTK_ERROR;
}
this->TerrainSource->GenerateTerrainForNode(node->GetChild(0));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(1));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(2));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(3));
return VTK_OK;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::InitializeTerrain(vtkGeoTerrain* terrain)
{
terrain->StartEdit();
terrain->AddNode(this->WesternHemisphere);
terrain->AddNode(this->EasternHemisphere);
terrain->FinishEdit();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::Request(vtkGeoTerrainNode* node, vtkGeoCamera* cam)
{
int evaluation = this->EvaluateNode(node, cam);
if (evaluation > 0)
{ // refine the node. Add the 4 children.
// For simplicity, lets just refine one level per update.
if ( node->GetChild(0) == 0)
{ // Temporarily refine here. Later we will have asynchronous refinement.
this->RefineNode(node);
}
else
{
this->Request(node->GetChild(0), cam);
this->Request(node->GetChild(1), cam);
this->Request(node->GetChild(2), cam);
this->Request(node->GetChild(3), cam);
}
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ThreadStart()
{
// Use mutex to avoid a busy loop. Select on a socket will be better.
while (1)
{
// Stupid gating a thread via mutex guntlet.
this->WaitForRequestMutex1->Lock();
this->WaitForRequestMutex1->Unlock();
if (this->Camera == 0)
{ // terminate
return;
}
// Variable to manage whoe has access to reading and changing tree.
// This thread never keeps this lock for long.
// We do not want to block the client.
this->GetWriteLock();
this->Request(this->WesternHemisphere, this->Camera);
this->Request(this->EasternHemisphere, this->Camera);
this->ReleaseWriteLock();
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::Request(vtkGeoCamera* camera)
{
if (camera == 0)
{
return;
}
double t = vtkTimerLog::GetUniversalTime();
this->TreeMutex->Lock();
// If a request is already in progress. I do not want to block.
if (this->TreeLock == 0)
{ // The request thread is idle.
this->Camera = camera;
this->WaitForRequestMutex1->Unlock();
vtkSleep(0.01);
this->WaitForRequestMutex1->Lock();
}
this->TreeMutex->Unlock();
t = vtkTimerLog::GetUniversalTime() - t;
if (t > 0.1)
{
cerr << "request took : " << t << endl;
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::RequestTerminate()
{
this->Camera = 0;
this->WaitForRequestMutex1->Unlock();
vtkSleep(0.01);
this->WaitForRequestMutex1->Lock();
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::GetReadLock()
{
this->TreeMutex->Lock();
if (this->TreeLock)
{ // The background thread is writeing to the tree..
this->TreeMutex->Unlock();
return false;
}
// Keep the mutex lock until we are finished.
return true;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ReleaseReadLock()
{
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::GetWriteLock()
{
this->TreeMutex->Lock();
this->TreeLock = 1;
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ReleaseWriteLock()
{
this->TreeMutex->Lock();
this->TreeLock = 0;
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::Update(vtkGeoTerrain* terrain, vtkGeoCamera* camera)
{
vtkGeoTerrainNode* node;
bool changedFlag = false;
int maxLevel = 0;
int hackCount = 0; // Do not change too many tiles at once.
double t1 = vtkTimerLog::GetUniversalTime();
// If we cannot get a lock, we should return immediately and not wait.
// Since the cache owns the terrain tree, it is responsible
// For managing the access to the tree from multiple threads.
if (this->GetReadLock() == false)
{
return false;
}
if (terrain->GetNumberOfNodes() == 0 )
{
// The terrain always covers the entire globe. If we have no nodes,
// then we need to initialize this terrain to have the lowest two
// nodes (East and west hemisphere).
changedFlag = true;
this->InitializeTerrain(terrain);
}
// Start a new list of nodes.
terrain->StartEdit();
// Create a new list of nodes and copy/refine old list to the new list.
// The order of nodes traces a strict depth first search.
// This makes merging nodes to a lower resolution simpler.
int numInNodes = terrain->GetNumberOfNodes();
int evaluation;
int outIdx = 0;
int inIdx = 0;
while (inIdx < numInNodes)
{
node = terrain->GetNode(inIdx);
vtkGeoTerrainNode* parent = node->GetParent();
evaluation = this->EvaluateNode(node, camera);
// Just a test to even out model changes over multiple renders.
//if (hackCount > 20)
// {
// evaluation = 0;
// }
if (evaluation < 0)
{ // Do not merge the children if the parent would want to split;
// I am trying to avoid oscilations.
if (parent && this->EvaluateNode(parent, camera) > 0)
{
evaluation = 0;
}
}
// We cannot split if there are no children.
if (evaluation > 0 && node->GetChild(0) == 0)
{
evaluation = 0;
}
if (evaluation > 0)
{ // refine the node. Add the 4 children.
// For simplicity, lets just refine one level per update.
if ( node->GetChild(0) == 0)
{ // sanity check. We checked for this above.
terrain->AddNode(node);
++outIdx;
if (node->GetLevel() > maxLevel) { maxLevel = node->GetLevel();}
}
else
{
//newList[outIdx++] = node->GetChild(0);
vtkGeoTerrainNode* child;
child = node->GetChild(0);
terrain->AddNode(child);
child = node->GetChild(1);
terrain->AddNode(child);
child = node->GetChild(2);
terrain->AddNode(child);
child = node->GetChild(3);
terrain->AddNode(child);
// Just for debugging.
if (child->GetLevel() > maxLevel) { maxLevel = child->GetLevel();}
hackCount += 4;
changedFlag = true;
}
++inIdx;
}
else if (evaluation < 0 && node->GetLevel() > 0 && node->GetWhichChildAreYou() == 0)
{ // Only merge if the first child wants to.
// TODO: Change this to use the "IsDescendantOf" method.
unsigned long parentId = parent->GetId();
// Now remove all nodes until we get to a node that is not a
// decendant of the parent node.
// All decendents will have the first N bits in their Id.
unsigned long mask = ((node->GetLevel() * 2) - 1);
mask = (1 << mask) - 1;
// No need to test heritage of first child.
unsigned long tmp = parentId;
// This leaves the inIdx point to the next node so
// other paths need to increment the inIdx at their end.
while ((tmp == parentId) && inIdx < numInNodes)
{
++inIdx;
// This while structure of this loop makes termination sort of complicated.
// We can go right past the end of the list here.
if (inIdx < numInNodes)
{
node = terrain->GetNode(inIdx);
tmp = node->GetId();
tmp = tmp & mask;
}
}
// Just add the parent for all the nodes we skipped.
if (parent->GetLevel() > maxLevel) { maxLevel = parent->GetLevel();} // Just for debugging
terrain->AddNode(parent);
hackCount += 1;
++outIdx;
changedFlag = true;
}
else
{ // Just pass the node through unchanged.
//newList[outIdx++] = node;
if (node->GetLevel() > maxLevel) { maxLevel = node->GetLevel();} // Just for debugging
terrain->AddNode(node);
++inIdx;
}
}
if (changedFlag)
{
terrain->FinishEdit();
}
this->ReleaseReadLock();
t1 = vtkTimerLog::GetUniversalTime() - t1;
if (t1 > 0.1)
{
cerr << "Update took : " << t1 << endl;
}
return changedFlag;
}
//-----------------------------------------------------------------------------
// Returns 0 if there should be no change, -1 if the node resolution is too
// high, and +1 if the nodes resolution is too low.
int vtkGeoTerrain::EvaluateNode(vtkGeoTerrainNode* node, vtkGeoCamera* cam)
{
double sphereViewSize;
if (cam == 0)
{
return 0;
}
// Size of the sphere in view area units (0 -> 1)
sphereViewSize = cam->GetNodeCoverage(node);
// Arbitrary tresholds
if (sphereViewSize > 0.75)
{
return 1;
}
if (sphereViewSize < 0.2)
{
return -1;
}
// Do not change the node.
return 0;
}
<commit_msg>COMP:Fixed old-style cast warning.<commit_after>/*=============================================================================
Program: Visualization Toolkit
Module: vtkGeoTerrain.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=============================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkObjectFactory.h"
#include "vtkGeoCamera.h"
#include "vtkGeoTerrainGlobeSource.h"
#include "vtkGeoTerrainNode.h"
#include "vtkGeoTerrainSource.h"
#include "vtkGeoTerrain.h"
#include "vtkPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkMutexLock.h"
// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>
vtkCxxRevisionMacro(vtkGeoTerrain, "1.4");
vtkStandardNewMacro(vtkGeoTerrain);
#if _WIN32
#include "windows.h"
#endif
#include "vtkTimerLog.h"
//-----------------------------------------------------------------------------
// Cross platform sleep
inline void vtkSleep(double duration)
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep((int)(1000*duration));
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = static_cast<int>(duration);
sleep_time.tv_nsec = static_cast<int>(1000000000*(duration-sleep_time.tv_sec));
nanosleep(&sleep_time,&dummy);
#endif
}
//-----------------------------------------------------------------------------
VTK_THREAD_RETURN_TYPE vtkGeoTerrainThreadStart( void *arg )
{
// int threadId = ((vtkMultiThreader::ThreadInfo *)(arg))->ThreadID;
// int threadCount = ((vtkMultiThreader::ThreadInfo *)(arg))->NumberOfThreads;
vtkGeoTerrain* self;
self = static_cast<vtkGeoTerrain *>
(static_cast<vtkMultiThreader::ThreadInfo *>(arg)->UserData);
self->ThreadStart();
return VTK_THREAD_RETURN_VALUE;
}
//----------------------------------------------------------------------------
vtkGeoTerrain::vtkGeoTerrain()
{
// It is OK to have a default,
// but the use should be able to change the .
vtkSmartPointer<vtkGeoTerrainSource> source;
source = vtkSmartPointer<vtkGeoTerrainGlobeSource>::New();
this->SetTerrainSource(source);
this->Threader = vtkSmartPointer<vtkMultiThreader>::New();
this->WaitForRequestMutex1 = vtkSmartPointer<vtkMutexLock>::New();
this->WaitForRequestMutex1->Lock();
this->TreeMutex = vtkSmartPointer<vtkMutexLock>::New();
this->TreeLock = 0;
// Spawn a thread to update the tree.
this->ThreadId = this->Threader->SpawnThread( vtkGeoTerrainThreadStart, this);
}
//-----------------------------------------------------------------------------
vtkGeoTerrain::~vtkGeoTerrain()
{
this->RequestTerminate();
this->Threader->TerminateThread(this->ThreadId);
this->ThreadId = -1;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::StartEdit()
{
this->NewNodes.clear();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::AddNode(vtkGeoTerrainNode* node)
{
this->NewNodes.push_back(node);
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::FinishEdit()
{
this->Nodes = this->NewNodes;
this->NewNodes.clear();
}
//-----------------------------------------------------------------------------
int vtkGeoTerrain::GetNumberOfNodes()
{
return static_cast<int>(this->Nodes.size());
}
//-----------------------------------------------------------------------------
vtkGeoTerrainNode* vtkGeoTerrain::GetNode(int idx)
{
return this->Nodes[idx];
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::Update(vtkGeoCamera* camera)
{
bool returnValue = this->Update(this, camera);
// I am putting the request second so that it will not block the Update.
this->Request(camera);
return returnValue;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::SetTerrainSource(vtkGeoTerrainSource* source)
{
if ( !source )
{
return;
}
this->TerrainSource = source;
this->WesternHemisphere = vtkSmartPointer<vtkGeoTerrainNode>::New();
this->EasternHemisphere = vtkSmartPointer<vtkGeoTerrainNode>::New();
this->WesternHemisphere->SetId(0);
this->EasternHemisphere->SetId(1);
// Id is a bitmap representation of the branch trace.
this->WesternHemisphere->SetLongitudeRange(-180.0,0.0);
this->WesternHemisphere->SetLatitudeRange(-90.0,90.0);
source->GenerateTerrainForNode(this->WesternHemisphere);
this->EasternHemisphere->SetLongitudeRange(0.0,180.0);
this->EasternHemisphere->SetLatitudeRange(-90.0,90.0);
source->GenerateTerrainForNode(this->EasternHemisphere);
}
//-----------------------------------------------------------------------------
// This could be done in a separate thread.
int vtkGeoTerrain::RefineNode(vtkGeoTerrainNode* node)
{
// Create the four children.
if (node->GetChild(0))
{ // This node is already refined.
return VTK_OK;
}
if (node->CreateChildren() == VTK_ERROR)
{
return VTK_ERROR;
}
this->TerrainSource->GenerateTerrainForNode(node->GetChild(0));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(1));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(2));
this->TerrainSource->GenerateTerrainForNode(node->GetChild(3));
return VTK_OK;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::InitializeTerrain(vtkGeoTerrain* terrain)
{
terrain->StartEdit();
terrain->AddNode(this->WesternHemisphere);
terrain->AddNode(this->EasternHemisphere);
terrain->FinishEdit();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::Request(vtkGeoTerrainNode* node, vtkGeoCamera* cam)
{
int evaluation = this->EvaluateNode(node, cam);
if (evaluation > 0)
{ // refine the node. Add the 4 children.
// For simplicity, lets just refine one level per update.
if ( node->GetChild(0) == 0)
{ // Temporarily refine here. Later we will have asynchronous refinement.
this->RefineNode(node);
}
else
{
this->Request(node->GetChild(0), cam);
this->Request(node->GetChild(1), cam);
this->Request(node->GetChild(2), cam);
this->Request(node->GetChild(3), cam);
}
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ThreadStart()
{
// Use mutex to avoid a busy loop. Select on a socket will be better.
while (1)
{
// Stupid gating a thread via mutex guntlet.
this->WaitForRequestMutex1->Lock();
this->WaitForRequestMutex1->Unlock();
if (this->Camera == 0)
{ // terminate
return;
}
// Variable to manage whoe has access to reading and changing tree.
// This thread never keeps this lock for long.
// We do not want to block the client.
this->GetWriteLock();
this->Request(this->WesternHemisphere, this->Camera);
this->Request(this->EasternHemisphere, this->Camera);
this->ReleaseWriteLock();
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::Request(vtkGeoCamera* camera)
{
if (camera == 0)
{
return;
}
double t = vtkTimerLog::GetUniversalTime();
this->TreeMutex->Lock();
// If a request is already in progress. I do not want to block.
if (this->TreeLock == 0)
{ // The request thread is idle.
this->Camera = camera;
this->WaitForRequestMutex1->Unlock();
vtkSleep(0.01);
this->WaitForRequestMutex1->Lock();
}
this->TreeMutex->Unlock();
t = vtkTimerLog::GetUniversalTime() - t;
if (t > 0.1)
{
cerr << "request took : " << t << endl;
}
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::RequestTerminate()
{
this->Camera = 0;
this->WaitForRequestMutex1->Unlock();
vtkSleep(0.01);
this->WaitForRequestMutex1->Lock();
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::GetReadLock()
{
this->TreeMutex->Lock();
if (this->TreeLock)
{ // The background thread is writeing to the tree..
this->TreeMutex->Unlock();
return false;
}
// Keep the mutex lock until we are finished.
return true;
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ReleaseReadLock()
{
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::GetWriteLock()
{
this->TreeMutex->Lock();
this->TreeLock = 1;
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
void vtkGeoTerrain::ReleaseWriteLock()
{
this->TreeMutex->Lock();
this->TreeLock = 0;
this->TreeMutex->Unlock();
}
//-----------------------------------------------------------------------------
bool vtkGeoTerrain::Update(vtkGeoTerrain* terrain, vtkGeoCamera* camera)
{
vtkGeoTerrainNode* node;
bool changedFlag = false;
int maxLevel = 0;
int hackCount = 0; // Do not change too many tiles at once.
double t1 = vtkTimerLog::GetUniversalTime();
// If we cannot get a lock, we should return immediately and not wait.
// Since the cache owns the terrain tree, it is responsible
// For managing the access to the tree from multiple threads.
if (this->GetReadLock() == false)
{
return false;
}
if (terrain->GetNumberOfNodes() == 0 )
{
// The terrain always covers the entire globe. If we have no nodes,
// then we need to initialize this terrain to have the lowest two
// nodes (East and west hemisphere).
changedFlag = true;
this->InitializeTerrain(terrain);
}
// Start a new list of nodes.
terrain->StartEdit();
// Create a new list of nodes and copy/refine old list to the new list.
// The order of nodes traces a strict depth first search.
// This makes merging nodes to a lower resolution simpler.
int numInNodes = terrain->GetNumberOfNodes();
int evaluation;
int outIdx = 0;
int inIdx = 0;
while (inIdx < numInNodes)
{
node = terrain->GetNode(inIdx);
vtkGeoTerrainNode* parent = node->GetParent();
evaluation = this->EvaluateNode(node, camera);
// Just a test to even out model changes over multiple renders.
//if (hackCount > 20)
// {
// evaluation = 0;
// }
if (evaluation < 0)
{ // Do not merge the children if the parent would want to split;
// I am trying to avoid oscilations.
if (parent && this->EvaluateNode(parent, camera) > 0)
{
evaluation = 0;
}
}
// We cannot split if there are no children.
if (evaluation > 0 && node->GetChild(0) == 0)
{
evaluation = 0;
}
if (evaluation > 0)
{ // refine the node. Add the 4 children.
// For simplicity, lets just refine one level per update.
if ( node->GetChild(0) == 0)
{ // sanity check. We checked for this above.
terrain->AddNode(node);
++outIdx;
if (node->GetLevel() > maxLevel) { maxLevel = node->GetLevel();}
}
else
{
//newList[outIdx++] = node->GetChild(0);
vtkGeoTerrainNode* child;
child = node->GetChild(0);
terrain->AddNode(child);
child = node->GetChild(1);
terrain->AddNode(child);
child = node->GetChild(2);
terrain->AddNode(child);
child = node->GetChild(3);
terrain->AddNode(child);
// Just for debugging.
if (child->GetLevel() > maxLevel) { maxLevel = child->GetLevel();}
hackCount += 4;
changedFlag = true;
}
++inIdx;
}
else if (evaluation < 0 && node->GetLevel() > 0 && node->GetWhichChildAreYou() == 0)
{ // Only merge if the first child wants to.
// TODO: Change this to use the "IsDescendantOf" method.
unsigned long parentId = parent->GetId();
// Now remove all nodes until we get to a node that is not a
// decendant of the parent node.
// All decendents will have the first N bits in their Id.
unsigned long mask = ((node->GetLevel() * 2) - 1);
mask = (1 << mask) - 1;
// No need to test heritage of first child.
unsigned long tmp = parentId;
// This leaves the inIdx point to the next node so
// other paths need to increment the inIdx at their end.
while ((tmp == parentId) && inIdx < numInNodes)
{
++inIdx;
// This while structure of this loop makes termination sort of complicated.
// We can go right past the end of the list here.
if (inIdx < numInNodes)
{
node = terrain->GetNode(inIdx);
tmp = node->GetId();
tmp = tmp & mask;
}
}
// Just add the parent for all the nodes we skipped.
if (parent->GetLevel() > maxLevel) { maxLevel = parent->GetLevel();} // Just for debugging
terrain->AddNode(parent);
hackCount += 1;
++outIdx;
changedFlag = true;
}
else
{ // Just pass the node through unchanged.
//newList[outIdx++] = node;
if (node->GetLevel() > maxLevel) { maxLevel = node->GetLevel();} // Just for debugging
terrain->AddNode(node);
++inIdx;
}
}
if (changedFlag)
{
terrain->FinishEdit();
}
this->ReleaseReadLock();
t1 = vtkTimerLog::GetUniversalTime() - t1;
if (t1 > 0.1)
{
cerr << "Update took : " << t1 << endl;
}
return changedFlag;
}
//-----------------------------------------------------------------------------
// Returns 0 if there should be no change, -1 if the node resolution is too
// high, and +1 if the nodes resolution is too low.
int vtkGeoTerrain::EvaluateNode(vtkGeoTerrainNode* node, vtkGeoCamera* cam)
{
double sphereViewSize;
if (cam == 0)
{
return 0;
}
// Size of the sphere in view area units (0 -> 1)
sphereViewSize = cam->GetNodeCoverage(node);
// Arbitrary tresholds
if (sphereViewSize > 0.75)
{
return 1;
}
if (sphereViewSize < 0.2)
{
return -1;
}
// Do not change the node.
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cassert>
#include <map>
#include <omp.h>
#include "global_config.hpp"
namespace mocc {
/**
* The \ref Timer class provides functionality for measuring the amount of
* runtime spent on various tasks. Each \ref Timer can have a number of
* "children," which comprise sub-\ref Timer for individual tasks of
* interest.
*
* Every \ref Timer maintains a total elapsed time, which may be accessed
* via the \ref Timer::time() method. A \ref Timer can be thought of as a
* stopwatch that is started with the \ref Timer::tic() method, and stopped
* with the \ref Timer::toc() method. The elapsed time is a sum of all time
* spent between calls the \ref Timer::tic() and \ref Timer::toc().
*
* There is a global \ref RootTimer, which is treated as the parent \ref
* Timer for the entire executable.
*/
class Timer {
public:
/**
* \brief Create a new \ref Timer object.
*/
Timer(std::string name);
/**
* \brief Create a new \ref Timer object and possibly start it.
*
* \param name the name of the \ref Timer
* \param start whether or not to start the timer at construction-time.
*
* This will create a new \ref Timer and possibly start the \ref Timer
* automatically if \p start is \c true. This is useful for
* instrumenting constructor time for objects with lots of heavy lifting
* to do in their initialization list. In such cases, starting the \ref
* Timer in the body of the initializer will miss much of the time spent
* constructing the objects in the initializer list. Placing a \ref
* Timer object at the top of the initializer list will allow
* measurement of this type of code.
*/
Timer(std::string name, bool start );
/**
* \brief Start the \ref Timer
*
* This starts the \ref Timer "running," by logging the wall time at
* which the \ref tic() function was called. The timer can then be
* stopped with a call to \ref toc().
*/
void tic();
/**
* \brief Stop the \ref Timer
*
* This stops the \ref Timer and returns the amount of time that elapsed
* between the calls to \ref tic() and the \ref toc(). The running
* sum of time for the \ref Timer is also incremented by this duration.
*/
real_t toc();
/**
* \brief Return the time accumulated so far for the timer.
*
* If the timer is currently running, this will not include time since
* last call to \ref tic().
*/
real_t time() const {
return time_;
}
/**
* \brief Return a reference the child Timer of the passed name
*/
Timer &operator[]( const std::string &name ) {
return children_.at(name);
}
/**
* \brief Return a const reference the child Timer of the passed name
*/
const Timer &operator[]( const std::string &name ) const {
return children_.at(name);
}
/**
* \brief Print the entire \ref Timer tree to the provided output
* stream.
*/
void print( std::ostream &os, int level=0 ) const;
/**
* \brief Create a new child \ref Timer and return a reference to it.
*/
Timer &new_timer( const std::string &name ) {
children_.emplace( name, Timer(name) );
return children_.at(name);
}
/**
* \brief Create and return a new child \ref Timer, possibly starting it
* automatically
*/
Timer &new_timer( const std::string &name, bool start ) {
children_.emplace( name, Timer(name, start) );
return children_.at(name);
}
friend std::ostream &operator<<( std::ostream &os,
const Timer &timer );
private:
std::string name_;
real_t time_;
bool running_;
real_t wtime_;
std::map<std::string, Timer> children_;
};
extern Timer RootTimer;
}
<commit_msg>Make time() work right when Timer is running<commit_after>#pragma once
#include <cassert>
#include <map>
#include <omp.h>
#include "global_config.hpp"
namespace mocc {
/**
* The \ref Timer class provides functionality for measuring the amount of
* runtime spent on various tasks. Each \ref Timer can have a number of
* "children," which comprise sub-\ref Timer for individual tasks of
* interest.
*
* Every \ref Timer maintains a total elapsed time, which may be accessed
* via the \ref Timer::time() method. A \ref Timer can be thought of as a
* stopwatch that is started with the \ref Timer::tic() method, and stopped
* with the \ref Timer::toc() method. The elapsed time is a sum of all time
* spent between calls the \ref Timer::tic() and \ref Timer::toc().
*
* There is a global \ref RootTimer, which is treated as the parent \ref
* Timer for the entire executable.
*/
class Timer {
public:
/**
* \brief Create a new \ref Timer object.
*/
Timer(std::string name);
/**
* \brief Create a new \ref Timer object and possibly start it.
*
* \param name the name of the \ref Timer
* \param start whether or not to start the timer at construction-time.
*
* This will create a new \ref Timer and possibly start the \ref Timer
* automatically if \p start is \c true. This is useful for
* instrumenting constructor time for objects with lots of heavy lifting
* to do in their initialization list. In such cases, starting the \ref
* Timer in the body of the initializer will miss much of the time spent
* constructing the objects in the initializer list. Placing a \ref
* Timer object at the top of the initializer list will allow
* measurement of this type of code.
*/
Timer(std::string name, bool start );
/**
* \brief Start the \ref Timer
*
* This starts the \ref Timer "running," by logging the wall time at
* which the \ref tic() function was called. The timer can then be
* stopped with a call to \ref toc().
*/
void tic();
/**
* \brief Stop the \ref Timer
*
* This stops the \ref Timer and returns the amount of time that elapsed
* between the calls to \ref tic() and the \ref toc(). The running
* sum of time for the \ref Timer is also incremented by this duration.
*/
real_t toc();
/**
* \brief Return the time accumulated so far for the timer.
*
*/
real_t time() const {
if( running_ ) {
return time_ + omp_get_wtime() - wtime_;
} else {
return time_;
}
}
/**
* \brief Return a reference the child Timer of the passed name
*/
Timer &operator[]( const std::string &name ) {
return children_.at(name);
}
/**
* \brief Return a const reference the child Timer of the passed name
*/
const Timer &operator[]( const std::string &name ) const {
return children_.at(name);
}
/**
* \brief Print the entire \ref Timer tree to the provided output
* stream.
*/
void print( std::ostream &os, int level=0 ) const;
/**
* \brief Create a new child \ref Timer and return a reference to it.
*/
Timer &new_timer( const std::string &name ) {
children_.emplace( name, Timer(name) );
return children_.at(name);
}
/**
* \brief Create and return a new child \ref Timer, possibly starting it
* automatically
*/
Timer &new_timer( const std::string &name, bool start ) {
children_.emplace( name, Timer(name, start) );
return children_.at(name);
}
friend std::ostream &operator<<( std::ostream &os,
const Timer &timer );
private:
std::string name_;
real_t time_;
bool running_;
real_t wtime_;
std::map<std::string, Timer> children_;
};
extern Timer RootTimer;
}
<|endoftext|>
|
<commit_before>#include "ClassWrapper.h"
#include "JavaClassUtils.h"
#include "JavaExceptionUtils.h"
#include "JniWeakGlobalRef.h"
#include <string.h>
namespace spotify {
namespace jni {
ClassWrapper::~ClassWrapper() {
// TODO: Delete mappings
}
bool ClassWrapper::isInitialized() const {
return _clazz.get() != NULL;
}
const char* ClassWrapper::getSimpleName() const {
const char* lastSlash = strrchr(getCanonicalName(), '/');
return lastSlash != NULL ? lastSlash + 1 : getCanonicalName();
}
void ClassWrapper::merge(const ClassWrapper *globalInstance) {
_clazz = globalInstance->_clazz;
_methods = globalInstance->_methods;
_fields = globalInstance->_fields;
_constructor = globalInstance->_constructor;
}
bool ClassWrapper::persist(JNIEnv *env, jobject javaThis) {
if (isPersisted()) {
if (javaThis == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalArgumentException,
"Cannot persist object without corresponding Java instance");
return false;
}
jlong resultPtr = reinterpret_cast<jlong>(this);
env->SetLongField(javaThis, getField(PERSIST_FIELD_NAME), resultPtr);
return true;
}
return false;
}
bool ClassWrapper::isPersisted() const {
// TODO: Need test for this
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call isPersisted without class info (forgot to merge?)");
return false;
}
// We expect the persisted field to be cached, otherwise searching for persisted
// fields in non-persisted classes will throw java.lang.NoSuchField exception. :(
const std::string key(PERSIST_FIELD_NAME);
FieldMap::const_iterator mapFindIter = _fields.find(key);
return mapFindIter != _fields.end();
}
ClassWrapper* ClassWrapper::getPersistedInstance(JNIEnv *env, jobject javaThis) const {
if (isPersisted()) {
jlong resultPtr = env->GetLongField(javaThis, getField(PERSIST_FIELD_NAME));
return reinterpret_cast<ClassWrapper*>(resultPtr);
} else {
return NULL;
}
}
void ClassWrapper::destroy(JNIEnv *env, jobject javaThis) {
if (isPersisted()) {
if (javaThis == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalArgumentException,
"Cannot destroy persisted object without corresponding Java instance");
return;
}
jfieldID persistField = getField(PERSIST_FIELD_NAME);
if (persistField == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot destroy, object lacks persist field");
return;
}
jlong resultPtr = env->GetLongField(javaThis, persistField);
ClassWrapper *instance = reinterpret_cast<ClassWrapper*>(resultPtr);
if (instance != NULL) {
delete instance;
env->SetLongField(javaThis, persistField, 0);
}
}
}
void ClassWrapper::setJavaObject(JNIEnv *env, jobject javaThis) {
// Set up field mappings, if this has not already been done
if (_field_mappings.empty()) {
mapFields();
}
FieldMap::iterator iter;
for (iter = _fields.begin(); iter != _fields.end(); ++iter) {
std::string key = iter->first;
jfieldID field = iter->second;
FieldMapping *mapping = _field_mappings[key]; // TODO: Should use getter here, if not null will be inserted
if (field != NULL && mapping != NULL) {
if (TYPE_EQUALS(mapping->type, kTypeInt)) {
int *address = static_cast<int*>(mapping->address);
*address = env->GetIntField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeShort)) {
short *address = static_cast<short*>(mapping->address);
*address = env->GetShortField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeBool)) {
bool *address = static_cast<bool*>(mapping->address);
*address = env->GetBooleanField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeFloat)) {
float *address = static_cast<float*>(mapping->address);
*address = env->GetFloatField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeDouble)) {
double *address = static_cast<double*>(mapping->address);
*address = env->GetDoubleField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeString)) {
jstring string = (jstring)env->GetObjectField(javaThis, field);
JavaString *address = static_cast<JavaString*>(mapping->address);
address->setValue(env, string);
} else if (TYPE_EQUALS(mapping->type, kTypeByte)) {
unsigned char *address = static_cast<unsigned char*>(mapping->address);
*address = env->GetByteField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeChar)) {
wchar_t *address = static_cast<wchar_t*>(mapping->address);
*address = env->GetCharField(javaThis, field);
} else {
// TODO throw
}
}
}
}
jobject ClassWrapper::toJavaObject(JNIEnv *env) {
if (_constructor == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot call toJavaObject without a constructor");
return NULL;
} else if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot call toJavaObject without registering class info");
return NULL;
}
// Set up field mappings, if this has not already been done
if (_field_mappings.empty()) {
mapFields();
}
// Create a new Java argument with the default constructor
// TODO: It would be nice to remove the requirement for a no-arg ctor
// However, I'm not really sure how to do that without cluttering the interface.
// Maybe provide an extra argument to setClass()? However, then we would lack
// the corresponding arguments we'd want to pass in here.
JniWeakGlobalRef<jobject> result;
result.set(env->NewObject(_clazz.get(), _constructor));
FieldMap::iterator iter;
for (iter = _fields.begin(); iter != _fields.end(); ++iter) {
std::string key = iter->first;
jfieldID field = iter->second;
FieldMapping *mapping = getFieldMapping(key.c_str());
if (field != NULL && mapping != NULL) {
if (TYPE_EQUALS(mapping->type, kTypeInt)) {
int *address = static_cast<int*>(mapping->address);
env->SetIntField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeShort)) {
short *address = static_cast<short*>(mapping->address);
env->SetShortField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeBool)) {
bool *address = static_cast<bool*>(mapping->address);
env->SetBooleanField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeFloat)) {
float *address = static_cast<float*>(mapping->address);
env->SetFloatField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeDouble)) {
double *address = static_cast<double*>(mapping->address);
env->SetDoubleField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeString)) {
JavaString *address = static_cast<JavaString*>(mapping->address);
JniLocalRef<jstring> string = address->getJavaString(env);
env->SetObjectField(result, field, string.get());
} else if (TYPE_EQUALS(mapping->type, kTypeByte)) {
unsigned char *address = static_cast<unsigned char*>(mapping->address);
env->SetByteField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeChar)) {
wchar_t *address = static_cast<wchar_t*>(mapping->address);
env->SetCharField(result, field, *address);
} else {
// TODO throw
}
}
}
// Persist the current object address to the Java instance
persist(env, result);
return result.leak();
}
JniGlobalRef<jclass> ClassWrapper::getClass() const {
return _clazz;
}
jmethodID ClassWrapper::getMethod(const char *method_name) const {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call getMethod without class info (forgot to merge?)");
return NULL;
}
const std::string key(method_name);
MethodMap::const_iterator mapFindIter = _methods.find(key);
if (mapFindIter == _methods.end()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalArgumentException,
"Method '%s' is not cached in class '%s'", method_name, getCanonicalName());
return NULL;
}
return mapFindIter->second;
}
jfieldID ClassWrapper::getField(const char* field_name) const {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call getField without class info (forgot to merge?)");
return NULL;
}
const std::string key(field_name);
FieldMap::const_iterator mapFindIter = _fields.find(key);
if (mapFindIter == _fields.end()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalArgumentException,
"Field '%s' is not cached in class '%s'", field_name, getCanonicalName());
return NULL;
}
return mapFindIter->second;
}
void ClassWrapper::setClass(JNIEnv *env) {
_clazz.set(env->FindClass(getCanonicalName()));
JavaExceptionUtils::checkException(env);
std::string signature;
JavaClassUtils::makeSignature(signature, kTypeVoid, NULL);
_constructor = env->GetMethodID(_clazz.get(), "<init>", signature.c_str());
}
void ClassWrapper::cacheMethod(JNIEnv *env, const char* method_name, const char* return_type, ...) {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Attempt to call cacheMethod without having set class info");
return;
}
va_list arguments;
va_start(arguments, return_type);
std::string signature;
JavaClassUtils::makeSignatureWithList(signature, return_type, arguments);
va_end(arguments);
jmethodID method = env->GetMethodID(_clazz.get(), method_name, signature.c_str());
JavaExceptionUtils::checkException(env);
if (method != NULL) {
_methods[method_name] = method;
}
}
void ClassWrapper::cacheField(JNIEnv *env, const char *field_name, const char *field_type) {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Attempt to call cacheField without having set class info");
return;
}
jfieldID field = env->GetFieldID(_clazz.get(), field_name, field_type);
JavaExceptionUtils::checkException(env);
if (field != NULL) {
_fields[field_name] = field;
}
}
void ClassWrapper::mapField(const char *field_name, const char *field_type, void *field_ptr) {
FieldMapping *mapping = new FieldMapping;
mapping->type = field_type;
mapping->address = field_ptr;
_field_mappings[field_name] = mapping;
}
FieldMapping* ClassWrapper::getFieldMapping(const char *key) const {
std::string keyString(key);
std::map<std::string, FieldMapping*>::const_iterator findMapIter = _field_mappings.find(keyString);
return findMapIter != _field_mappings.end() ? findMapIter->second : NULL;
}
void ClassWrapper::addNativeMethod(const char *method_name, void *function, const char *return_type, ...) {
JNINativeMethod nativeMethod;
nativeMethod.name = const_cast<char*>(method_name);
nativeMethod.fnPtr = function;
va_list arguments;
va_start(arguments, return_type);
std::string signature;
JavaClassUtils::makeSignatureWithList(signature, return_type, arguments);
nativeMethod.signature = const_cast<char*>(strdup(signature.c_str()));
va_end(arguments);
_jni_methods.push_back(nativeMethod);
}
bool ClassWrapper::registerNativeMethods(JNIEnv *env) {
if (_jni_methods.empty()) {
return false;
}
if (!isInitialized()) {
JavaExceptionUtils::throwRuntimeException(env, "Could not find cached class for %s", getCanonicalName());
return false;
}
return (env->RegisterNatives(_clazz.get(), &_jni_methods[0], (jint)_jni_methods.size()) < 0);
}
} // namespace jni
} // namespace spotify
<commit_msg>Fix memory leak<commit_after>#include "ClassWrapper.h"
#include "JavaClassUtils.h"
#include "JavaExceptionUtils.h"
#include "JniWeakGlobalRef.h"
#include <string.h>
namespace spotify {
namespace jni {
ClassWrapper::~ClassWrapper() {
// TODO: Delete mappings
}
bool ClassWrapper::isInitialized() const {
return _clazz.get() != NULL;
}
const char* ClassWrapper::getSimpleName() const {
const char* lastSlash = strrchr(getCanonicalName(), '/');
return lastSlash != NULL ? lastSlash + 1 : getCanonicalName();
}
void ClassWrapper::merge(const ClassWrapper *globalInstance) {
_clazz = globalInstance->_clazz;
_methods = globalInstance->_methods;
_fields = globalInstance->_fields;
_constructor = globalInstance->_constructor;
}
bool ClassWrapper::persist(JNIEnv *env, jobject javaThis) {
if (isPersisted()) {
if (javaThis == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalArgumentException,
"Cannot persist object without corresponding Java instance");
return false;
}
jlong resultPtr = reinterpret_cast<jlong>(this);
env->SetLongField(javaThis, getField(PERSIST_FIELD_NAME), resultPtr);
return true;
}
return false;
}
bool ClassWrapper::isPersisted() const {
// TODO: Need test for this
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call isPersisted without class info (forgot to merge?)");
return false;
}
// We expect the persisted field to be cached, otherwise searching for persisted
// fields in non-persisted classes will throw java.lang.NoSuchField exception. :(
const std::string key(PERSIST_FIELD_NAME);
FieldMap::const_iterator mapFindIter = _fields.find(key);
return mapFindIter != _fields.end();
}
ClassWrapper* ClassWrapper::getPersistedInstance(JNIEnv *env, jobject javaThis) const {
if (isPersisted()) {
jlong resultPtr = env->GetLongField(javaThis, getField(PERSIST_FIELD_NAME));
return reinterpret_cast<ClassWrapper*>(resultPtr);
} else {
return NULL;
}
}
void ClassWrapper::destroy(JNIEnv *env, jobject javaThis) {
if (isPersisted()) {
if (javaThis == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalArgumentException,
"Cannot destroy persisted object without corresponding Java instance");
return;
}
jfieldID persistField = getField(PERSIST_FIELD_NAME);
if (persistField == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot destroy, object lacks persist field");
return;
}
jlong resultPtr = env->GetLongField(javaThis, persistField);
ClassWrapper *instance = reinterpret_cast<ClassWrapper*>(resultPtr);
if (instance != NULL) {
delete instance;
env->SetLongField(javaThis, persistField, 0);
}
}
}
void ClassWrapper::setJavaObject(JNIEnv *env, jobject javaThis) {
// Set up field mappings, if this has not already been done
if (_field_mappings.empty()) {
mapFields();
}
FieldMap::iterator iter;
for (iter = _fields.begin(); iter != _fields.end(); ++iter) {
std::string key = iter->first;
jfieldID field = iter->second;
FieldMapping *mapping = _field_mappings[key]; // TODO: Should use getter here, if not null will be inserted
if (field != NULL && mapping != NULL) {
if (TYPE_EQUALS(mapping->type, kTypeInt)) {
int *address = static_cast<int*>(mapping->address);
*address = env->GetIntField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeShort)) {
short *address = static_cast<short*>(mapping->address);
*address = env->GetShortField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeBool)) {
bool *address = static_cast<bool*>(mapping->address);
*address = env->GetBooleanField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeFloat)) {
float *address = static_cast<float*>(mapping->address);
*address = env->GetFloatField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeDouble)) {
double *address = static_cast<double*>(mapping->address);
*address = env->GetDoubleField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeString)) {
jstring string = (jstring)env->GetObjectField(javaThis, field);
JavaString *address = static_cast<JavaString*>(mapping->address);
address->setValue(env, string);
} else if (TYPE_EQUALS(mapping->type, kTypeByte)) {
unsigned char *address = static_cast<unsigned char*>(mapping->address);
*address = env->GetByteField(javaThis, field);
} else if (TYPE_EQUALS(mapping->type, kTypeChar)) {
wchar_t *address = static_cast<wchar_t*>(mapping->address);
*address = env->GetCharField(javaThis, field);
} else {
// TODO throw
}
}
}
}
jobject ClassWrapper::toJavaObject(JNIEnv *env) {
if (_constructor == NULL) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot call toJavaObject without a constructor");
return NULL;
} else if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Cannot call toJavaObject without registering class info");
return NULL;
}
// Set up field mappings, if this has not already been done
if (_field_mappings.empty()) {
mapFields();
}
// Create a new Java argument with the default constructor
// TODO: It would be nice to remove the requirement for a no-arg ctor
// However, I'm not really sure how to do that without cluttering the interface.
// Maybe provide an extra argument to setClass()? However, then we would lack
// the corresponding arguments we'd want to pass in here.
JniLocalRef<jobject> result;
result.set(env->NewObject(_clazz.get(), _constructor));
FieldMap::iterator iter;
for (iter = _fields.begin(); iter != _fields.end(); ++iter) {
std::string key = iter->first;
jfieldID field = iter->second;
FieldMapping *mapping = getFieldMapping(key.c_str());
if (field != NULL && mapping != NULL) {
if (TYPE_EQUALS(mapping->type, kTypeInt)) {
int *address = static_cast<int*>(mapping->address);
env->SetIntField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeShort)) {
short *address = static_cast<short*>(mapping->address);
env->SetShortField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeBool)) {
bool *address = static_cast<bool*>(mapping->address);
env->SetBooleanField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeFloat)) {
float *address = static_cast<float*>(mapping->address);
env->SetFloatField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeDouble)) {
double *address = static_cast<double*>(mapping->address);
env->SetDoubleField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeString)) {
JavaString *address = static_cast<JavaString*>(mapping->address);
JniLocalRef<jstring> string = address->getJavaString(env);
env->SetObjectField(result, field, string.get());
} else if (TYPE_EQUALS(mapping->type, kTypeByte)) {
unsigned char *address = static_cast<unsigned char*>(mapping->address);
env->SetByteField(result, field, *address);
} else if (TYPE_EQUALS(mapping->type, kTypeChar)) {
wchar_t *address = static_cast<wchar_t*>(mapping->address);
env->SetCharField(result, field, *address);
} else {
// TODO throw
}
}
}
// Persist the current object address to the Java instance
persist(env, result);
return result.leak();
}
JniGlobalRef<jclass> ClassWrapper::getClass() const {
return _clazz;
}
jmethodID ClassWrapper::getMethod(const char *method_name) const {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call getMethod without class info (forgot to merge?)");
return NULL;
}
const std::string key(method_name);
MethodMap::const_iterator mapFindIter = _methods.find(key);
if (mapFindIter == _methods.end()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalArgumentException,
"Method '%s' is not cached in class '%s'", method_name, getCanonicalName());
return NULL;
}
return mapFindIter->second;
}
jfieldID ClassWrapper::getField(const char* field_name) const {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalStateException,
"Cannot call getField without class info (forgot to merge?)");
return NULL;
}
const std::string key(field_name);
FieldMap::const_iterator mapFindIter = _fields.find(key);
if (mapFindIter == _fields.end()) {
JavaExceptionUtils::throwExceptionOfType(JavaThreadUtils::getEnvForCurrentThread(),
kTypeIllegalArgumentException,
"Field '%s' is not cached in class '%s'", field_name, getCanonicalName());
return NULL;
}
return mapFindIter->second;
}
void ClassWrapper::setClass(JNIEnv *env) {
_clazz.set(env->FindClass(getCanonicalName()));
JavaExceptionUtils::checkException(env);
std::string signature;
JavaClassUtils::makeSignature(signature, kTypeVoid, NULL);
_constructor = env->GetMethodID(_clazz.get(), "<init>", signature.c_str());
}
void ClassWrapper::cacheMethod(JNIEnv *env, const char* method_name, const char* return_type, ...) {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Attempt to call cacheMethod without having set class info");
return;
}
va_list arguments;
va_start(arguments, return_type);
std::string signature;
JavaClassUtils::makeSignatureWithList(signature, return_type, arguments);
va_end(arguments);
jmethodID method = env->GetMethodID(_clazz.get(), method_name, signature.c_str());
JavaExceptionUtils::checkException(env);
if (method != NULL) {
_methods[method_name] = method;
}
}
void ClassWrapper::cacheField(JNIEnv *env, const char *field_name, const char *field_type) {
if (!isInitialized()) {
JavaExceptionUtils::throwExceptionOfType(env, kTypeIllegalStateException,
"Attempt to call cacheField without having set class info");
return;
}
jfieldID field = env->GetFieldID(_clazz.get(), field_name, field_type);
JavaExceptionUtils::checkException(env);
if (field != NULL) {
_fields[field_name] = field;
}
}
void ClassWrapper::mapField(const char *field_name, const char *field_type, void *field_ptr) {
FieldMapping *mapping = new FieldMapping;
mapping->type = field_type;
mapping->address = field_ptr;
_field_mappings[field_name] = mapping;
}
FieldMapping* ClassWrapper::getFieldMapping(const char *key) const {
std::string keyString(key);
std::map<std::string, FieldMapping*>::const_iterator findMapIter = _field_mappings.find(keyString);
return findMapIter != _field_mappings.end() ? findMapIter->second : NULL;
}
void ClassWrapper::addNativeMethod(const char *method_name, void *function, const char *return_type, ...) {
JNINativeMethod nativeMethod;
nativeMethod.name = const_cast<char*>(method_name);
nativeMethod.fnPtr = function;
va_list arguments;
va_start(arguments, return_type);
std::string signature;
JavaClassUtils::makeSignatureWithList(signature, return_type, arguments);
nativeMethod.signature = const_cast<char*>(strdup(signature.c_str()));
va_end(arguments);
_jni_methods.push_back(nativeMethod);
}
bool ClassWrapper::registerNativeMethods(JNIEnv *env) {
if (_jni_methods.empty()) {
return false;
}
if (!isInitialized()) {
JavaExceptionUtils::throwRuntimeException(env, "Could not find cached class for %s", getCanonicalName());
return false;
}
return (env->RegisterNatives(_clazz.get(), &_jni_methods[0], (jint)_jni_methods.size()) < 0);
}
} // namespace jni
} // namespace spotify
<|endoftext|>
|
<commit_before>/*
This file is part of KAddressbook.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qdatetimeedit.h>
#include <qlayout.h>
#include <qobjectlist.h>
#include <qspinbox.h>
#include <qwidgetfactory.h>
#include <kdatepicker.h>
#include <kdatetimewidget.h>
#include <kdialog.h>
#include <klineedit.h>
#include <kstandarddirs.h>
#include "advancedcustomfields.h"
static void splitField( const QString&, QString&, QString&, QString& );
AdvancedCustomFields::AdvancedCustomFields( const QString &uiFile, KABC::AddressBook *ab,
QWidget *parent, const char *name )
: KAB::ContactEditorWidget( ab, parent, name )
{
initGUI( uiFile );
}
void AdvancedCustomFields::loadContact( KABC::Addressee *addr )
{
QStringList customs = addr->customs();
QStringList::ConstIterator it;
for ( it = customs.begin(); it != customs.end(); ++it ) {
QString app, name, value;
splitField( *it, app, name, value );
if ( app == "KADDRESSBOOK" ) {
QMap<QString, QWidget*>::Iterator it = mWidgets.find( name );
if ( it != mWidgets.end() ) {
if ( it.data()->isA( "QLineEdit" ) || it.data()->isA( "KLineEdit" ) ) {
QLineEdit *wdg = static_cast<QLineEdit*>( it.data() );
wdg->setText( value );
} else if ( it.data()->isA( "QSpinBox" ) ) {
QSpinBox *wdg = static_cast<QSpinBox*>( it.data() );
wdg->setValue( value.toInt() );
} else if ( it.data()->isA( "QCheckBox" ) ) {
QCheckBox *wdg = static_cast<QCheckBox*>( it.data() );
wdg->setChecked( value == "true" || value == "1" );
} else if ( it.data()->isA( "QDateTimeEdit" ) ) {
QDateTimeEdit *wdg = static_cast<QDateTimeEdit*>( it.data() );
wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "KDateTimeWidget" ) ) {
KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( it.data() );
wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "KDatePicker" ) ) {
KDatePicker *wdg = static_cast<KDatePicker*>( it.data() );
wdg->setDate( QDate::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "QComboBox" ) ) {
QComboBox *wdg = static_cast<QComboBox*>( it.data() );
wdg->setCurrentText( value );
}
}
}
}
}
void AdvancedCustomFields::storeContact( KABC::Addressee *addr )
{
QMap<QString, QWidget*>::Iterator it;
for ( it = mWidgets.begin(); it != mWidgets.end(); ++it ) {
QString value;
if ( it.data()->isA( "QLineEdit" ) || it.data()->isA( "KLineEdit" ) ) {
QLineEdit *wdg = static_cast<QLineEdit*>( it.data() );
value = wdg->text();
} else if ( it.data()->isA( "QSpinBox" ) ) {
QSpinBox *wdg = static_cast<QSpinBox*>( it.data() );
value = QString::number( wdg->value() );
} else if ( it.data()->isA( "QCheckBox" ) ) {
QCheckBox *wdg = static_cast<QCheckBox*>( it.data() );
value = ( wdg->isChecked() ? "true" : "false" );
} else if ( it.data()->isA( "QDateTimeEdit" ) ) {
QDateTimeEdit *wdg = static_cast<QDateTimeEdit*>( it.data() );
value = wdg->dateTime().toString( Qt::ISODate );
} else if ( it.data()->isA( "KDateTimeWidget" ) ) {
KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( it.data() );
value = wdg->dateTime().toString( Qt::ISODate );
} else if ( it.data()->isA( "KDatePicker" ) ) {
KDatePicker *wdg = static_cast<KDatePicker*>( it.data() );
value = wdg->date().toString( Qt::ISODate );
} else if ( it.data()->isA( "QComboBox" ) ) {
QComboBox *wdg = static_cast<QComboBox*>( it.data() );
value = wdg->currentText();
}
addr->insertCustom( "KADDRESSBOOK", it.key(), value );
}
}
void AdvancedCustomFields::setReadOnly( bool readOnly )
{
QMap<QString, QWidget*>::Iterator it;
for ( it = mWidgets.begin(); it != mWidgets.end(); ++it )
it.data()->setEnabled( !readOnly );
}
void AdvancedCustomFields::initGUI( const QString &uiFile )
{
QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
KDialog::spacingHint() );
QWidget *wdg = QWidgetFactory::create( uiFile, 0, this );
if ( !wdg ) {
kdError() << "No ui file found" << endl;
return;
}
mTitle = wdg->caption();
mIdentifier = wdg->name();
layout->addWidget( wdg );
QObjectList *list = wdg->queryList( "QWidget" );
QObjectListIt it( *list );
QStringList allowedTypes;
allowedTypes << "QLineEdit"
<< "QSpinBox"
<< "QCheckBox"
<< "QComboBox"
<< "QDateTimeEdit"
<< "KLineEdit"
<< "KDateTimeWidget"
<< "KDatePicker";
while ( it.current() ) {
if ( allowedTypes.contains( it.current()->className() ) ) {
QString name = it.current()->name();
if ( name.startsWith( "X_" ) ) {
name = name.mid( 2 );
if ( !name.isEmpty() )
mWidgets.insert( name, static_cast<QWidget*>( it.current() ) );
if ( it.current()->isA( "QLineEdit" ) ||
it.current()->isA( "KLineEdit" ) )
connect( it.current(), SIGNAL( textChanged( const QString& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QSpinBox" ) )
connect( it.current(), SIGNAL( valueChanged( int ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QCheckBox" ) )
connect( it.current(), SIGNAL( toggled( bool ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QComboBox" ) )
connect( it.current(), SIGNAL( activated( const QString& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QDateTimeEdit" ) )
connect( it.current(), SIGNAL( valueChanged( const QDateTime& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "KDateTimeWidget" ) )
connect( it.current(), SIGNAL( valueChanged( const QDateTime& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "KDatePicker" ) )
connect( it.current(), SIGNAL( dateChanged( QDate ) ),
this, SIGNAL( changed() ) );
}
}
++it;
}
}
QString AdvancedCustomFields::pageIdentifier() const
{
return mIdentifier;
}
QString AdvancedCustomFields::pageTitle() const
{
return mTitle;
}
static void splitField( const QString &str, QString &app, QString &name, QString &value )
{
int colon = str.find( ':' );
if ( colon != -1 ) {
QString tmp = str.left( colon );
value = str.mid( colon + 1 );
int dash = tmp.find( '-' );
if ( dash != -1 ) {
app = tmp.left( dash );
name = tmp.mid( dash + 1 );
}
}
}
#include "advancedcustomfields.moc"
<commit_msg>Remove an rmpty item from the address book<commit_after>/*
This file is part of KAddressbook.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qdatetimeedit.h>
#include <qlayout.h>
#include <qobjectlist.h>
#include <qspinbox.h>
#include <qwidgetfactory.h>
#include <kdatepicker.h>
#include <kdatetimewidget.h>
#include <kdialog.h>
#include <klineedit.h>
#include <kstandarddirs.h>
#include "advancedcustomfields.h"
static void splitField( const QString&, QString&, QString&, QString& );
AdvancedCustomFields::AdvancedCustomFields( const QString &uiFile, KABC::AddressBook *ab,
QWidget *parent, const char *name )
: KAB::ContactEditorWidget( ab, parent, name )
{
initGUI( uiFile );
}
void AdvancedCustomFields::loadContact( KABC::Addressee *addr )
{
QStringList customs = addr->customs();
QStringList::ConstIterator it;
for ( it = customs.begin(); it != customs.end(); ++it ) {
QString app, name, value;
splitField( *it, app, name, value );
if ( app == "KADDRESSBOOK" ) {
QMap<QString, QWidget*>::Iterator it = mWidgets.find( name );
if ( it != mWidgets.end() ) {
if ( it.data()->isA( "QLineEdit" ) || it.data()->isA( "KLineEdit" ) ) {
QLineEdit *wdg = static_cast<QLineEdit*>( it.data() );
wdg->setText( value );
} else if ( it.data()->isA( "QSpinBox" ) ) {
QSpinBox *wdg = static_cast<QSpinBox*>( it.data() );
wdg->setValue( value.toInt() );
} else if ( it.data()->isA( "QCheckBox" ) ) {
QCheckBox *wdg = static_cast<QCheckBox*>( it.data() );
wdg->setChecked( value == "true" || value == "1" );
} else if ( it.data()->isA( "QDateTimeEdit" ) ) {
QDateTimeEdit *wdg = static_cast<QDateTimeEdit*>( it.data() );
wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "KDateTimeWidget" ) ) {
KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( it.data() );
wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "KDatePicker" ) ) {
KDatePicker *wdg = static_cast<KDatePicker*>( it.data() );
wdg->setDate( QDate::fromString( value, Qt::ISODate ) );
} else if ( it.data()->isA( "QComboBox" ) ) {
QComboBox *wdg = static_cast<QComboBox*>( it.data() );
wdg->setCurrentText( value );
}
}
}
}
}
void AdvancedCustomFields::storeContact( KABC::Addressee *addr )
{
QMap<QString, QWidget*>::Iterator it;
for ( it = mWidgets.begin(); it != mWidgets.end(); ++it ) {
QString value;
if ( it.data()->isA( "QLineEdit" ) || it.data()->isA( "KLineEdit" ) ) {
QLineEdit *wdg = static_cast<QLineEdit*>( it.data() );
value = wdg->text();
} else if ( it.data()->isA( "QSpinBox" ) ) {
QSpinBox *wdg = static_cast<QSpinBox*>( it.data() );
value = QString::number( wdg->value() );
} else if ( it.data()->isA( "QCheckBox" ) ) {
QCheckBox *wdg = static_cast<QCheckBox*>( it.data() );
value = ( wdg->isChecked() ? "true" : "false" );
} else if ( it.data()->isA( "QDateTimeEdit" ) ) {
QDateTimeEdit *wdg = static_cast<QDateTimeEdit*>( it.data() );
value = wdg->dateTime().toString( Qt::ISODate );
} else if ( it.data()->isA( "KDateTimeWidget" ) ) {
KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( it.data() );
value = wdg->dateTime().toString( Qt::ISODate );
} else if ( it.data()->isA( "KDatePicker" ) ) {
KDatePicker *wdg = static_cast<KDatePicker*>( it.data() );
value = wdg->date().toString( Qt::ISODate );
} else if ( it.data()->isA( "QComboBox" ) ) {
QComboBox *wdg = static_cast<QComboBox*>( it.data() );
value = wdg->currentText();
}
if ( value.isEmpty() )
addr->removeCustom( "KADDRESSBOOK", it.key() );
else
addr->insertCustom( "KADDRESSBOOK", it.key(), value );
}
}
void AdvancedCustomFields::setReadOnly( bool readOnly )
{
QMap<QString, QWidget*>::Iterator it;
for ( it = mWidgets.begin(); it != mWidgets.end(); ++it )
it.data()->setEnabled( !readOnly );
}
void AdvancedCustomFields::initGUI( const QString &uiFile )
{
QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
KDialog::spacingHint() );
QWidget *wdg = QWidgetFactory::create( uiFile, 0, this );
if ( !wdg ) {
kdError() << "No ui file found" << endl;
return;
}
mTitle = wdg->caption();
mIdentifier = wdg->name();
layout->addWidget( wdg );
QObjectList *list = wdg->queryList( "QWidget" );
QObjectListIt it( *list );
QStringList allowedTypes;
allowedTypes << "QLineEdit"
<< "QSpinBox"
<< "QCheckBox"
<< "QComboBox"
<< "QDateTimeEdit"
<< "KLineEdit"
<< "KDateTimeWidget"
<< "KDatePicker";
while ( it.current() ) {
if ( allowedTypes.contains( it.current()->className() ) ) {
QString name = it.current()->name();
if ( name.startsWith( "X_" ) ) {
name = name.mid( 2 );
if ( !name.isEmpty() )
mWidgets.insert( name, static_cast<QWidget*>( it.current() ) );
if ( it.current()->isA( "QLineEdit" ) ||
it.current()->isA( "KLineEdit" ) )
connect( it.current(), SIGNAL( textChanged( const QString& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QSpinBox" ) )
connect( it.current(), SIGNAL( valueChanged( int ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QCheckBox" ) )
connect( it.current(), SIGNAL( toggled( bool ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QComboBox" ) )
connect( it.current(), SIGNAL( activated( const QString& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "QDateTimeEdit" ) )
connect( it.current(), SIGNAL( valueChanged( const QDateTime& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "KDateTimeWidget" ) )
connect( it.current(), SIGNAL( valueChanged( const QDateTime& ) ),
this, SIGNAL( changed() ) );
else if ( it.current()->isA( "KDatePicker" ) )
connect( it.current(), SIGNAL( dateChanged( QDate ) ),
this, SIGNAL( changed() ) );
}
}
++it;
}
}
QString AdvancedCustomFields::pageIdentifier() const
{
return mIdentifier;
}
QString AdvancedCustomFields::pageTitle() const
{
return mTitle;
}
static void splitField( const QString &str, QString &app, QString &name, QString &value )
{
int colon = str.find( ':' );
if ( colon != -1 ) {
QString tmp = str.left( colon );
value = str.mid( colon + 1 );
int dash = tmp.find( '-' );
if ( dash != -1 ) {
app = tmp.left( dash );
name = tmp.mid( dash + 1 );
}
}
}
#include "advancedcustomfields.moc"
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: NeighborhoodIterators6.cxx,v $
Language: C++
Date: $Date: 2005/02/08 03:59:00 $
Version: $Revision: 1.18 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkNeighborhoodIterator.h"
#include "itkFastMarchingImageFilter.h"
#include "itkNumericTraits.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6a.png}
// 100 100
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6b.png}
// 50 150
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6c.png}
// 150 50
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Some image processing routines do not need to visit every pixel in an
// image. Flood-fill and connected-component algorithms, for example, only
// visit pixels that are locally connected to one another. Algorithms
// such as these can be efficiently written using the random access
// capabilities of the neighborhood iterator.
//
// The following example finds local minima. Given a seed point, we can search
// the neighborhood of that point and pick the smallest value $m$. While $m$
// is not at the center of our current neighborhood, we move in the direction
// of $m$ and repeat the analysis. Eventually we discover a local minimum and
// stop. This algorithm is made trivially simple in ND using an ITK
// neighborhood iterator.
//
// To illustrate the process, we create an image that descends everywhere to a
// single minimum: a positive distance transform to a point. The details of
// creating the distance transform are not relevant to the discussion of
// neighborhood iterators, but can be found in the source code of this
// example. Some noise has been added to the distance transform image for
// additional interest.
//
// Software Guide : EndLatex
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " outputImageFile startX startY"
<< std::endl;
return -1;
}
typedef double PixelType;
typedef otb::Image< PixelType, 2 > ImageType;
typedef itk::NeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::FastMarchingImageFilter<ImageType, ImageType> FastMarchingFilterType;
FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New();
typedef FastMarchingFilterType::NodeContainer NodeContainer;
typedef FastMarchingFilterType::NodeType NodeType;
NodeContainer::Pointer seeds = NodeContainer::New();
ImageType::IndexType seedPosition;
seedPosition[0] = 128;
seedPosition[1] = 128;
const double initialDistance = 1.0;
NodeType node;
const double seedValue = - initialDistance;
ImageType::SizeType size = {{256, 256}};
node.SetValue( seedValue );
node.SetIndex( seedPosition );
seeds->Initialize();
seeds->InsertElement( 0, node );
fastMarching->SetTrialPoints( seeds );
fastMarching->SetSpeedConstant( 1.0 );
itk::AddImageFilter<ImageType, ImageType, ImageType>::Pointer adder
= itk::AddImageFilter<ImageType, ImageType, ImageType>::New();
itk::RandomImageSource<ImageType>::Pointer noise
= itk::RandomImageSource<ImageType>::New();
noise->SetSize(size.m_Size);
noise->SetMin(-.7);
noise->SetMax(.8);
adder->SetInput1(noise->GetOutput());
adder->SetInput2(fastMarching->GetOutput());
try
{
fastMarching->SetOutputSize( size );
fastMarching->Update();
adder->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
ImageType::Pointer input = adder->GetOutput();
// Software Guide : BeginLatex
//
// The variable \code{input} is the pointer to the distance transform image.
// The local minimum algorithm is initialized with a seed point read from the
// command line.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType index;
index[0] = ::atoi(argv[2]);
index[1] = ::atoi(argv[3]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Next we create the neighborhood iterator and position it at the seed point.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighborhoodIteratorType::RadiusType radius;
radius.Fill(1);
NeighborhoodIteratorType it(radius, input, input->GetRequestedRegion());
it.SetLocation(index);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Searching for the local minimum involves finding the minimum in the current
// neighborhood, then shifting the neighborhood in the direction of that
// minimum. The \code{for} loop below records the \doxygen{itk}{Offset} of the
// minimum neighborhood pixel. The neighborhood iterator is then moved using
// that offset. When a local minimum is detected, \code{flag} will remain
// false and the \code{while} loop will exit. Note that this code is
// valid for an image of any dimensionality.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
bool flag = true;
while ( flag == true )
{
NeighborhoodIteratorType::OffsetType nextMove;
nextMove.Fill(0);
flag = false;
PixelType min = it.GetCenterPixel();
for (unsigned i = 0; i < it.Size(); i++)
{
if ( it.GetPixel(i) < min )
{
min = it.GetPixel(i);
nextMove = it.GetOffset(i);
flag = true;
}
}
it.SetCenterPixel( 255.0 );
it += nextMove;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:NeighborhoodExample6} shows the results of the algorithm
// for several seed points. The white line is the path of the iterator from
// the seed point to the minimum in the center of the image. The effect of the
// additive noise is visible as the small perturbations in the paths.
//
// \begin{figure} \centering
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6a.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6b.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6c.eps}
// \itkcaption[Finding local minima]{Paths traversed by the neighborhood
// iterator from different seed points to the local minimum.
// The true minimum is at the center
// of the image. The path of the iterator is shown in white. The effect of
// noise in the image is seen as small perturbations in each path. }
// \protect\label{fig:NeighborhoodExample6} \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef otb::Image< WritePixelType, 2 > WriteImageType;
typedef otb::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ImageType,
WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput( input );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return 0;
}
<commit_msg>float ou double-> juste un pixel<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: NeighborhoodIterators6.cxx,v $
Language: C++
Date: $Date: 2005/02/08 03:59:00 $
Version: $Revision: 1.18 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkNeighborhoodIterator.h"
#include "itkFastMarchingImageFilter.h"
#include "itkNumericTraits.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6a.png}
// 100 100
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6b.png}
// 50 150
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6c.png}
// 150 50
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Some image processing routines do not need to visit every pixel in an
// image. Flood-fill and connected-component algorithms, for example, only
// visit pixels that are locally connected to one another. Algorithms
// such as these can be efficiently written using the random access
// capabilities of the neighborhood iterator.
//
// The following example finds local minima. Given a seed point, we can search
// the neighborhood of that point and pick the smallest value $m$. While $m$
// is not at the center of our current neighborhood, we move in the direction
// of $m$ and repeat the analysis. Eventually we discover a local minimum and
// stop. This algorithm is made trivially simple in ND using an ITK
// neighborhood iterator.
//
// To illustrate the process, we create an image that descends everywhere to a
// single minimum: a positive distance transform to a point. The details of
// creating the distance transform are not relevant to the discussion of
// neighborhood iterators, but can be found in the source code of this
// example. Some noise has been added to the distance transform image for
// additional interest.
//
// Software Guide : EndLatex
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " outputImageFile startX startY"
<< std::endl;
return -1;
}
typedef float PixelType;
typedef otb::Image< PixelType, 2 > ImageType;
typedef itk::NeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::FastMarchingImageFilter<ImageType, ImageType> FastMarchingFilterType;
FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New();
typedef FastMarchingFilterType::NodeContainer NodeContainer;
typedef FastMarchingFilterType::NodeType NodeType;
NodeContainer::Pointer seeds = NodeContainer::New();
ImageType::IndexType seedPosition;
seedPosition[0] = 128;
seedPosition[1] = 128;
const double initialDistance = 1.0;
NodeType node;
const double seedValue = - initialDistance;
ImageType::SizeType size = {{256, 256}};
node.SetValue( seedValue );
node.SetIndex( seedPosition );
seeds->Initialize();
seeds->InsertElement( 0, node );
fastMarching->SetTrialPoints( seeds );
fastMarching->SetSpeedConstant( 1.0 );
itk::AddImageFilter<ImageType, ImageType, ImageType>::Pointer adder
= itk::AddImageFilter<ImageType, ImageType, ImageType>::New();
itk::RandomImageSource<ImageType>::Pointer noise
= itk::RandomImageSource<ImageType>::New();
noise->SetSize(size.m_Size);
noise->SetMin(-.7);
noise->SetMax(.8);
adder->SetInput1(noise->GetOutput());
adder->SetInput2(fastMarching->GetOutput());
try
{
fastMarching->SetOutputSize( size );
fastMarching->Update();
adder->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
ImageType::Pointer input = adder->GetOutput();
// Software Guide : BeginLatex
//
// The variable \code{input} is the pointer to the distance transform image.
// The local minimum algorithm is initialized with a seed point read from the
// command line.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType index;
index[0] = ::atoi(argv[2]);
index[1] = ::atoi(argv[3]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Next we create the neighborhood iterator and position it at the seed point.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighborhoodIteratorType::RadiusType radius;
radius.Fill(1);
NeighborhoodIteratorType it(radius, input, input->GetRequestedRegion());
it.SetLocation(index);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Searching for the local minimum involves finding the minimum in the current
// neighborhood, then shifting the neighborhood in the direction of that
// minimum. The \code{for} loop below records the \doxygen{itk}{Offset} of the
// minimum neighborhood pixel. The neighborhood iterator is then moved using
// that offset. When a local minimum is detected, \code{flag} will remain
// false and the \code{while} loop will exit. Note that this code is
// valid for an image of any dimensionality.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
bool flag = true;
while ( flag == true )
{
NeighborhoodIteratorType::OffsetType nextMove;
nextMove.Fill(0);
flag = false;
PixelType min = it.GetCenterPixel();
for (unsigned i = 0; i < it.Size(); i++)
{
if ( it.GetPixel(i) < min )
{
min = it.GetPixel(i);
nextMove = it.GetOffset(i);
flag = true;
}
}
it.SetCenterPixel( 255.0 );
it += nextMove;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:NeighborhoodExample6} shows the results of the algorithm
// for several seed points. The white line is the path of the iterator from
// the seed point to the minimum in the center of the image. The effect of the
// additive noise is visible as the small perturbations in the paths.
//
// \begin{figure} \centering
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6a.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6b.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6c.eps}
// \itkcaption[Finding local minima]{Paths traversed by the neighborhood
// iterator from different seed points to the local minimum.
// The true minimum is at the center
// of the image. The path of the iterator is shown in white. The effect of
// noise in the image is seen as small perturbations in each path. }
// \protect\label{fig:NeighborhoodExample6} \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef otb::Image< WritePixelType, 2 > WriteImageType;
typedef otb::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ImageType,
WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput( input );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>// FeatureExtractionCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HaemoragingImage.hpp"
#include "HistogramNormalize.hpp"
const char* keys =
{
"{1||| must specify reference image name}"
"{2||| must specify image name}"
};
Mat src, src_gray, reference;
RNG rng(12345);
string sourceWindow("Source");
ParamBag params;
unique_ptr<HaemoragingImage> haemorage(new HaemoragingImage);
vector<vector<Point>> * FindHaemorages(unique_ptr<HaemoragingImage>&, Mat&, ParamBag&);
void thresh_callback(int, void *)
{
unique_ptr<vector<vector<Point>>> contours(FindHaemorages(haemorage, src, params));
Mat img;
src.copyTo(img);
TransformImage::DrawContours(*contours, vector<Vec4i>(), img);
/// Draw contours
/// Show in a window
imshow(sourceWindow, img);
}
int main(int argc, char** argv)
{
CommandLineParser parser(argc, argv, keys);
string ref_file_name = parser.get<string>("1");
string file_name = parser.get<string>("2");
gpu::printCudaDeviceInfo(0);
Mat rgb;
rgb = imread(file_name, IMREAD_COLOR);
auto hi = HaemoragingImage(rgb);
hi.PyramidDown();
Mat src = hi.getEnhanced();
rgb = imread(ref_file_name, IMREAD_COLOR);
auto ref_image = HaemoragingImage(rgb);
ref_image.PyramidDown();
reference = ref_image.getEnhanced();
Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE};
vector<Channels> channels(_channels, _channels + 3);
auto histSpec = HistogramNormalize(reference, channels);
Mat dest;
histSpec.HistogramSpecification(src, dest);
namedWindow(sourceWindow, WINDOW_NORMAL);
imshow(sourceWindow, dest);
//params.cannyThresh = 30;
//createTrackbar("Track", sourceWindow, &(params.cannyThresh), 100, thresh_callback);
//thresh_callback(0, &(params.cannyThresh));
//ref_image.DisplayEnhanced(true);
waitKey(0);
return(0);
}
<commit_msg>cleanup<commit_after>// FeatureExtractionCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HaemoragingImage.hpp"
#include "HistogramNormalize.hpp"
const char* keys =
{
"{1||| must specify reference image name}"
"{2||| must specify image name}"
};
Mat src, src_gray, reference;
RNG rng(12345);
string sourceWindow("Source");
string targetWindow("Target");
string transformedWindow("Transformed");
ParamBag params;
unique_ptr<HaemoragingImage> haemorage(new HaemoragingImage);
vector<vector<Point>> * FindHaemorages(unique_ptr<HaemoragingImage>&, Mat&, ParamBag&);
void thresh_callback(int, void *)
{
unique_ptr<vector<vector<Point>>> contours(FindHaemorages(haemorage, src, params));
Mat img;
src.copyTo(img);
TransformImage::DrawContours(*contours, vector<Vec4i>(), img);
/// Draw contours
/// Show in a window
imshow(sourceWindow, img);
}
int main(int argc, char** argv)
{
CommandLineParser parser(argc, argv, keys);
string ref_file_name = parser.get<string>("1");
string file_name = parser.get<string>("2");
gpu::printCudaDeviceInfo(0);
Mat rgb;
rgb = imread(file_name, IMREAD_COLOR);
auto hi = HaemoragingImage(rgb);
hi.PyramidDown();
src = hi.getEnhanced();
rgb = imread(ref_file_name, IMREAD_COLOR);
auto ref_image = HaemoragingImage(rgb);
ref_image.PyramidDown();
reference = ref_image.getEnhanced();
Channels _channels[3] = { Channels::RED, Channels::GREEN, Channels::BLUE};
vector<Channels> channels(_channels, _channels + 3);
auto histSpec = HistogramNormalize(reference, channels);
Mat dest;
histSpec.HistogramSpecification(src, dest);
namedWindow(sourceWindow, WINDOW_NORMAL);
namedWindow(targetWindow, WINDOW_NORMAL);
namedWindow(transformedWindow, WINDOW_NORMAL);
imshow(sourceWindow, reference);
imshow(targetWindow, src);
imshow(transformedWindow, dest);
//params.cannyThresh = 30;
//createTrackbar("Track", sourceWindow, &(params.cannyThresh), 100, thresh_callback);
//thresh_callback(0, &(params.cannyThresh));
//ref_image.DisplayEnhanced(true);
waitKey(0);
return(0);
}
<|endoftext|>
|
<commit_before>/*
* Check the bulldog-tyke status directory.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "bulldog.hxx"
#include "net/SocketAddress.hxx"
#include <daemon/log.h>
#include <socket/address.h>
#include <glib.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define WORKERS "/workers/"
static struct {
char path[4096];
size_t path_length;
} bulldog;
void
bulldog_init(const char *path)
{
if (path == nullptr)
return;
if (strlen(path) + sizeof(WORKERS) + 16 >= sizeof(bulldog.path)) {
daemon_log(1, "bulldog path is too long\n");
return;
}
strcpy(bulldog.path, path);
strcat(bulldog.path, WORKERS);
bulldog.path_length = strlen(bulldog.path);
}
void
bulldog_deinit()
{
}
gcc_pure
static const char *
bulldog_node_path(SocketAddress address,
const char *attribute_name)
{
assert(!address.IsNull());
assert(attribute_name != nullptr);
assert(*attribute_name != 0);
if (bulldog.path[0] == 0)
/* disabled */
return nullptr;
if (!socket_address_to_string(bulldog.path + bulldog.path_length,
sizeof(bulldog.path) - bulldog.path_length,
address.GetAddress(), address.GetSize()))
return nullptr;
g_strlcat(bulldog.path, "/", sizeof(bulldog.path));
g_strlcat(bulldog.path, attribute_name, sizeof(bulldog.path));
return bulldog.path;
}
gcc_pure
static const char *
read_first_line(const char *path, char *buffer, size_t buffer_size)
{
assert(path != nullptr);
assert(buffer != nullptr);
assert(buffer_size > 0);
int fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return nullptr;
ssize_t nbytes = read(fd, buffer, buffer_size - 1);
if (nbytes < 0)
return nullptr;
close(fd);
/* use only the first line */
char *p = (char *)memchr(buffer, '\n', nbytes);
if (p == nullptr)
p = buffer + nbytes;
*p = 0;
return buffer;
}
bool
bulldog_check(SocketAddress address)
{
const char *path = bulldog_node_path(address, "status");
if (path == nullptr)
/* disabled */
return true;
char buffer[32];
const char *value = read_first_line(path, buffer, sizeof(buffer));
if (value == nullptr) {
if (errno != ENOENT)
daemon_log(2, "Failed to read %s: %s\n",
path, strerror(errno));
else
daemon_log(4, "No such bulldog-tyke status file: %s\n",
path);
return true;
}
daemon_log(5, "bulldog: %s='%s'\n", path, value);
return strcmp(value, "alive") == 0;
}
bool
bulldog_is_fading(SocketAddress address)
{
const char *path = bulldog_node_path(address, "graceful");
if (path == nullptr)
/* disabled */
return false;
char buffer[32];
const char *value = read_first_line(path, buffer, sizeof(buffer));
if (value == nullptr)
return false;
daemon_log(5, "bulldog: %s='%s'\n", path, value);
return strcmp(value, "1") == 0;
}
<commit_msg>bulldog: use class StringBuilder<commit_after>/*
* Check the bulldog-tyke status directory.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "bulldog.hxx"
#include "net/SocketAddress.hxx"
#include "util/StringBuilder.hxx"
#include <daemon/log.h>
#include <socket/address.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define WORKERS "/workers/"
static struct {
char path[4096];
size_t path_length;
} bulldog;
void
bulldog_init(const char *path)
try {
if (path == nullptr)
return;
StringBuilder<> b(bulldog.path, sizeof(bulldog.path));
b.Append(path);
b.Append(WORKERS);
bulldog.path_length = strlen(bulldog.path);
} catch (StringBuilder<>::Overflow) {
bulldog.path[0] = 0;
daemon_log(1, "bulldog path is too long\n");
}
void
bulldog_deinit()
{
}
gcc_pure
static const char *
bulldog_node_path(SocketAddress address,
const char *attribute_name)
try {
assert(!address.IsNull());
assert(attribute_name != nullptr);
assert(*attribute_name != 0);
if (bulldog.path[0] == 0)
/* disabled */
return nullptr;
if (!socket_address_to_string(bulldog.path + bulldog.path_length,
sizeof(bulldog.path) - bulldog.path_length,
address.GetAddress(), address.GetSize()))
return nullptr;
StringBuilder<> b(bulldog.path + strlen(bulldog.path),
bulldog.path + sizeof(bulldog.path));
b.Append('/');
b.Append(attribute_name);
return bulldog.path;
} catch (StringBuilder<>::Overflow) {
return nullptr;
}
gcc_pure
static const char *
read_first_line(const char *path, char *buffer, size_t buffer_size)
{
assert(path != nullptr);
assert(buffer != nullptr);
assert(buffer_size > 0);
int fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return nullptr;
ssize_t nbytes = read(fd, buffer, buffer_size - 1);
if (nbytes < 0)
return nullptr;
close(fd);
/* use only the first line */
char *p = (char *)memchr(buffer, '\n', nbytes);
if (p == nullptr)
p = buffer + nbytes;
*p = 0;
return buffer;
}
bool
bulldog_check(SocketAddress address)
{
const char *path = bulldog_node_path(address, "status");
if (path == nullptr)
/* disabled */
return true;
char buffer[32];
const char *value = read_first_line(path, buffer, sizeof(buffer));
if (value == nullptr) {
if (errno != ENOENT)
daemon_log(2, "Failed to read %s: %s\n",
path, strerror(errno));
else
daemon_log(4, "No such bulldog-tyke status file: %s\n",
path);
return true;
}
daemon_log(5, "bulldog: %s='%s'\n", path, value);
return strcmp(value, "alive") == 0;
}
bool
bulldog_is_fading(SocketAddress address)
{
const char *path = bulldog_node_path(address, "graceful");
if (path == nullptr)
/* disabled */
return false;
char buffer[32];
const char *value = read_first_line(path, buffer, sizeof(buffer));
if (value == nullptr)
return false;
daemon_log(5, "bulldog: %s='%s'\n", path, value);
return strcmp(value, "1") == 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/program_options.hpp>
#include <mettle/driver/cmd_line.hpp>
#include <mettle/driver/log/child.hpp>
#include <mettle/driver/log/summary.hpp>
#include <mettle/driver/log/term.hpp>
#include "run_test_files.hpp"
namespace caliber {
namespace {
struct all_options : mettle::generic_options, mettle::output_options,
mettle::child_options {
METTLE_OPTIONAL_NS::optional<int> child_fd;
std::vector<std::string> files;
};
}
} // namespace caliber
int main(int argc, const char *argv[]) {
using namespace mettle;
namespace opts = boost::program_options;
caliber::all_options args;
auto generic = make_generic_options(args);
auto output = make_output_options(args);
auto child = make_child_options(args);
opts::options_description hidden("Hidden options");
hidden.add_options()
("child", opts::value(&args.child_fd), "run this file as a child process")
("file", opts::value(&args.files), "input file")
;
opts::positional_options_description pos;
pos.add("file", -1);
opts::variables_map vm;
std::vector<std::string> child_args;
try {
opts::options_description all;
all.add(generic).add(output).add(child).add(hidden);
auto parsed = opts::command_line_parser(argc, argv)
.options(all).positional(pos).run();
opts::store(parsed, vm);
opts::notify(vm);
} catch(const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
if(args.show_help) {
opts::options_description displayed;
displayed.add(generic).add(output).add(child);
std::cout << displayed << std::endl;
return 1;
}
if(args.files.empty()) {
std::cerr << "no inputs specified" << std::endl;
return 1;
}
if(args.child_fd) {
if(auto output_opt = has_option(output, vm)) {
using namespace opts::command_line_style;
std::cerr << output_opt->canonical_display_name(allow_long)
<< " can't be used with --child" << std::endl;
return 1;
}
namespace io = boost::iostreams;
io::stream<io::file_descriptor_sink> fds(
*args.child_fd, io::never_close_handle
);
log::child logger(fds);
caliber::run_test_files(args.files, logger, args.filters);
return 0;
}
if(args.no_fork && args.show_terminal) {
std::cerr << "--show-terminal requires forking tests" << std::endl;
return 1;
}
term::enable(std::cout, args.color);
indenting_ostream out(std::cout);
auto progress_log = make_progress_logger(out, args);
log::summary logger(out, progress_log.get(), args.show_time,
args.show_terminal);
caliber::run_test_files(args.files, logger, args.filters);
logger.summarize();
return !logger.good();
}
<commit_msg>Remove unused variable<commit_after>#include <iostream>
#include <vector>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/program_options.hpp>
#include <mettle/driver/cmd_line.hpp>
#include <mettle/driver/log/child.hpp>
#include <mettle/driver/log/summary.hpp>
#include <mettle/driver/log/term.hpp>
#include "run_test_files.hpp"
namespace caliber {
namespace {
struct all_options : mettle::generic_options, mettle::output_options,
mettle::child_options {
METTLE_OPTIONAL_NS::optional<int> child_fd;
std::vector<std::string> files;
};
}
} // namespace caliber
int main(int argc, const char *argv[]) {
using namespace mettle;
namespace opts = boost::program_options;
caliber::all_options args;
auto generic = make_generic_options(args);
auto output = make_output_options(args);
auto child = make_child_options(args);
opts::options_description hidden("Hidden options");
hidden.add_options()
("child", opts::value(&args.child_fd), "run this file as a child process")
("file", opts::value(&args.files), "input file")
;
opts::positional_options_description pos;
pos.add("file", -1);
opts::variables_map vm;
try {
opts::options_description all;
all.add(generic).add(output).add(child).add(hidden);
auto parsed = opts::command_line_parser(argc, argv)
.options(all).positional(pos).run();
opts::store(parsed, vm);
opts::notify(vm);
} catch(const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
if(args.show_help) {
opts::options_description displayed;
displayed.add(generic).add(output).add(child);
std::cout << displayed << std::endl;
return 1;
}
if(args.files.empty()) {
std::cerr << "no inputs specified" << std::endl;
return 1;
}
if(args.child_fd) {
if(auto output_opt = has_option(output, vm)) {
using namespace opts::command_line_style;
std::cerr << output_opt->canonical_display_name(allow_long)
<< " can't be used with --child" << std::endl;
return 1;
}
namespace io = boost::iostreams;
io::stream<io::file_descriptor_sink> fds(
*args.child_fd, io::never_close_handle
);
log::child logger(fds);
caliber::run_test_files(args.files, logger, args.filters);
return 0;
}
if(args.no_fork && args.show_terminal) {
std::cerr << "--show-terminal requires forking tests" << std::endl;
return 1;
}
term::enable(std::cout, args.color);
indenting_ostream out(std::cout);
auto progress_log = make_progress_logger(out, args);
log::summary logger(out, progress_log.get(), args.show_time,
args.show_terminal);
caliber::run_test_files(args.files, logger, args.filters);
logger.summarize();
return !logger.good();
}
<|endoftext|>
|
<commit_before>#include <SFML/Network.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#define NB_BYTE_PER_PACKET 8192
enum SCommand : signed char {
NotAuthorized = -127,
TooBig,
AlreadyExist,
ServerFailure,
UnknownIssue,
ServerReady = 0,
Upload = 1,
Download,
Ls
};
unsigned int getFileLength( std::string const& filename ) {
std::ifstream file( filename.c_str(), std::ios::binary | std::ios::in );
if( !file.fail() )
{
file.seekg( 0, std::ios::end );
return file.tellg();
}
return 0;
}
bool startUpload( std::ifstream& infile, unsigned int& file_size, sf::TcpSocket& server ) { //Starts an upload by opening the file and telling the server about its name and size
//Also retrieves server's answer (upload accepted or denied)
std::string filename;
std::cout << "File name : ";
std::cin >> filename;
file_size = getFileLength( filename ) ;
infile.open(filename.c_str(), std::ios::binary | std::ios::in);
if( file_size == 0 || infile.fail() ) {
std::cout << "There was a problem reading the file" << std::endl;
return false;
}
sf::Packet packet;
packet << Upload << filename << file_size << NB_BYTE_PER_PACKET;
server.send(packet);
packet.clear();
int server_state;
server.receive(packet);
if( packet.getDataSize() > sizeof( int ) || !(packet >> server_state) ){
std::cout << "There was an error retrieving server state" << std::endl;
return false;
}
switch( static_cast<char>(server_state) ){
case ServerReady :
return true;
default:
std::cout << "The server is busy" << std::endl;
return false;
}
std::cout << "Unknown error" << std::endl;
return false;
}
bool sconnect( sf::TcpSocket& socket ) {
unsigned short remote_port;
std::string remote_address;
std::cout << "Remote address : ";
std::cin >> remote_address;
std::cout << "Remote port : ";
std::cin >> remote_port;
std::cout << "Connecting to the remote @ " << remote_address << ":" << remote_port << std::endl;
if( socket.connect( remote_address, remote_port ) != sf::Socket::Done ){
std::cout << "Connection wasn't successful" << std::endl;
return false;
}
std::cout << "Successfully connected" << std::endl;
return true;
}
bool sendData( sf::TcpSocket& server ){
std::ifstream input_file;
unsigned int file_size;
if( !startUpload( input_file, file_size, server) ){
std::cout << "Could not send the file" << std::endl; //Preparing to upload
return false;
}
unsigned int loop_number=file_size/NB_BYTE_PER_PACKET;
char input_data_array[NB_BYTE_PER_PACKET];
sf::Packet spacket;
spacket.clear();
unsigned char percentage_count(0);
std::cout << "Upload is starting" << std::endl;
for( unsigned int i(0) ; i<loop_number ; ++i ){ //Reading an sending the file
input_file.read( input_data_array, NB_BYTE_PER_PACKET);
for( unsigned int j(0) ; j<NB_BYTE_PER_PACKET ; ++j)
spacket << static_cast<sf::Int8>(input_data_array[j]);
if( server.send(spacket) == sf::Socket::Disconnected ){
std::cout << "Lost connection with server !" << std::endl;
return false;
}
spacket.clear();
server.receive(spacket); //Sync with server
spacket.clear();
if( static_cast<unsigned char>(100*i/loop_number) > percentage_count ){
percentage_count = static_cast<unsigned char>(100*i/loop_number);
std::cout << "[" << static_cast<short>(percentage_count) << "%] - File being transfered" << std::endl; //Displaying upload percentage
}
}
file_size -= loop_number * NB_BYTE_PER_PACKET;
if( file_size > 0){ //There is some more to be transferred
char* file_tail = new char[file_size];
input_file.read( file_tail, file_size);
for( unsigned int j(0) ; j< file_size ; ++j)
spacket << file_tail[j];
if( server.send(spacket) == sf::Socket::Disconnected ){
std::cout << "Too bad. You almost done it but you were disconnected by server :(" << std::endl;
delete file_tail;
return false;
}
delete file_tail;
}
std::cout << "Transfer terminated successfully" << std::endl;
return true;
}
bool retrieveData( sf::TcpSocket& server ) {
return false;
}
int main(int argc, char* argv[]) {
sf::TcpSocket socket;
std::string user_input;
if( !sconnect( socket ) )
return 1;
do{
std::cout << "Do you wish to upload a file ? [y/n/q] ";
std::cin >> user_input;
if( user_input == "" || user_input == "y" || user_input == "Y" ) {
if( !sendData( socket ) ){
std::cout << "Failed to upload data to server" << std::endl;
}
}
if( user_input == "q"){
std::cout << "Closing connection and exiting" << std::endl;
socket.disconnect();
return 0;
}
std::cout << "Do you wish to download a file ? [y/n/q] ";
std::cin >> user_input;
if( user_input == "" || user_input == "y" || user_input == "Y" ) {
if( !retrieveData( socket ) ){
std::cout << "Failed to retrieve data from server" << std::endl;
}
}
if( user_input == "q" ){
std::cout << "Closing Connection and exiting" << std::endl;
socket.disconnect();
return 0;
}
}while(true);
}
<commit_msg>Adding server answer interpretation<commit_after>#include <SFML/Network.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#define NB_BYTE_PER_PACKET 8192
enum SCommand : signed char {
NotAuthorized = -127,
TooBig,
AlreadyExist,
ServerFailure,
UnknownIssue,
ServerReady = 0,
Upload = 1,
Download,
Ls
};
bool interpretServerAns( signed char sanswer){ //Sends message to console telling the problem // success
std::cout << "Server :";
switch( sanswer ){
case NotAuthorized :
std::cout << "action unauthorized" << std::endl;
return false;
case TooBig:
std::cout << "file too heavy" << std::endl;
return false;
case AlreadyExist:
std::cout << "this file already exists" << std::endl;
return false;
case ServerFailure:
std::cout << "an error has occured" << std::endl;
return false;
case UnknownIssue:
std::cout << "dafuq has happened ?!?" << std::endl;
return false;
case ServerReady:
std::cout << "ready" << std::endl;
return true;
default:
std::cout << "unexpected answer from server" << std::endl;
return false;
}
}
unsigned int getFileLength( std::string const& filename ) { //Retrieving file size in bytes
std::ifstream file( filename.c_str(), std::ios::binary | std::ios::in );
if( !file.fail() )
{
file.seekg( 0, std::ios::end );
return file.tellg();
}
return 0;
}
bool startUpload( std::ifstream& infile, unsigned int& file_size, sf::TcpSocket& server ) { //Starts an upload by opening the file and telling the server about its name and size
//Also retrieves server's answer (upload accepted or denied)
std::string filename;
std::cout << "File name : ";
std::cin >> filename;
file_size = getFileLength( filename ) ;
infile.open(filename.c_str(), std::ios::binary | std::ios::in);
if( file_size == 0 || infile.fail() ) {
std::cout << "There was a problem reading the file" << std::endl;
return false;
}
sf::Packet packet;
packet << Upload << filename << file_size << NB_BYTE_PER_PACKET;
server.send(packet);
packet.clear();
int server_state;
server.receive(packet);
if( packet.getDataSize() > sizeof( int ) || !(packet >> server_state) ){
std::cout << "There was an error retrieving server state" << std::endl;
return false;
}
return interpretServerAns( static_cast<char>(server_state) );
}
bool sconnect( sf::TcpSocket& socket ) { //Connect the client to the server
unsigned short remote_port;
std::string remote_address;
std::cout << "Remote address : ";
std::cin >> remote_address;
std::cout << "Remote port : ";
std::cin >> remote_port;
std::cout << "Connecting to the remote @ " << remote_address << ":" << remote_port << std::endl;
if( socket.connect( remote_address, remote_port ) != sf::Socket::Done ){
std::cout << "Connection wasn't successful" << std::endl;
return false;
}
std::cout << "Successfully connected" << std::endl;
return true;
}
bool sendData( sf::TcpSocket& server ){ // Sends a file to the server
std::ifstream input_file;
unsigned int file_size;
if( !startUpload( input_file, file_size, server) ){
std::cout << "Could not send the file" << std::endl; //Preparing to upload
return false;
}
unsigned int loop_number=file_size/NB_BYTE_PER_PACKET;
char input_data_array[NB_BYTE_PER_PACKET];
sf::Packet spacket;
spacket.clear();
unsigned char percentage_count(0);
std::cout << "Upload is starting" << std::endl;
for( unsigned int i(0) ; i<loop_number ; ++i ){ //Reading an sending the file
input_file.read( input_data_array, NB_BYTE_PER_PACKET);
for( unsigned int j(0) ; j<NB_BYTE_PER_PACKET ; ++j)
spacket << static_cast<sf::Int8>(input_data_array[j]);
if( server.send(spacket) == sf::Socket::Disconnected ){
std::cout << "Lost connection with server !" << std::endl;
return false;
}
spacket.clear();
server.receive(spacket); //Sync with server
spacket.clear();
if( static_cast<unsigned char>(100*i/loop_number) > percentage_count ){
percentage_count = static_cast<unsigned char>(100*i/loop_number);
std::cout << "[" << static_cast<short>(percentage_count) << "%] - File being transfered" << std::endl; //Displaying upload percentage
}
}
file_size -= loop_number * NB_BYTE_PER_PACKET;
if( file_size > 0){ //There is some more to be transferred
char* file_tail = new char[file_size];
input_file.read( file_tail, file_size);
for( unsigned int j(0) ; j< file_size ; ++j)
spacket << file_tail[j];
if( server.send(spacket) == sf::Socket::Disconnected ){
std::cout << "Too bad. You almost done it but you were disconnected by server :(" << std::endl;
delete file_tail;
return false;
}
delete file_tail;
}
std::cout << "Transfer terminated successfully" << std::endl;
return true;
}
bool retrieveData( sf::TcpSocket& server ) { //Retrieves a file from the server
return false;
}
int main(int argc, char* argv[]) {
sf::TcpSocket socket;
std::string user_input;
if( !sconnect( socket ) )
return 1;
do{
std::cout << "Do you wish to upload a file ? [y/n/q] ";
std::cin >> user_input;
if( user_input == "" || user_input == "y" || user_input == "Y" ) {
if( !sendData( socket ) ){
std::cout << "Failed to upload data to server" << std::endl;
}
}
if( user_input == "q"){
std::cout << "Closing connection and exiting" << std::endl;
socket.disconnect();
return 0;
}
std::cout << "Do you wish to download a file ? [y/n/q] ";
std::cin >> user_input;
if( user_input == "" || user_input == "y" || user_input == "Y" ) {
if( !retrieveData( socket ) ){
std::cout << "Failed to retrieve data from server" << std::endl;
}
}
if( user_input == "q" ){
std::cout << "Closing Connection and exiting" << std::endl;
socket.disconnect();
return 0;
}
}while(true);
}
<|endoftext|>
|
<commit_before>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include <assert.h>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'});
const std::unordered_set<char> Compiler::MULT_OPS({'*', '/'});
//constructors
Compiler::Compiler (std::ostream& output)
: m_input_stream (std::ios::in|std::ios::out), m_output_stream(output)
{
}
void Compiler::compile_intermediate (const std::string input_line) {
//clear contents and error flags on m_input_stream
m_input_stream.str("");
m_input_stream.clear();
m_input_stream << input_line;
try {
start_symbol();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
throw std::runtime_error("Compilation failed.\n");
}
}
void Compiler::compile_full (const std::vector<std::string> source, const std::string class_name) {
compile_start(class_name);
for (auto line : source) {
compile_intermediate(line);
}
compile_end();
}
void Compiler::compile_start (const std::string class_name) const {
add_includes();
//begin class declaration, qualify everything as public
emit_line("class "+ class_name + "{");
emit_line("public:");
define_member_variables();
define_constructor(class_name);
define_cpu_pop();
define_getters();
define_is_stack_empty();
emit_line("void run() {"); //begin definition of run()
}
void Compiler::compile_end () const {
//TODO - should I assert that cpu_stack is empty?
emit_line("}"); //end definition of run()
define_dump();
emit_line("};"); //close class definition
}
void Compiler::add_includes() const {
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
emit_line("#include <unordered_map>");
}
void Compiler::define_member_variables() const {
emit_line("std::stack<int> cpu_stack;");
emit_line("std::vector<int> cpu_registers;");
emit_line("std::unordered_map<char, int> cpu_variables;");
}
void Compiler::define_constructor(const std::string class_name) const {
emit_line(class_name + "() ");
emit_line(": cpu_stack()");
emit_line(", cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0)");
emit_line(", cpu_variables()");
emit_line("{}");
}
//emit definition of a function for easier stack handling
void Compiler::define_cpu_pop() const {
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
}
void Compiler::define_getters() const {
emit_line("int get_register(int index) {");
emit_line("return cpu_registers.at(index);}");
emit_line("int get_variable(char var_name) {");
emit_line("return cpu_variables.at(var_name);}");
//no getter for stack; stack should always be empty
}
void Compiler::define_is_stack_empty() const {
emit_line("bool is_stack_empty() {");
emit_line("return cpu_stack.empty();}");
}
void Compiler::define_dump() const {
//TODO - are these dumps necessary?
emit_line("void dump () {");
emit_line("std::cout << \"Register contents\\n\";");
emit_line("for (int i = 0; i < " + std::to_string(NUM_REGISTERS) + "; ++i)");
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
emit_line("std::cout << \"Stack contents (top to bottom)\\n\";");
emit_line("while (!cpu_stack.empty()) {");
emit_line("std::cout << cpu_stack.top() << '\\n';");
emit_line("cpu_stack.pop();}");
emit_line("std::cout << \"Variable contents\\n\";");
emit_line("for (auto i = cpu_variables.begin(); i != cpu_variables.end(); ++i)");
emit_line("std::cout << \"cpu_variables[\" << i->first << \"] = \" << i->second << '\\n';");
emit_line("}");
}
void Compiler::start_symbol () {
}
//cradle methods
void Compiler::report_error(const std::string err) const {
m_output_stream << '\n';
m_output_stream << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) {
if (m_input_stream.peek() == c) {
m_input_stream.get();
} else {
expected(c);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () {
if (!std::isalpha(m_input_stream.peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(m_input_stream.get());
}
}
//gets a number
char Compiler::get_num () {
if (!std::isdigit(m_input_stream.peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return m_input_stream.get();
}
}
//output a string
void Compiler::emit (std::string s) const {
m_output_stream << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
bool Compiler::is_in(const char elem, const std::unordered_set<char> us) {
return us.find(elem) != us.end();
}
} //end namespace<commit_msg>Remove TODO note in define_dump(); dump functions are useful for debugging<commit_after>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include <assert.h>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'});
const std::unordered_set<char> Compiler::MULT_OPS({'*', '/'});
//constructors
Compiler::Compiler (std::ostream& output)
: m_input_stream (std::ios::in|std::ios::out), m_output_stream(output)
{
}
void Compiler::compile_intermediate (const std::string input_line) {
//clear contents and error flags on m_input_stream
m_input_stream.str("");
m_input_stream.clear();
m_input_stream << input_line;
try {
start_symbol();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
throw std::runtime_error("Compilation failed.\n");
}
}
void Compiler::compile_full (const std::vector<std::string> source, const std::string class_name) {
compile_start(class_name);
for (auto line : source) {
compile_intermediate(line);
}
compile_end();
}
void Compiler::compile_start (const std::string class_name) const {
add_includes();
//begin class declaration, qualify everything as public
emit_line("class "+ class_name + "{");
emit_line("public:");
define_member_variables();
define_constructor(class_name);
define_cpu_pop();
define_getters();
define_is_stack_empty();
emit_line("void run() {"); //begin definition of run()
}
void Compiler::compile_end () const {
//TODO - should I assert that cpu_stack is empty?
emit_line("}"); //end definition of run()
define_dump();
emit_line("};"); //close class definition
}
void Compiler::add_includes() const {
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
emit_line("#include <unordered_map>");
}
void Compiler::define_member_variables() const {
emit_line("std::stack<int> cpu_stack;");
emit_line("std::vector<int> cpu_registers;");
emit_line("std::unordered_map<char, int> cpu_variables;");
}
void Compiler::define_constructor(const std::string class_name) const {
emit_line(class_name + "() ");
emit_line(": cpu_stack()");
emit_line(", cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0)");
emit_line(", cpu_variables()");
emit_line("{}");
}
//emit definition of a function for easier stack handling
void Compiler::define_cpu_pop() const {
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
}
void Compiler::define_getters() const {
emit_line("int get_register(int index) {");
emit_line("return cpu_registers.at(index);}");
emit_line("int get_variable(char var_name) {");
emit_line("return cpu_variables.at(var_name);}");
//no getter for stack; stack should always be empty
}
void Compiler::define_is_stack_empty() const {
emit_line("bool is_stack_empty() {");
emit_line("return cpu_stack.empty();}");
}
void Compiler::define_dump() const {
emit_line("void dump () {");
emit_line("std::cout << \"Register contents\\n\";");
emit_line("for (int i = 0; i < " + std::to_string(NUM_REGISTERS) + "; ++i)");
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
emit_line("std::cout << \"Stack contents (top to bottom)\\n\";");
emit_line("while (!cpu_stack.empty()) {");
emit_line("std::cout << cpu_stack.top() << '\\n';");
emit_line("cpu_stack.pop();}");
emit_line("std::cout << \"Variable contents\\n\";");
emit_line("for (auto i = cpu_variables.begin(); i != cpu_variables.end(); ++i)");
emit_line("std::cout << \"cpu_variables[\" << i->first << \"] = \" << i->second << '\\n';");
emit_line("}");
}
void Compiler::start_symbol () {
}
//cradle methods
void Compiler::report_error(const std::string err) const {
m_output_stream << '\n';
m_output_stream << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) {
if (m_input_stream.peek() == c) {
m_input_stream.get();
} else {
expected(c);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () {
if (!std::isalpha(m_input_stream.peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(m_input_stream.get());
}
}
//gets a number
char Compiler::get_num () {
if (!std::isdigit(m_input_stream.peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return m_input_stream.get();
}
}
//output a string
void Compiler::emit (std::string s) const {
m_output_stream << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
bool Compiler::is_in(const char elem, const std::unordered_set<char> us) {
return us.find(elem) != us.end();
}
} //end namespace<|endoftext|>
|
<commit_before>/* 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 HEADER_GUARD_CLASS_CONTENTS_H
#define HEADER_GUARD_CLASS_CONTENTS_H
#include <memory>
#include <mutex>
#include <string>
#include <type_traits>
#include <vector>
#include <cstddef>
#include "change.hh"
#include "mode.hh"
namespace vick {
/*!
* \file contents.hh
*
* \brief Defines the class contents, which contains all the
* information about the buffer.
*/
/*!
* \brief Define `move_t` so that code can be more descriptive and
* can change it from one place.
*/
using move_t = std::size_t;
/*!
* \brief Define `move_ts` to be a signed version of `move_t`
*
* \see move_t
*/
using move_ts = typename std::make_signed<move_t>::type;
/*!
* \brief Define `move_tu` to be an unsigned version of `move_t`
*
* \see move_t
*/
using move_tu = typename std::make_unsigned<move_t>::type;
/*!
* \class contents contents.hh "contents.hh"
*
* \brief Defines all the information about the buffer.
*/
class contents {
public:
std::map<char, std::function<boost::optional<std::shared_ptr<
change> >(contents &, boost::optional<int>)> >
normal_map /*!< \brief The contents buffer (file) specfic
* normal mode character mappings. */,
insert_map /*!< \brief The contents buffer (file) specfic
* insert mode character mappings. */;
/*!
* \brief The type of file the buffer is.
*
* Default mode is fundamental;
*/
mode* buffer_mode;
/*!
* \brief The literal contents of the buffer
*/
std::vector<std::string> cont;
/*!
* \brief The list of changes to the buffer. This is public so
* that treed-undo (a la Emacs) can be implemented the same as
* linear is.
*/
std::vector<std::shared_ptr<change> > changes;
/*!
* \brief For use to lock access to `cont` when it is being
* updated in one thread and displayed in another.
*/
std::mutex print_mutex;
/*!
* \brief The current change the buffer is in
*/
size_t changes_i = 0;
move_t
y = 0 /*!< \brief The y (vertical) position in the buffer. */,
x = 0 /*!< \brief The x (horizontal) position in the buffer. */,
desired_x = 0 /*!< \brief This will be set to the x value we
* want when you move to a different line but
* the line you move to is too short
*
* \see waiting_for_desired */,
y_offset = 0 /*!< \brief The number of lines that are not
* displayed (off the top) */,
max_y /*!< \brief The vertical height the buffer has been
* allocated on the screen - [0, max_y) */,
max_x /*!< \brief The horizontal width the buffer has been
* allocated on the screen - [0, max_x) */;
bool waiting_for_desired = false /*!< \brief Controls if the x
* value will try to adjust to
* desired_x
*
* \see desired_x */,
refresh = true /*!< \brief Controls if the screen should
* refresh everytime something happens */,
delete_mode = false /*!< \brief Controls if the private mode
* pointer variable will be deleted in the
* destructor */,
is_inserting = false /*!< \brief Will be true if the user is
* currently inserting text into the
* buffer. This will cause the
* print_contents method to not have
* undefined behavior if x is too
* large. */,
windows_file_endings = false /*!< \brief If true, then when
* saving, appends the byte 13 to
* each line. We use this to
* maintain plugin consistency
* across platforms. (The buffer
* is in no way affected by this
* variable)
*/;
explicit contents(
std::vector<std::string> cont = std::vector<std::string>(),
mode* buffer_mode = &fundamental_mode);
explicit contents(mode* buffer_mode);
contents(move_t y, move_t x,
mode* buffer_mode = &fundamental_mode);
/*!
* \brief Constructs this contents object as a copy of the other
* contents object.
*
* This forces the private mode member to make a deep copy.
*/
contents(const contents&);
contents(contents&&) = default;
/*!
* \brief If delete_mode is true, then it will delete the private
* mode pointer member.
*
* \see delete_mode
*/
~contents();
/*!
* \brief Constructs this contents object as a copy of the other
* contents object.
*
* This forces the private mode member to make a deep copy.
*/
contents& operator=(const contents&);
contents& operator=(contents&&);
/*!
* \brief Calls the private mode member's `operator()` with
* `*this` and the character given to this function.
*/
bool operator()(char);
/*!
* \brief Updates the values of ``max_y`` and ``max_x``
*
* \see max_y
* \see max_x
*/
void refreshmaxyx();
/*!
* \brief Calls ``cont.push_back(str)``
*
* \see cont
*
* \param str The string to be put at the end of the vector of
* strings, `cont`
*/
void push_back(const std::string& str);
};
}
#endif
<commit_msg>Add a `file_name` field to `contents`<commit_after>/* 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 HEADER_GUARD_CLASS_CONTENTS_H
#define HEADER_GUARD_CLASS_CONTENTS_H
#include <memory>
#include <mutex>
#include <string>
#include <type_traits>
#include <vector>
#include <cstddef>
#include "change.hh"
#include "mode.hh"
namespace vick {
/*!
* \file contents.hh
*
* \brief Defines the class contents, which contains all the
* information about the buffer.
*/
/*!
* \brief Define `move_t` so that code can be more descriptive and
* can change it from one place.
*/
using move_t = std::size_t;
/*!
* \brief Define `move_ts` to be a signed version of `move_t`
*
* \see move_t
*/
using move_ts = typename std::make_signed<move_t>::type;
/*!
* \brief Define `move_tu` to be an unsigned version of `move_t`
*
* \see move_t
*/
using move_tu = typename std::make_unsigned<move_t>::type;
/*!
* \class contents contents.hh "contents.hh"
*
* \brief Defines all the information about the buffer.
*/
class contents {
public:
std::map<char, std::function<boost::optional<std::shared_ptr<
change> >(contents &, boost::optional<int>)> >
normal_map /*!< \brief The contents buffer (file) specfic
* normal mode character mappings. */,
insert_map /*!< \brief The contents buffer (file) specfic
* insert mode character mappings. */;
/*!
* \brief The type of file the buffer is.
*
* Default mode is fundamental;
*/
mode* buffer_mode;
/*!
* \brief The literal contents of the buffer
*/
std::vector<std::string> cont;
/*!
* \brief The list of changes to the buffer. This is public so
* that treed-undo (a la Emacs) can be implemented the same as
* linear is.
*/
std::vector<std::shared_ptr<change> > changes;
/*!
* \brief For use to lock access to `cont` when it is being
* updated in one thread and displayed in another.
*/
std::mutex print_mutex;
/*!
* \brief The file that the contents was read from.
*/
std::string file_name;
/*!
* \brief The current change the buffer is in
*/
size_t changes_i = 0;
move_t
y = 0 /*!< \brief The y (vertical) position in the buffer. */,
x = 0 /*!< \brief The x (horizontal) position in the buffer. */,
desired_x = 0 /*!< \brief This will be set to the x value we
* want when you move to a different line but
* the line you move to is too short
*
* \see waiting_for_desired */,
y_offset = 0 /*!< \brief The number of lines that are not
* displayed (off the top) */,
max_y /*!< \brief The vertical height the buffer has been
* allocated on the screen - [0, max_y) */,
max_x /*!< \brief The horizontal width the buffer has been
* allocated on the screen - [0, max_x) */;
bool waiting_for_desired = false /*!< \brief Controls if the x
* value will try to adjust to
* desired_x
*
* \see desired_x */,
refresh = true /*!< \brief Controls if the screen should
* refresh everytime something happens */,
delete_mode = false /*!< \brief Controls if the private mode
* pointer variable will be deleted in the
* destructor */,
is_inserting = false /*!< \brief Will be true if the user is
* currently inserting text into the
* buffer. This will cause the
* print_contents method to not have
* undefined behavior if x is too
* large. */,
windows_file_endings = false /*!< \brief If true, then when
* saving, appends the byte 13 to
* each line. We use this to
* maintain plugin consistency
* across platforms. (The buffer
* is in no way affected by this
* variable)
*/;
explicit contents(
std::vector<std::string> cont = std::vector<std::string>(),
mode* buffer_mode = &fundamental_mode);
explicit contents(mode* buffer_mode);
contents(move_t y, move_t x,
mode* buffer_mode = &fundamental_mode);
/*!
* \brief Constructs this contents object as a copy of the other
* contents object.
*
* This forces the private mode member to make a deep copy.
*/
contents(const contents&);
contents(contents&&) = default;
/*!
* \brief If delete_mode is true, then it will delete the private
* mode pointer member.
*
* \see delete_mode
*/
~contents();
/*!
* \brief Constructs this contents object as a copy of the other
* contents object.
*
* This forces the private mode member to make a deep copy.
*/
contents& operator=(const contents&);
contents& operator=(contents&&);
/*!
* \brief Calls the private mode member's `operator()` with
* `*this` and the character given to this function.
*/
bool operator()(char);
/*!
* \brief Updates the values of ``max_y`` and ``max_x``
*
* \see max_y
* \see max_x
*/
void refreshmaxyx();
/*!
* \brief Calls ``cont.push_back(str)``
*
* \see cont
*
* \param str The string to be put at the end of the vector of
* strings, `cont`
*/
void push_back(const std::string& str);
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *eng)
{
auto engine= (Engine*) eng;
auto sc = new Peer_Ptr<Scene>(new Scene);
sc->get()->engine = engine;
engine->scenes.push_back(sc->peer());
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (Peer_Ptr<Scene> *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = lock_resource<redc::Scene>(sc);
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = lock_resource<redc::Scene>(sc);
if(scene->objs[cam-1].obj.which() == Object::Cam)
{
scene->active_camera = cam;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = lock_resource<redc::Scene>(sc);
auto id = scene->index_gen.get();
CHECK_ID(id);
auto mesh = lock_resource<gfx::Mesh_Chunk>(ms);
scene->objs[id - 1].obj = Mesh_Object{std::move(mesh), glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent-1];
}
return id;
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
#ifdef REDC_LOG_FRAMES
++scene->frame_count;
if(scene->frame_timer.has_been(std::chrono::seconds(1)))
{
log_d("fps: %", scene->frame_count);
scene->frame_count = 0;
scene->frame_timer.reset();
}
#endif
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i)
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
// Put the increment in the expression because we always want to be
// incrementing the counter, otherwise we risk rendering the same object
// many times
while(!scene->index_gen.is_valid((++cur_id)));
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id-1];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
gfx::render_chunk(*mesh_obj.chunk);
}
}
}
}
<commit_msg>Use object model when rendering<commit_after>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *eng)
{
auto engine= (Engine*) eng;
auto sc = new Peer_Ptr<Scene>(new Scene);
sc->get()->engine = engine;
engine->scenes.push_back(sc->peer());
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (Peer_Ptr<Scene> *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = lock_resource<redc::Scene>(sc);
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = lock_resource<redc::Scene>(sc);
if(scene->objs[cam-1].obj.which() == Object::Cam)
{
scene->active_camera = cam;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = lock_resource<redc::Scene>(sc);
auto id = scene->index_gen.get();
CHECK_ID(id);
auto mesh = lock_resource<gfx::Mesh_Chunk>(ms);
scene->objs[id - 1].obj = Mesh_Object{std::move(mesh), glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent-1];
}
return id;
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = lock_resource<redc::Scene>(sc);
#ifdef REDC_LOG_FRAMES
++scene->frame_count;
if(scene->frame_timer.has_been(std::chrono::seconds(1)))
{
log_d("fps: %", scene->frame_count);
scene->frame_count = 0;
scene->frame_timer.reset();
}
#endif
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i)
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
// Put the increment in the expression because we always want to be
// incrementing the counter, otherwise we risk rendering the same object
// many times
while(!scene->index_gen.is_valid((++cur_id)));
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id-1];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
scene->engine->driver->active_shader()->set_model(model);
gfx::render_chunk(*mesh_obj.chunk);
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *engine)
{
auto sc = new redc::Scene;
sc->engine = (redc::Engine *) engine;
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (redc::Scene *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = (redc::Scene *) sc;
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = (redc::Scene *) sc;
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = (redc::Scene *) sc;
if(scene->objs[cam].obj.which() == Object::Cam)
{
scene->active_camera = cam;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = (redc::Scene *) sc;
auto mesh = (redc::gfx::Mesh_Chunk *) ms;
auto id = scene->index_gen.get();
CHECK_ID(id);
scene->objs[id - 1].obj = Mesh_Object{gfx::copy_mesh_chunk_share_mesh(*mesh),
glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent];
}
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = (redc::Scene *) sc;
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = (redc::Scene *) sc;
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i);
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
while(!scene->index_gen.is_valid((cur_id + 1))) { ++cur_id; }
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
gfx::render_chunk(mesh_obj.chunk);
}
}
}
}
<commit_msg>Active camera should be set to the id not the index<commit_after>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *engine)
{
auto sc = new redc::Scene;
sc->engine = (redc::Engine *) engine;
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (redc::Scene *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = (redc::Scene *) sc;
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = (redc::Scene *) sc;
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = (redc::Scene *) sc;
if(scene->objs[cam].obj.which() == Object::Cam)
{
scene->active_camera = cam+1;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = (redc::Scene *) sc;
auto mesh = (redc::gfx::Mesh_Chunk *) ms;
auto id = scene->index_gen.get();
CHECK_ID(id);
scene->objs[id - 1].obj = Mesh_Object{gfx::copy_mesh_chunk_share_mesh(*mesh),
glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent];
}
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = (redc::Scene *) sc;
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = (redc::Scene *) sc;
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i);
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
while(!scene->index_gen.is_valid((cur_id + 1))) { ++cur_id; }
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
gfx::render_chunk(mesh_obj.chunk);
}
}
}
}
<|endoftext|>
|
<commit_before>//===-- SIFixSGPRCopies.cpp - Remove potential VGPR => SGPR copies --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// Copies from VGPR to SGPR registers are illegal and the register coalescer
/// will sometimes generate these illegal copies in situations like this:
///
/// Register Class <vsrc> is the union of <vgpr> and <sgpr>
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// %vreg1 <vsrc> = COPY %vreg0 <sgpr>
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <vsrc> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <vsrc> = PHI %vreg1 <vsrc>, <BB#0>, %vreg3 <vrsc>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <vsrc>
///
///
/// The coalescer will begin at BB0 and eliminate its copy, then the resulting
/// code will look like this:
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <vsrc> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <sgpr> = PHI %vreg0 <sgpr>, <BB#0>, %vreg3 <vsrc>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <sgpr>
///
/// Now that the result of the PHI instruction is an SGPR, the register
/// allocator is now forced to constrain the register class of %vreg3 to
/// <sgpr> so we end up with final code like this:
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <sgpr> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <sgpr> = PHI %vreg0 <sgpr>, <BB#0>, %vreg3 <sgpr>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <sgpr>
///
/// Now this code contains an illegal copy from a VGPR to an SGPR.
///
/// In order to avoid this problem, this pass searches for PHI instructions
/// which define a <vsrc> register and constrains its definition class to
/// <vgpr> if the user of the PHI's definition register is a vector instruction.
/// If the PHI's definition class is constrained to <vgpr> then the coalescer
/// will be unable to perform the COPY removal from the above example which
/// ultimately led to the creation of an illegal COPY.
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "sgpr-copies"
namespace {
class SIFixSGPRCopies : public MachineFunctionPass {
public:
static char ID;
SIFixSGPRCopies() : MachineFunctionPass(ID) { }
bool runOnMachineFunction(MachineFunction &MF) override;
const char *getPassName() const override {
return "SI Fix SGPR copies";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
};
} // End anonymous namespace
INITIALIZE_PASS(SIFixSGPRCopies, DEBUG_TYPE,
"SI Fix SGPR copies", false, false)
char SIFixSGPRCopies::ID = 0;
char &llvm::SIFixSGPRCopiesID = SIFixSGPRCopies::ID;
FunctionPass *llvm::createSIFixSGPRCopiesPass() {
return new SIFixSGPRCopies();
}
static bool hasVGPROperands(const MachineInstr &MI, const SIRegisterInfo *TRI) {
const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
if (!MI.getOperand(i).isReg() ||
!TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
continue;
if (TRI->hasVGPRs(MRI.getRegClass(MI.getOperand(i).getReg())))
return true;
}
return false;
}
static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
getCopyRegClasses(const MachineInstr &Copy,
const SIRegisterInfo &TRI,
const MachineRegisterInfo &MRI) {
unsigned DstReg = Copy.getOperand(0).getReg();
unsigned SrcReg = Copy.getOperand(1).getReg();
const TargetRegisterClass *SrcRC =
TargetRegisterInfo::isVirtualRegister(SrcReg) ?
MRI.getRegClass(SrcReg) :
TRI.getPhysRegClass(SrcReg);
// We don't really care about the subregister here.
// SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
const TargetRegisterClass *DstRC =
TargetRegisterInfo::isVirtualRegister(DstReg) ?
MRI.getRegClass(DstReg) :
TRI.getPhysRegClass(DstReg);
return std::make_pair(SrcRC, DstRC);
}
static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
const TargetRegisterClass *DstRC,
const SIRegisterInfo &TRI) {
return TRI.isSGPRClass(DstRC) && TRI.hasVGPRs(SrcRC);
}
static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
const TargetRegisterClass *DstRC,
const SIRegisterInfo &TRI) {
return TRI.isSGPRClass(SrcRC) && TRI.hasVGPRs(DstRC);
}
// Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
//
// SGPRx = ...
// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
// VGPRz = COPY SGPRy
//
// ==>
//
// VGPRx = COPY SGPRx
// VGPRz = REG_SEQUENCE VGPRx, sub0
//
// This exposes immediate folding opportunities when materializing 64-bit
// immediates.
static bool foldVGPRCopyIntoRegSequence(MachineInstr &MI,
const SIRegisterInfo *TRI,
const SIInstrInfo *TII,
MachineRegisterInfo &MRI) {
assert(MI.isRegSequence());
unsigned DstReg = MI.getOperand(0).getReg();
if (!TRI->isSGPRClass(MRI.getRegClass(DstReg)))
return false;
if (!MRI.hasOneUse(DstReg))
return false;
MachineInstr &CopyUse = *MRI.use_instr_begin(DstReg);
if (!CopyUse.isCopy())
return false;
const TargetRegisterClass *SrcRC, *DstRC;
std::tie(SrcRC, DstRC) = getCopyRegClasses(CopyUse, *TRI, MRI);
if (!isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
return false;
// TODO: Could have multiple extracts?
unsigned SubReg = CopyUse.getOperand(1).getSubReg();
if (SubReg != AMDGPU::NoSubRegister)
return false;
MRI.setRegClass(DstReg, DstRC);
// SGPRx = ...
// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
// VGPRz = COPY SGPRy
// =>
// VGPRx = COPY SGPRx
// VGPRz = REG_SEQUENCE VGPRx, sub0
MI.getOperand(0).setReg(CopyUse.getOperand(0).getReg());
for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
unsigned SrcReg = MI.getOperand(I).getReg();
unsigned SrcSubReg = MI.getOperand(I).getSubReg();
const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
assert(TRI->isSGPRClass(SrcRC) &&
"Expected SGPR REG_SEQUENCE to only have SGPR inputs");
SrcRC = TRI->getSubRegClass(SrcRC, SrcSubReg);
const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SrcRC);
unsigned TmpReg = MRI.createVirtualRegister(NewSrcRC);
BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY), TmpReg)
.addOperand(MI.getOperand(I));
MI.getOperand(I).setReg(TmpReg);
}
CopyUse.eraseFromParent();
return true;
}
bool SIFixSGPRCopies::runOnMachineFunction(MachineFunction &MF) {
MachineRegisterInfo &MRI = MF.getRegInfo();
const SIRegisterInfo *TRI =
static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
const SIInstrInfo *TII =
static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
SmallVector<MachineInstr *, 16> Worklist;
for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
BI != BE; ++BI) {
MachineBasicBlock &MBB = *BI;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
I != E; ++I) {
MachineInstr &MI = *I;
switch (MI.getOpcode()) {
default:
continue;
case AMDGPU::COPY: {
// If the destination register is a physical register there isn't really
// much we can do to fix this.
if (!TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg()))
continue;
const TargetRegisterClass *SrcRC, *DstRC;
std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, MRI);
if (isVGPRToSGPRCopy(SrcRC, DstRC, *TRI)) {
DEBUG(dbgs() << "Fixing VGPR -> SGPR copy: " << MI);
TII->moveToVALU(MI);
}
break;
}
case AMDGPU::PHI: {
DEBUG(dbgs() << "Fixing PHI: " << MI);
unsigned Reg = MI.getOperand(0).getReg();
if (!TRI->isSGPRClass(MRI.getRegClass(Reg)))
break;
// If a PHI node defines an SGPR and any of its operands are VGPRs,
// then we need to move it to the VALU.
//
// Also, if a PHI node defines an SGPR and has all SGPR operands
// we must move it to the VALU, because the SGPR operands will
// all end up being assigned the same register, which means
// there is a potential for a conflict if different threads take
// different control flow paths.
//
// For Example:
//
// sgpr0 = def;
// ...
// sgpr1 = def;
// ...
// sgpr2 = PHI sgpr0, sgpr1
// use sgpr2;
//
// Will Become:
//
// sgpr2 = def;
// ...
// sgpr2 = def;
// ...
// use sgpr2
//
// FIXME: This is OK if the branching decision is made based on an
// SGPR value.
bool SGPRBranch = false;
// The one exception to this rule is when one of the operands
// is defined by a SI_BREAK, SI_IF_BREAK, or SI_ELSE_BREAK
// instruction. In this case, there we know the program will
// never enter the second block (the loop) without entering
// the first block (where the condition is computed), so there
// is no chance for values to be over-written.
bool HasBreakDef = false;
for (unsigned i = 1; i < MI.getNumOperands(); i+=2) {
unsigned Reg = MI.getOperand(i).getReg();
if (TRI->hasVGPRs(MRI.getRegClass(Reg))) {
TII->moveToVALU(MI);
break;
}
MachineInstr *DefInstr = MRI.getUniqueVRegDef(Reg);
assert(DefInstr);
switch(DefInstr->getOpcode()) {
case AMDGPU::SI_BREAK:
case AMDGPU::SI_IF_BREAK:
case AMDGPU::SI_ELSE_BREAK:
// If we see a PHI instruction that defines an SGPR, then that PHI
// instruction has already been considered and should have
// a *_BREAK as an operand.
case AMDGPU::PHI:
HasBreakDef = true;
break;
}
}
if (!SGPRBranch && !HasBreakDef)
TII->moveToVALU(MI);
break;
}
case AMDGPU::REG_SEQUENCE: {
if (TRI->hasVGPRs(TII->getOpRegClass(MI, 0)) ||
!hasVGPROperands(MI, TRI)) {
foldVGPRCopyIntoRegSequence(MI, TRI, TII, MRI);
continue;
}
DEBUG(dbgs() << "Fixing REG_SEQUENCE: " << MI);
TII->moveToVALU(MI);
break;
}
case AMDGPU::INSERT_SUBREG: {
const TargetRegisterClass *DstRC, *Src0RC, *Src1RC;
DstRC = MRI.getRegClass(MI.getOperand(0).getReg());
Src0RC = MRI.getRegClass(MI.getOperand(1).getReg());
Src1RC = MRI.getRegClass(MI.getOperand(2).getReg());
if (TRI->isSGPRClass(DstRC) &&
(TRI->hasVGPRs(Src0RC) || TRI->hasVGPRs(Src1RC))) {
DEBUG(dbgs() << " Fixing INSERT_SUBREG: " << MI);
TII->moveToVALU(MI);
}
break;
}
}
}
}
return true;
}
<commit_msg>AMDGPU: Fix debug name of pass to better match<commit_after>//===-- SIFixSGPRCopies.cpp - Remove potential VGPR => SGPR copies --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// Copies from VGPR to SGPR registers are illegal and the register coalescer
/// will sometimes generate these illegal copies in situations like this:
///
/// Register Class <vsrc> is the union of <vgpr> and <sgpr>
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// %vreg1 <vsrc> = COPY %vreg0 <sgpr>
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <vsrc> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <vsrc> = PHI %vreg1 <vsrc>, <BB#0>, %vreg3 <vrsc>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <vsrc>
///
///
/// The coalescer will begin at BB0 and eliminate its copy, then the resulting
/// code will look like this:
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <vsrc> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <sgpr> = PHI %vreg0 <sgpr>, <BB#0>, %vreg3 <vsrc>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <sgpr>
///
/// Now that the result of the PHI instruction is an SGPR, the register
/// allocator is now forced to constrain the register class of %vreg3 to
/// <sgpr> so we end up with final code like this:
///
/// BB0:
/// %vreg0 <sgpr> = SCALAR_INST
/// ...
/// BRANCH %cond BB1, BB2
/// BB1:
/// %vreg2 <vgpr> = VECTOR_INST
/// %vreg3 <sgpr> = COPY %vreg2 <vgpr>
/// BB2:
/// %vreg4 <sgpr> = PHI %vreg0 <sgpr>, <BB#0>, %vreg3 <sgpr>, <BB#1>
/// %vreg5 <vgpr> = VECTOR_INST %vreg4 <sgpr>
///
/// Now this code contains an illegal copy from a VGPR to an SGPR.
///
/// In order to avoid this problem, this pass searches for PHI instructions
/// which define a <vsrc> register and constrains its definition class to
/// <vgpr> if the user of the PHI's definition register is a vector instruction.
/// If the PHI's definition class is constrained to <vgpr> then the coalescer
/// will be unable to perform the COPY removal from the above example which
/// ultimately led to the creation of an illegal COPY.
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "si-fix-sgpr-copies"
namespace {
class SIFixSGPRCopies : public MachineFunctionPass {
public:
static char ID;
SIFixSGPRCopies() : MachineFunctionPass(ID) { }
bool runOnMachineFunction(MachineFunction &MF) override;
const char *getPassName() const override {
return "SI Fix SGPR copies";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
};
} // End anonymous namespace
INITIALIZE_PASS(SIFixSGPRCopies, DEBUG_TYPE,
"SI Fix SGPR copies", false, false)
char SIFixSGPRCopies::ID = 0;
char &llvm::SIFixSGPRCopiesID = SIFixSGPRCopies::ID;
FunctionPass *llvm::createSIFixSGPRCopiesPass() {
return new SIFixSGPRCopies();
}
static bool hasVGPROperands(const MachineInstr &MI, const SIRegisterInfo *TRI) {
const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
if (!MI.getOperand(i).isReg() ||
!TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
continue;
if (TRI->hasVGPRs(MRI.getRegClass(MI.getOperand(i).getReg())))
return true;
}
return false;
}
static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
getCopyRegClasses(const MachineInstr &Copy,
const SIRegisterInfo &TRI,
const MachineRegisterInfo &MRI) {
unsigned DstReg = Copy.getOperand(0).getReg();
unsigned SrcReg = Copy.getOperand(1).getReg();
const TargetRegisterClass *SrcRC =
TargetRegisterInfo::isVirtualRegister(SrcReg) ?
MRI.getRegClass(SrcReg) :
TRI.getPhysRegClass(SrcReg);
// We don't really care about the subregister here.
// SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
const TargetRegisterClass *DstRC =
TargetRegisterInfo::isVirtualRegister(DstReg) ?
MRI.getRegClass(DstReg) :
TRI.getPhysRegClass(DstReg);
return std::make_pair(SrcRC, DstRC);
}
static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
const TargetRegisterClass *DstRC,
const SIRegisterInfo &TRI) {
return TRI.isSGPRClass(DstRC) && TRI.hasVGPRs(SrcRC);
}
static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
const TargetRegisterClass *DstRC,
const SIRegisterInfo &TRI) {
return TRI.isSGPRClass(SrcRC) && TRI.hasVGPRs(DstRC);
}
// Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
//
// SGPRx = ...
// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
// VGPRz = COPY SGPRy
//
// ==>
//
// VGPRx = COPY SGPRx
// VGPRz = REG_SEQUENCE VGPRx, sub0
//
// This exposes immediate folding opportunities when materializing 64-bit
// immediates.
static bool foldVGPRCopyIntoRegSequence(MachineInstr &MI,
const SIRegisterInfo *TRI,
const SIInstrInfo *TII,
MachineRegisterInfo &MRI) {
assert(MI.isRegSequence());
unsigned DstReg = MI.getOperand(0).getReg();
if (!TRI->isSGPRClass(MRI.getRegClass(DstReg)))
return false;
if (!MRI.hasOneUse(DstReg))
return false;
MachineInstr &CopyUse = *MRI.use_instr_begin(DstReg);
if (!CopyUse.isCopy())
return false;
const TargetRegisterClass *SrcRC, *DstRC;
std::tie(SrcRC, DstRC) = getCopyRegClasses(CopyUse, *TRI, MRI);
if (!isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
return false;
// TODO: Could have multiple extracts?
unsigned SubReg = CopyUse.getOperand(1).getSubReg();
if (SubReg != AMDGPU::NoSubRegister)
return false;
MRI.setRegClass(DstReg, DstRC);
// SGPRx = ...
// SGPRy = REG_SEQUENCE SGPRx, sub0 ...
// VGPRz = COPY SGPRy
// =>
// VGPRx = COPY SGPRx
// VGPRz = REG_SEQUENCE VGPRx, sub0
MI.getOperand(0).setReg(CopyUse.getOperand(0).getReg());
for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
unsigned SrcReg = MI.getOperand(I).getReg();
unsigned SrcSubReg = MI.getOperand(I).getSubReg();
const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
assert(TRI->isSGPRClass(SrcRC) &&
"Expected SGPR REG_SEQUENCE to only have SGPR inputs");
SrcRC = TRI->getSubRegClass(SrcRC, SrcSubReg);
const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SrcRC);
unsigned TmpReg = MRI.createVirtualRegister(NewSrcRC);
BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY), TmpReg)
.addOperand(MI.getOperand(I));
MI.getOperand(I).setReg(TmpReg);
}
CopyUse.eraseFromParent();
return true;
}
bool SIFixSGPRCopies::runOnMachineFunction(MachineFunction &MF) {
MachineRegisterInfo &MRI = MF.getRegInfo();
const SIRegisterInfo *TRI =
static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
const SIInstrInfo *TII =
static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo());
SmallVector<MachineInstr *, 16> Worklist;
for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
BI != BE; ++BI) {
MachineBasicBlock &MBB = *BI;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
I != E; ++I) {
MachineInstr &MI = *I;
switch (MI.getOpcode()) {
default:
continue;
case AMDGPU::COPY: {
// If the destination register is a physical register there isn't really
// much we can do to fix this.
if (!TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg()))
continue;
const TargetRegisterClass *SrcRC, *DstRC;
std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, MRI);
if (isVGPRToSGPRCopy(SrcRC, DstRC, *TRI)) {
DEBUG(dbgs() << "Fixing VGPR -> SGPR copy: " << MI);
TII->moveToVALU(MI);
}
break;
}
case AMDGPU::PHI: {
DEBUG(dbgs() << "Fixing PHI: " << MI);
unsigned Reg = MI.getOperand(0).getReg();
if (!TRI->isSGPRClass(MRI.getRegClass(Reg)))
break;
// If a PHI node defines an SGPR and any of its operands are VGPRs,
// then we need to move it to the VALU.
//
// Also, if a PHI node defines an SGPR and has all SGPR operands
// we must move it to the VALU, because the SGPR operands will
// all end up being assigned the same register, which means
// there is a potential for a conflict if different threads take
// different control flow paths.
//
// For Example:
//
// sgpr0 = def;
// ...
// sgpr1 = def;
// ...
// sgpr2 = PHI sgpr0, sgpr1
// use sgpr2;
//
// Will Become:
//
// sgpr2 = def;
// ...
// sgpr2 = def;
// ...
// use sgpr2
//
// FIXME: This is OK if the branching decision is made based on an
// SGPR value.
bool SGPRBranch = false;
// The one exception to this rule is when one of the operands
// is defined by a SI_BREAK, SI_IF_BREAK, or SI_ELSE_BREAK
// instruction. In this case, there we know the program will
// never enter the second block (the loop) without entering
// the first block (where the condition is computed), so there
// is no chance for values to be over-written.
bool HasBreakDef = false;
for (unsigned i = 1; i < MI.getNumOperands(); i+=2) {
unsigned Reg = MI.getOperand(i).getReg();
if (TRI->hasVGPRs(MRI.getRegClass(Reg))) {
TII->moveToVALU(MI);
break;
}
MachineInstr *DefInstr = MRI.getUniqueVRegDef(Reg);
assert(DefInstr);
switch(DefInstr->getOpcode()) {
case AMDGPU::SI_BREAK:
case AMDGPU::SI_IF_BREAK:
case AMDGPU::SI_ELSE_BREAK:
// If we see a PHI instruction that defines an SGPR, then that PHI
// instruction has already been considered and should have
// a *_BREAK as an operand.
case AMDGPU::PHI:
HasBreakDef = true;
break;
}
}
if (!SGPRBranch && !HasBreakDef)
TII->moveToVALU(MI);
break;
}
case AMDGPU::REG_SEQUENCE: {
if (TRI->hasVGPRs(TII->getOpRegClass(MI, 0)) ||
!hasVGPROperands(MI, TRI)) {
foldVGPRCopyIntoRegSequence(MI, TRI, TII, MRI);
continue;
}
DEBUG(dbgs() << "Fixing REG_SEQUENCE: " << MI);
TII->moveToVALU(MI);
break;
}
case AMDGPU::INSERT_SUBREG: {
const TargetRegisterClass *DstRC, *Src0RC, *Src1RC;
DstRC = MRI.getRegClass(MI.getOperand(0).getReg());
Src0RC = MRI.getRegClass(MI.getOperand(1).getReg());
Src1RC = MRI.getRegClass(MI.getOperand(2).getReg());
if (TRI->isSGPRClass(DstRC) &&
(TRI->hasVGPRs(Src0RC) || TRI->hasVGPRs(Src1RC))) {
DEBUG(dbgs() << " Fixing INSERT_SUBREG: " << MI);
TII->moveToVALU(MI);
}
break;
}
}
}
}
return true;
}
<|endoftext|>
|
<commit_before>//
// database.cpp
// Xapiand
//
// Created by Germán M. Bravo on 2/23/15.
// Copyright (c) 2015 Germán M. Bravo. All rights reserved.
//
#include "database.h"
Database::Database(Endpoints &endpoints_, bool writable_)
: endpoints(endpoints_),
writable(writable_)
{
hash = endpoints.hash(writable);
reopen();
}
void
Database::reopen()
{
// FIXME: Handle remote endpoints and figure out if the endpoint is a local database
if (writable) {
db = new Xapian::WritableDatabase(endpoints[0].path, Xapian::DB_CREATE_OR_OPEN);
} else {
db = new Xapian::Database(endpoints[0].path, Xapian::DB_CREATE_OR_OPEN);
if (!writable) {
std::vector<Endpoint>::const_iterator i(endpoints.begin());
for (++i; i != endpoints.end(); ++i) {
db->add_database(Xapian::Database((*i).path));
}
} else if (endpoints.size() != 1) {
printf("ERROR: Expecting exactly one database.");
}
}
}
Database::~Database()
{
delete db;
}
DatabaseQueue::~DatabaseQueue()
{
// std::queue<Database *>::const_iterator i(queue.begin());
// for (; i != databases.end(); ++i) {
// (*i).second.finish();
// }
}
DatabasePool::DatabasePool()
{
pthread_mutex_init(&qmtx, 0);
}
DatabasePool::~DatabasePool()
{
finish();
pthread_mutex_destroy(&qmtx);
}
void DatabasePool::finish() {
pthread_mutex_lock(&qmtx);
finished = true;
pthread_mutex_unlock(&qmtx);
}
bool
DatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable)
{
Database *database_ = NULL;
pthread_mutex_lock(&qmtx);
if (!finished && *database == NULL) {
size_t hash = endpoints.hash(writable);
DatabaseQueue &queue = databases[hash];
if (!queue.pop(database_, 0)) {
if (!writable || queue.instances_count == 0) {
database_ = new Database(endpoints, writable);
queue.instances_count++;
}
// FIXME: lock until a database is available if it can't get one
}
*database = database_;
}
pthread_mutex_unlock(&qmtx);
return database_ != NULL;
}
void
DatabasePool::checkin(Database **database)
{
pthread_mutex_lock(&qmtx);
DatabaseQueue &queue = databases[(*database)->hash];
queue.push(*database);
*database = NULL;
pthread_mutex_unlock(&qmtx);
}
<commit_msg>Initialization fixes<commit_after>//
// database.cpp
// Xapiand
//
// Created by Germán M. Bravo on 2/23/15.
// Copyright (c) 2015 Germán M. Bravo. All rights reserved.
//
#include "database.h"
Database::Database(Endpoints &endpoints_, bool writable_)
: endpoints(endpoints_),
writable(writable_)
{
hash = endpoints.hash(writable);
reopen();
}
void
Database::reopen()
{
// FIXME: Handle remote endpoints and figure out if the endpoint is a local database
if (writable) {
db = new Xapian::WritableDatabase(endpoints[0].path, Xapian::DB_CREATE_OR_OPEN);
} else {
db = new Xapian::Database(endpoints[0].path, Xapian::DB_CREATE_OR_OPEN);
if (!writable) {
std::vector<Endpoint>::const_iterator i(endpoints.begin());
for (++i; i != endpoints.end(); ++i) {
db->add_database(Xapian::Database((*i).path));
}
} else if (endpoints.size() != 1) {
printf("ERROR: Expecting exactly one database.");
}
}
}
Database::~Database()
{
delete db;
}
DatabaseQueue::DatabaseQueue()
: count(0)
{
}
DatabaseQueue::~DatabaseQueue()
{
// std::queue<Database *>::const_iterator i(queue.begin());
// for (; i != databases.end(); ++i) {
// (*i).second.finish();
// }
}
DatabasePool::DatabasePool()
: finished(false)
{
pthread_mutex_init(&qmtx, 0);
}
DatabasePool::~DatabasePool()
{
finish();
pthread_mutex_destroy(&qmtx);
}
void DatabasePool::finish() {
pthread_mutex_lock(&qmtx);
finished = true;
pthread_mutex_unlock(&qmtx);
}
bool
DatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable)
{
Database *database_ = NULL;
pthread_mutex_lock(&qmtx);
if (!finished && *database == NULL) {
size_t hash = endpoints.hash(writable);
DatabaseQueue &queue = databases[hash];
if (!queue.pop(database_, 0)) {
if (!writable || queue.count == 0) {
database_ = new Database(endpoints, writable);
queue.count++;
}
// FIXME: lock until a database is available if it can't get one
}
*database = database_;
}
pthread_mutex_unlock(&qmtx);
return database_ != NULL;
}
void
DatabasePool::checkin(Database **database)
{
pthread_mutex_lock(&qmtx);
DatabaseQueue &queue = databases[(*database)->hash];
queue.push(*database);
*database = NULL;
pthread_mutex_unlock(&qmtx);
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->Inherit(EventEmitter::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("Database"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "parallelize", Parallelize);
target->Set(String::NewSymbol("Database"),
constructor_template->GetFunction());
}
void Database::Process() {
if (!open && locked && !queue.empty()) {
EXCEPTION(String::New("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {
TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {
if (!open && locked) {
EXCEPTION(String::New("Database is closed"), SQLITE_MISUSE, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(handle_, baton->callback, 1, argv);
}
else {
Local<Value> argv[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
Handle<Value> Database::New(const Arguments& args) {
HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(Exception::TypeError(
String::New("Use the new operator to create new Database objects"))
);
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(String::NewSymbol("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("mode"), Integer::New(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);
EIO_BeginOpen(baton);
return args.This();
}
void Database::EIO_BeginOpen(Baton* baton) {
eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);
}
int Database::EIO_Open(eio_req *req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterOpen(eio_req *req) {
HandleScope scope;
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = Local<Value>::New(Null());
}
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
if (db->open) {
Local<Value> args[] = { String::NewSymbol("open") };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Close(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(EIO_BeginClose, baton, true);
return args.This();
}
void Database::EIO_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);
}
int Database::EIO_Close(eio_req *req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
}
else {
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterClose(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = Local<Value>::New(Null());
}
// Fire callbacks.
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
assert(baton->db->locked);
assert(!baton->db->open);
assert(!baton->db->handle);
assert(baton->db->pending == 0);
if (!db->open) {
Local<Value> args[] = { String::NewSymbol("close"), argv[0] };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Serialize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Parallelize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Exec(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(EIO_BeginExec, baton, true);
return args.This();
}
void Database::EIO_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);
}
int Database::EIO_Exec(eio_req *req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
return 0;
}
int Database::EIO_AfterExec(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(db->handle_, 2, args);
}
}
else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { Local<Value>::New(Null()) };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
db->Process();
delete baton;
return 0;
}
/**
* Override this so that we can properly close the database when this object
* gets garbage collected.
*/
void Database::Wrap(Handle<Object> handle) {
assert(handle_.IsEmpty());
assert(handle->InternalFieldCount() > 0);
handle_ = Persistent<Object>::New(handle);
handle_->SetPointerInInternalField(0, this);
handle_.MakeWeak(this, Destruct);
}
inline void Database::MakeWeak (void) {
handle_.MakeWeak(this, Destruct);
}
void Database::Unref() {
assert(!handle_.IsEmpty());
assert(!handle_.IsWeak());
assert(refs_ > 0);
if (--refs_ == 0) { MakeWeak(); }
}
void Database::Destruct(Persistent<Value> value, void *data) {
Database* db = static_cast<Database*>(data);
if (db->handle) {
eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);
ev_ref(EV_DEFAULT_UC);
}
else {
delete db;
}
}
int Database::EIO_Destruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
sqlite3_close(db->handle);
db->handle = NULL;
return 0;
}
int Database::EIO_AfterDestruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
ev_unref(EV_DEFAULT_UC);
delete db;
return 0;
}
<commit_msg>fix random "Use the new operator to create new Database objects" message<commit_after>#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->Inherit(EventEmitter::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("Database"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "parallelize", Parallelize);
target->Set(String::NewSymbol("Database"),
constructor_template->GetFunction());
}
void Database::Process() {
if (!open && locked && !queue.empty()) {
EXCEPTION(String::New("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {
TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {
if (!open && locked) {
EXCEPTION(String::New("Database is closed"), SQLITE_MISUSE, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(handle_, baton->callback, 1, argv);
}
else {
Local<Value> argv[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(handle_, 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
Handle<Value> Database::New(const Arguments& args) {
HandleScope scope;
if (!Database::HasInstance(args.This())) {
return ThrowException(Exception::TypeError(
String::New("Use the new operator to create new Database objects"))
);
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(String::NewSymbol("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("mode"), Integer::New(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);
EIO_BeginOpen(baton);
return args.This();
}
void Database::EIO_BeginOpen(Baton* baton) {
eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);
}
int Database::EIO_Open(eio_req *req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterOpen(eio_req *req) {
HandleScope scope;
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = Local<Value>::New(Null());
}
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
if (db->open) {
Local<Value> args[] = { String::NewSymbol("open") };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Close(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(EIO_BeginClose, baton, true);
return args.This();
}
void Database::EIO_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);
}
int Database::EIO_Close(eio_req *req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->handle));
}
else {
db->handle = NULL;
}
return 0;
}
int Database::EIO_AfterClose(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = Local<Value>::New(Null());
}
// Fire callbacks.
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { String::NewSymbol("error"), argv[0] };
EMIT_EVENT(db->handle_, 2, args);
}
assert(baton->db->locked);
assert(!baton->db->open);
assert(!baton->db->handle);
assert(baton->db->pending == 0);
if (!db->open) {
Local<Value> args[] = { String::NewSymbol("close"), argv[0] };
EMIT_EVENT(db->handle_, 1, args);
db->Process();
}
delete baton;
return 0;
}
Handle<Value> Database::Serialize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Parallelize(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
return args.This();
}
Handle<Value> Database::Exec(const Arguments& args) {
HandleScope scope;
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(EIO_BeginExec, baton, true);
return args.This();
}
void Database::EIO_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->handle);
assert(baton->db->pending == 0);
eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);
}
int Database::EIO_Exec(eio_req *req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
return 0;
}
int Database::EIO_AfterExec(eio_req *req) {
HandleScope scope;
Baton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
if (baton->status != SQLITE_OK) {
EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);
if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
else {
Local<Value> args[] = { String::NewSymbol("error"), exception };
EMIT_EVENT(db->handle_, 2, args);
}
}
else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {
Local<Value> argv[] = { Local<Value>::New(Null()) };
TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);
}
db->Process();
delete baton;
return 0;
}
/**
* Override this so that we can properly close the database when this object
* gets garbage collected.
*/
void Database::Wrap(Handle<Object> handle) {
assert(handle_.IsEmpty());
assert(handle->InternalFieldCount() > 0);
handle_ = Persistent<Object>::New(handle);
handle_->SetPointerInInternalField(0, this);
handle_.MakeWeak(this, Destruct);
}
inline void Database::MakeWeak (void) {
handle_.MakeWeak(this, Destruct);
}
void Database::Unref() {
assert(!handle_.IsEmpty());
assert(!handle_.IsWeak());
assert(refs_ > 0);
if (--refs_ == 0) { MakeWeak(); }
}
void Database::Destruct(Persistent<Value> value, void *data) {
Database* db = static_cast<Database*>(data);
if (db->handle) {
eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);
ev_ref(EV_DEFAULT_UC);
}
else {
delete db;
}
}
int Database::EIO_Destruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
sqlite3_close(db->handle);
db->handle = NULL;
return 0;
}
int Database::EIO_AfterDestruct(eio_req *req) {
Database* db = static_cast<Database*>(req->data);
ev_unref(EV_DEFAULT_UC);
delete db;
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef STORED_VALUE_H
#define STORED_VALUE_H 1
#include "locks.hh"
extern "C" {
extern rel_time_t (*ep_current_time)();
}
// Forward declaration for StoredValue
class HashTable;
class StoredValue {
public:
StoredValue(const Item &itm, StoredValue *n) :
key(itm.getKey()), value(itm.getValue()),
flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n),
cas(itm.getCas())
{
markDirty();
}
StoredValue(const Item &itm, StoredValue *n, bool setDirty) :
key(itm.getKey()), value(itm.getValue()),
flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n),
cas(itm.getCas())
{
if (setDirty) {
markDirty();
} else {
markClean(NULL, NULL);
}
}
~StoredValue() {
}
void markDirty() {
data_age = ep_current_time();
if (!isDirty()) {
dirtied = data_age;
}
}
void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) {
data_age = dataAge;
dirtied = dirtyAge;
}
// returns time this object was dirtied.
void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) {
if (dirtyAge) {
*dirtyAge = dirtied;
}
if (dataAge) {
*dataAge = data_age;
}
dirtied = 0;
data_age = 0;
}
bool isDirty() const {
return dirtied != 0;
}
bool isClean() const {
return dirtied == 0;
}
const std::string &getKey() const {
return key;
}
value_t getValue() const {
return value;
}
rel_time_t getExptime() const {
return exptime;
}
uint32_t getFlags() const {
return flags;
}
void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
cas = theCas;
flags = newFlags;
exptime = newExp;
value = v;
markDirty();
}
uint64_t getCas() const {
return cas;
}
// for stats
rel_time_t getDirtied() const {
return dirtied;
}
rel_time_t getDataAge() const {
return data_age;
}
private:
friend class HashTable;
std::string key;
value_t value;
uint32_t flags;
rel_time_t exptime;
rel_time_t dirtied;
rel_time_t data_age;
StoredValue *next;
uint64_t cas;
DISALLOW_COPY_AND_ASSIGN(StoredValue);
};
typedef enum {
NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY
} mutation_type_t;
class HashTableVisitor {
public:
virtual ~HashTableVisitor() {}
virtual void visit(StoredValue *v) = 0;
};
class HashTable {
public:
// Construct with number of buckets and locks.
HashTable(size_t s = 196613, size_t l = 193) {
size = s;
n_locks = l;
active = true;
values = (StoredValue**)calloc(s, sizeof(StoredValue**));
mutexes = new Mutex[l];
}
~HashTable() {
clear();
delete []mutexes;
free(values);
}
void clear() {
assert(active);
for (int i = 0; i < (int)size; i++) {
LockHolder lh(getMutex(i));
while (values[i]) {
StoredValue *v = values[i];
values[i] = v->next;
delete v;
}
}
}
StoredValue *find(std::string &key) {
assert(active);
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
return unlocked_find(key, bucket_num);
}
mutation_type_t set(const Item &val) {
assert(active);
mutation_type_t rv = NOT_FOUND;
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
Item &itm = const_cast<Item&>(val);
if (v) {
if (val.getCas() != 0 && val.getCas() != v->getCas()) {
return INVALID_CAS;
}
itm.setCas();
rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY;
v->setValue(itm.getValue(),
itm.getFlags(), itm.getExptime(),
itm.getCas());
} else {
if (itm.getCas() != 0) {
return INVALID_CAS;
}
itm.setCas();
v = new StoredValue(itm, values[bucket_num]);
values[bucket_num] = v;
}
return rv;
}
bool add(const Item &val, bool isDirty = true) {
assert(active);
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
if (v) {
return false;
} else {
Item &itm = const_cast<Item&>(val);
itm.setCas();
v = new StoredValue(itm, values[bucket_num], isDirty);
values[bucket_num] = v;
}
return true;
}
StoredValue *unlocked_find(const std::string &key, int bucket_num) {
StoredValue *v = values[bucket_num];
while (v) {
if (key.compare(v->key) == 0) {
return v;
}
v = v->next;
}
return NULL;
}
inline int bucket(const std::string &key) {
assert(active);
int h=5381;
int i=0;
const char *str = key.c_str();
for(i=0; str[i] != 0x00; i++) {
h = ((h << 5) + h) ^ str[i];
}
return abs(h) % (int)size;
}
// Get the mutex for a bucket (for doing your own lock management)
inline Mutex &getMutex(int bucket_num) {
assert(active);
assert(bucket_num < (int)size);
assert(bucket_num >= 0);
int lock_num = bucket_num % (int)n_locks;
assert(lock_num < (int)n_locks);
assert(lock_num >= 0);
return mutexes[lock_num];
}
// True if it existed
bool del(const std::string &key) {
assert(active);
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
StoredValue *v = values[bucket_num];
// Special case empty bucket.
if (!v) {
return false;
}
// Special case the first one
if (key.compare(v->key) == 0) {
values[bucket_num] = v->next;
delete v;
return true;
}
while (v->next) {
if (key.compare(v->next->key) == 0) {
StoredValue *tmp = v->next;
v->next = v->next->next;
delete tmp;
return true;
} else {
v = v->next;
}
}
return false;
}
void visit(HashTableVisitor &visitor) {
for (int i = 0; i < (int)size; i++) {
LockHolder lh(getMutex(i));
StoredValue *v = values[i];
while (v) {
visitor.visit(v);
v = v->next;
}
}
}
private:
size_t size;
size_t n_locks;
bool active;
StoredValue **values;
Mutex *mutexes;
DISALLOW_COPY_AND_ASSIGN(HashTable);
};
#endif /* STORED_VALUE_H */
<commit_msg>Use new[] for hash table values.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef STORED_VALUE_H
#define STORED_VALUE_H 1
#include <algorithm>
#include "locks.hh"
extern "C" {
extern rel_time_t (*ep_current_time)();
}
// Forward declaration for StoredValue
class HashTable;
class StoredValue {
public:
StoredValue(const Item &itm, StoredValue *n) :
key(itm.getKey()), value(itm.getValue()),
flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n),
cas(itm.getCas())
{
markDirty();
}
StoredValue(const Item &itm, StoredValue *n, bool setDirty) :
key(itm.getKey()), value(itm.getValue()),
flags(itm.getFlags()), exptime(itm.getExptime()), dirtied(0), next(n),
cas(itm.getCas())
{
if (setDirty) {
markDirty();
} else {
markClean(NULL, NULL);
}
}
~StoredValue() {
}
void markDirty() {
data_age = ep_current_time();
if (!isDirty()) {
dirtied = data_age;
}
}
void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) {
data_age = dataAge;
dirtied = dirtyAge;
}
// returns time this object was dirtied.
void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) {
if (dirtyAge) {
*dirtyAge = dirtied;
}
if (dataAge) {
*dataAge = data_age;
}
dirtied = 0;
data_age = 0;
}
bool isDirty() const {
return dirtied != 0;
}
bool isClean() const {
return dirtied == 0;
}
const std::string &getKey() const {
return key;
}
value_t getValue() const {
return value;
}
rel_time_t getExptime() const {
return exptime;
}
uint32_t getFlags() const {
return flags;
}
void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
cas = theCas;
flags = newFlags;
exptime = newExp;
value = v;
markDirty();
}
uint64_t getCas() const {
return cas;
}
// for stats
rel_time_t getDirtied() const {
return dirtied;
}
rel_time_t getDataAge() const {
return data_age;
}
private:
friend class HashTable;
std::string key;
value_t value;
uint32_t flags;
rel_time_t exptime;
rel_time_t dirtied;
rel_time_t data_age;
StoredValue *next;
uint64_t cas;
DISALLOW_COPY_AND_ASSIGN(StoredValue);
};
typedef enum {
NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY
} mutation_type_t;
class HashTableVisitor {
public:
virtual ~HashTableVisitor() {}
virtual void visit(StoredValue *v) = 0;
};
class HashTable {
public:
// Construct with number of buckets and locks.
HashTable(size_t s = 196613, size_t l = 193) {
size = s;
n_locks = l;
active = true;
values = new StoredValue*[s];
std::fill_n(values, s, static_cast<StoredValue*>(NULL));
mutexes = new Mutex[l];
}
~HashTable() {
clear();
delete []mutexes;
delete []values;
}
void clear() {
assert(active);
for (int i = 0; i < (int)size; i++) {
LockHolder lh(getMutex(i));
while (values[i]) {
StoredValue *v = values[i];
values[i] = v->next;
delete v;
}
}
}
StoredValue *find(std::string &key) {
assert(active);
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
return unlocked_find(key, bucket_num);
}
mutation_type_t set(const Item &val) {
assert(active);
mutation_type_t rv = NOT_FOUND;
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
Item &itm = const_cast<Item&>(val);
if (v) {
if (val.getCas() != 0 && val.getCas() != v->getCas()) {
return INVALID_CAS;
}
itm.setCas();
rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY;
v->setValue(itm.getValue(),
itm.getFlags(), itm.getExptime(),
itm.getCas());
} else {
if (itm.getCas() != 0) {
return INVALID_CAS;
}
itm.setCas();
v = new StoredValue(itm, values[bucket_num]);
values[bucket_num] = v;
}
return rv;
}
bool add(const Item &val, bool isDirty = true) {
assert(active);
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
if (v) {
return false;
} else {
Item &itm = const_cast<Item&>(val);
itm.setCas();
v = new StoredValue(itm, values[bucket_num], isDirty);
values[bucket_num] = v;
}
return true;
}
StoredValue *unlocked_find(const std::string &key, int bucket_num) {
StoredValue *v = values[bucket_num];
while (v) {
if (key.compare(v->key) == 0) {
return v;
}
v = v->next;
}
return NULL;
}
inline int bucket(const std::string &key) {
assert(active);
int h=5381;
int i=0;
const char *str = key.c_str();
for(i=0; str[i] != 0x00; i++) {
h = ((h << 5) + h) ^ str[i];
}
return abs(h) % (int)size;
}
// Get the mutex for a bucket (for doing your own lock management)
inline Mutex &getMutex(int bucket_num) {
assert(active);
assert(bucket_num < (int)size);
assert(bucket_num >= 0);
int lock_num = bucket_num % (int)n_locks;
assert(lock_num < (int)n_locks);
assert(lock_num >= 0);
return mutexes[lock_num];
}
// True if it existed
bool del(const std::string &key) {
assert(active);
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
StoredValue *v = values[bucket_num];
// Special case empty bucket.
if (!v) {
return false;
}
// Special case the first one
if (key.compare(v->key) == 0) {
values[bucket_num] = v->next;
delete v;
return true;
}
while (v->next) {
if (key.compare(v->next->key) == 0) {
StoredValue *tmp = v->next;
v->next = v->next->next;
delete tmp;
return true;
} else {
v = v->next;
}
}
return false;
}
void visit(HashTableVisitor &visitor) {
for (int i = 0; i < (int)size; i++) {
LockHolder lh(getMutex(i));
StoredValue *v = values[i];
while (v) {
visitor.visit(v);
v = v->next;
}
}
}
private:
size_t size;
size_t n_locks;
bool active;
StoredValue **values;
Mutex *mutexes;
DISALLOW_COPY_AND_ASSIGN(HashTable);
};
#endif /* STORED_VALUE_H */
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Matthew Harvey
*
* 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 "date_parser.hpp"
#include "date.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <jewel/assert.hpp>
#include <jewel/log.hpp>
#include <jewel/optional.hpp>
#include <wx/datetime.h>
#include <wx/intl.h>
#include <wx/string.h>
#include <algorithm>
#include <exception>
#include <iterator>
#include <map>
#include <string>
#include <unordered_set>
#include <vector>
using boost::algorithm::split;
using boost::lexical_cast;
using boost::optional;
using jewel::Log;
using jewel::value;
using std::back_inserter;
using std::begin;
using std::end;
using std::find;
using std::find_first_of;
using std::map;
using std::out_of_range;
using std::string;
using std::transform;
using std::unordered_set;
using std::vector;
namespace gregorian = boost::gregorian;
namespace lambda = boost::lambda;
namespace dcm
{
namespace
{
// Returns true if and only if c is one of the special characters that
// can appear in a strftime format string representing a field date or
// time field.
// TODO MEDIUM PRIORITY There characters under the C++11 standard in
// addition to the below.
bool is_date_time_format_char(char c)
{
static char const chars_a[] =
{ 'a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'P',
'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z'
};
static unordered_set<char> const chars(begin(chars_a), end(chars_a));
return chars.find(c) != chars.end();
}
enum class DateComponentType: unsigned char
{
day,
month,
year
};
map<char, DateComponentType> const&
ordinary_date_format_chars_map()
{
typedef map<char, DateComponentType> Map;
static Map ret;
if (ret.empty())
{
ret['d'] = DateComponentType::day; // day of month (01-31)
ret['m'] = DateComponentType::month; // month (01-12)
ret['y'] = DateComponentType::year; // year in century (00-99)
ret['Y'] = DateComponentType::year; // full year
# ifndef NDEBUG
for (auto const& elem: ret)
{
JEWEL_ASSERT (is_date_time_format_char(elem.first));
}
# endif // NDEBUG
}
JEWEL_ASSERT (!ret.empty());
return ret;
}
// Returns true if and only if c is one of the special characters that
// can appear in a strftime format string representing a field in a tm
// struct, which is a date field and not a time field, and which
// represents in numerical format, either the day of the month, the
// month, or the year.
bool is_ordinary_date_format_char(char c)
{
map<char, DateComponentType> const& map =
ordinary_date_format_chars_map();
return map.find(c) != map.end();
}
// Examines a strftime-like date format string. If the string is an
// "ordinary" date format string, returns an optional initialized with the
// character that separates the fields in that string; otherwise, returns
// an uninitialized optional. For this purpose, the string is an
// "ordinary" date format string if and only if: (a) there are exactly
// three date fields, being a day-of-month, month, and year field
// (not necessarily in that order), such that each of these fields is
// represented by a character for which is_ordinary_date_format_char
// returns true (along with the usual '%' and possible other modifiers
// between the '%' and the format char); and (b) there is exactly one
// separator character, which appears twice in the string, separating
// the first and second fields, and separating the second and third
// fields.
optional<char> separating_char(wxString const& str)
{
// Analyse the string; if at any point we find anything inconsistent
// with "ordinary date format", then we return an uninitialized
// optional.
JEWEL_LOG_TRACE();
JEWEL_LOG_VALUE(Log::info, str);
optional<char> separator;
wxString::const_iterator it = str.begin();
wxString::const_iterator const end = str.end();
size_t num_fields = 0;
while (it != end)
{
if (*it == '%')
{
// Skip over any "modifiers"
while ((it != end) && !is_date_time_format_char(*it)) ++it;
// If we've reached the end without find a
// date_time_format_char, then it's not ordinary format.
if (it == end)
{
return optional<char>();
}
JEWEL_ASSERT (is_date_time_format_char(*it));
// If our format char is not ordinary, then it's not
// ordinary format.
if (!is_ordinary_date_format_char(*it))
{
return optional<char>();
}
JEWEL_ASSERT (is_ordinary_date_format_char(*it));
++num_fields;
++it;
// Have we found all the fields? Then we should
// be at the end.
if (num_fields == 3)
{
JEWEL_ASSERT (separator || (it != end));
return separator;
}
JEWEL_ASSERT (num_fields < 3);
// To be an ordinary format string,
// the next character should be a separator, and not another
// format char, and not the end. If we already
// have encountered a separator, then this should be an
// instance of the same separator.
if
( (it == end) ||
(is_date_time_format_char(*it)) ||
(separator && (*separator != *it))
)
{
return optional<char>();
}
separator = *it;
++it;
}
else
{
return optional<char>();
}
}
return separator;
}
optional<DateComponentType> maybe_date_component_type(char c)
{
optional<DateComponentType> ret;
switch (c)
{
case 'd':
ret = DateComponentType::day;
break;
case 'm':
ret = DateComponentType::month;
break;
case 'y': // fall through
case 'Y':
ret = DateComponentType::year;
break;
default:
; // do nothing and fall through
}
JEWEL_ASSERT
( static_cast<bool>(ret) ==
is_ordinary_date_format_char(c)
);
return ret;
}
// Should only call if we know the last character of s is such as
// to return an initialized optional when passed to date_component_type.
DateComponentType date_component_type(wxString const s)
{
JEWEL_ASSERT (!s.IsEmpty());
return value(maybe_date_component_type(static_cast<char>(s.Last())));
}
void fill_missing_components(map<DateComponentType, int>& out)
{
switch (out.size())
{
case 0:
out[DateComponentType::day] = today().day();
goto fill_month;
case 1:
if (out.find(DateComponentType::day) == out.end()) return;
fill_month: out[DateComponentType::month] = today().month();
goto fill_year;
case 2:
if (out.find(DateComponentType::month) == out.end()) return;
fill_year: out[DateComponentType::year] = today().year();
// fall through
default:
return;
}
}
optional<gregorian::date>
tolerant_parse_aux
( wxString const& p_target,
wxString const& p_format
)
{
optional<char> const maybe_sep = separating_char(p_format);
if (!maybe_sep)
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (maybe_sep);
char const sep = *maybe_sep;
JEWEL_LOG_VALUE(Log::trace, sep);
vector<wxString> target_fields;
vector<wxString> format_fields;
split(target_fields, p_target, (lambda::_1 == sep));
split(format_fields, p_format, (lambda::_1 == sep));
if ((target_fields.size() > 3) || (format_fields.size() != 3))
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (target_fields.size() <= 3);
JEWEL_ASSERT (format_fields.size() == 3);
vector<DateComponentType> component_types;
transform
( format_fields.begin(),
format_fields.end(),
back_inserter(component_types),
date_component_type
);
JEWEL_ASSERT (component_types.size() == 3);
map<DateComponentType, int> components;
// bare scope
{
vector<wxString>::size_type j = 0;
vector<wxString>::size_type const szj = target_fields.size();
for ( ; j != szj; ++j)
{
wxString field = target_fields[j];
if ((*(field.begin()) == '0') && (field.size() > 1))
{
field = wxString(field.begin() + 1, field.end());
}
int val = -1;
try
{
val = lexical_cast<int>(field);
}
catch (boost::bad_lexical_cast&)
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (val >= 0);
JEWEL_ASSERT (j < 3);
DateComponentType component_type = component_types[j];
if (target_fields.size() == 1)
{
component_type = DateComponentType::day;
}
else if (target_fields.size() == 2)
{
DateComponentType const day_and_month[] =
{ DateComponentType::day,
DateComponentType::month
};
DateComponentType const first = *find_first_of
( component_types.begin(),
component_types.end(),
begin(day_and_month),
end(day_and_month)
);
switch (j)
{
case 0:
component_type = first;
break;
case 1:
component_type =
( (first == DateComponentType::day)?
DateComponentType::month:
DateComponentType::day
);
break;
default:
JEWEL_HARD_ASSERT (false);
}
}
components[component_type] = val;
}
} // end bare scope
fill_missing_components(components);
if (components.size() != 3)
{
return optional<gregorian::date>();
}
if (components.at(DateComponentType::year) < 100)
{
components[DateComponentType::year] += 2000;
}
try
{
JEWEL_LOG_TRACE();
JEWEL_ASSERT (components.size() == 3);
return optional<gregorian::date>
( gregorian::date
( components.at(DateComponentType::year),
components.at(DateComponentType::month),
components.at(DateComponentType::day)
)
);
}
catch (out_of_range&)
{
return optional<gregorian::date>();
}
}
} // end anonymous namespace
DateParser::DateParser
( wxString const& p_primary_format,
wxString const& p_secondary_format
):
m_primary_format(p_primary_format),
m_secondary_format(p_secondary_format)
{
}
optional<gregorian::date>
DateParser::parse(wxString const& p_string, bool p_be_tolerant) const
{
optional<gregorian::date> ret;
wxString::const_iterator parsed_to_position;
wxDateTime date_wx;
wxString const* const formats[] =
{ &m_primary_format,
&m_secondary_format
};
for (wxString const* const format: formats)
{
date_wx.ParseFormat
( p_string,
*(format),
&parsed_to_position
);
if (parsed_to_position == p_string.end())
{
// Parsing was successful
int year = date_wx.GetYear();
if (year < 100) year += 2000;
int const month = static_cast<int>(date_wx.GetMonth()) + 1;
int const day = date_wx.GetDay();
try
{
ret = gregorian::date(year, month, day);
return ret;
}
catch (boost::exception&)
{
}
}
}
if (p_be_tolerant)
{
return tolerant_parse(p_string);
}
return ret;
}
optional<gregorian::date>
DateParser::tolerant_parse(wxString const& p_string) const
{
JEWEL_LOG_TRACE();
optional<gregorian::date> const ret =
tolerant_parse_aux(p_string, m_primary_format);
return (ret? ret: tolerant_parse_aux(p_string, m_secondary_format));
}
} // namespace dcm
<commit_msg>Minor simplification and comment edit in date_parser.cpp.<commit_after>/*
* Copyright 2013 Matthew Harvey
*
* 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 "date_parser.hpp"
#include "date.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <jewel/assert.hpp>
#include <jewel/log.hpp>
#include <jewel/optional.hpp>
#include <wx/datetime.h>
#include <wx/intl.h>
#include <wx/string.h>
#include <algorithm>
#include <exception>
#include <iterator>
#include <map>
#include <string>
#include <unordered_set>
#include <vector>
using boost::algorithm::split;
using boost::lexical_cast;
using boost::optional;
using jewel::Log;
using jewel::value;
using std::back_inserter;
using std::begin;
using std::end;
using std::find;
using std::find_first_of;
using std::map;
using std::out_of_range;
using std::string;
using std::transform;
using std::unordered_set;
using std::vector;
namespace gregorian = boost::gregorian;
namespace lambda = boost::lambda;
namespace dcm
{
namespace
{
// Returns true if and only if c is one of the special characters that
// can appear in a strftime format string representing a field date or
// time field.
// TODO MEDIUM PRIORITY There are characters under the C++11 standard in
// addition to the below.
bool is_date_time_format_char(char c)
{
static unordered_set<char> const chars
{ 'a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'P',
'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z'
};
return chars.find(c) != chars.end();
}
enum class DateComponentType: unsigned char
{
day,
month,
year
};
map<char, DateComponentType> const&
ordinary_date_format_chars_map()
{
typedef map<char, DateComponentType> Map;
static Map ret;
if (ret.empty())
{
ret['d'] = DateComponentType::day; // day of month (01-31)
ret['m'] = DateComponentType::month; // month (01-12)
ret['y'] = DateComponentType::year; // year in century (00-99)
ret['Y'] = DateComponentType::year; // full year
# ifndef NDEBUG
for (auto const& elem: ret)
{
JEWEL_ASSERT (is_date_time_format_char(elem.first));
}
# endif // NDEBUG
}
JEWEL_ASSERT (!ret.empty());
return ret;
}
// Returns true if and only if c is one of the special characters that
// can appear in a strftime format string representing a field in a tm
// struct, which is a date field and not a time field, and which
// represents in numerical format, either the day of the month, the
// month, or the year.
bool is_ordinary_date_format_char(char c)
{
map<char, DateComponentType> const& map =
ordinary_date_format_chars_map();
return map.find(c) != map.end();
}
// Examines a strftime-like date format string. If the string is an
// "ordinary" date format string, returns an optional initialized with the
// character that separates the fields in that string; otherwise, returns
// an uninitialized optional. For this purpose, the string is an
// "ordinary" date format string if and only if: (a) there are exactly
// three date fields, being a day-of-month, month, and year field
// (not necessarily in that order), such that each of these fields is
// represented by a character for which is_ordinary_date_format_char
// returns true (along with the usual '%' and possible other modifiers
// between the '%' and the format char); and (b) there is exactly one
// separator character, which appears twice in the string, separating
// the first and second fields, and separating the second and third
// fields.
optional<char> separating_char(wxString const& str)
{
// Analyse the string; if at any point we find anything inconsistent
// with "ordinary date format", then we return an uninitialized
// optional.
JEWEL_LOG_TRACE();
JEWEL_LOG_VALUE(Log::info, str);
optional<char> separator;
wxString::const_iterator it = str.begin();
wxString::const_iterator const end = str.end();
size_t num_fields = 0;
while (it != end)
{
if (*it == '%')
{
// Skip over any "modifiers"
while ((it != end) && !is_date_time_format_char(*it)) ++it;
// If we've reached the end without find a
// date_time_format_char, then it's not ordinary format.
if (it == end)
{
return optional<char>();
}
JEWEL_ASSERT (is_date_time_format_char(*it));
// If our format char is not ordinary, then it's not
// ordinary format.
if (!is_ordinary_date_format_char(*it))
{
return optional<char>();
}
JEWEL_ASSERT (is_ordinary_date_format_char(*it));
++num_fields;
++it;
// Have we found all the fields? Then we should
// be at the end.
if (num_fields == 3)
{
JEWEL_ASSERT (separator || (it != end));
return separator;
}
JEWEL_ASSERT (num_fields < 3);
// To be an ordinary format string,
// the next character should be a separator, and not another
// format char, and not the end. If we already
// have encountered a separator, then this should be an
// instance of the same separator.
if
( (it == end) ||
(is_date_time_format_char(*it)) ||
(separator && (*separator != *it))
)
{
return optional<char>();
}
separator = *it;
++it;
}
else
{
return optional<char>();
}
}
return separator;
}
optional<DateComponentType> maybe_date_component_type(char c)
{
optional<DateComponentType> ret;
switch (c)
{
case 'd':
ret = DateComponentType::day;
break;
case 'm':
ret = DateComponentType::month;
break;
case 'y': // fall through
case 'Y':
ret = DateComponentType::year;
break;
default:
; // do nothing and fall through
}
JEWEL_ASSERT
( static_cast<bool>(ret) ==
is_ordinary_date_format_char(c)
);
return ret;
}
// Should only call if we know the last character of s is such as
// to return an initialized optional when passed to date_component_type.
DateComponentType date_component_type(wxString const s)
{
JEWEL_ASSERT (!s.IsEmpty());
return value(maybe_date_component_type(static_cast<char>(s.Last())));
}
void fill_missing_components(map<DateComponentType, int>& out)
{
switch (out.size())
{
case 0:
out[DateComponentType::day] = today().day();
goto fill_month;
case 1:
if (out.find(DateComponentType::day) == out.end()) return;
fill_month: out[DateComponentType::month] = today().month();
goto fill_year;
case 2:
if (out.find(DateComponentType::month) == out.end()) return;
fill_year: out[DateComponentType::year] = today().year();
// fall through
default:
return;
}
}
optional<gregorian::date>
tolerant_parse_aux
( wxString const& p_target,
wxString const& p_format
)
{
optional<char> const maybe_sep = separating_char(p_format);
if (!maybe_sep)
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (maybe_sep);
char const sep = *maybe_sep;
JEWEL_LOG_VALUE(Log::trace, sep);
vector<wxString> target_fields;
vector<wxString> format_fields;
split(target_fields, p_target, (lambda::_1 == sep));
split(format_fields, p_format, (lambda::_1 == sep));
if ((target_fields.size() > 3) || (format_fields.size() != 3))
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (target_fields.size() <= 3);
JEWEL_ASSERT (format_fields.size() == 3);
vector<DateComponentType> component_types;
transform
( format_fields.begin(),
format_fields.end(),
back_inserter(component_types),
date_component_type
);
JEWEL_ASSERT (component_types.size() == 3);
map<DateComponentType, int> components;
// bare scope
{
vector<wxString>::size_type j = 0;
vector<wxString>::size_type const szj = target_fields.size();
for ( ; j != szj; ++j)
{
wxString field = target_fields[j];
if ((*(field.begin()) == '0') && (field.size() > 1))
{
field = wxString(field.begin() + 1, field.end());
}
int val = -1;
try
{
val = lexical_cast<int>(field);
}
catch (boost::bad_lexical_cast&)
{
return optional<gregorian::date>();
}
JEWEL_ASSERT (val >= 0);
JEWEL_ASSERT (j < 3);
DateComponentType component_type = component_types[j];
if (target_fields.size() == 1)
{
component_type = DateComponentType::day;
}
else if (target_fields.size() == 2)
{
DateComponentType const day_and_month[] =
{ DateComponentType::day,
DateComponentType::month
};
DateComponentType const first = *find_first_of
( component_types.begin(),
component_types.end(),
begin(day_and_month),
end(day_and_month)
);
switch (j)
{
case 0:
component_type = first;
break;
case 1:
component_type =
( (first == DateComponentType::day)?
DateComponentType::month:
DateComponentType::day
);
break;
default:
JEWEL_HARD_ASSERT (false);
}
}
components[component_type] = val;
}
} // end bare scope
fill_missing_components(components);
if (components.size() != 3)
{
return optional<gregorian::date>();
}
if (components.at(DateComponentType::year) < 100)
{
components[DateComponentType::year] += 2000;
}
try
{
JEWEL_LOG_TRACE();
JEWEL_ASSERT (components.size() == 3);
return optional<gregorian::date>
( gregorian::date
( components.at(DateComponentType::year),
components.at(DateComponentType::month),
components.at(DateComponentType::day)
)
);
}
catch (out_of_range&)
{
return optional<gregorian::date>();
}
}
} // end anonymous namespace
DateParser::DateParser
( wxString const& p_primary_format,
wxString const& p_secondary_format
):
m_primary_format(p_primary_format),
m_secondary_format(p_secondary_format)
{
}
optional<gregorian::date>
DateParser::parse(wxString const& p_string, bool p_be_tolerant) const
{
optional<gregorian::date> ret;
wxString::const_iterator parsed_to_position;
wxDateTime date_wx;
wxString const* const formats[] =
{ &m_primary_format,
&m_secondary_format
};
for (wxString const* const format: formats)
{
date_wx.ParseFormat
( p_string,
*(format),
&parsed_to_position
);
if (parsed_to_position == p_string.end())
{
// Parsing was successful
int year = date_wx.GetYear();
if (year < 100) year += 2000;
int const month = static_cast<int>(date_wx.GetMonth()) + 1;
int const day = date_wx.GetDay();
try
{
ret = gregorian::date(year, month, day);
return ret;
}
catch (boost::exception&)
{
}
}
}
if (p_be_tolerant)
{
return tolerant_parse(p_string);
}
return ret;
}
optional<gregorian::date>
DateParser::tolerant_parse(wxString const& p_string) const
{
JEWEL_LOG_TRACE();
optional<gregorian::date> const ret =
tolerant_parse_aux(p_string, m_primary_format);
return (ret? ret: tolerant_parse_aux(p_string, m_secondary_format));
}
} // namespace dcm
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* random_pcg.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "random_pcg.h"
#include "core/os/os.h"
RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) :
pcg(),
current_inc(p_inc) {
seed(p_seed);
}
void RandomPCG::randomize() {
seed(OS::get_singleton()->get_ticks_usec() * pcg.state + PCG_DEFAULT_INC_64);
}
double RandomPCG::random(double p_from, double p_to) {
return randd() * (p_to - p_from) + p_from;
}
float RandomPCG::random(float p_from, float p_to) {
return randf() * (p_to - p_from) + p_from;
}
int RandomPCG::random(int p_from, int p_to) {
if (p_from == p_to) {
return p_from;
}
return rand(abs(p_from - p_to) + 1) + MIN(p_from, p_to);
}
<commit_msg>Make randomize() use unix time too<commit_after>/*************************************************************************/
/* random_pcg.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "random_pcg.h"
#include "core/os/os.h"
RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) :
pcg(),
current_inc(p_inc) {
seed(p_seed);
}
void RandomPCG::randomize() {
seed((OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64);
}
double RandomPCG::random(double p_from, double p_to) {
return randd() * (p_to - p_from) + p_from;
}
float RandomPCG::random(float p_from, float p_to) {
return randf() * (p_to - p_from) + p_from;
}
int RandomPCG::random(int p_from, int p_to) {
if (p_from == p_to) {
return p_from;
}
return rand(abs(p_from - p_to) + 1) + MIN(p_from, p_to);
}
<|endoftext|>
|
<commit_before>#include "style.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"
#include "csscolorparser.hpp"
#include "geom.h" // for CLAMP
#include <sstream>
namespace Tangram {
std::unordered_map<Style::StyleCacheKey, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;
using namespace Tangram;
Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}
Style::~Style() {
m_layers.clear();
}
uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
uint32_t color = 0;
if (isdigit(_colorPropStr.front())) {
// try to parse as comma-separated rgba components
float r, g, b;
if (sscanf(_colorPropStr.c_str(), "%f,%f,%f", &r, &g, &b) == 3) {
color = 0xff000000
| (CLAMP(static_cast<uint32_t>(r * 255.), 0, 255)) << 16
| (CLAMP(static_cast<uint32_t>(g * 255.), 0, 255)) << 8
| (CLAMP(static_cast<uint32_t>(b * 255.), 0, 255));
} else {
color = 0xffff00ff;
}
} else { // parse as css color or #hex-num
bool isValid;
color = CSSColorParser::parse(_colorPropStr, isValid).getInt();
if (!isValid) {
color = 0xffff00ff;
}
}
return color;
}
void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {
constructVertexLayout();
constructShaderProgram();
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
m_material->injectOnProgram(m_shaderProgram);
for (auto& light : _lights) {
light->injectOnProgram(m_shaderProgram);
}
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material = _material;
}
void Style::setLightingType(LightingType _type){
m_lightingType = _type;
}
void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {
m_layers.push_back(std::move(_layer));
}
void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, StyleCacheKey& _uniqueID,
StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {
std::vector<std::shared_ptr<SceneLayer>> sLayers;
sLayers.reserve(_uberLayer->getSublayers().size() + 1);
sLayers.push_back(_uberLayer);
auto sLayerItr = sLayers.begin();
// A BFS traversal of the SceneLayer graph
while (sLayerItr != sLayers.end()) {
auto sceneLyr = *sLayerItr;
if (sceneLyr->getFilter().eval(_feature, _ctx)) { // filter matches
_uniqueID.set(sceneLyr->getID());
{
std::lock_guard<std::mutex> lock(s_cacheMutex);
// Get or create cache entry
auto& entry = s_styleParamMapCache[_uniqueID];
if (!entry.empty()) {
_styleParamMapMix = entry;
} else {
// Update StyleParam with subLayer parameters
auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
for(auto& styleParam : layerStyleParamMap) {
_styleParamMapMix[styleParam.first] = styleParam.second;
}
entry = _styleParamMapMix;
}
}
// Append sLayers with sublayers of this layer
auto& ssLayers = sceneLyr->getSublayers();
sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
} else {
sLayerItr++;
}
}
}
void Style::addData(TileData& _data, Tile& _tile) {
std::shared_ptr<VboMesh> mesh(newMesh());
onBeginBuildTile(*mesh);
Context ctx;
ctx["$zoom"] = Value(_tile.getID().z);
for (auto& layer : _data.layers) {
// Skip any layers that this style doesn't have a rule for
auto it = m_layers.begin();
while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
if (it == m_layers.end()) { continue; }
// Loop over all features
for (auto& feature : layer.features) {
StyleCacheKey uniqueID(0);
StyleParamMap styleParamMapMix;
applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));
if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
switch (feature.geometryType) {
case GeometryType::points:
// Build points
for (auto& point : feature.points) {
buildPoint(point, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
case GeometryType::lines:
// Build lines
for (auto& line : feature.lines) {
buildLine(line, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
case GeometryType::polygons:
// Build polygons
for (auto& polygon : feature.polygons) {
buildPolygon(polygon, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
default:
break;
}
}
}
}
onEndBuildTile(*mesh);
if (mesh->numVertices() == 0) {
mesh.reset();
} else {
mesh->compileVertexBuffer();
_tile.addMesh(*this, mesh);
}
}
void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {
m_material->setupProgram(m_shaderProgram);
// Set up lights
for (const auto& light : _scene->getLights()) {
light->setupProgram(_view, m_shaderProgram);
}
m_shaderProgram->setUniformf("u_zoom", _view->getZoom());
// default capabilities
RenderState::blending(GL_FALSE);
RenderState::depthTest(GL_TRUE);
}
void Style::onBeginBuildTile(VboMesh& _mesh) const {
// No-op by default
}
void Style::onEndBuildTile(VboMesh& _mesh) const {
// No-op by default
}
void Style::buildPoint(Point& _point, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
void Style::buildLine(Line& _line, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
void Style::buildPolygon(Polygon& _polygon, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
}
<commit_msg>remove invalid color hint<commit_after>#include "style.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"
#include "csscolorparser.hpp"
#include "geom.h" // for CLAMP
#include <sstream>
namespace Tangram {
std::unordered_map<Style::StyleCacheKey, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;
using namespace Tangram;
Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}
Style::~Style() {
m_layers.clear();
}
uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
uint32_t color = 0;
if (isdigit(_colorPropStr.front())) {
// try to parse as comma-separated rgba components
float r, g, b;
if (sscanf(_colorPropStr.c_str(), "%f,%f,%f", &r, &g, &b) == 3) {
color = 0xff000000
| (CLAMP(static_cast<uint32_t>(r * 255.), 0, 255)) << 16
| (CLAMP(static_cast<uint32_t>(g * 255.), 0, 255)) << 8
| (CLAMP(static_cast<uint32_t>(b * 255.), 0, 255));
}
} else {
// parse as css color or #hex-num
color = CSSColorParser::parse(_colorPropStr).getInt();
}
return color;
}
void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {
constructVertexLayout();
constructShaderProgram();
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
m_material->injectOnProgram(m_shaderProgram);
for (auto& light : _lights) {
light->injectOnProgram(m_shaderProgram);
}
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material = _material;
}
void Style::setLightingType(LightingType _type){
m_lightingType = _type;
}
void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {
m_layers.push_back(std::move(_layer));
}
void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, StyleCacheKey& _uniqueID,
StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {
std::vector<std::shared_ptr<SceneLayer>> sLayers;
sLayers.reserve(_uberLayer->getSublayers().size() + 1);
sLayers.push_back(_uberLayer);
auto sLayerItr = sLayers.begin();
// A BFS traversal of the SceneLayer graph
while (sLayerItr != sLayers.end()) {
auto sceneLyr = *sLayerItr;
if (sceneLyr->getFilter().eval(_feature, _ctx)) { // filter matches
_uniqueID.set(sceneLyr->getID());
{
std::lock_guard<std::mutex> lock(s_cacheMutex);
// Get or create cache entry
auto& entry = s_styleParamMapCache[_uniqueID];
if (!entry.empty()) {
_styleParamMapMix = entry;
} else {
// Update StyleParam with subLayer parameters
auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
for(auto& styleParam : layerStyleParamMap) {
_styleParamMapMix[styleParam.first] = styleParam.second;
}
entry = _styleParamMapMix;
}
}
// Append sLayers with sublayers of this layer
auto& ssLayers = sceneLyr->getSublayers();
sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
} else {
sLayerItr++;
}
}
}
void Style::addData(TileData& _data, Tile& _tile) {
std::shared_ptr<VboMesh> mesh(newMesh());
onBeginBuildTile(*mesh);
Context ctx;
ctx["$zoom"] = Value(_tile.getID().z);
for (auto& layer : _data.layers) {
// Skip any layers that this style doesn't have a rule for
auto it = m_layers.begin();
while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
if (it == m_layers.end()) { continue; }
// Loop over all features
for (auto& feature : layer.features) {
StyleCacheKey uniqueID(0);
StyleParamMap styleParamMapMix;
applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));
if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
switch (feature.geometryType) {
case GeometryType::points:
// Build points
for (auto& point : feature.points) {
buildPoint(point, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
case GeometryType::lines:
// Build lines
for (auto& line : feature.lines) {
buildLine(line, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
case GeometryType::polygons:
// Build polygons
for (auto& polygon : feature.polygons) {
buildPolygon(polygon, styleParamMapMix, feature.props, *mesh, _tile);
}
break;
default:
break;
}
}
}
}
onEndBuildTile(*mesh);
if (mesh->numVertices() == 0) {
mesh.reset();
} else {
mesh->compileVertexBuffer();
_tile.addMesh(*this, mesh);
}
}
void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {
m_material->setupProgram(m_shaderProgram);
// Set up lights
for (const auto& light : _scene->getLights()) {
light->setupProgram(_view, m_shaderProgram);
}
m_shaderProgram->setUniformf("u_zoom", _view->getZoom());
// default capabilities
RenderState::blending(GL_FALSE);
RenderState::depthTest(GL_TRUE);
}
void Style::onBeginBuildTile(VboMesh& _mesh) const {
// No-op by default
}
void Style::onEndBuildTile(VboMesh& _mesh) const {
// No-op by default
}
void Style::buildPoint(Point& _point, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
void Style::buildLine(Line& _line, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
void Style::buildPolygon(Polygon& _polygon, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// No-op by default
}
}
<|endoftext|>
|
<commit_before>//
// yas_worker.cpp
//
#include "yas_worker.h"
#include <atomic>
#include <thread>
#include "yas_stl_utils.h"
using namespace yas;
struct workable::resource {
std::vector<task_f> tasks;
std::atomic<bool> is_continue{true};
resource(std::vector<task_f> &&tasks) : tasks(std::move(tasks)) {
}
};
worker::worker(std::chrono::milliseconds const &duration) : _sleep_duration(duration) {
}
worker::~worker() {
this->stop();
}
void worker::add_task(uint32_t const priority, task_f &&task) {
if (this->_resource) {
throw std::runtime_error("worker add_task() - already started.");
}
this->_tasks.emplace(priority, std::move(task));
}
void worker::start() {
if (this->_resource) {
throw std::runtime_error("worker start() - already started.");
}
if (this->_tasks.size() == 0) {
throw std::runtime_error("worker start() - task is empty.");
}
auto tasks = to_vector<task_f>(this->_tasks, [](auto const &pair) { return pair.second; });
this->_resource = std::make_shared<resource>(std::move(tasks));
std::thread thread{[resource = this->_resource, sleep_duration = this->_sleep_duration] {
while (resource->is_continue) {
while (resource->is_continue) {
bool processed = false;
std::vector<std::size_t> completed;
std::size_t idx = 0;
for (auto const &task : resource->tasks) {
auto const result = task();
if (result == task_result::processed) {
processed = true;
std::this_thread::yield();
break;
} else if (result == task_result::completed) {
completed.emplace_back(idx);
}
++idx;
}
if (completed.size() > 0) {
std::reverse(completed.begin(), completed.end());
for (auto const &idx : completed) {
erase_at(resource->tasks, idx);
}
}
if (!processed) {
break;
}
}
std::this_thread::sleep_for(sleep_duration);
}
}};
thread.detach();
}
void worker::stop() {
if (this->_resource) {
this->_resource->is_continue = false;
this->_resource = nullptr;
}
}
worker_ptr worker::make_shared() {
return worker::make_shared(std::chrono::milliseconds{10});
}
worker_ptr worker::make_shared(std::chrono::milliseconds const &duration) {
return worker_ptr(new worker{duration});
}
<commit_msg>separate process<commit_after>//
// yas_worker.cpp
//
#include "yas_worker.h"
#include <atomic>
#include <thread>
#include "yas_stl_utils.h"
using namespace yas;
namespace yas::worker_utils {
bool process(std::vector<workable::task_f> &tasks) {
bool processed = false;
std::vector<std::size_t> completed;
std::size_t idx = 0;
for (auto const &task : tasks) {
auto const result = task();
if (result == workable::task_result::processed) {
processed = true;
std::this_thread::yield();
break;
} else if (result == workable::task_result::completed) {
completed.emplace_back(idx);
}
++idx;
}
if (completed.size() > 0) {
std::reverse(completed.begin(), completed.end());
for (auto const &idx : completed) {
erase_at(tasks, idx);
}
}
return processed;
}
} // namespace yas::worker_utils
struct workable::resource {
std::vector<task_f> tasks;
std::atomic<bool> is_continue{true};
resource(std::vector<task_f> &&tasks) : tasks(std::move(tasks)) {
}
};
worker::worker(std::chrono::milliseconds const &duration) : _sleep_duration(duration) {
}
worker::~worker() {
this->stop();
}
void worker::add_task(uint32_t const priority, task_f &&task) {
if (this->_resource) {
throw std::runtime_error("worker add_task() - already started.");
}
this->_tasks.emplace(priority, std::move(task));
}
void worker::start() {
if (this->_resource) {
throw std::runtime_error("worker start() - already started.");
}
if (this->_tasks.size() == 0) {
throw std::runtime_error("worker start() - task is empty.");
}
auto tasks = to_vector<task_f>(this->_tasks, [](auto const &pair) { return pair.second; });
this->_resource = std::make_shared<resource>(std::move(tasks));
std::thread thread{[resource = this->_resource, sleep_duration = this->_sleep_duration] {
while (resource->is_continue) {
while (resource->is_continue) {
if (!worker_utils::process(resource->tasks)) {
break;
}
}
std::this_thread::sleep_for(sleep_duration);
}
}};
thread.detach();
}
void worker::stop() {
if (this->_resource) {
this->_resource->is_continue = false;
this->_resource = nullptr;
}
}
worker_ptr worker::make_shared() {
return worker::make_shared(std::chrono::milliseconds{10});
}
worker_ptr worker::make_shared(std::chrono::milliseconds const &duration) {
return worker_ptr(new worker{duration});
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cppdom/cppdom.h>
bool configureInput( const std::string& filename )
{
cppdom::XMLContextPtr ctx( new cppdom::XMLContext );
cppdom::XMLDocument doc( ctx );
// load a xml document from a file
try
{
doc.loadFile( filename );
}
catch (cppdom::XMLError e)
{
std::cerr << "Error: " << e.getString() << std::endl;
if (e.getInfo().size())
{
std::cerr << "File: " << e.getInfo() << std::endl;
}
if (e.getError() != cppdom::xml_filename_invalid &&
e.getError() != cppdom::xml_file_access)
{
/*
e.show_error( ctx );
e.show_line( ctx, filename );
*/
std::cout << "Error: (need to impl the show functions)" << std::endl;
}
return false;
}
std::cerr << "succesfully loaded " << filename << std::endl;
cppdom::XMLNodeList nl = doc.getChild( "gameinput" )->getChildren();
cppdom::XMLNodeListIterator it = nl.begin();
while (it != nl.end())
{
std::cerr << "in name: " << (*it)->getName() << std::endl;
try
{
cppdom::XMLAttributes& attr = (*it)->getAttrMap();
std::cout << "attr: " << attr.get( "action" ) << "\n" << std::flush;
std::cout << "attr: " << attr.get( "device" ) << "\n" << std::flush;
std::cout << "attr: " << attr.get( "input" ) << "\n" << std::flush;
cppdom::XMLNode* parent = (*it)->getParent();
assert(parent != NULL && parent->getName() == std::string("gameinput"));
}
catch (cppdom::XMLError e)
{
std::cerr << "Error: " << e.getString() << std::endl;
it++;
continue;
}
it++;
}
return true;
}
/** Main function */
int main()
{
// Just call single function to load and process input file
configureInput( "game.xml" );
return 1;
}
<commit_msg>compiles under win32 now, added assert.h<commit_after>#include <assert.h>
#include <iostream>
#include <string>
#include <cppdom/cppdom.h>
bool configureInput( const std::string& filename )
{
cppdom::XMLContextPtr ctx( new cppdom::XMLContext );
cppdom::XMLDocument doc( ctx );
// load a xml document from a file
try
{
doc.loadFile( filename );
}
catch (cppdom::XMLError e)
{
std::cerr << "Error: " << e.getString() << std::endl;
if (e.getInfo().size())
{
std::cerr << "File: " << e.getInfo() << std::endl;
}
if (e.getError() != cppdom::xml_filename_invalid &&
e.getError() != cppdom::xml_file_access)
{
/*
e.show_error( ctx );
e.show_line( ctx, filename );
*/
std::cout << "Error: (need to impl the show functions)" << std::endl;
}
return false;
}
std::cerr << "succesfully loaded " << filename << std::endl;
cppdom::XMLNodeList nl = doc.getChild( "gameinput" )->getChildren();
cppdom::XMLNodeListIterator it = nl.begin();
while (it != nl.end())
{
std::cerr << "in name: " << (*it)->getName() << std::endl;
try
{
cppdom::XMLAttributes& attr = (*it)->getAttrMap();
std::cout << "attr: " << attr.get( "action" ) << "\n" << std::flush;
std::cout << "attr: " << attr.get( "device" ) << "\n" << std::flush;
std::cout << "attr: " << attr.get( "input" ) << "\n" << std::flush;
cppdom::XMLNode* parent = (*it)->getParent();
assert(parent != NULL && parent->getName() == std::string("gameinput"));
}
catch (cppdom::XMLError e)
{
std::cerr << "Error: " << e.getString() << std::endl;
it++;
continue;
}
it++;
}
return true;
}
/** Main function */
int main()
{
// Just call single function to load and process input file
configureInput( "game.xml" );
return 1;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "session_context.h"
#include <algorithm>
#include "curl/curl.h"
#include "cvmfs_config.h"
#include "gateway_util.h"
#include "json_document.h"
#include "swissknife_lease_curl.h"
#include "util/string.h"
namespace upload {
size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) {
CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp);
size_t max_chunk_size = size * nmemb;
if (max_chunk_size < 1) {
return 0;
}
size_t current_chunk_size = 0;
while (current_chunk_size < max_chunk_size) {
if (payload->index < payload->json_message->size()) {
// Can add a chunk from the JSON message
const size_t read_size =
std::min(max_chunk_size - current_chunk_size,
payload->json_message->size() - payload->index);
current_chunk_size += read_size;
std::memcpy(ptr, payload->json_message->data() + payload->index,
read_size);
payload->index += read_size;
} else {
// Can add a chunk from the payload
const size_t max_read_size = max_chunk_size - current_chunk_size;
const unsigned nbytes = payload->pack_serializer->ProduceNext(
max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size);
current_chunk_size += nbytes;
if (!nbytes) {
break;
}
}
}
return current_chunk_size;
}
size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {
std::string* my_buffer = static_cast<std::string*>(userp);
if (size * nmemb < 1) {
return 0;
}
*my_buffer = static_cast<char*>(buffer);
return my_buffer->size();
}
SessionContextBase::SessionContextBase()
: upload_results_(1000, 1000),
api_url_(),
session_token_(),
key_id_(),
secret_(),
queue_was_flushed_(1, 1),
max_pack_size_(ObjectPack::kDefaultLimit),
active_handles_(),
current_pack_(NULL),
current_pack_mtx_(),
objects_dispatched_(0),
bytes_committed_(0),
bytes_dispatched_(0) {}
SessionContextBase::~SessionContextBase() {}
bool SessionContextBase::Initialize(const std::string& api_url,
const std::string& session_token,
const std::string& key_id,
const std::string& secret,
uint64_t max_pack_size) {
bool ret = true;
// Initialize session context lock
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) ||
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) ||
pthread_mutex_init(¤t_pack_mtx_, &attr) ||
pthread_mutexattr_destroy(&attr)) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Could not initialize SessionContext lock.");
return false;
}
// Set upstream URL and session token
api_url_ = api_url;
session_token_ = session_token;
key_id_ = key_id;
secret_ = secret;
max_pack_size_ = max_pack_size;
atomic_init64(&objects_dispatched_);
bytes_committed_ = 0u;
bytes_dispatched_ = 0u;
// Ensure that the upload job and result queues are empty
upload_results_.Drop();
queue_was_flushed_.Drop();
queue_was_flushed_.Enqueue(true);
// Ensure that there are not open object packs
if (current_pack_) {
LogCvmfs(
kLogUploadGateway, kLogStderr,
"Could not initialize SessionContext - Existing open object packs.");
ret = false;
}
ret = InitializeDerived() && ret;
return ret;
}
bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash,
const std::string& new_root_hash) {
assert(active_handles_.empty());
{
MutexLockGuard lock(current_pack_mtx_);
if (current_pack_ && current_pack_->GetNoObjects() > 0) {
Dispatch();
current_pack_ = NULL;
}
}
bool results = true;
int64_t jobs_finished = 0;
while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) {
Future<bool>* future = upload_results_.Dequeue();
results = future->Get() && results;
delete future;
jobs_finished++;
}
if (commit) {
if (old_root_hash.empty() || new_root_hash.empty()) {
return false;
}
results &= Commit(old_root_hash, new_root_hash);
}
results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_);
pthread_mutex_destroy(¤t_pack_mtx_);
return results;
}
void SessionContextBase::WaitForUpload() {
if (!upload_results_.IsEmpty()) {
queue_was_flushed_.Dequeue();
}
}
ObjectPack::BucketHandle SessionContextBase::NewBucket() {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
current_pack_ = new ObjectPack(max_pack_size_);
}
ObjectPack::BucketHandle hd = current_pack_->NewBucket();
active_handles_.push_back(hd);
return hd;
}
bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type,
const shash::Any& id,
const ObjectPack::BucketHandle handle,
const std::string& name,
const bool force_dispatch) {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Error: Called SessionBaseContext::CommitBucket without an open "
"ObjectPack.");
return false;
}
uint64_t size0 = current_pack_->size();
bool committed = current_pack_->CommitBucket(type, id, handle, name);
if (committed) { // Current pack is still not full
active_handles_.erase(
std::remove(active_handles_.begin(), active_handles_.end(), handle),
active_handles_.end());
uint64_t size1 = current_pack_->size();
bytes_committed_ += size1 - size0;
if (force_dispatch) {
Dispatch();
current_pack_ = NULL;
}
} else { // Current pack is full and can be dispatched
uint64_t new_size = 0;
if (handle->capacity > max_pack_size_) {
new_size = handle->capacity + 1;
} else {
new_size = max_pack_size_;
}
ObjectPack* new_pack = new ObjectPack(new_size);
for (size_t i = 0u; i < active_handles_.size(); ++i) {
current_pack_->TransferBucket(active_handles_[i], new_pack);
}
if (current_pack_->GetNoObjects() > 0) {
Dispatch();
}
current_pack_ = new_pack;
CommitBucket(type, id, handle, name, false);
}
return true;
}
int64_t SessionContextBase::NumJobsSubmitted() const {
return atomic_read64(&objects_dispatched_);
}
void SessionContextBase::Dispatch() {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
return;
}
atomic_inc64(&objects_dispatched_);
bytes_dispatched_ += current_pack_->size();
upload_results_.Enqueue(DispatchObjectPack(current_pack_));
}
SessionContext::SessionContext()
: SessionContextBase(),
upload_jobs_(1000, 900),
worker_terminate_(),
worker_() {}
bool SessionContext::InitializeDerived() {
// Start worker thread
atomic_init32(&worker_terminate_);
atomic_write32(&worker_terminate_, 0);
upload_jobs_.Drop();
int retval =
pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this));
return !retval;
}
bool SessionContext::FinalizeDerived() {
atomic_write32(&worker_terminate_, 1);
pthread_join(worker_, NULL);
return true;
}
bool SessionContext::Commit(const std::string& old_root_hash,
const std::string& new_root_hash) {
std::string request;
JsonStringInput request_input;
request_input.push_back(
std::make_pair("old_root_hash", old_root_hash.c_str()));
request_input.push_back(
std::make_pair("new_root_hash", new_root_hash.c_str()));
ToJsonString(request_input, &request);
CurlBuffer buffer;
return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_,
request, &buffer);
}
Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) {
UploadJob* job = new UploadJob;
job->pack = pack;
job->result = new Future<bool>();
upload_jobs_.Enqueue(job);
return job->result;
}
bool SessionContext::DoUpload(const SessionContext::UploadJob* job) {
// Set up the object pack serializer
ObjectPackProducer serializer(job->pack);
shash::Any payload_digest(shash::kSha1);
serializer.GetDigest(&payload_digest);
const std::string json_msg =
"{\"session_token\" : \"" + session_token_ +
"\", \"payload_digest\" : \"" + Base64(payload_digest.ToString(false)) +
"\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) +
"\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}";
// Compute HMAC
shash::Any hmac(shash::kSha1);
shash::HmacString(secret_, json_msg, &hmac);
CurlSendPayload payload;
payload.json_message = &json_msg;
payload.pack_serializer = &serializer;
payload.index = 0;
const size_t payload_size =
json_msg.size() + serializer.GetHeaderSize() + job->pack->size();
// Prepare the Curl POST request
CURL* h_curl = curl_easy_init();
if (!h_curl) {
return false;
}
// Set HTTP headers (Authorization and Message-Size)
std::string header_str = std::string("Authorization: ") + key_id_ + " " +
Base64(hmac.ToString(false));
struct curl_slist* auth_header = NULL;
auth_header = curl_slist_append(auth_header, header_str.c_str());
header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size());
auth_header = curl_slist_append(auth_header, header_str.c_str());
curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header);
std::string reply;
curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION);
curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str());
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL);
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
static_cast<curl_off_t>(payload_size));
curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload);
curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply);
// Perform the Curl POST request
CURLcode ret = curl_easy_perform(h_curl);
const bool ok = (reply == "{\"status\":\"ok\"}");
curl_easy_cleanup(h_curl);
h_curl = NULL;
return ok && !ret;
}
void* SessionContext::UploadLoop(void* data) {
SessionContext* ctx = reinterpret_cast<SessionContext*>(data);
int64_t jobs_processed = 0;
while (!ctx->ShouldTerminate()) {
while (jobs_processed < ctx->NumJobsSubmitted()) {
UploadJob* job = ctx->upload_jobs_.Dequeue();
ctx->DoUpload(job);
job->result->Set(true);
delete job->pack;
delete job;
jobs_processed++;
}
if (ctx->queue_was_flushed_.IsEmpty()) {
ctx->queue_was_flushed_.Enqueue(true);
}
}
return NULL;
}
bool SessionContext::ShouldTerminate() {
return atomic_read32(&worker_terminate_);
}
} // namespace upload
<commit_msg>Gateway uploader: abort transaction on payload submission error<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "session_context.h"
#include <algorithm>
#include "curl/curl.h"
#include "cvmfs_config.h"
#include "gateway_util.h"
#include "json_document.h"
#include "swissknife_lease_curl.h"
#include "util/string.h"
namespace upload {
size_t SendCB(void* ptr, size_t size, size_t nmemb, void* userp) {
CurlSendPayload* payload = static_cast<CurlSendPayload*>(userp);
size_t max_chunk_size = size * nmemb;
if (max_chunk_size < 1) {
return 0;
}
size_t current_chunk_size = 0;
while (current_chunk_size < max_chunk_size) {
if (payload->index < payload->json_message->size()) {
// Can add a chunk from the JSON message
const size_t read_size =
std::min(max_chunk_size - current_chunk_size,
payload->json_message->size() - payload->index);
current_chunk_size += read_size;
std::memcpy(ptr, payload->json_message->data() + payload->index,
read_size);
payload->index += read_size;
} else {
// Can add a chunk from the payload
const size_t max_read_size = max_chunk_size - current_chunk_size;
const unsigned nbytes = payload->pack_serializer->ProduceNext(
max_read_size, static_cast<unsigned char*>(ptr) + current_chunk_size);
current_chunk_size += nbytes;
if (!nbytes) {
break;
}
}
}
return current_chunk_size;
}
size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {
std::string* my_buffer = static_cast<std::string*>(userp);
if (size * nmemb < 1) {
return 0;
}
*my_buffer = static_cast<char*>(buffer);
return my_buffer->size();
}
SessionContextBase::SessionContextBase()
: upload_results_(1000, 1000),
api_url_(),
session_token_(),
key_id_(),
secret_(),
queue_was_flushed_(1, 1),
max_pack_size_(ObjectPack::kDefaultLimit),
active_handles_(),
current_pack_(NULL),
current_pack_mtx_(),
objects_dispatched_(0),
bytes_committed_(0),
bytes_dispatched_(0) {}
SessionContextBase::~SessionContextBase() {}
bool SessionContextBase::Initialize(const std::string& api_url,
const std::string& session_token,
const std::string& key_id,
const std::string& secret,
uint64_t max_pack_size) {
bool ret = true;
// Initialize session context lock
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) ||
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) ||
pthread_mutex_init(¤t_pack_mtx_, &attr) ||
pthread_mutexattr_destroy(&attr)) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Could not initialize SessionContext lock.");
return false;
}
// Set upstream URL and session token
api_url_ = api_url;
session_token_ = session_token;
key_id_ = key_id;
secret_ = secret;
max_pack_size_ = max_pack_size;
atomic_init64(&objects_dispatched_);
bytes_committed_ = 0u;
bytes_dispatched_ = 0u;
// Ensure that the upload job and result queues are empty
upload_results_.Drop();
queue_was_flushed_.Drop();
queue_was_flushed_.Enqueue(true);
// Ensure that there are not open object packs
if (current_pack_) {
LogCvmfs(
kLogUploadGateway, kLogStderr,
"Could not initialize SessionContext - Existing open object packs.");
ret = false;
}
ret = InitializeDerived() && ret;
return ret;
}
bool SessionContextBase::Finalize(bool commit, const std::string& old_root_hash,
const std::string& new_root_hash) {
assert(active_handles_.empty());
{
MutexLockGuard lock(current_pack_mtx_);
if (current_pack_ && current_pack_->GetNoObjects() > 0) {
Dispatch();
current_pack_ = NULL;
}
}
bool results = true;
int64_t jobs_finished = 0;
while (!upload_results_.IsEmpty() || (jobs_finished < NumJobsSubmitted())) {
Future<bool>* future = upload_results_.Dequeue();
results = future->Get() && results;
delete future;
jobs_finished++;
}
if (commit) {
if (old_root_hash.empty() || new_root_hash.empty()) {
return false;
}
results &= Commit(old_root_hash, new_root_hash);
}
results &= FinalizeDerived() && (bytes_committed_ == bytes_dispatched_);
pthread_mutex_destroy(¤t_pack_mtx_);
return results;
}
void SessionContextBase::WaitForUpload() {
if (!upload_results_.IsEmpty()) {
queue_was_flushed_.Dequeue();
}
}
ObjectPack::BucketHandle SessionContextBase::NewBucket() {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
current_pack_ = new ObjectPack(max_pack_size_);
}
ObjectPack::BucketHandle hd = current_pack_->NewBucket();
active_handles_.push_back(hd);
return hd;
}
bool SessionContextBase::CommitBucket(const ObjectPack::BucketContentType type,
const shash::Any& id,
const ObjectPack::BucketHandle handle,
const std::string& name,
const bool force_dispatch) {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"Error: Called SessionBaseContext::CommitBucket without an open "
"ObjectPack.");
return false;
}
uint64_t size0 = current_pack_->size();
bool committed = current_pack_->CommitBucket(type, id, handle, name);
if (committed) { // Current pack is still not full
active_handles_.erase(
std::remove(active_handles_.begin(), active_handles_.end(), handle),
active_handles_.end());
uint64_t size1 = current_pack_->size();
bytes_committed_ += size1 - size0;
if (force_dispatch) {
Dispatch();
current_pack_ = NULL;
}
} else { // Current pack is full and can be dispatched
uint64_t new_size = 0;
if (handle->capacity > max_pack_size_) {
new_size = handle->capacity + 1;
} else {
new_size = max_pack_size_;
}
ObjectPack* new_pack = new ObjectPack(new_size);
for (size_t i = 0u; i < active_handles_.size(); ++i) {
current_pack_->TransferBucket(active_handles_[i], new_pack);
}
if (current_pack_->GetNoObjects() > 0) {
Dispatch();
}
current_pack_ = new_pack;
CommitBucket(type, id, handle, name, false);
}
return true;
}
int64_t SessionContextBase::NumJobsSubmitted() const {
return atomic_read64(&objects_dispatched_);
}
void SessionContextBase::Dispatch() {
MutexLockGuard lock(current_pack_mtx_);
if (!current_pack_) {
return;
}
atomic_inc64(&objects_dispatched_);
bytes_dispatched_ += current_pack_->size();
upload_results_.Enqueue(DispatchObjectPack(current_pack_));
}
SessionContext::SessionContext()
: SessionContextBase(),
upload_jobs_(1000, 900),
worker_terminate_(),
worker_() {}
bool SessionContext::InitializeDerived() {
// Start worker thread
atomic_init32(&worker_terminate_);
atomic_write32(&worker_terminate_, 0);
upload_jobs_.Drop();
int retval =
pthread_create(&worker_, NULL, UploadLoop, reinterpret_cast<void*>(this));
return !retval;
}
bool SessionContext::FinalizeDerived() {
atomic_write32(&worker_terminate_, 1);
pthread_join(worker_, NULL);
return true;
}
bool SessionContext::Commit(const std::string& old_root_hash,
const std::string& new_root_hash) {
std::string request;
JsonStringInput request_input;
request_input.push_back(
std::make_pair("old_root_hash", old_root_hash.c_str()));
request_input.push_back(
std::make_pair("new_root_hash", new_root_hash.c_str()));
ToJsonString(request_input, &request);
CurlBuffer buffer;
return MakeEndRequest("POST", key_id_, secret_, session_token_, api_url_,
request, &buffer);
}
Future<bool>* SessionContext::DispatchObjectPack(ObjectPack* pack) {
UploadJob* job = new UploadJob;
job->pack = pack;
job->result = new Future<bool>();
upload_jobs_.Enqueue(job);
return job->result;
}
bool SessionContext::DoUpload(const SessionContext::UploadJob* job) {
// Set up the object pack serializer
ObjectPackProducer serializer(job->pack);
shash::Any payload_digest(shash::kSha1);
serializer.GetDigest(&payload_digest);
const std::string json_msg =
"{\"session_token\" : \"" + session_token_ +
"\", \"payload_digest\" : \"" + Base64(payload_digest.ToString(false)) +
"\", \"header_size\" : \"" + StringifyInt(serializer.GetHeaderSize()) +
"\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}";
// Compute HMAC
shash::Any hmac(shash::kSha1);
shash::HmacString(secret_, json_msg, &hmac);
CurlSendPayload payload;
payload.json_message = &json_msg;
payload.pack_serializer = &serializer;
payload.index = 0;
const size_t payload_size =
json_msg.size() + serializer.GetHeaderSize() + job->pack->size();
// Prepare the Curl POST request
CURL* h_curl = curl_easy_init();
if (!h_curl) {
return false;
}
// Set HTTP headers (Authorization and Message-Size)
std::string header_str = std::string("Authorization: ") + key_id_ + " " +
Base64(hmac.ToString(false));
struct curl_slist* auth_header = NULL;
auth_header = curl_slist_append(auth_header, header_str.c_str());
header_str = std::string("Message-Size: ") + StringifyInt(json_msg.size());
auth_header = curl_slist_append(auth_header, header_str.c_str());
curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header);
std::string reply;
curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(h_curl, CURLOPT_USERAGENT, "cvmfs/" VERSION);
curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(h_curl, CURLOPT_URL, (api_url_ + "/payloads").c_str());
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL);
curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,
static_cast<curl_off_t>(payload_size));
curl_easy_setopt(h_curl, CURLOPT_READDATA, &payload);
curl_easy_setopt(h_curl, CURLOPT_READFUNCTION, SendCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);
curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, &reply);
// Perform the Curl POST request
CURLcode ret = curl_easy_perform(h_curl);
const bool ok = (reply == "{\"status\":\"ok\"}");
curl_easy_cleanup(h_curl);
h_curl = NULL;
return ok && !ret;
}
void* SessionContext::UploadLoop(void* data) {
SessionContext* ctx = reinterpret_cast<SessionContext*>(data);
int64_t jobs_processed = 0;
while (!ctx->ShouldTerminate()) {
while (jobs_processed < ctx->NumJobsSubmitted()) {
UploadJob* job = ctx->upload_jobs_.Dequeue();
if (!ctx->DoUpload(job)) {
LogCvmfs(kLogUploadGateway, kLogStderr,
"SessionContext: could not submit payload. Aborting.");
abort();
}
job->result->Set(true);
delete job->pack;
delete job;
jobs_processed++;
}
if (ctx->queue_was_flushed_.IsEmpty()) {
ctx->queue_was_flushed_.Enqueue(true);
}
}
return NULL;
}
bool SessionContext::ShouldTerminate() {
return atomic_read32(&worker_terminate_);
}
} // namespace upload
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include <string>
#include "cvmfs_config.h"
#include <cassert>
#include "logging.h"
#include "swissknife.h"
#include "swissknife_check.h"
#include "swissknife_diff.h"
#include "swissknife_gc.h"
#include "swissknife_graft.h"
#include "swissknife_hash.h"
#include "swissknife_history.h"
#include "swissknife_info.h"
#include "swissknife_ingest.h"
#include "swissknife_lease.h"
#include "swissknife_letter.h"
#include "swissknife_lsrepo.h"
#include "swissknife_migrate.h"
#include "swissknife_pull.h"
#include "swissknife_reflog.h"
#include "swissknife_scrub.h"
#include "swissknife_sign.h"
#include "swissknife_sync.h"
#include "swissknife_zpipe.h"
#include "util/string.h"
using namespace std; // NOLINT
typedef vector<swissknife::Command *> Commands;
Commands command_list;
void Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM-FS repository storage management commands\n"
"Version %s\n"
"Usage (normally called from cvmfs_server):\n"
" cvmfs_swissknife <command> [options]\n",
VERSION);
for (unsigned i = 0; i < command_list.size(); ++i) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "\n"
"Command %s\n"
"--------", command_list[i]->GetName().c_str());
for (unsigned j = 0; j < command_list[i]->GetName().length(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "-");
}
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command_list[i]->GetDescription().c_str());
swissknife::ParameterList params = command_list[i]->GetParams();
if (!params.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout, "Options:");
for (unsigned j = 0; j < params.size(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " -%c %s",
params[j].key(), params[j].description().c_str());
if (params[j].optional())
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " (optional)");
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
} // Parameter list
} // Command list
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
int main(int argc, char **argv) {
// FILE *f = fopen("/home/ddosaru/cvmfs/build/log_dbg", "w"); // used for debugging
// if (f == NULL) {
// printf("Error opening file!\n");
// return -1;
// }
command_list.push_back(new swissknife::CommandCreate());
command_list.push_back(new swissknife::CommandUpload());
command_list.push_back(new swissknife::CommandRemove());
command_list.push_back(new swissknife::CommandPeek());
command_list.push_back(new swissknife::CommandSync());
command_list.push_back(new swissknife::CommandApplyDirtab());
command_list.push_back(new swissknife::CommandEditTag());
command_list.push_back(new swissknife::CommandListTags());
command_list.push_back(new swissknife::CommandInfoTag());
command_list.push_back(new swissknife::CommandRollbackTag());
command_list.push_back(new swissknife::CommandEmptyRecycleBin());
command_list.push_back(new swissknife::CommandSign());
command_list.push_back(new swissknife::CommandLetter());
command_list.push_back(new swissknife::CommandCheck());
command_list.push_back(new swissknife::CommandListCatalogs());
command_list.push_back(new swissknife::CommandDiff());
command_list.push_back(new swissknife::CommandPull());
command_list.push_back(new swissknife::CommandZpipe());
command_list.push_back(new swissknife::CommandGraft());
command_list.push_back(new swissknife::CommandHash());
command_list.push_back(new swissknife::CommandInfo());
command_list.push_back(new swissknife::CommandVersion());
command_list.push_back(new swissknife::CommandMigrate());
command_list.push_back(new swissknife::CommandScrub());
command_list.push_back(new swissknife::CommandGc());
command_list.push_back(new swissknife::CommandReconstructReflog());
command_list.push_back(new swissknife::CommandLease());
command_list.push_back(new swissknife::Ingest());
if (argc < 2) {
Usage();
return 1;
}
if ((string(argv[1]) == "--help")) {
Usage();
return 0;
}
if ((string(argv[1]) == "--version")) {
swissknife::CommandVersion().Main(swissknife::ArgumentList());
return 0;
}
// find the command to be run
swissknife::Command *command = NULL;
for (unsigned i = 0; i < command_list.size(); ++i) {
if (command_list[i]->GetName() == string(argv[1])) {
command = command_list[i];
break;
}
}
if (NULL == command) {
Usage();
return 1;
}
bool display_statistics = false;
// parse the command line arguments for the Command
swissknife::ArgumentList args;
optind = 1;
string option_string = "";
swissknife::ParameterList params = command->GetParams();
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only())
option_string.push_back(':');
}
// Now adding the generic -+ extra option command
option_string.push_back(swissknife::Command::kGenericParam);
option_string.push_back(':');
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
//fprintf(f, "getopt --> %c\n", c);
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
assert(c != swissknife::Command::kGenericParam);
valid_option = true;
string *argument = NULL;
if (!params[j].switch_only()) {
argument = new string(optarg);
}
args[c] = argument;
break;
}
}
if (c == swissknife::Command::kGenericParam) {
valid_option = true;
vector<string> flags = SplitString(optarg,
swissknife::
Command::kGenericParamSeparator);
for (unsigned i = 0; i < flags.size(); ++i) {
if (flags[i] == "stats") {
display_statistics = true;
}
}
}
if (!valid_option) {
Usage();
return 1;
}
}
for (unsigned j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (args.find(params[j].key()) == args.end()) {
LogCvmfs(kLogCvmfs, kLogStderr, "parameter -%c missing",
params[j].key());
return 1;
}
}
}
// run the command
const int retval = command->Main(args);
if (display_statistics) {
LogCvmfs(kLogCvmfs, kLogStdout, "Command statistics");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command->statistics()
->PrintList(perf::Statistics::kPrintHeader).c_str());
}
// delete the command list
Commands::const_iterator i = command_list.begin();
const Commands::const_iterator iend = command_list.end();
for (; i != iend; ++i) {
delete *i;
}
command_list.clear();
//fclose(f);
return retval;
}
<commit_msg>Solved cpplint errors.<commit_after>/**
* This file is part of the CernVM File System.
*/
#include <string>
#include "cvmfs_config.h"
#include <cassert>
#include "logging.h"
#include "swissknife.h"
#include "swissknife_check.h"
#include "swissknife_diff.h"
#include "swissknife_gc.h"
#include "swissknife_graft.h"
#include "swissknife_hash.h"
#include "swissknife_history.h"
#include "swissknife_info.h"
#include "swissknife_ingest.h"
#include "swissknife_lease.h"
#include "swissknife_letter.h"
#include "swissknife_lsrepo.h"
#include "swissknife_migrate.h"
#include "swissknife_pull.h"
#include "swissknife_reflog.h"
#include "swissknife_scrub.h"
#include "swissknife_sign.h"
#include "swissknife_sync.h"
#include "swissknife_zpipe.h"
#include "util/string.h"
using namespace std; // NOLINT
typedef vector<swissknife::Command *> Commands;
Commands command_list;
void Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM-FS repository storage management commands\n"
"Version %s\n"
"Usage (normally called from cvmfs_server):\n"
" cvmfs_swissknife <command> [options]\n",
VERSION);
for (unsigned i = 0; i < command_list.size(); ++i) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "\n"
"Command %s\n"
"--------", command_list[i]->GetName().c_str());
for (unsigned j = 0; j < command_list[i]->GetName().length(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "-");
}
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command_list[i]->GetDescription().c_str());
swissknife::ParameterList params = command_list[i]->GetParams();
if (!params.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout, "Options:");
for (unsigned j = 0; j < params.size(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " -%c %s",
params[j].key(), params[j].description().c_str());
if (params[j].optional())
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " (optional)");
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
} // Parameter list
} // Command list
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
int main(int argc, char **argv) {
// // used for debugging
// FILE *f = fopen("/home/ddosaru/cvmfs/build/log_dbg", "w");
// if (f == NULL) {
// printf("Error opening file!\n");
// return -1;
// }
command_list.push_back(new swissknife::CommandCreate());
command_list.push_back(new swissknife::CommandUpload());
command_list.push_back(new swissknife::CommandRemove());
command_list.push_back(new swissknife::CommandPeek());
command_list.push_back(new swissknife::CommandSync());
command_list.push_back(new swissknife::CommandApplyDirtab());
command_list.push_back(new swissknife::CommandEditTag());
command_list.push_back(new swissknife::CommandListTags());
command_list.push_back(new swissknife::CommandInfoTag());
command_list.push_back(new swissknife::CommandRollbackTag());
command_list.push_back(new swissknife::CommandEmptyRecycleBin());
command_list.push_back(new swissknife::CommandSign());
command_list.push_back(new swissknife::CommandLetter());
command_list.push_back(new swissknife::CommandCheck());
command_list.push_back(new swissknife::CommandListCatalogs());
command_list.push_back(new swissknife::CommandDiff());
command_list.push_back(new swissknife::CommandPull());
command_list.push_back(new swissknife::CommandZpipe());
command_list.push_back(new swissknife::CommandGraft());
command_list.push_back(new swissknife::CommandHash());
command_list.push_back(new swissknife::CommandInfo());
command_list.push_back(new swissknife::CommandVersion());
command_list.push_back(new swissknife::CommandMigrate());
command_list.push_back(new swissknife::CommandScrub());
command_list.push_back(new swissknife::CommandGc());
command_list.push_back(new swissknife::CommandReconstructReflog());
command_list.push_back(new swissknife::CommandLease());
command_list.push_back(new swissknife::Ingest());
if (argc < 2) {
Usage();
return 1;
}
if ((string(argv[1]) == "--help")) {
Usage();
return 0;
}
if ((string(argv[1]) == "--version")) {
swissknife::CommandVersion().Main(swissknife::ArgumentList());
return 0;
}
// find the command to be run
swissknife::Command *command = NULL;
for (unsigned i = 0; i < command_list.size(); ++i) {
if (command_list[i]->GetName() == string(argv[1])) {
command = command_list[i];
break;
}
}
if (NULL == command) {
Usage();
return 1;
}
bool display_statistics = false;
// parse the command line arguments for the Command
swissknife::ArgumentList args;
optind = 1;
string option_string = "";
swissknife::ParameterList params = command->GetParams();
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only())
option_string.push_back(':');
}
// Now adding the generic -+ extra option command
option_string.push_back(swissknife::Command::kGenericParam);
option_string.push_back(':');
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
// fprintf(f, "getopt --> %c\n", c);
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
assert(c != swissknife::Command::kGenericParam);
valid_option = true;
string *argument = NULL;
if (!params[j].switch_only()) {
argument = new string(optarg);
}
args[c] = argument;
break;
}
}
if (c == swissknife::Command::kGenericParam) {
valid_option = true;
vector<string> flags = SplitString(optarg,
swissknife::
Command::kGenericParamSeparator);
for (unsigned i = 0; i < flags.size(); ++i) {
if (flags[i] == "stats") {
display_statistics = true;
}
}
}
if (!valid_option) {
Usage();
return 1;
}
}
for (unsigned j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (args.find(params[j].key()) == args.end()) {
LogCvmfs(kLogCvmfs, kLogStderr, "parameter -%c missing",
params[j].key());
return 1;
}
}
}
// run the command
const int retval = command->Main(args);
if (display_statistics) {
LogCvmfs(kLogCvmfs, kLogStdout, "Command statistics");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command->statistics()
->PrintList(perf::Statistics::kPrintHeader).c_str());
}
// delete the command list
Commands::const_iterator i = command_list.begin();
const Commands::const_iterator iend = command_list.end();
for (; i != iend; ++i) {
delete *i;
}
command_list.clear();
// fclose(f);
return retval;
}
<|endoftext|>
|
<commit_before><commit_msg>check TRG_HasMasterPage before TRG_GetMasterPage<commit_after><|endoftext|>
|
<commit_before><commit_msg>sd: fix gcc-4.7 build<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuconarc.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:27:20 $
*
* 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_sd.hxx"
#include "fuconarc.hxx"
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDOCIRC_HXX //autogen
#include <svx/svdocirc.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#include <svx/svxids.hrc>
#include <math.h>
#include "app.hrc"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "res_bmp.hrc"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_TOOL_BAR_MANAGER_HXX
#include "ToolBarManager.hxx"
#endif
// #97016#
#ifndef _SXCIAITM_HXX
#include <svx/sxciaitm.hxx>
#endif
namespace sd {
TYPEINIT1( FuConstructArc, FuConstruct );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuConstructArc::FuConstructArc (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq )
: FuConstruct( pViewSh, pWin, pView, pDoc, rReq )
{
}
FunctionReference FuConstructArc::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent )
{
FuConstructArc* pFunc;
FunctionReference xFunc( pFunc = new FuConstructArc( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
pFunc->SetPermanent(bPermanent);
return xFunc;
}
void FuConstructArc::DoExecute( SfxRequest& rReq )
{
FuConstruct::DoExecute( rReq );
pViewShell->GetViewShellBase().GetToolBarManager().SetToolBar(
ToolBarManager::TBG_FUNCTION,
ToolBarManager::msDrawingObjectToolBar);
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
{
SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);
SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);
SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);
SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);
SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);
SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);
Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () / 2,
pCenterY->GetValue () - pAxisY->GetValue () / 2,
pCenterX->GetValue () + pAxisX->GetValue () / 2,
pCenterY->GetValue () + pAxisY->GetValue () / 2);
Activate(); // Setzt aObjKind
SdrCircObj* pNewCircle =
new SdrCircObj((SdrObjKind) pView->GetCurrentObjIdentifier(),
aNewRectangle,
(long) (pPhiStart->GetValue () * 10.0),
(long) (pPhiEnd->GetValue () * 10.0));
SdrPageView *pPV = pView->GetSdrPageView();
pView->InsertObjectAtView(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);
}
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );
if ( rMEvt.IsLeft() && !pView->IsAction() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
pWindow->CaptureMouse();
USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );
pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);
SdrObject* pObj = pView->GetCreateObj();
if (pObj)
{
SfxItemSet aAttr(pDoc->GetPool());
SetStyleSheet(aAttr, pObj);
//-/ pObj->NbcSetAttributes(aAttr, FALSE);
pObj->SetMergedItemSet(aAttr);
}
bReturn = TRUE;
}
return bReturn;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )
{
return FuConstruct::MouseMove(rMEvt);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )
{
BOOL bReturn = FALSE;
BOOL bCreated = FALSE;
if ( pView->IsCreateObj() && rMEvt.IsLeft() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
ULONG nCount = pView->GetSdrPageView()->GetObjList()->GetObjCount();
if (pView->EndCreateObj(SDRCREATE_NEXTPOINT) )
{
if (nCount != pView->GetSdrPageView()->GetObjList()->GetObjCount())
{
bCreated = TRUE;
}
}
bReturn = TRUE;
}
bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;
if (!bPermanent && bCreated)
pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
return bReturn;
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FuConstruct::KeyInput(rKEvt);
return(bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuConstructArc::Activate()
{
SdrObjKind aObjKind;
switch( nSlotId )
{
case SID_DRAW_ARC :
case SID_DRAW_CIRCLEARC:
{
aObjKind = OBJ_CARC;
}
break;
case SID_DRAW_PIE :
case SID_DRAW_PIE_NOFILL :
case SID_DRAW_CIRCLEPIE :
case SID_DRAW_CIRCLEPIE_NOFILL:
{
aObjKind = OBJ_SECT;
}
break;
case SID_DRAW_ELLIPSECUT :
case SID_DRAW_ELLIPSECUT_NOFILL:
case SID_DRAW_CIRCLECUT :
case SID_DRAW_CIRCLECUT_NOFILL :
{
aObjKind = OBJ_CCUT;
}
break;
default:
{
aObjKind = OBJ_CARC;
}
break;
}
pView->SetCurrentObj(aObjKind);
FuConstruct::Activate();
// FuDraw::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuConstructArc::Deactivate()
{
FuConstruct::Deactivate();
// FuDraw::Deactivate();
}
// #97016#
SdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)
{
// case SID_DRAW_ARC:
// case SID_DRAW_CIRCLEARC:
// case SID_DRAW_PIE:
// case SID_DRAW_PIE_NOFILL:
// case SID_DRAW_CIRCLEPIE:
// case SID_DRAW_CIRCLEPIE_NOFILL:
// case SID_DRAW_ELLIPSECUT:
// case SID_DRAW_ELLIPSECUT_NOFILL:
// case SID_DRAW_CIRCLECUT:
// case SID_DRAW_CIRCLECUT_NOFILL:
SdrObject* pObj = SdrObjFactory::MakeNewObject(
pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),
0L, pDoc);
if(pObj)
{
if(pObj->ISA(SdrCircObj))
{
Rectangle aRect(rRectangle);
if(SID_DRAW_ARC == nID ||
SID_DRAW_CIRCLEARC == nID ||
SID_DRAW_CIRCLEPIE == nID ||
SID_DRAW_CIRCLEPIE_NOFILL == nID ||
SID_DRAW_CIRCLECUT == nID ||
SID_DRAW_CIRCLECUT_NOFILL == nID)
{
// force quadratic
ImpForceQuadratic(aRect);
}
pObj->SetLogicRect(aRect);
SfxItemSet aAttr(pDoc->GetPool());
aAttr.Put(SdrCircStartAngleItem(9000));
aAttr.Put(SdrCircEndAngleItem(0));
if(SID_DRAW_PIE_NOFILL == nID ||
SID_DRAW_CIRCLEPIE_NOFILL == nID ||
SID_DRAW_ELLIPSECUT_NOFILL == nID ||
SID_DRAW_CIRCLECUT_NOFILL == nID)
{
aAttr.Put(XFillStyleItem(XFILL_NONE));
}
pObj->SetMergedItemSet(aAttr);
}
else
{
DBG_ERROR("Object is NO circle object");
}
}
return pObj;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.13.36); FILE MERGED 2006/11/27 13:48:01 cl 1.13.36.3: #i69285# warning free code changes for sd project 2006/11/22 15:03:44 cl 1.13.36.2: RESYNC: (1.13-1.14); FILE MERGED 2006/11/22 12:41:51 cl 1.13.36.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuconarc.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2006-12-12 17:14:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "fuconarc.hxx"
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDOCIRC_HXX //autogen
#include <svx/svdocirc.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#include <svx/svxids.hrc>
#include <math.h>
#include "app.hrc"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "res_bmp.hrc"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_TOOL_BAR_MANAGER_HXX
#include "ToolBarManager.hxx"
#endif
// #97016#
#ifndef _SXCIAITM_HXX
#include <svx/sxciaitm.hxx>
#endif
namespace sd {
TYPEINIT1( FuConstructArc, FuConstruct );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuConstructArc::FuConstructArc (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq )
: FuConstruct( pViewSh, pWin, pView, pDoc, rReq )
{
}
FunctionReference FuConstructArc::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent )
{
FuConstructArc* pFunc;
FunctionReference xFunc( pFunc = new FuConstructArc( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
pFunc->SetPermanent(bPermanent);
return xFunc;
}
void FuConstructArc::DoExecute( SfxRequest& rReq )
{
FuConstruct::DoExecute( rReq );
mpViewShell->GetViewShellBase().GetToolBarManager().SetToolBar(
ToolBarManager::TBG_FUNCTION,
ToolBarManager::msDrawingObjectToolBar);
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
{
SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);
SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);
SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);
SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);
SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);
SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);
Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () / 2,
pCenterY->GetValue () - pAxisY->GetValue () / 2,
pCenterX->GetValue () + pAxisX->GetValue () / 2,
pCenterY->GetValue () + pAxisY->GetValue () / 2);
Activate(); // Setzt aObjKind
SdrCircObj* pNewCircle =
new SdrCircObj((SdrObjKind) mpView->GetCurrentObjIdentifier(),
aNewRectangle,
(long) (pPhiStart->GetValue () * 10.0),
(long) (pPhiEnd->GetValue () * 10.0));
SdrPageView *pPV = mpView->GetSdrPageView();
mpView->InsertObjectAtView(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);
}
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );
if ( rMEvt.IsLeft() && !mpView->IsAction() )
{
Point aPnt( mpWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
mpWindow->CaptureMouse();
USHORT nDrgLog = USHORT ( mpWindow->PixelToLogic(Size(DRGPIX,0)).Width() );
mpView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);
SdrObject* pObj = mpView->GetCreateObj();
if (pObj)
{
SfxItemSet aAttr(mpDoc->GetPool());
SetStyleSheet(aAttr, pObj);
//-/ pObj->NbcSetAttributes(aAttr, FALSE);
pObj->SetMergedItemSet(aAttr);
}
bReturn = TRUE;
}
return bReturn;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )
{
return FuConstruct::MouseMove(rMEvt);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )
{
BOOL bReturn = FALSE;
BOOL bCreated = FALSE;
if ( mpView->IsCreateObj() && rMEvt.IsLeft() )
{
Point aPnt( mpWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
ULONG nCount = mpView->GetSdrPageView()->GetObjList()->GetObjCount();
if (mpView->EndCreateObj(SDRCREATE_NEXTPOINT) )
{
if (nCount != mpView->GetSdrPageView()->GetObjList()->GetObjCount())
{
bCreated = TRUE;
}
}
bReturn = TRUE;
}
bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;
if (!bPermanent && bCreated)
mpViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
return bReturn;
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FuConstruct::KeyInput(rKEvt);
return(bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuConstructArc::Activate()
{
SdrObjKind aObjKind;
switch( nSlotId )
{
case SID_DRAW_ARC :
case SID_DRAW_CIRCLEARC:
{
aObjKind = OBJ_CARC;
}
break;
case SID_DRAW_PIE :
case SID_DRAW_PIE_NOFILL :
case SID_DRAW_CIRCLEPIE :
case SID_DRAW_CIRCLEPIE_NOFILL:
{
aObjKind = OBJ_SECT;
}
break;
case SID_DRAW_ELLIPSECUT :
case SID_DRAW_ELLIPSECUT_NOFILL:
case SID_DRAW_CIRCLECUT :
case SID_DRAW_CIRCLECUT_NOFILL :
{
aObjKind = OBJ_CCUT;
}
break;
default:
{
aObjKind = OBJ_CARC;
}
break;
}
mpView->SetCurrentObj((UINT16)aObjKind);
FuConstruct::Activate();
// FuDraw::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuConstructArc::Deactivate()
{
FuConstruct::Deactivate();
// FuDraw::Deactivate();
}
// #97016#
SdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)
{
// case SID_DRAW_ARC:
// case SID_DRAW_CIRCLEARC:
// case SID_DRAW_PIE:
// case SID_DRAW_PIE_NOFILL:
// case SID_DRAW_CIRCLEPIE:
// case SID_DRAW_CIRCLEPIE_NOFILL:
// case SID_DRAW_ELLIPSECUT:
// case SID_DRAW_ELLIPSECUT_NOFILL:
// case SID_DRAW_CIRCLECUT:
// case SID_DRAW_CIRCLECUT_NOFILL:
SdrObject* pObj = SdrObjFactory::MakeNewObject(
mpView->GetCurrentObjInventor(), mpView->GetCurrentObjIdentifier(),
0L, mpDoc);
if(pObj)
{
if(pObj->ISA(SdrCircObj))
{
Rectangle aRect(rRectangle);
if(SID_DRAW_ARC == nID ||
SID_DRAW_CIRCLEARC == nID ||
SID_DRAW_CIRCLEPIE == nID ||
SID_DRAW_CIRCLEPIE_NOFILL == nID ||
SID_DRAW_CIRCLECUT == nID ||
SID_DRAW_CIRCLECUT_NOFILL == nID)
{
// force quadratic
ImpForceQuadratic(aRect);
}
pObj->SetLogicRect(aRect);
SfxItemSet aAttr(mpDoc->GetPool());
aAttr.Put(SdrCircStartAngleItem(9000));
aAttr.Put(SdrCircEndAngleItem(0));
if(SID_DRAW_PIE_NOFILL == nID ||
SID_DRAW_CIRCLEPIE_NOFILL == nID ||
SID_DRAW_ELLIPSECUT_NOFILL == nID ||
SID_DRAW_CIRCLECUT_NOFILL == nID)
{
aAttr.Put(XFillStyleItem(XFILL_NONE));
}
pObj->SetMergedItemSet(aAttr);
}
else
{
DBG_ERROR("Object is NO circle object");
}
}
return pObj;
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>#include <TimerOne.h> //Needed to make this file compile because hibike compiler bugs.
#include "ui.h"
#include "motor.h"
#include "pid.h"
#include "encoder.h"
//Code here that helps deal with the human-readable UI.
//Will contain code that will do the following:
//Let the user set State: Disabled, Enabled (open loop), Enabled (PID velocity), Enabled (PID position).
//Let the user set the setpoint.
//Let the user set the current limit stuff?
//Let the user enable/disable printing of various outputs (Position, current, etc)
//This code will be called by void loop in Integrated. It will NOT use timers or interrupts.
void manual_ui()
{
if (heartbeat > heartbeatLimit) {
disable();
Serial.println("We ded");
}
if (continualPrint) {
Serial.print("PWM: ");
Serial.print(pwmPID,5);
Serial.print(" | Encoder Pos: ");
Serial.print(pos);
Serial.print(" | Encoder Vel: ");
Serial.println(vel);
}
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if ( (c == 10) || (c == 13)) //if c is \n or \r
{
//do nothing.
}
else if (c == 's')
{
pwmInput = Serial.parseFloat();
Serial.print("New Speed: ");
Serial.println(pwmInput);
}
else if (c == 'c') {
Serial.println("Clearing Fault");
clearFault();
}
else if (c == 'p') {
Serial.read();
char val = Serial.read();
if (val == 'p') {
driveMode = 2;
enablePos();
Serial.println("Turning on PID Position mode");
}
else if (val == 'v') {
driveMode = 1;
enableVel();
Serial.println("Turning on PID Position mode");
}
}
else if (c == 'm') {
Serial.println("Turning on manual mode");
disablePID();
driveMode = 0;
}
else if (c == 'e') {
Serial.println("Enabled");
enable();
}
else if (c == 'd') {
Serial.println("Disabled");
disable();
}
else if (c == 'r') {
Serial.print("Encoder Pos: ");
Serial.println(encoder());
Serial.print("Encoder Vel: ");
Serial.println(vel);
Serial.print("Current: ");
Serial.println(readCurrent());
}
else if (c == 't') {
continualPrint = !continualPrint;
Serial.println("Toggling readout prints");
}
else if (c == 'w') {
Serial.read();
char val1 = Serial.read();
char val2 = Serial.read();
if (val1 == 'c') {
current_threshold = Serial.parseFloat();
Serial.print("New current threshold: ");
Serial.println(current_threshold);
}
else if (val1 == 'p') {
if (val2 == 'p'){
PIDPosKP = Serial.parseFloat();
Serial.print("New PID position KP value: ");
Serial.println(PIDPosKP);
}
else if (val2 == 'i'){
PIDPosKI = Serial.parseFloat();
Serial.print("New PID position KI value: ");
Serial.println(PIDPosKI);
}
else if (val2 == 'd'){
PIDPosKD = Serial.parseFloat();
Serial.print("New PID position KD value: ");
Serial.println(PIDPosKD);
}
else {
PIDPos = Serial.parseFloat();
Serial.print("New PID position: ");
Serial.println(PIDPos);
}
updatePosPID();
}
else if (val1 == 'v') {
if (val2 == 'p') {
PIDVelKP = Serial.parseFloat();
Serial.print("New PID velocity KP value: ");
Serial.println(PIDVelKP);
}
else if (val2 == 'i') {
PIDVelKI = Serial.parseFloat();
Serial.print("New PID velocity KI value: ");
Serial.println(PIDVelKI);
}
else if (val2 == 'd') {
PIDVelKD = Serial.parseFloat();
Serial.print("New PID velocity KD value: ");
Serial.println(PIDVelKD);
}
else {
PIDVel = Serial.parseFloat();
Serial.print("New PID velocity: ");
Serial.println(PIDVel);
}
updateVelPID();
}
else {
Serial.println("Cannot write to that");
}
}
else if (c == 'b') {
Serial.println("Heartbeat");
heartbeat = 0;
}
else if (c == 'h') {
hibike = true;
heartbeatLimit = 500;
Serial.println("Going to hibike mode");
}
else if (c == 'z') {
hibike = false;
heartbeatLimit = 30000;
Serial.println("Turning off hibike");
}
else if (c == '?') {
Serial.println("Manual Controls: \ns <x> - sets pwm to x \nc - clears faults \np <x> - turns on PID mode, velocity if x = v, position if x = p \nm - turns on manual input mode \ne - enables motor \nd - disables motor \nr - displays 1 print of all readable values \nt - toggles continual printing of pos and vel \nb - send heartbeat \nh - switch hibike mode \nz - switch human controls \nw <x> <y> - writes the value y to the variable x");
}
else {
Serial.println("Bad input");
}
}
delay(10);
}
<commit_msg>Figured out that weird bug where I had to pull in unrelated library.<commit_after>#include "Arduino.h" //to get digital write, etc.
#include "ui.h"
#include "motor.h"
#include "pid.h"
#include "encoder.h"
//Code here that helps deal with the human-readable UI.
//Will contain code that will do the following:
//Let the user set State: Disabled, Enabled (open loop), Enabled (PID velocity), Enabled (PID position).
//Let the user set the setpoint.
//Let the user set the current limit stuff?
//Let the user enable/disable printing of various outputs (Position, current, etc)
//This code will be called by void loop in Integrated. It will NOT use timers or interrupts.
void manual_ui()
{
if (heartbeat > heartbeatLimit) {
disable();
Serial.println("We ded");
}
if (continualPrint) {
Serial.print("PWM: ");
Serial.print(pwmPID,5);
Serial.print(" | Encoder Pos: ");
Serial.print(pos);
Serial.print(" | Encoder Vel: ");
Serial.println(vel);
}
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if ( (c == 10) || (c == 13)) //if c is \n or \r
{
//do nothing.
}
else if (c == 's')
{
pwmInput = Serial.parseFloat();
Serial.print("New Speed: ");
Serial.println(pwmInput);
}
else if (c == 'c') {
Serial.println("Clearing Fault");
clearFault();
}
else if (c == 'p') {
Serial.read();
char val = Serial.read();
if (val == 'p') {
driveMode = 2;
enablePos();
Serial.println("Turning on PID Position mode");
}
else if (val == 'v') {
driveMode = 1;
enableVel();
Serial.println("Turning on PID Position mode");
}
}
else if (c == 'm') {
Serial.println("Turning on manual mode");
disablePID();
driveMode = 0;
}
else if (c == 'e') {
Serial.println("Enabled");
enable ();
}
else if (c == 'd') {
Serial.println("Disabled");
disable();
}
else if (c == 'r') {
Serial.print("Encoder Pos: ");
Serial.println(encoder());
Serial.print("Encoder Vel: ");
Serial.println(vel);
Serial.print("Current: ");
Serial.println(readCurrent());
}
else if (c == 't') {
continualPrint = !continualPrint;
Serial.println("Toggling readout prints");
}
else if (c == 'w') {
Serial.read();
char val1 = Serial.read();
char val2 = Serial.read();
if (val1 == 'c') {
current_threshold = Serial.parseFloat();
Serial.print("New current threshold: ");
Serial.println(current_threshold);
}
else if (val1 == 'p') {
if (val2 == 'p'){
PIDPosKP = Serial.parseFloat();
Serial.print("New PID position KP value: ");
Serial.println(PIDPosKP);
}
else if (val2 == 'i'){
PIDPosKI = Serial.parseFloat();
Serial.print("New PID position KI value: ");
Serial.println(PIDPosKI);
}
else if (val2 == 'd'){
PIDPosKD = Serial.parseFloat();
Serial.print("New PID position KD value: ");
Serial.println(PIDPosKD);
}
else {
PIDPos = Serial.parseFloat();
Serial.print("New PID position: ");
Serial.println(PIDPos);
}
updatePosPID();
}
else if (val1 == 'v') {
if (val2 == 'p') {
PIDVelKP = Serial.parseFloat();
Serial.print("New PID velocity KP value: ");
Serial.println(PIDVelKP);
}
else if (val2 == 'i') {
PIDVelKI = Serial.parseFloat();
Serial.print("New PID velocity KI value: ");
Serial.println(PIDVelKI);
}
else if (val2 == 'd') {
PIDVelKD = Serial.parseFloat();
Serial.print("New PID velocity KD value: ");
Serial.println(PIDVelKD);
}
else {
PIDVel = Serial.parseFloat();
Serial.print("New PID velocity: ");
Serial.println(PIDVel);
}
updateVelPID();
}
else {
Serial.println("Cannot write to that");
}
}
else if (c == 'b') {
Serial.println("Heartbeat");
heartbeat = 0;
}
else if (c == 'h') {
hibike = true;
heartbeatLimit = 500;
Serial.println("Going to hibike mode");
}
else if (c == 'z') {
hibike = false;
heartbeatLimit = 30000;
Serial.println("Turning off hibike");
}
else if (c == '?') {
Serial.println("Manual Controls: \ns <x> - sets pwm to x \nc - clears faults \np <x> - turns on PID mode, velocity if x = v, position if x = p \nm - turns on manual input mode \ne - enables motor \nd - disables motor \nr - displays 1 print of all readable values \nt - toggles continual printing of pos and vel \nb - send heartbeat \nh - switch hibike mode \nz - switch human controls \nw <x> <y> - writes the value y to the variable x");
}
else {
Serial.println("Bad input");
}
}
delay(10);
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* audio_stream.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "audio_stream.h"
//////////////////////////////
void AudioStreamPlaybackResampled::_begin_resample() {
//clear cubic interpolation history
internal_buffer[0] = AudioFrame(0.0, 0.0);
internal_buffer[1] = AudioFrame(0.0, 0.0);
internal_buffer[2] = AudioFrame(0.0, 0.0);
internal_buffer[3] = AudioFrame(0.0, 0.0);
//mix buffer
_mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
mix_offset = 0;
}
void AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
float target_rate = AudioServer::get_singleton()->get_mix_rate() * p_rate_scale;
uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double(FP_LEN));
for (int i = 0; i < p_frames; i++) {
uint32_t idx = CUBIC_INTERP_HISTORY + uint32_t(mix_offset >> FP_BITS);
//standard cubic interpolation (great quality/performance ratio)
//this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory.
float mu = (mix_offset & FP_MASK) / float(FP_LEN);
AudioFrame y0 = internal_buffer[idx - 3];
AudioFrame y1 = internal_buffer[idx - 2];
AudioFrame y2 = internal_buffer[idx - 1];
AudioFrame y3 = internal_buffer[idx - 0];
float mu2 = mu * mu;
AudioFrame a0 = y3 - y2 - y0 + y1;
AudioFrame a1 = y0 - y1 - a0;
AudioFrame a2 = y2 - y0;
AudioFrame a3 = y1;
p_buffer[i] = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3);
mix_offset += mix_increment;
while ((mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN) {
internal_buffer[0] = internal_buffer[INTERNAL_BUFFER_LEN + 0];
internal_buffer[1] = internal_buffer[INTERNAL_BUFFER_LEN + 1];
internal_buffer[2] = internal_buffer[INTERNAL_BUFFER_LEN + 2];
internal_buffer[3] = internal_buffer[INTERNAL_BUFFER_LEN + 3];
if (!is_playing()) {
for (int i = 4; i < INTERNAL_BUFFER_LEN; ++i) {
internal_buffer[i] = AudioFrame(0, 0);
}
return;
}
_mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
mix_offset -= (INTERNAL_BUFFER_LEN << FP_BITS);
}
}
}
////////////////////////////////
void AudioStreamRandomPitch::set_audio_stream(const Ref<AudioStream> &p_audio_stream) {
audio_stream = p_audio_stream;
if (audio_stream.is_valid()) {
for (Set<AudioStreamPlaybackRandomPitch *>::Element *E = playbacks.front(); E; E = E->next()) {
E->get()->playback = audio_stream->instance_playback();
}
}
}
Ref<AudioStream> AudioStreamRandomPitch::get_audio_stream() const {
return audio_stream;
}
void AudioStreamRandomPitch::set_random_pitch(float p_pitch) {
if (p_pitch < 1)
p_pitch = 1;
random_pitch = p_pitch;
}
float AudioStreamRandomPitch::get_random_pitch() const {
return random_pitch;
}
Ref<AudioStreamPlayback> AudioStreamRandomPitch::instance_playback() {
Ref<AudioStreamPlaybackRandomPitch> playback;
playback.instance();
if (audio_stream.is_valid())
playback->playback = audio_stream->instance_playback();
playbacks.insert(playback.ptr());
playback->random_pitch = Ref<AudioStreamRandomPitch>((AudioStreamRandomPitch *)this);
return playback;
}
String AudioStreamRandomPitch::get_stream_name() const {
if (audio_stream.is_valid()) {
return "Random: " + audio_stream->get_name();
}
return "RandomPitch";
}
void AudioStreamRandomPitch::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_audio_stream", "stream"), &AudioStreamRandomPitch::set_audio_stream);
ClassDB::bind_method(D_METHOD("get_audio_stream"), &AudioStreamRandomPitch::get_audio_stream);
ClassDB::bind_method(D_METHOD("set_random_pitch", "scale"), &AudioStreamRandomPitch::set_random_pitch);
ClassDB::bind_method(D_METHOD("get_random_pitch"), &AudioStreamRandomPitch::get_random_pitch);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "audio_stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_audio_stream", "get_audio_stream");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "random_pitch", PROPERTY_HINT_RANGE, "1,16,0.01"), "set_random_pitch", "get_random_pitch");
}
AudioStreamRandomPitch::AudioStreamRandomPitch() {
random_pitch = 1.1;
}
void AudioStreamPlaybackRandomPitch::start(float p_from_pos) {
playing = playback;
float range_from = 1.0 / random_pitch->random_pitch;
float range_to = random_pitch->random_pitch;
pitch_scale = range_from + Math::randf() * (range_to - range_from);
if (playing.is_valid()) {
playing->start(p_from_pos);
}
}
void AudioStreamPlaybackRandomPitch::stop() {
if (playing.is_valid()) {
playing->stop();
;
}
}
bool AudioStreamPlaybackRandomPitch::is_playing() const {
if (playing.is_valid()) {
return playing->is_playing();
}
return false;
}
int AudioStreamPlaybackRandomPitch::get_loop_count() const {
if (playing.is_valid()) {
return playing->get_loop_count();
}
return 0;
}
float AudioStreamPlaybackRandomPitch::get_playback_position() const {
if (playing.is_valid()) {
return playing->get_playback_position();
}
return 0;
}
void AudioStreamPlaybackRandomPitch::seek(float p_time) {
if (playing.is_valid()) {
playing->seek(p_time);
}
}
void AudioStreamPlaybackRandomPitch::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
if (playing.is_valid()) {
playing->mix(p_buffer, p_rate_scale * pitch_scale, p_frames);
} else {
for (int i = 0; i < p_frames; i++) {
p_buffer[i] = AudioFrame(0, 0);
}
}
}
float AudioStreamPlaybackRandomPitch::get_length() const {
if (playing.is_valid()) {
return playing->get_length();
}
return 0;
}
AudioStreamPlaybackRandomPitch::~AudioStreamPlaybackRandomPitch() {
random_pitch->playbacks.erase(this);
}
<commit_msg>Properly silence buffer while not in use, fixes #14866<commit_after>/*************************************************************************/
/* audio_stream.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "audio_stream.h"
//////////////////////////////
void AudioStreamPlaybackResampled::_begin_resample() {
//clear cubic interpolation history
internal_buffer[0] = AudioFrame(0.0, 0.0);
internal_buffer[1] = AudioFrame(0.0, 0.0);
internal_buffer[2] = AudioFrame(0.0, 0.0);
internal_buffer[3] = AudioFrame(0.0, 0.0);
//mix buffer
_mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
mix_offset = 0;
}
void AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
float target_rate = AudioServer::get_singleton()->get_mix_rate() * p_rate_scale;
uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double(FP_LEN));
for (int i = 0; i < p_frames; i++) {
uint32_t idx = CUBIC_INTERP_HISTORY + uint32_t(mix_offset >> FP_BITS);
//standard cubic interpolation (great quality/performance ratio)
//this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory.
float mu = (mix_offset & FP_MASK) / float(FP_LEN);
AudioFrame y0 = internal_buffer[idx - 3];
AudioFrame y1 = internal_buffer[idx - 2];
AudioFrame y2 = internal_buffer[idx - 1];
AudioFrame y3 = internal_buffer[idx - 0];
float mu2 = mu * mu;
AudioFrame a0 = y3 - y2 - y0 + y1;
AudioFrame a1 = y0 - y1 - a0;
AudioFrame a2 = y2 - y0;
AudioFrame a3 = y1;
p_buffer[i] = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3);
mix_offset += mix_increment;
while ((mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN) {
internal_buffer[0] = internal_buffer[INTERNAL_BUFFER_LEN + 0];
internal_buffer[1] = internal_buffer[INTERNAL_BUFFER_LEN + 1];
internal_buffer[2] = internal_buffer[INTERNAL_BUFFER_LEN + 2];
internal_buffer[3] = internal_buffer[INTERNAL_BUFFER_LEN + 3];
if (is_playing()) {
_mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
} else {
//fill with silence, not playing
for (int i = 0; i < INTERNAL_BUFFER_LEN; ++i) {
internal_buffer[i + 4] = AudioFrame(0, 0);
}
}
mix_offset -= (INTERNAL_BUFFER_LEN << FP_BITS);
}
}
}
////////////////////////////////
void AudioStreamRandomPitch::set_audio_stream(const Ref<AudioStream> &p_audio_stream) {
audio_stream = p_audio_stream;
if (audio_stream.is_valid()) {
for (Set<AudioStreamPlaybackRandomPitch *>::Element *E = playbacks.front(); E; E = E->next()) {
E->get()->playback = audio_stream->instance_playback();
}
}
}
Ref<AudioStream> AudioStreamRandomPitch::get_audio_stream() const {
return audio_stream;
}
void AudioStreamRandomPitch::set_random_pitch(float p_pitch) {
if (p_pitch < 1)
p_pitch = 1;
random_pitch = p_pitch;
}
float AudioStreamRandomPitch::get_random_pitch() const {
return random_pitch;
}
Ref<AudioStreamPlayback> AudioStreamRandomPitch::instance_playback() {
Ref<AudioStreamPlaybackRandomPitch> playback;
playback.instance();
if (audio_stream.is_valid())
playback->playback = audio_stream->instance_playback();
playbacks.insert(playback.ptr());
playback->random_pitch = Ref<AudioStreamRandomPitch>((AudioStreamRandomPitch *)this);
return playback;
}
String AudioStreamRandomPitch::get_stream_name() const {
if (audio_stream.is_valid()) {
return "Random: " + audio_stream->get_name();
}
return "RandomPitch";
}
void AudioStreamRandomPitch::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_audio_stream", "stream"), &AudioStreamRandomPitch::set_audio_stream);
ClassDB::bind_method(D_METHOD("get_audio_stream"), &AudioStreamRandomPitch::get_audio_stream);
ClassDB::bind_method(D_METHOD("set_random_pitch", "scale"), &AudioStreamRandomPitch::set_random_pitch);
ClassDB::bind_method(D_METHOD("get_random_pitch"), &AudioStreamRandomPitch::get_random_pitch);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "audio_stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_audio_stream", "get_audio_stream");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "random_pitch", PROPERTY_HINT_RANGE, "1,16,0.01"), "set_random_pitch", "get_random_pitch");
}
AudioStreamRandomPitch::AudioStreamRandomPitch() {
random_pitch = 1.1;
}
void AudioStreamPlaybackRandomPitch::start(float p_from_pos) {
playing = playback;
float range_from = 1.0 / random_pitch->random_pitch;
float range_to = random_pitch->random_pitch;
pitch_scale = range_from + Math::randf() * (range_to - range_from);
if (playing.is_valid()) {
playing->start(p_from_pos);
}
}
void AudioStreamPlaybackRandomPitch::stop() {
if (playing.is_valid()) {
playing->stop();
;
}
}
bool AudioStreamPlaybackRandomPitch::is_playing() const {
if (playing.is_valid()) {
return playing->is_playing();
}
return false;
}
int AudioStreamPlaybackRandomPitch::get_loop_count() const {
if (playing.is_valid()) {
return playing->get_loop_count();
}
return 0;
}
float AudioStreamPlaybackRandomPitch::get_playback_position() const {
if (playing.is_valid()) {
return playing->get_playback_position();
}
return 0;
}
void AudioStreamPlaybackRandomPitch::seek(float p_time) {
if (playing.is_valid()) {
playing->seek(p_time);
}
}
void AudioStreamPlaybackRandomPitch::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
if (playing.is_valid()) {
playing->mix(p_buffer, p_rate_scale * pitch_scale, p_frames);
} else {
for (int i = 0; i < p_frames; i++) {
p_buffer[i] = AudioFrame(0, 0);
}
}
}
float AudioStreamPlaybackRandomPitch::get_length() const {
if (playing.is_valid()) {
return playing->get_length();
}
return 0;
}
AudioStreamPlaybackRandomPitch::~AudioStreamPlaybackRandomPitch() {
random_pitch->playbacks.erase(this);
}
<|endoftext|>
|
<commit_before>/**
* @file radon.cpp
*
* @date Oct 28, 2012
* @author tack
*/
#include "radon.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
static once_flag oflag;
radon::radon() : itsInit(false), itsRadonDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::radon::InitPool, this);
}
void radon::InitPool()
{
NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
char* base = getenv("MASALA_BASE");
if (string(base) == "/masala")
{
NFmiRadonDBPool::Instance()->Username("wetodb");
NFmiRadonDBPool::Instance()->Password("3loHRgdio");
}
else
{
itsLogger->Warning("Program executed as uid 1459 ('weto') but MASALA_BASE not set");
}
}
}
vector<string> radon::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
// long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
string forecastTypeValue = (options.ftype.Type() == kEpsPerturbation) ? boost::lexical_cast<string> (options.ftype.Value()) : "-1";
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string geomid = gridgeoms[i][0];
string parm_name = options.param.Name();
string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server "
"FROM "+tablename+"_v "
"WHERE analysis_time = '"+analtime+"' "
"AND param_name = '"+parm_name+"' "
"AND level_name = upper('"+level_name+"') "
"AND level_value = "+levelvalue+" "
"AND forecast_period = '"+util::MakeSQLInterval(options.time)+"' "
"AND geometry_id = "+geomid+" "
"AND forecast_type_id = "+boost::lexical_cast<string> (options.ftype.Type())+" "
"AND forecast_type_value = "+forecastTypeValue+" "
"ORDER BY forecast_period, level_id, level_value";
itsRadonDB->Query(query);
vector<string> values = itsRadonDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][3]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool radon::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to radon for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
query << "SELECT geometry_id "
<< "FROM geom_v "
<< "WHERE nj = " << g->Nj()
<< " AND ni = " << g->Ni()
<< " AND first_lat = " << firstGridPoint.Y()
<< " AND first_lon = " << firstGridPoint.X();
itsRadonDB->Query(query.str());
vector<string> row;
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from radon");
return false;
}
string geom_id = row[0];
query.str("");
query << "SELECT "
<< "id, table_name "
<< "FROM as_grid "
<< "WHERE geometry_id = '" << geom_id << "'"
<< " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'"
<< " AND producer_id = " << resultInfo.Producer().Id();
itsRadonDB->Query(query.str());
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from radon");
return false;
}
string table_name = row[1];
string dset_id = row[0];
query.str("");
string host = "undetermined host";
char* hostname = getenv("HOSTNAME");
if (hostname != NULL)
{
host = string(hostname);
}
/*
* We have our own error logging for unique key violations
*/
// itsRadonDB->Verbose(false);
double forecastTypeValue = (resultInfo.ForecastType().Type() == kEpsPerturbation) ? resultInfo.ForecastType().Value() : -1.;
query << "INSERT INTO data." << table_name
<< " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, forecast_type_value, file_location, file_server) "
<< "SELECT " << resultInfo.Producer().Id() << ", "
<< "'" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "', "
<< "'" << geom_id << "', "
<< "param.id, level.id, "
<< resultInfo.Level().Value() << ", "
<< "'" << util::MakeSQLInterval(resultInfo.Time()) << "', "
<< resultInfo.ForecastType().Type() << ", "
<< forecastTypeValue << ","
<< "'" << theFileName << "', "
<< "'" << host << "' "
<< "FROM param, level "
<< "WHERE param.name = '" << resultInfo.Param().Name() << "' "
<< "AND level.name = upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "')";
try
{
itsRadonDB->Execute(query.str());
itsRadonDB->Commit();
}
catch (int e)
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsRadonDB->Rollback();
return false;
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to radon");
return true;
}
map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->GetParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value);
return paramName;
}
map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->GetParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value);
return paramName;
}
string radon::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<commit_msg>update as_grid @ radon<commit_after>/**
* @file radon.cpp
*
* @date Oct 28, 2012
* @author tack
*/
#include "radon.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
static once_flag oflag;
radon::radon() : itsInit(false), itsRadonDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::radon::InitPool, this);
}
void radon::InitPool()
{
NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
NFmiRadonDBPool::Instance()->Username("wetodb");
NFmiRadonDBPool::Instance()->Password("3loHRgdio");
}
}
vector<string> radon::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
// long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
string forecastTypeValue = (options.ftype.Type() == kEpsPerturbation) ? boost::lexical_cast<string> (options.ftype.Value()) : "-1";
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string geomid = gridgeoms[i][0];
string parm_name = options.param.Name();
string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server "
"FROM "+tablename+"_v "
"WHERE analysis_time = '"+analtime+"' "
"AND param_name = '"+parm_name+"' "
"AND level_name = upper('"+level_name+"') "
"AND level_value = "+levelvalue+" "
"AND forecast_period = '"+util::MakeSQLInterval(options.time)+"' "
"AND geometry_id = "+geomid+" "
"AND forecast_type_id = "+boost::lexical_cast<string> (options.ftype.Type())+" "
"AND forecast_type_value = "+forecastTypeValue+" "
"ORDER BY forecast_period, level_id, level_value";
itsRadonDB->Query(query);
vector<string> values = itsRadonDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][3]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool radon::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to radon for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
query << "SELECT geometry_id "
<< "FROM geom_v "
<< "WHERE nj = " << g->Nj()
<< " AND ni = " << g->Ni()
<< " AND first_lat = " << firstGridPoint.Y()
<< " AND first_lon = " << firstGridPoint.X();
itsRadonDB->Query(query.str());
vector<string> row;
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from radon");
return false;
}
string geom_id = row[0];
query.str("");
query << "SELECT "
<< "id, table_name "
<< "FROM as_grid "
<< "WHERE geometry_id = '" << geom_id << "'"
<< " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'"
<< " AND producer_id = " << resultInfo.Producer().Id();
itsRadonDB->Query(query.str());
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from radon");
return false;
}
string table_name = row[1];
string dset_id = row[0];
query.str("");
char host[255];
gethostname(host, 255);
auto paraminfo = itsRadonDB->GetParameterFromDatabaseName(resultInfo.Producer().Id(), resultInfo.Param().Name());
auto levelinfo = itsRadonDB->GetLevelFromGrib(resultInfo.Producer().Id(), resultInfo.Level().Type(), 1);
/*
* We have our own error logging for unique key violations
*/
// itsRadonDB->Verbose(false);
double forecastTypeValue = (resultInfo.ForecastType().Type() == kEpsPerturbation) ? resultInfo.ForecastType().Value() : -1.;
string analysisTime = resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00");
query << "INSERT INTO data." << table_name
<< " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, forecast_type_value, file_location, file_server) VALUES ("
<< resultInfo.Producer().Id() << ", "
<< "'" << analysisTime << "', "
<< geom_id << ", "
<< paraminfo["id"] << ", "
<< levelinfo["id"] << ", "
<< resultInfo.Level().Value() << ", "
<< "'" << util::MakeSQLInterval(resultInfo.Time()) << "', "
<< resultInfo.ForecastType().Type() << ", "
<< forecastTypeValue << ","
<< "'" << theFileName << "', "
<< "'" << host << "')"
;
try
{
itsRadonDB->Execute(query.str());
query.str("");
query << "UPDATE as_grid SET record_count = record_count+1 WHERE producer_id = " << resultInfo.Producer().Id()
<< " AND geometry_id = " << geom_id
<< " AND analysis_time = '" << analysisTime << "'";
itsRadonDB->Execute(query.str());
itsRadonDB->Commit();
}
catch (int e)
{
itsRadonDB->Rollback();
if (e == 7)
{
query.str("");
query << "UPDATE data." << table_name << " SET "
<< "file_location = '" << theFileName << "', "
<< "file_server = '" << host << "' WHERE "
<< "producer_id = " << resultInfo.Producer().Id() << " AND "
<< "analysis_time = '" << analysisTime << "' AND "
<< "geometry_id = " << geom_id << " AND "
<< "param_id = " << paraminfo["id"] << " AND "
<< "level_id = " << levelinfo["id"] << " AND "
<< "level_value = " << resultInfo.Level().Value() << " AND "
<< "forecast_period = " << "'" << util::MakeSQLInterval(resultInfo.Time()) << "' AND "
<< "forecast_type_id = " << resultInfo.ForecastType().Type() << " AND "
<< "forecast_type_value = " << forecastTypeValue;
itsRadonDB->Execute(query.str());
itsRadonDB->Commit();
}
else
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
}
return false;
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to radon");
return true;
}
map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->GetParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value);
return paramName;
}
map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->GetParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value);
return paramName;
}
string radon::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<|endoftext|>
|
<commit_before>/*
* This file is part of KDevelop
*
* Copyright 2010 Niko Sams <niko.sams@gmail.com>
* Copyright 2010 Alexander Dymo <adymo@kdevelop.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This 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 "declarationbuilder.h"
#include <interfaces/icore.h>
#include <language/duchain/classdeclaration.h>
#include <language/duchain/functiondeclaration.h>
#include <language/duchain/classfunctiondeclaration.h>
#include <language/duchain/types/functiontype.h>
#include "parser/rubyast.h"
#include "editorintegrator.h"
namespace Ruby
{
DeclarationBuilder::DeclarationBuilder(EditorIntegrator* editor):
DeclarationBuilderBase()
{
setEditor(editor);
}
void DeclarationBuilder::closeDeclaration()
{
eventuallyAssignInternalContext();
DeclarationBuilderBase::closeDeclaration();
}
void DeclarationBuilder::visitClass(ClassAST* ast)
{
{
KDevelop::SimpleRange range = editor()->findRange(ast);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
KDevelop::ClassDeclaration* decl = openDefinition<KDevelop::ClassDeclaration>(id, range);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
decl->clearBaseClasses();
decl->setClassType(KDevelop::ClassDeclarationData::Class);
}
DeclarationBuilderBase::visitClass(ast);
closeDeclaration();
}
void DeclarationBuilder::visitFunction(FunctionAST* ast)
{
KDevelop::Declaration *x = 0;
{
KDevelop::SimpleRange range = editor()->findRange(ast->name);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
if (ast->isMember) {
KDevelop::ClassFunctionDeclaration *decl = openDefinition<KDevelop::ClassFunctionDeclaration>(id, range);
decl->setAccessPolicy(ast->access);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
x = decl;
} else {
KDevelop::FunctionDeclaration *decl = openDefinition<KDevelop::FunctionDeclaration>(id, range);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
x = decl;
}
}
DeclarationBuilderBase::visitFunction(ast);
closeDeclaration();
/* {
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
kDebug(9047) << x->toString();
kDebug(9047) << x->type<KDevelop::FunctionType>()->partToString(KDevelop::FunctionType::SignatureArguments);
}*/
}
void DeclarationBuilder::visitFunctionArgument(FunctionArgumentAST* ast)
{
{
// create variable declaration for argument
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
KDevelop::SimpleRange range = editor()->findRange(ast->name);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
openDefinition<KDevelop::Declaration>(id, range);
currentDeclaration()->setKind(KDevelop::Declaration::Instance);
}
DeclarationBuilderBase::visitFunctionArgument(ast);
closeDeclaration();
}
void DeclarationBuilder::updateCurrentType()
{
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
currentDeclaration()->setAbstractType(currentAbstractType());
}
}
<commit_msg>Remove commented code and debug output<commit_after>/*
* This file is part of KDevelop
*
* Copyright 2010 Niko Sams <niko.sams@gmail.com>
* Copyright 2010 Alexander Dymo <adymo@kdevelop.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This 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 "declarationbuilder.h"
#include <interfaces/icore.h>
#include <language/duchain/classdeclaration.h>
#include <language/duchain/functiondeclaration.h>
#include <language/duchain/classfunctiondeclaration.h>
#include <language/duchain/types/functiontype.h>
#include "parser/rubyast.h"
#include "editorintegrator.h"
namespace Ruby
{
DeclarationBuilder::DeclarationBuilder(EditorIntegrator* editor):
DeclarationBuilderBase()
{
setEditor(editor);
}
void DeclarationBuilder::closeDeclaration()
{
eventuallyAssignInternalContext();
DeclarationBuilderBase::closeDeclaration();
}
void DeclarationBuilder::visitClass(ClassAST* ast)
{
{
KDevelop::SimpleRange range = editor()->findRange(ast);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
KDevelop::ClassDeclaration* decl = openDefinition<KDevelop::ClassDeclaration>(id, range);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
decl->clearBaseClasses();
decl->setClassType(KDevelop::ClassDeclarationData::Class);
}
DeclarationBuilderBase::visitClass(ast);
closeDeclaration();
}
void DeclarationBuilder::visitFunction(FunctionAST* ast)
{
{
KDevelop::SimpleRange range = editor()->findRange(ast->name);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
if (ast->isMember) {
KDevelop::ClassFunctionDeclaration *decl = openDefinition<KDevelop::ClassFunctionDeclaration>(id, range);
decl->setAccessPolicy(ast->access);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
} else {
KDevelop::FunctionDeclaration *decl = openDefinition<KDevelop::FunctionDeclaration>(id, range);
decl->setDeclarationIsDefinition(true);
decl->setKind(KDevelop::Declaration::Type);
}
}
DeclarationBuilderBase::visitFunction(ast);
closeDeclaration();
}
void DeclarationBuilder::visitFunctionArgument(FunctionArgumentAST* ast)
{
{
// create variable declaration for argument
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
KDevelop::SimpleRange range = editor()->findRange(ast->name);
KDevelop::QualifiedIdentifier id(KDevelop::Identifier(KDevelop::IndexedString(ast->name->name)));
openDefinition<KDevelop::Declaration>(id, range);
currentDeclaration()->setKind(KDevelop::Declaration::Instance);
}
DeclarationBuilderBase::visitFunctionArgument(ast);
closeDeclaration();
}
void DeclarationBuilder::updateCurrentType()
{
KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
currentDeclaration()->setAbstractType(currentAbstractType());
}
}
<|endoftext|>
|
<commit_before>// This file is part of DVS-ROS - the RPG DVS ROS Package
//
// DVS-ROS is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DVS-ROS 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 DVS-ROS. If not, see <http://www.gnu.org/licenses/>.
#include <ros/ros.h>
#include <fstream>
#include <ctime>
#include <dvs_msgs/Event.h>
#include <dvs_msgs/EventArray.h>
std::ofstream myfile;
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d_%H-%M-%S", &tstruct);
return buf;
}
void eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg) {
for (int i=0; i<msg->events.size(); ++i) {
myfile << (int) msg->events[i].x << " ";
myfile << (int) msg->events[i].y << " ";
myfile << (int) msg->events[i].polarity << " ";
myfile << msg->events[i].time << std::endl;
}
}
int main(int argc, char* argv[])
{
ros::init(argc, argv, "dvs_file_writer");
ros::NodeHandle nh;
std::string file_name = std::string("events-" + currentDateTime() + ".txt");
myfile.open(file_name.c_str());
ROS_INFO("Writing events to %s.", file_name.c_str());
ros::Subscriber sub = nh.subscribe("dvs/events", 1000, eventsCallback);
ros::spin();
myfile.close();
return 0;
}
<commit_msg>removed dot at the end for easier copying<commit_after>// This file is part of DVS-ROS - the RPG DVS ROS Package
//
// DVS-ROS is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DVS-ROS 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 DVS-ROS. If not, see <http://www.gnu.org/licenses/>.
#include <ros/ros.h>
#include <fstream>
#include <ctime>
#include <dvs_msgs/Event.h>
#include <dvs_msgs/EventArray.h>
std::ofstream myfile;
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d_%H-%M-%S", &tstruct);
return buf;
}
void eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg) {
for (int i=0; i<msg->events.size(); ++i) {
myfile << (int) msg->events[i].x << " ";
myfile << (int) msg->events[i].y << " ";
myfile << (int) msg->events[i].polarity << " ";
myfile << msg->events[i].time << std::endl;
}
}
int main(int argc, char* argv[])
{
ros::init(argc, argv, "dvs_file_writer");
ros::NodeHandle nh;
std::string file_name = std::string("events-" + currentDateTime() + ".txt");
myfile.open(file_name.c_str());
ROS_INFO("Writing events to %s", file_name.c_str());
ros::Subscriber sub = nh.subscribe("dvs/events", 1000, eventsCallback);
ros::spin();
myfile.close();
return 0;
}
<|endoftext|>
|
<commit_before>#include "tangram.h"
#include "platform.h"
#include "gl.h"
// Input handling
// ==============
const double double_tap_time = 0.5; // seconds
const double scroll_multiplier = 0.05; // scaling for zoom
bool was_panning = false;
double last_mouse_up = -double_tap_time; // First click should never trigger a double tap
double last_x_down = 0.0;
double last_y_down = 0.0;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button != GLFW_MOUSE_BUTTON_1) {
return; // This event is for a mouse button that we don't care about
}
if (was_panning) {
was_panning = false;
return; // Clicks with movement don't count as taps
}
double x, y;
glfwGetCursorPos(window, &x, &y);
double time = glfwGetTime();
if (action == GLFW_PRESS) {
last_x_down = x;
last_y_down = y;
return;
}
if (time - last_mouse_up < double_tap_time) {
Tangram::handleDoubleTapGesture(x, y);
} else {
Tangram::handleTapGesture(x, y);
}
last_mouse_up = time;
}
void cursor_pos_callback(GLFWwindow* window, double x, double y) {
int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1);
if (action == GLFW_PRESS) {
if (was_panning) {
Tangram::handlePanGesture(x - last_x_down, y - last_y_down);
}
was_panning = true;
last_x_down = x;
last_y_down = y;
}
}
void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) {
double x, y;
glfwGetCursorPos(window, &x, &y);
Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_E && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
Tangram::handleRotateGesture(0.0f, 0.0f, -0.1f);
}
if (key == GLFW_KEY_Q && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
Tangram::handleRotateGesture(0.0f, 0.0f, 0.1f);
}
}
// Window handling
// ===============
void window_size_callback(GLFWwindow* window, int width, int height) {
Tangram::resize(width, height);
}
// Main program
// ============
int main(void) {
GLFWwindow* window;
int width = 800;
int height = 600;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, "GLFW Window", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
Tangram::initialize();
Tangram::resize(width, height);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetKeyCallback(window, key_callback);
glfwSwapInterval(1);
double lastTime = glfwGetTime();
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window)) {
double currentTime = glfwGetTime();
double delta = currentTime - lastTime;
lastTime = currentTime;
/* Render here */
Tangram::update(delta);
Tangram::render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
Tangram::teardown();
glfwTerminate();
return 0;
}
<commit_msg>Forgot that I changed a function signature<commit_after>#include "tangram.h"
#include "platform.h"
#include "gl.h"
// Input handling
// ==============
const double double_tap_time = 0.5; // seconds
const double scroll_multiplier = 0.05; // scaling for zoom
bool was_panning = false;
double last_mouse_up = -double_tap_time; // First click should never trigger a double tap
double last_x_down = 0.0;
double last_y_down = 0.0;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button != GLFW_MOUSE_BUTTON_1) {
return; // This event is for a mouse button that we don't care about
}
if (was_panning) {
was_panning = false;
return; // Clicks with movement don't count as taps
}
double x, y;
glfwGetCursorPos(window, &x, &y);
double time = glfwGetTime();
if (action == GLFW_PRESS) {
last_x_down = x;
last_y_down = y;
return;
}
if (time - last_mouse_up < double_tap_time) {
Tangram::handleDoubleTapGesture(x, y);
} else {
Tangram::handleTapGesture(x, y);
}
last_mouse_up = time;
}
void cursor_pos_callback(GLFWwindow* window, double x, double y) {
int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1);
if (action == GLFW_PRESS) {
if (was_panning) {
Tangram::handlePanGesture(x - last_x_down, y - last_y_down);
}
was_panning = true;
last_x_down = x;
last_y_down = y;
}
}
void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) {
double x, y;
glfwGetCursorPos(window, &x, &y);
Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_E && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
Tangram::handleRotateGesture(-0.1f);
}
if (key == GLFW_KEY_Q && (action == GLFW_PRESS || action == GLFW_REPEAT)) {
Tangram::handleRotateGesture(0.1f);
}
}
// Window handling
// ===============
void window_size_callback(GLFWwindow* window, int width, int height) {
Tangram::resize(width, height);
}
// Main program
// ============
int main(void) {
GLFWwindow* window;
int width = 800;
int height = 600;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, "GLFW Window", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
Tangram::initialize();
Tangram::resize(width, height);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetKeyCallback(window, key_callback);
glfwSwapInterval(1);
double lastTime = glfwGetTime();
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window)) {
double currentTime = glfwGetTime();
double delta = currentTime - lastTime;
lastTime = currentTime;
/* Render here */
Tangram::update(delta);
Tangram::render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
Tangram::teardown();
glfwTerminate();
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <iostream>
#include <iomanip>
#include <string.h>
// void print(const int it, const double energy);
template<typename T>
std::string to_string(const T& t)
{
std::ostringstream strs;
strs << std::scientific << std::setprecision(3) << t;
return strs.str();
}
template<typename T>
std::string red(const T& t)
{
return "\033[31m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string green(const T& t)
{
return "\033[32m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string yellow(const T& t)
{
return "\033[33m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string blue(const T& t)
{
return "\033[34m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string white(const T& t)
{
return "\033[37m" + to_string(t) + "\033[0m";
}
std::string red(const std::string& s);
std::string green(const std::string& s);
std::string yellow(const std::string& s);
std::string blue(const std::string& s);
std::string white(const std::string& s);
void bar();
// template<typename Solver, typename Color>
// template<typename Solver, typename T, typename Color = std::string (*Color)(T&)>
// template<typename T, std::string (*Color)(const T&), typename Solver>
// void print(
// const Solver& s
// // , const Color& c
// )
// {
// std::cout << Color(s.current_it) << "\t";
// std::cout << Color(s.current_temperature) << "\t";
// std::cout << Color(s.current_temperature - s.temperature(s.current_temperature)) << "\t";
// std::cout << Color(s.current_energy) << "\t";
// // // std::cout << s.d_energy << "\t";
// std::cout << std::endl;
// }
struct Accepted{};
struct Rejected{};
template<typename Solver>
void print(
const Solver& s
, Accepted
)
{
// std::cout << green(s.current_it) << "\t";
std::cout << green(s.current_temperature) << "\t";
std::cout << green(s.current_temperature - s.temperature()) << "\t";
std::cout << green(s.current_energy) << "\t";
// // std::cout << s.d_energy << "\t";
std::cout << "\n\r\e[A";
std::cout << std::string(100, ' ');
std::cout << "\r";
// std::cout << "\n\r\e[A";
}
template<typename Solver>
void print(
const Solver& s
, Rejected
)
{
// std::cout << red(s.current_it) << "\t";
std::cout << red(s.current_temperature) << "\t";
std::cout << red(s.current_temperature - s.temperature()) << "\t";
std::cout << red(s.current_energy) << "\t";
// // std::cout << s.d_energy << "\t";
std::cout << "\n\r\e[A";
std::cout << std::string(100, ' ');
std::cout << "\r";
}
template<typename Solver>
void final_print(const Solver& s)
{
std::cout << std::endl;
std::cout << "Final temperature: " << s.current_temperature << "\n";
std::cout << "Final energy: " << s.current_energy << "\n";
std::cout << std::endl;
}
<commit_msg>[display] major update<commit_after>#pragma once
#include <iostream>
#include <iomanip>
#include <string.h>
// void print(const int it, const double energy);
template<typename T>
std::string to_string(const T& t)
{
std::ostringstream strs;
strs << std::scientific << std::setprecision(3) << t;
return strs.str();
}
template<typename T>
std::string red(const T& t)
{
return "\033[31m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string green(const T& t)
{
return "\033[32m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string yellow(const T& t)
{
return "\033[33m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string blue(const T& t)
{
return "\033[34m" + to_string(t) + "\033[0m";
}
template<typename T>
std::string white(const T& t)
{
return "\033[37m" + to_string(t) + "\033[0m";
}
std::string red(const std::string& s);
std::string green(const std::string& s);
std::string yellow(const std::string& s);
std::string blue(const std::string& s);
std::string white(const std::string& s);
void bar();
// template<typename Solver, typename Color>
// template<typename Solver, typename T, typename Color = std::string (*Color)(T&)>
// template<typename T, std::string (*Color)(const T&), typename Solver>
// void print(
// const Solver& s
// // , const Color& c
// )
// {
// std::cout << Color(s.current_it) << "\t";
// std::cout << Color(s.current_temperature) << "\t";
// std::cout << Color(s.current_temperature - s.temperature(s.current_temperature)) << "\t";
// std::cout << Color(s.current_energy) << "\t";
// // // std::cout << s.d_energy << "\t";
// std::cout << std::endl;
// }
struct Accepted{};
struct Rejected{};
template<typename Solver>
void print(
const Solver& s
, Accepted
)
{
// std::cout << green(s.current_it) << "\t";
std::cout << green(s.current_temperature) << "\t";
std::cout << green(s.current_temperature - s.temperature()) << "\t";
std::cout << green(s.current_energy) << "\t";
// // std::cout << s.d_energy << "\t";
std::cout << "\r";
}
template<typename Solver>
void print(
const Solver& s
, Rejected
)
{
// std::cout << red(s.current_it) << "\t";
std::cout << red(s.current_temperature) << "\t";
std::cout << red(s.current_temperature - s.temperature()) << "\t";
std::cout << red(s.current_energy) << "\t";
// // std::cout << s.d_energy << "\t";
std::cout << "\r";
}
template<typename Solver>
void final_print(const Solver& s)
{
std::cout << std::endl;
std::cout << "Final temperature: " << s.current_temperature << "\n";
std::cout << "Final energy: " << s.current_energy << "\n";
std::cout << std::endl;
}
<|endoftext|>
|
<commit_before>#include "duktape.h"
#include "dukbind.h"
#include "dukbindconf.h"
#include "dukbind_proxy_function.h"
#include "dukbind_private.h"
#include "utils/dukbind_debug.h"
namespace dukbind
{
struct Box
{
void * ObjectPointer;
size_t ClassIndex;
finalizer_t Finalizer;
};
void Push( duk_context * ctx, const bool value, const bool* )
{
duk_push_boolean( ctx, value );
}
void Push( duk_context * ctx, const char * value, const char ** )
{
duk_push_string( ctx, value );
}
void Push( duk_context * ctx, const int value, const int * )
{
dukbind_assert(
( (int)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
void Push( duk_context * ctx, const float value, const float * )
{
dukbind_assert(
( (float)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
void Push( duk_context * ctx, const double value, const double * )
{
dukbind_assert(
( (double)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
bool Get( duk_context * ctx, const int index, const bool * )
{
dukbind_assert( duk_is_boolean( ctx, index ), "No conversion is allowed in Get methods" );
return duk_to_boolean( ctx, index );
}
const char * Get( duk_context * ctx, const int index, const char ** )
{
dukbind_assert(
duk_is_null_or_undefined( ctx, index ) || duk_is_string( ctx, index ),
"No conversion is allowed in Get methods" );
if( duk_is_null_or_undefined( ctx, index ) )
{
return 0;
}
else
{
return duk_to_string( ctx, index );
}
}
int Get( duk_context * ctx, const int index, const int * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
duk_double_t double_result = duk_to_number( ctx, index );
int int_result = static_cast<int>( double_result );
dukbind_assert( double_result == (duk_double_t)int_result, "Number is not a valid integer" );
return int_result;
}
float Get( duk_context * ctx, const int index, const float * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
duk_double_t double_result = duk_to_number( ctx, index );
float float_result = static_cast<float>( double_result );
#if DUKBIND_NO_FLOAT_CONVERSION
dukbind_assert( double_result == (duk_double_t)float_result, "Number is not a valid integer" );
#endif
return float_result;
}
double Get( duk_context * ctx, const int index, const double * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
return duk_to_number( ctx, index );
}
static Box * PrivatePush( duk_context * ctx, const size_t class_index, const size_t object_size, finalizer_t finalizer )
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_remove( ctx, -2 );
duk_push_object( ctx );
size_t require_size = sizeof( Box ) + object_size;
Box * box = reinterpret_cast<Box*>( duk_push_fixed_buffer( ctx, require_size ) );
box->ClassIndex = class_index;
box->Finalizer = finalizer;
duk_put_prop_string( ctx, -2, "\xFF" "Box" );
duk_push_c_function( ctx, &internal::ClassFinalizer, 1 );
duk_set_finalizer( ctx, -2 );
duk_push_heap_stash( ctx );
duk_get_prop_string( ctx, -1, "InstanceHandler" );
duk_remove( ctx, -2 );
duk_new( ctx, 2 );
return box;
}
void * Push( duk_context * ctx, const size_t class_index, const size_t object_size, finalizer_t finalizer )
{
Box * box = PrivatePush( ctx, class_index, object_size, finalizer );
box->ObjectPointer = box + 1;
return box->ObjectPointer;
}
void * Push( duk_context * ctx, const size_t class_index, void * object_pointer, finalizer_t finalizer )
{
Box * box = PrivatePush( ctx, class_index, 0, finalizer );
box->ObjectPointer = object_pointer;
return box->ObjectPointer;
}
void * Get( duk_context * ctx, duk_idx_t index, size_t & class_index, finalizer_t & finalizer )
{
duk_size_t size;
duk_get_prop_string( ctx, index, "\xFF" "Box" );
dukbind_assert( duk_is_fixed_buffer( ctx, -1 ), "Boxing is always implemented as fixed buffer" );
Box * box = reinterpret_cast<Box*>( duk_to_buffer( ctx, -1, &size ) );
duk_pop( ctx );
dukbind_assert( sizeof( Box ) <= size, "Fixed buffer is not a box" );
class_index = box->ClassIndex;
finalizer = box->Finalizer;
return box->ObjectPointer;
}
void Setup( duk_context * ctx, const BindingInfo & info, const char * module )
{
debug::StackMonitor monitor( ctx );
duk_push_global_stash( ctx );
void * info_buffer = duk_push_fixed_buffer( ctx, sizeof( BindingInfo * ) );
*reinterpret_cast<const BindingInfo**>( info_buffer ) = &info; // :TODO: Ref count
duk_put_prop_string( ctx, -2, DUKBIND_BINDING_NAME );
duk_pop( ctx );
if( module )
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_push_object( ctx );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::BindingGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::BindingHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_push_c_function( ctx, internal::ForbidSet, 3 );
duk_put_prop_string( ctx, -2, "set" );
duk_push_c_function( ctx, internal::ForbidDelete, 1 );
duk_put_prop_string( ctx, -2, "deleteProperty" );
duk_new( ctx, 2 );
duk_put_prop_string( ctx, -2, module );
duk_pop( ctx );
}
else
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_dup( ctx, -2 );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::GlobalsGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::GlobalsHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_new( ctx, 2 );
duk_set_global_object( ctx );
duk_pop( ctx );
}
duk_push_heap_stash( ctx );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::ClassGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::ClassHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_push_c_function( ctx, internal::ClassSet, 3 );
duk_put_prop_string( ctx, -2, "set" );
duk_push_c_function( ctx, internal::ForbidDelete, 1 );
duk_put_prop_string( ctx, -2, "deleteProperty" );
duk_put_prop_string( ctx, -2, "InstanceHandler" );
duk_pop( ctx );
}
}
<commit_msg>Handle null pointer in push char*<commit_after>#include "duktape.h"
#include "dukbind.h"
#include "dukbindconf.h"
#include "dukbind_proxy_function.h"
#include "dukbind_private.h"
#include "utils/dukbind_debug.h"
namespace dukbind
{
struct Box
{
void * ObjectPointer;
size_t ClassIndex;
finalizer_t Finalizer;
};
void Push( duk_context * ctx, const bool value, const bool* )
{
duk_push_boolean( ctx, value );
}
void Push( duk_context * ctx, const char * value, const char ** )
{
if( value )
{
duk_push_string( ctx, value );
}
else
{
duk_push_null( ctx );
}
}
void Push( duk_context * ctx, const int value, const int * )
{
dukbind_assert(
( (int)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
void Push( duk_context * ctx, const float value, const float * )
{
dukbind_assert(
( (float)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
void Push( duk_context * ctx, const double value, const double * )
{
dukbind_assert(
( (double)(duk_double_t) value ) == value,
"Value does not fit into a duk_double_t"
);
duk_push_number( ctx, (duk_double_t)value );
}
bool Get( duk_context * ctx, const int index, const bool * )
{
dukbind_assert( duk_is_boolean( ctx, index ), "No conversion is allowed in Get methods" );
return duk_to_boolean( ctx, index );
}
const char * Get( duk_context * ctx, const int index, const char ** )
{
dukbind_assert(
duk_is_null_or_undefined( ctx, index ) || duk_is_string( ctx, index ),
"No conversion is allowed in Get methods" );
if( duk_is_null_or_undefined( ctx, index ) )
{
return 0;
}
else
{
return duk_to_string( ctx, index );
}
}
int Get( duk_context * ctx, const int index, const int * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
duk_double_t double_result = duk_to_number( ctx, index );
int int_result = static_cast<int>( double_result );
dukbind_assert( double_result == (duk_double_t)int_result, "Number is not a valid integer" );
return int_result;
}
float Get( duk_context * ctx, const int index, const float * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
duk_double_t double_result = duk_to_number( ctx, index );
float float_result = static_cast<float>( double_result );
#if DUKBIND_NO_FLOAT_CONVERSION
dukbind_assert( double_result == (duk_double_t)float_result, "Number is not a valid integer" );
#endif
return float_result;
}
double Get( duk_context * ctx, const int index, const double * )
{
dukbind_assert( duk_is_number( ctx, index ), "No conversion is allowed in Get methods" );
return duk_to_number( ctx, index );
}
static Box * PrivatePush( duk_context * ctx, const size_t class_index, const size_t object_size, finalizer_t finalizer )
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_remove( ctx, -2 );
duk_push_object( ctx );
size_t require_size = sizeof( Box ) + object_size;
Box * box = reinterpret_cast<Box*>( duk_push_fixed_buffer( ctx, require_size ) );
box->ClassIndex = class_index;
box->Finalizer = finalizer;
duk_put_prop_string( ctx, -2, "\xFF" "Box" );
duk_push_c_function( ctx, &internal::ClassFinalizer, 1 );
duk_set_finalizer( ctx, -2 );
duk_push_heap_stash( ctx );
duk_get_prop_string( ctx, -1, "InstanceHandler" );
duk_remove( ctx, -2 );
duk_new( ctx, 2 );
return box;
}
void * Push( duk_context * ctx, const size_t class_index, const size_t object_size, finalizer_t finalizer )
{
Box * box = PrivatePush( ctx, class_index, object_size, finalizer );
box->ObjectPointer = box + 1;
return box->ObjectPointer;
}
void * Push( duk_context * ctx, const size_t class_index, void * object_pointer, finalizer_t finalizer )
{
Box * box = PrivatePush( ctx, class_index, 0, finalizer );
box->ObjectPointer = object_pointer;
return box->ObjectPointer;
}
void * Get( duk_context * ctx, duk_idx_t index, size_t & class_index, finalizer_t & finalizer )
{
duk_size_t size;
duk_get_prop_string( ctx, index, "\xFF" "Box" );
dukbind_assert( duk_is_fixed_buffer( ctx, -1 ), "Boxing is always implemented as fixed buffer" );
Box * box = reinterpret_cast<Box*>( duk_to_buffer( ctx, -1, &size ) );
duk_pop( ctx );
dukbind_assert( sizeof( Box ) <= size, "Fixed buffer is not a box" );
class_index = box->ClassIndex;
finalizer = box->Finalizer;
return box->ObjectPointer;
}
void Setup( duk_context * ctx, const BindingInfo & info, const char * module )
{
debug::StackMonitor monitor( ctx );
duk_push_global_stash( ctx );
void * info_buffer = duk_push_fixed_buffer( ctx, sizeof( BindingInfo * ) );
*reinterpret_cast<const BindingInfo**>( info_buffer ) = &info; // :TODO: Ref count
duk_put_prop_string( ctx, -2, DUKBIND_BINDING_NAME );
duk_pop( ctx );
if( module )
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_push_object( ctx );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::BindingGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::BindingHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_push_c_function( ctx, internal::ForbidSet, 3 );
duk_put_prop_string( ctx, -2, "set" );
duk_push_c_function( ctx, internal::ForbidDelete, 1 );
duk_put_prop_string( ctx, -2, "deleteProperty" );
duk_new( ctx, 2 );
duk_put_prop_string( ctx, -2, module );
duk_pop( ctx );
}
else
{
duk_push_global_object( ctx );
duk_get_prop_string( ctx, -1, "Proxy" );
duk_dup( ctx, -2 );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::GlobalsGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::GlobalsHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_new( ctx, 2 );
duk_set_global_object( ctx );
duk_pop( ctx );
}
duk_push_heap_stash( ctx );
duk_push_object( ctx );
duk_push_c_function( ctx, internal::ClassGet, 2 );
duk_put_prop_string( ctx, -2, "get" );
duk_push_c_function( ctx, internal::ClassHas, 1 );
duk_put_prop_string( ctx, -2, "has" );
duk_push_c_function( ctx, internal::ClassSet, 3 );
duk_put_prop_string( ctx, -2, "set" );
duk_push_c_function( ctx, internal::ForbidDelete, 1 );
duk_put_prop_string( ctx, -2, "deleteProperty" );
duk_put_prop_string( ctx, -2, "InstanceHandler" );
duk_pop( ctx );
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@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) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dictionarymanager.h"
#include "pluginmanager.h"
#include <QtCore/QFileInfoList>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QPluginLoader>
using namespace MulaCore;
MULA_DEFINE_SINGLETON( DictionaryManager )
class DictionaryManager::Private
{
public:
Private()
{
}
~Private()
{
}
QMultiHash<QString, QString> loadedDictionaryList;
};
DictionaryManager::DictionaryManager(QObject *parent)
: MulaCore::Singleton< MulaCore::DictionaryManager >( parent )
, d(new Private)
{
loadDictionarySettings();
}
DictionaryManager::~DictionaryManager()
{
saveDictionarySettings();
}
bool
DictionaryManager::isTranslatable(const QString &word)
{
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (dictionaryPlugin->isTranslatable(i.value(), word))
return true;
}
return false;
}
QString
DictionaryManager::translate(const QString &word)
{
QString simplifiedWord = word.simplified();
QString translatedWord;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (!dictionaryPlugin->isTranslatable(i.key(), simplifiedWord))
continue;
MulaCore::Translation translation = dictionaryPlugin->translate(i.key(), simplifiedWord);
translatedWord.append(QString("<p>\n")
+ "<font class=\"dict_name\">" + translation.dictionaryName() + "</font><br>\n"
+ "<font class=\"title\">" + translation.title() + "</font><br>\n"
+ translation.translation() + "</p>\n");
}
return translatedWord;
}
QStringList
DictionaryManager::findSimilarWords(const QString &word)
{
QString simplifiedWord = word.simplified();
QStringList similarWords;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (!dictionaryPlugin->features().testFlag(DictionaryPlugin::SearchSimilar))
continue;
QStringList similarWords = dictionaryPlugin->findSimilarWords(i.value(), simplifiedWord);
foreach (const QString& similarWord, similarWords)
{
if (!similarWords.contains(similarWord, Qt::CaseSensitive))
similarWords.append(similarWord);
}
}
return similarWords;
}
QMultiHash<QString, QString>
DictionaryManager::availableDictionaryList() const
{
QMultiHash<QString, QString> availableDictionaryList;
// for (QHash<QString, QPluginLoader*>::const_iterator i = m_plugins.begin(); i != m_plugins.end(); ++i)
// {
// DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());
// QStringList dictionaries = plugin->availableDictionaryList();
// foreach (const QString& dictionary, dictionaries)
// availableDictionaryList.append(DictionaryDataItem(i.key(), dictionary));
// }
return availableDictionaryList;
}
void
DictionaryManager::setLoadedDictionaryList(const QMultiHash<QString, QString> &loadedDictionaryList)
{
QMultiHash<QString, QString> dictionaries = loadedDictionaryList;
for (QMultiHash<QString, QString>::const_iterator i = dictionaries.begin(); i != dictionaries.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
// TODO: this statement must be revisited for correction since we should
// add the whole list, not values separately or at least change the set
// API
dictionaryPlugin->setLoadedDictionaryList(QStringList() << i.value());
foreach (const QString& dictionaryName, dictionaryPlugin->loadedDictionaryList())
dictionaries.insert(i.key(), dictionaryName);
}
d->loadedDictionaryList.clear();
for (QMultiHash<QString, QString>::const_iterator i = loadedDictionaryList.begin(); i != loadedDictionaryList.end(); ++i)
{
if (dictionaries.keys().contains(i.key()) && dictionaries.value(i.key()).contains(i.value()))
d->loadedDictionaryList.insert(i.key(), i.value());
}
}
void
DictionaryManager::saveDictionarySettings()
{
QStringList rawDictionaryList;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
rawDictionaryList.append(i.key());
rawDictionaryList.append(i.value());
}
QSettings settings;
settings.setValue("DictionaryManager/loadedDictionaryList", rawDictionaryList);
}
void
DictionaryManager::loadDictionarySettings()
{
QSettings settings;
QStringList rawDictionaryList = settings.value("DictionaryManager/loadedDictionaryList").toStringList();
if (rawDictionaryList.isEmpty())
{
setLoadedDictionaryList(availableDictionaryList());
}
else
{
QMultiHash<QString, QString> dictionaries;
for (QStringList::const_iterator i = rawDictionaryList.begin(); i != rawDictionaryList.end(); i += 2)
dictionaries.insert(*i, *(i + 1));
setLoadedDictionaryList(dictionaries);
}
}
void
DictionaryManager::reloadDictionaryList()
{
QMultiHash<QString, QString> loadedDictionaryList;
// for (QHash<QString, QPluginLoader*>::const_iterator i = d->plugins.begin(); i != d->plugins.end(); ++i)
// {
// DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());
// plugin->setLoadedDictionaryList(plugin->loadedDictionaryList());
// foreach(const QString& dictionaryName, plugin->loadedDictionaryList())
// loadedDictionaryList.append(DictionaryDataItem(i.key(), dictionaryName));
// }
QMultiHash<QString, QString> oldDictionaryList = d->loadedDictionaryList;
d->loadedDictionaryList.clear();
for (QMultiHash<QString, QString>::const_iterator i = oldDictionaryList.begin(); i != oldDictionaryList.end(); ++i)
{
if (loadedDictionaryList.contains(i.key(), i.value()))
d->loadedDictionaryList.insert(i.key(), i.value());
}
}
#include "dictionarymanager.moc"
<commit_msg>Fill in the dictionary plugin class with the dictionary list properly<commit_after>/******************************************************************************
* This file is part of the Mula project
* Copyright (c) 2011 Laszlo Papp <lpapp@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) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dictionarymanager.h"
#include "pluginmanager.h"
#include <QtCore/QFileInfoList>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QPluginLoader>
using namespace MulaCore;
MULA_DEFINE_SINGLETON( DictionaryManager )
class DictionaryManager::Private
{
public:
Private()
{
}
~Private()
{
}
QMultiHash<QString, QString> loadedDictionaryList;
};
DictionaryManager::DictionaryManager(QObject *parent)
: MulaCore::Singleton< MulaCore::DictionaryManager >( parent )
, d(new Private)
{
loadDictionarySettings();
}
DictionaryManager::~DictionaryManager()
{
saveDictionarySettings();
}
bool
DictionaryManager::isTranslatable(const QString &word)
{
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (dictionaryPlugin->isTranslatable(i.value(), word))
return true;
}
return false;
}
QString
DictionaryManager::translate(const QString &word)
{
QString simplifiedWord = word.simplified();
QString translatedWord;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (!dictionaryPlugin->isTranslatable(i.key(), simplifiedWord))
continue;
MulaCore::Translation translation = dictionaryPlugin->translate(i.key(), simplifiedWord);
translatedWord.append(QString("<p>\n")
+ "<font class=\"dict_name\">" + translation.dictionaryName() + "</font><br>\n"
+ "<font class=\"title\">" + translation.title() + "</font><br>\n"
+ translation.translation() + "</p>\n");
}
return translatedWord;
}
QStringList
DictionaryManager::findSimilarWords(const QString &word)
{
QString simplifiedWord = word.simplified();
QStringList similarWords;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());
if (!dictionaryPlugin)
continue;
if (!dictionaryPlugin->features().testFlag(DictionaryPlugin::SearchSimilar))
continue;
QStringList similarWords = dictionaryPlugin->findSimilarWords(i.value(), simplifiedWord);
foreach (const QString& similarWord, similarWords)
{
if (!similarWords.contains(similarWord, Qt::CaseSensitive))
similarWords.append(similarWord);
}
}
return similarWords;
}
QMultiHash<QString, QString>
DictionaryManager::availableDictionaryList() const
{
QMultiHash<QString, QString> availableDictionaryList;
// for (QHash<QString, QPluginLoader*>::const_iterator i = m_plugins.begin(); i != m_plugins.end(); ++i)
// {
// DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());
// QStringList dictionaries = plugin->availableDictionaryList();
// foreach (const QString& dictionary, dictionaries)
// availableDictionaryList.append(DictionaryDataItem(i.key(), dictionary));
// }
return availableDictionaryList;
}
void
DictionaryManager::setLoadedDictionaryList(const QMultiHash<QString, QString> &loadedDictionaryList)
{
QMultiHash<QString, QString> dictionaries = loadedDictionaryList;
foreach (const QString& pluginName, dictionaries.keys())
{
MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(pluginName);
if (!dictionaryPlugin)
continue;
dictionaryPlugin->setLoadedDictionaryList(dictionaries.values());
foreach (const QString& dictionaryName, dictionaryPlugin->loadedDictionaryList())
dictionaries.insert(pluginName, dictionaryName);
}
d->loadedDictionaryList.clear();
for (QMultiHash<QString, QString>::const_iterator i = loadedDictionaryList.begin(); i != loadedDictionaryList.end(); ++i)
{
if (dictionaries.keys().contains(i.key()) && dictionaries.value(i.key()).contains(i.value()))
d->loadedDictionaryList.insert(i.key(), i.value());
}
}
void
DictionaryManager::saveDictionarySettings()
{
QStringList rawDictionaryList;
for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)
{
rawDictionaryList.append(i.key());
rawDictionaryList.append(i.value());
}
QSettings settings;
settings.setValue("DictionaryManager/loadedDictionaryList", rawDictionaryList);
}
void
DictionaryManager::loadDictionarySettings()
{
QSettings settings;
QStringList rawDictionaryList = settings.value("DictionaryManager/loadedDictionaryList").toStringList();
if (rawDictionaryList.isEmpty())
{
setLoadedDictionaryList(availableDictionaryList());
}
else
{
QMultiHash<QString, QString> dictionaries;
for (QStringList::const_iterator i = rawDictionaryList.begin(); i != rawDictionaryList.end(); i += 2)
dictionaries.insert(*i, *(i + 1));
setLoadedDictionaryList(dictionaries);
}
}
void
DictionaryManager::reloadDictionaryList()
{
QMultiHash<QString, QString> loadedDictionaryList;
// for (QHash<QString, QPluginLoader*>::const_iterator i = d->plugins.begin(); i != d->plugins.end(); ++i)
// {
// DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());
// plugin->setLoadedDictionaryList(plugin->loadedDictionaryList());
// foreach(const QString& dictionaryName, plugin->loadedDictionaryList())
// loadedDictionaryList.append(DictionaryDataItem(i.key(), dictionaryName));
// }
QMultiHash<QString, QString> oldDictionaryList = d->loadedDictionaryList;
d->loadedDictionaryList.clear();
for (QMultiHash<QString, QString>::const_iterator i = oldDictionaryList.begin(); i != oldDictionaryList.end(); ++i)
{
if (loadedDictionaryList.contains(i.key(), i.value()))
d->loadedDictionaryList.insert(i.key(), i.value());
}
}
#include "dictionarymanager.moc"
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details
#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include <vector>
#include "CPU.h"
struct ROM : public hcc::IROM {
ROM() : data(0x8000, 0) { }
bool load(const char *filename)
{
std::ifstream input(filename);
std::string line;
auto it = begin(data);
while (input.good() && it != end(data)) {
getline(input, line);
if (line.size() == 0) {
continue;
}
if (line.size() != 16) {
return false;
}
unsigned int instruction = 0;
for (unsigned int i = 0; i<16; ++i) {
instruction <<= 1;
switch (line[i]) {
case '0':
break;
case '1':
instruction |= 1;
break;
default:
return false;
}
}
*it++ = instruction;
}
// clear the rest
while (it != end(data)) {
*it++ = 0;
}
return true;
}
unsigned short get(unsigned int address) const override
{ return data.at(address); }
private:
std::vector<unsigned short> data;
};
gboolean on_draw(GtkWidget*, cairo_t* cr, gpointer data)
{
GdkPixbuf* pixbuf = reinterpret_cast<GdkPixbuf*>(data);
gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
cairo_paint(cr);
return FALSE;
}
struct RAM : public hcc::IRAM {
static const unsigned int CHANNELS = 3;
static const unsigned int SCREEN_WIDTH = 512;
static const unsigned int SCREEN_HEIGHT = 256;
std::vector<unsigned short> data;
GdkPixbuf *pixbuf;
GtkWidget *screen;
void putpixel(unsigned short x, unsigned short y, bool black) {
int color = black ? 0x00 : 0xff;
int n_channels = gdk_pixbuf_get_n_channels (pixbuf);
int rowstride = gdk_pixbuf_get_rowstride (pixbuf);
guchar* pixels = gdk_pixbuf_get_pixels(pixbuf);
guchar* p = pixels + y * rowstride + x * n_channels;
p[0] = color;
p[1] = color;
p[2] = color;
}
public:
RAM() : data(0x6001, 0)
{
pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT);
gdk_pixbuf_fill(pixbuf, 0x0000000);
screen = gtk_drawing_area_new();
gtk_widget_set_size_request(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
g_signal_connect(screen, "draw", G_CALLBACK(on_draw), pixbuf);
}
void keyboard(unsigned short value) {
data[0x6000] = value;
}
GtkWidget* getScreenWidget() {
return screen;
}
void set(unsigned int address, unsigned short value) override
{
data.at(address) = value;
// check if we are writing to video RAM
if (0x4000 <= address && address <0x6000) {
address -= 0x4000;
unsigned short y = address / 32;
unsigned short x = 16*(address % 32);
for (int bit = 0; bit<16; ++bit) {
putpixel(x + bit, y, value & 1);
value = value >> 1;
}
gdk_threads_enter();
gtk_widget_queue_draw(screen);
gdk_threads_leave();
}
}
unsigned short get(unsigned int address) const override
{ return data.at(address); }
};
struct emulator {
emulator();
void load_clicked();
void run_clicked();
void pause_clicked();
gboolean keyboard_callback(GdkEventKey* event);
void run_thread();
GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback);
ROM rom;
RAM ram;
hcc::CPU cpu;
bool running = false;
GtkWidget* window;
GtkWidget* load_dialog;
GtkWidget* error_dialog;
GtkToolItem* button_load;
GtkToolItem* button_run;
GtkToolItem* button_pause;
};
gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data)
{ return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); }
void c_load_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->load_clicked(); }
void c_run_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->run_clicked(); }
void c_pause_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->pause_clicked(); }
gpointer c_run_thread(gpointer user_data)
{
reinterpret_cast<emulator*>(user_data)->run_thread();
return NULL;
}
// Translate special keys. See Figure 5.6 in TECS book.
unsigned short translate(guint keyval)
{
switch (keyval) {
case GDK_KEY_Return: return 128;
case GDK_KEY_BackSpace: return 129;
case GDK_KEY_Left: return 130;
case GDK_KEY_Up: return 131;
case GDK_KEY_Right: return 132;
case GDK_KEY_Down: return 133;
case GDK_KEY_Home: return 134;
case GDK_KEY_End: return 135;
case GDK_KEY_Page_Up: return 136;
case GDK_KEY_Page_Down: return 137;
case GDK_KEY_Insert: return 138;
case GDK_KEY_Delete: return 139;
case GDK_KEY_Escape: return 140;
case GDK_KEY_F1: return 141;
case GDK_KEY_F2: return 142;
case GDK_KEY_F3: return 143;
case GDK_KEY_F4: return 144;
case GDK_KEY_F5: return 145;
case GDK_KEY_F6: return 146;
case GDK_KEY_F7: return 147;
case GDK_KEY_F8: return 148;
case GDK_KEY_F9: return 149;
case GDK_KEY_F10: return 150;
case GDK_KEY_F11: return 151;
case GDK_KEY_F12: return 152;
}
return keyval;
}
emulator::emulator()
{
/* toolbar buttons */
button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked));
button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked));
button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked));
GtkToolItem *separator1 = gtk_separator_tool_item_new();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
/* toolbar itself */
GtkWidget *toolbar = gtk_toolbar_new();
gtk_widget_set_hexpand(toolbar, TRUE);
gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);
/* keyboard */
GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this);
g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this);
/* main layout */
GtkWidget *grid = gtk_grid_new();
gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);
/* main window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "HACK emulator");
gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
gtk_window_set_focus(GTK_WINDOW(window), NULL);
g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_container_add(GTK_CONTAINER(window), grid);
gtk_widget_show_all(window);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
load_dialog = gtk_file_chooser_dialog_new(
"Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN,
"gtk-cancel", GTK_RESPONSE_CANCEL,
"gtk-open", GTK_RESPONSE_ACCEPT,
NULL);
error_dialog = gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
"Error loading program");
}
GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback)
{
GtkToolItem *button = gtk_tool_button_new(NULL, text);
gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id);
gtk_tool_item_set_tooltip_text(button, text);
g_signal_connect(button, "clicked", callback, this);
return button;
}
void emulator::load_clicked()
{
const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog));
gtk_widget_hide(load_dialog);
if (result != GTK_RESPONSE_ACCEPT) {
return;
}
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog));
const bool loaded = rom.load(filename);
g_free(filename);
if (!loaded) {
gtk_dialog_run(GTK_DIALOG(error_dialog));
gtk_widget_hide(error_dialog);
return;
}
cpu.reset();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
}
void emulator::run_clicked()
{
assert(!running);
running = true;
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);
g_thread_create(c_run_thread, this, FALSE, NULL);
}
void emulator::pause_clicked()
{
assert(running);
running = false;
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);
}
gboolean emulator::keyboard_callback(GdkEventKey* event)
{
if (event->type == GDK_KEY_RELEASE) {
ram.keyboard(0);
} else {
ram.keyboard(translate(event->keyval));
}
return TRUE;
}
void emulator::run_thread()
{
int steps = 0;
while (running) {
cpu.step(&rom, &ram);
if (steps>100) {
g_usleep(10);
steps = 0;
}
++steps;
}
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
emulator e;
gtk_main();
return 0;
}
<commit_msg>Got rid of last deprecated functions<commit_after>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details
#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include <vector>
#include "CPU.h"
struct ROM : public hcc::IROM {
ROM() : data(0x8000, 0) { }
bool load(const char *filename)
{
std::ifstream input(filename);
std::string line;
auto it = begin(data);
while (input.good() && it != end(data)) {
getline(input, line);
if (line.size() == 0) {
continue;
}
if (line.size() != 16) {
return false;
}
unsigned int instruction = 0;
for (unsigned int i = 0; i<16; ++i) {
instruction <<= 1;
switch (line[i]) {
case '0':
break;
case '1':
instruction |= 1;
break;
default:
return false;
}
}
*it++ = instruction;
}
// clear the rest
while (it != end(data)) {
*it++ = 0;
}
return true;
}
unsigned short get(unsigned int address) const override
{ return data.at(address); }
private:
std::vector<unsigned short> data;
};
gboolean on_draw(GtkWidget*, cairo_t* cr, gpointer data)
{
GdkPixbuf* pixbuf = reinterpret_cast<GdkPixbuf*>(data);
gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
cairo_paint(cr);
return FALSE;
}
gboolean queue_redraw(gpointer widget)
{
gtk_widget_queue_draw(GTK_WIDGET(widget));
return FALSE;
}
struct RAM : public hcc::IRAM {
static const unsigned int CHANNELS = 3;
static const unsigned int SCREEN_WIDTH = 512;
static const unsigned int SCREEN_HEIGHT = 256;
std::vector<unsigned short> data;
GdkPixbuf *pixbuf;
GtkWidget *screen;
void putpixel(unsigned short x, unsigned short y, bool black) {
int color = black ? 0x00 : 0xff;
int n_channels = gdk_pixbuf_get_n_channels (pixbuf);
int rowstride = gdk_pixbuf_get_rowstride (pixbuf);
guchar* pixels = gdk_pixbuf_get_pixels(pixbuf);
guchar* p = pixels + y * rowstride + x * n_channels;
p[0] = color;
p[1] = color;
p[2] = color;
}
public:
RAM() : data(0x6001, 0)
{
pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT);
gdk_pixbuf_fill(pixbuf, 0x0000000);
screen = gtk_drawing_area_new();
gtk_widget_set_size_request(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
g_signal_connect(screen, "draw", G_CALLBACK(on_draw), pixbuf);
}
void keyboard(unsigned short value) {
data[0x6000] = value;
}
GtkWidget* getScreenWidget() {
return screen;
}
void set(unsigned int address, unsigned short value) override
{
data.at(address) = value;
// check if we are writing to video RAM
if (0x4000 <= address && address <0x6000) {
address -= 0x4000;
unsigned short y = address / 32;
unsigned short x = 16*(address % 32);
for (int bit = 0; bit<16; ++bit) {
putpixel(x + bit, y, value & 1);
value = value >> 1;
}
gdk_threads_add_idle(queue_redraw, screen);
}
}
unsigned short get(unsigned int address) const override
{ return data.at(address); }
};
struct emulator {
emulator();
void load_clicked();
void run_clicked();
void pause_clicked();
gboolean keyboard_callback(GdkEventKey* event);
void run_thread();
GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback);
ROM rom;
RAM ram;
hcc::CPU cpu;
bool running = false;
GtkWidget* window;
GtkWidget* load_dialog;
GtkWidget* error_dialog;
GtkToolItem* button_load;
GtkToolItem* button_run;
GtkToolItem* button_pause;
};
gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data)
{ return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); }
void c_load_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->load_clicked(); }
void c_run_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->run_clicked(); }
void c_pause_clicked(GtkButton*, gpointer user_data)
{ reinterpret_cast<emulator*>(user_data)->pause_clicked(); }
gpointer c_run_thread(gpointer user_data)
{
reinterpret_cast<emulator*>(user_data)->run_thread();
return NULL;
}
// Translate special keys. See Figure 5.6 in TECS book.
unsigned short translate(guint keyval)
{
switch (keyval) {
case GDK_KEY_Return: return 128;
case GDK_KEY_BackSpace: return 129;
case GDK_KEY_Left: return 130;
case GDK_KEY_Up: return 131;
case GDK_KEY_Right: return 132;
case GDK_KEY_Down: return 133;
case GDK_KEY_Home: return 134;
case GDK_KEY_End: return 135;
case GDK_KEY_Page_Up: return 136;
case GDK_KEY_Page_Down: return 137;
case GDK_KEY_Insert: return 138;
case GDK_KEY_Delete: return 139;
case GDK_KEY_Escape: return 140;
case GDK_KEY_F1: return 141;
case GDK_KEY_F2: return 142;
case GDK_KEY_F3: return 143;
case GDK_KEY_F4: return 144;
case GDK_KEY_F5: return 145;
case GDK_KEY_F6: return 146;
case GDK_KEY_F7: return 147;
case GDK_KEY_F8: return 148;
case GDK_KEY_F9: return 149;
case GDK_KEY_F10: return 150;
case GDK_KEY_F11: return 151;
case GDK_KEY_F12: return 152;
}
return keyval;
}
emulator::emulator()
{
/* toolbar buttons */
button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked));
button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked));
button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked));
GtkToolItem *separator1 = gtk_separator_tool_item_new();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
/* toolbar itself */
GtkWidget *toolbar = gtk_toolbar_new();
gtk_widget_set_hexpand(toolbar, TRUE);
gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);
/* keyboard */
GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this);
g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this);
/* main layout */
GtkWidget *grid = gtk_grid_new();
gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);
/* main window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "HACK emulator");
gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
gtk_window_set_focus(GTK_WINDOW(window), NULL);
g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_container_add(GTK_CONTAINER(window), grid);
gtk_widget_show_all(window);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
load_dialog = gtk_file_chooser_dialog_new(
"Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN,
"gtk-cancel", GTK_RESPONSE_CANCEL,
"gtk-open", GTK_RESPONSE_ACCEPT,
NULL);
error_dialog = gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
"Error loading program");
}
GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback)
{
GtkToolItem *button = gtk_tool_button_new(NULL, text);
gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id);
gtk_tool_item_set_tooltip_text(button, text);
g_signal_connect(button, "clicked", callback, this);
return button;
}
void emulator::load_clicked()
{
const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog));
gtk_widget_hide(load_dialog);
if (result != GTK_RESPONSE_ACCEPT) {
return;
}
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog));
const bool loaded = rom.load(filename);
g_free(filename);
if (!loaded) {
gtk_dialog_run(GTK_DIALOG(error_dialog));
gtk_widget_hide(error_dialog);
return;
}
cpu.reset();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
}
void emulator::run_clicked()
{
assert(!running);
running = true;
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);
g_thread_new("c_run_thread", c_run_thread, this);
}
void emulator::pause_clicked()
{
assert(running);
running = false;
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);
}
gboolean emulator::keyboard_callback(GdkEventKey* event)
{
if (event->type == GDK_KEY_RELEASE) {
ram.keyboard(0);
} else {
ram.keyboard(translate(event->keyval));
}
return TRUE;
}
void emulator::run_thread()
{
int steps = 0;
while (running) {
cpu.step(&rom, &ram);
if (steps>100) {
g_usleep(10);
steps = 0;
}
++steps;
}
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
emulator e;
gtk_main();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015-2018 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "endpoint.h"
#include <stdlib.h> // for atoi
#include <xapian.h> // for SerialisationError
#include "length.h" // for serialise_length, unserialise_length, ser...
#include "manager.h" // for XapiandManager::manager->opts
#include "serialise.h" // for Serialise
atomic_shared_ptr<const Node> local_node(std::make_shared<const Node>());
static inline std::string
normalize(const void *p, size_t size)
{
try {
return Unserialise::uuid(Serialise::uuid(std::string(static_cast<const char*>(p), size)), XapiandManager::manager->opts.uuid_repr);
} catch (const SerialisationError&) {
return "";
}
}
static inline std::string
normalize_and_partition(const void *p, size_t size)
{
std::string normalized;
try {
normalized = Unserialise::uuid(Serialise::uuid(std::string(static_cast<const char*>(p), size)), XapiandManager::manager->opts.uuid_repr);
} catch (const SerialisationError& exc) {
return normalized;
}
std::string ret;
auto cit = normalized.cbegin();
auto cit_e = normalized.cend();
ret.reserve(2 + normalized.size());
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back('/');
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back('/');
ret.append(cit, cit_e);
return ret;
}
typedef std::string(*normalizer_t)(const void *p, size_t size);
template<normalizer_t normalize>
static inline std::string
normalizer(const void *p, size_t size)
{
std::string buf;
buf.reserve(size);
auto q = static_cast<const char *>(p);
auto p_end = q + size;
auto oq = q;
while (q != p_end) {
char c = *q++;
switch (c) {
case '.':
case '/': {
auto sz = q - oq - 1;
if (sz) {
auto normalized = normalize(oq, sz);
if (!normalized.empty()) {
buf.resize(buf.size() - sz);
buf.append(normalized);
}
}
buf.push_back(c);
oq = q;
break;
}
default:
buf.push_back(c);
}
}
auto sz = q - oq;
if (sz) {
auto normalized = normalize(oq, sz);
if (!normalized.empty()) {
buf.resize(buf.size() - sz);
buf.append(normalized);
}
}
return buf;
}
std::string
Node::serialise() const
{
std::string node_str;
if (!name.empty()) {
node_str.append(serialise_length(addr.sin_addr.s_addr));
node_str.append(serialise_length(http_port));
node_str.append(serialise_length(binary_port));
node_str.append(serialise_length(region));
node_str.append(serialise_string(name));
}
return node_str;
}
Node
Node::unserialise(const char **p, const char *end)
{
const char *ptr = *p;
Node node;
node.addr.sin_addr.s_addr = static_cast<int>(unserialise_length(&ptr, end, false));
node.http_port = static_cast<int>(unserialise_length(&ptr, end, false));
node.binary_port = static_cast<int>(unserialise_length(&ptr, end, false));
node.region = static_cast<int>(unserialise_length(&ptr, end, false));
node.name = unserialise_string(&ptr, end);
if (node.name.empty()) {
throw Xapian::SerialisationError("Bad Node: No name");
}
*p = ptr;
return node;
}
std::string Endpoint::cwd("/");
Endpoint::Endpoint()
: port(-1),
mastery_level(-1) { }
Endpoint::Endpoint(const std::string& uri_, const Node* node_, long long mastery_level_, const std::string& node_name_)
: node_name(node_name_),
mastery_level(mastery_level_)
{
std::string uri(uri_);
char buffer[PATH_MAX + 1];
std::string protocol = slice_before(uri, "://");
if (protocol.empty()) {
protocol = "file";
}
search = slice_after(uri, "?");
path = slice_after(uri, "/");
std::string userpass = slice_before(uri, "@");
password = slice_after(userpass, ":");
user = userpass;
std::string portstring = slice_after(uri, ":");
port = atoi(portstring.c_str());
if (protocol == "file") {
if (path.empty()) {
path = uri;
} else {
path = uri + "/" + path;
}
port = 0;
search = "";
password = "";
user = "";
} else {
host = uri;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
if (!startswith(path, "/")) {
path = Endpoint::cwd + path;
}
path = normalize_path(path, buffer);
if (path.substr(0, Endpoint::cwd.size()) == Endpoint::cwd) {
path.erase(0, Endpoint::cwd.size());
}
if (path.size() != 1 && endswith(path, '/')) {
path = path.substr(0, path.size() - 1);
}
if (XapiandManager::manager->opts.uuid_partition) {
path = normalizer<normalize_and_partition>(path.data(), path.size());
} else {
path = normalizer<normalize>(path.data(), path.size());
}
if (protocol == "file") {
auto local_node_ = local_node.load();
if (!node_) {
node_ = local_node_.get();
}
host = node_->host();
port = node_->binary_port;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
}
inline std::string
Endpoint::slice_after(std::string& subject, const std::string& delimiter) const
{
size_t delimiter_location = subject.find(delimiter);
std::string output;
if (delimiter_location != std::string::npos) {
size_t start = delimiter_location + delimiter.length();
output = subject.substr(start, subject.length() - start);
if (!output.empty()) {
subject = subject.substr(0, delimiter_location);
}
}
return output;
}
inline std::string
Endpoint::slice_before(std::string& subject, const std::string& delimiter) const
{
size_t delimiter_location = subject.find(delimiter);
std::string output;
if (delimiter_location != std::string::npos) {
size_t start = delimiter_location + delimiter.length();
output = subject.substr(0, delimiter_location);
subject = subject.substr(start, subject.length() - start);
}
return output;
}
std::string
Endpoint::to_string() const
{
std::string ret;
if (path.empty()) {
return ret;
}
ret += "xapian://";
if (!user.empty() || !password.empty()) {
ret += user;
if (!password.empty()) {
ret += ":" + password;
}
ret += "@";
}
ret += host;
if (port > 0) {
ret += ":";
ret += std::to_string(port);
}
if (!host.empty() || port > 0) {
ret += "/";
}
ret += path;
if (!search.empty()) {
ret += "?" + search;
}
return ret;
}
bool
Endpoint::operator<(const Endpoint& other) const
{
return hash() < other.hash();
}
size_t
Endpoint::hash() const
{
static std::hash<std::string> hash_fn_string;
std::hash<int> hash_fn_int;
return (
hash_fn_string(path) ^
hash_fn_string(user) ^
hash_fn_string(password) ^
hash_fn_string(host) ^
hash_fn_int(port) ^
hash_fn_string(search)
);
}
std::string
Endpoints::to_string() const
{
std::string ret;
auto j = endpoints.cbegin();
for (int i = 0; j != endpoints.cend(); ++j, ++i) {
if (i) ret += ";";
ret += (*j).to_string();
}
return ret;
}
size_t
Endpoints::hash() const
{
size_t hash = 0;
std::hash<Endpoint> hash_fn;
auto j = endpoints.cbegin();
for (int i = 0; j != endpoints.cend(); ++j, ++i) {
hash ^= hash_fn(*j);
}
return hash;
}
bool
operator==(const Endpoint& le, const Endpoint& re)
{
std::hash<Endpoint> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool
operator==(const Endpoints& le, const Endpoints& re)
{
std::hash<Endpoints> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool
operator!=(const Endpoint& le, const Endpoint& re)
{
return !(le == re);
}
bool
operator!=(const Endpoints& le, const Endpoints& re)
{
return !(le == re);
}
size_t
std::hash<Endpoint>::operator()(const Endpoint& e) const
{
return e.hash();
}
size_t
std::hash<Endpoints>::operator()(const Endpoints& e) const
{
return e.hash();
}
<commit_msg>UUID serializer: Path expansion is different for simple vs. non-encoded UUIDs<commit_after>/*
* Copyright (C) 2015-2018 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "endpoint.h"
#include <stdlib.h> // for atoi
#include <xapian.h> // for SerialisationError
#include "length.h" // for serialise_length, unserialise_length, ser...
#include "manager.h" // for XapiandManager::manager->opts
#include "serialise.h" // for Serialise
atomic_shared_ptr<const Node> local_node(std::make_shared<const Node>());
static inline std::string
normalize(const void *p, size_t size)
{
try {
return Unserialise::uuid(Serialise::uuid(std::string(static_cast<const char*>(p), size)), XapiandManager::manager->opts.uuid_repr);
} catch (const SerialisationError&) {
return "";
}
}
static inline std::string
normalize_and_partition(const void *p, size_t size)
{
std::string ret;
std::string normalized;
try {
auto serialised_uuid = Serialise::uuid(std::string(static_cast<const char*>(p), size));
normalized = Unserialise::uuid(serialised_uuid, XapiandManager::manager->opts.uuid_repr);
if (XapiandManager::manager->opts.uuid_repr == UUIDRepr::simple || serialised_uuid.front() == 1 || (serialised_uuid.back() & 1) != 0) {
ret.append(&normalized[9], &normalized[13]);
ret.push_back('/');
ret.append(normalized);
return ret;
}
} catch (const SerialisationError& exc) {
return normalized;
}
auto cit = normalized.cbegin();
auto cit_e = normalized.cend();
ret.reserve(2 + normalized.size());
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back('/');
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back(*cit++);
if (cit == cit_e) return ret;
ret.push_back('/');
ret.append(cit, cit_e);
return ret;
}
typedef std::string(*normalizer_t)(const void *p, size_t size);
template<normalizer_t normalize>
static inline std::string
normalizer(const void *p, size_t size)
{
std::string buf;
buf.reserve(size);
auto q = static_cast<const char *>(p);
auto p_end = q + size;
auto oq = q;
while (q != p_end) {
char c = *q++;
switch (c) {
case '.':
case '/': {
auto sz = q - oq - 1;
if (sz) {
auto normalized = normalize(oq, sz);
if (!normalized.empty()) {
buf.resize(buf.size() - sz);
buf.append(normalized);
}
}
buf.push_back(c);
oq = q;
break;
}
default:
buf.push_back(c);
}
}
auto sz = q - oq;
if (sz) {
auto normalized = normalize(oq, sz);
if (!normalized.empty()) {
buf.resize(buf.size() - sz);
buf.append(normalized);
}
}
return buf;
}
std::string
Node::serialise() const
{
std::string node_str;
if (!name.empty()) {
node_str.append(serialise_length(addr.sin_addr.s_addr));
node_str.append(serialise_length(http_port));
node_str.append(serialise_length(binary_port));
node_str.append(serialise_length(region));
node_str.append(serialise_string(name));
}
return node_str;
}
Node
Node::unserialise(const char **p, const char *end)
{
const char *ptr = *p;
Node node;
node.addr.sin_addr.s_addr = static_cast<int>(unserialise_length(&ptr, end, false));
node.http_port = static_cast<int>(unserialise_length(&ptr, end, false));
node.binary_port = static_cast<int>(unserialise_length(&ptr, end, false));
node.region = static_cast<int>(unserialise_length(&ptr, end, false));
node.name = unserialise_string(&ptr, end);
if (node.name.empty()) {
throw Xapian::SerialisationError("Bad Node: No name");
}
*p = ptr;
return node;
}
std::string Endpoint::cwd("/");
Endpoint::Endpoint()
: port(-1),
mastery_level(-1) { }
Endpoint::Endpoint(const std::string& uri_, const Node* node_, long long mastery_level_, const std::string& node_name_)
: node_name(node_name_),
mastery_level(mastery_level_)
{
std::string uri(uri_);
char buffer[PATH_MAX + 1];
std::string protocol = slice_before(uri, "://");
if (protocol.empty()) {
protocol = "file";
}
search = slice_after(uri, "?");
path = slice_after(uri, "/");
std::string userpass = slice_before(uri, "@");
password = slice_after(userpass, ":");
user = userpass;
std::string portstring = slice_after(uri, ":");
port = atoi(portstring.c_str());
if (protocol == "file") {
if (path.empty()) {
path = uri;
} else {
path = uri + "/" + path;
}
port = 0;
search = "";
password = "";
user = "";
} else {
host = uri;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
if (!startswith(path, "/")) {
path = Endpoint::cwd + path;
}
path = normalize_path(path, buffer);
if (path.substr(0, Endpoint::cwd.size()) == Endpoint::cwd) {
path.erase(0, Endpoint::cwd.size());
}
if (path.size() != 1 && endswith(path, '/')) {
path = path.substr(0, path.size() - 1);
}
if (XapiandManager::manager->opts.uuid_partition) {
path = normalizer<normalize_and_partition>(path.data(), path.size());
} else {
path = normalizer<normalize>(path.data(), path.size());
}
if (protocol == "file") {
auto local_node_ = local_node.load();
if (!node_) {
node_ = local_node_.get();
}
host = node_->host();
port = node_->binary_port;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
}
inline std::string
Endpoint::slice_after(std::string& subject, const std::string& delimiter) const
{
size_t delimiter_location = subject.find(delimiter);
std::string output;
if (delimiter_location != std::string::npos) {
size_t start = delimiter_location + delimiter.length();
output = subject.substr(start, subject.length() - start);
if (!output.empty()) {
subject = subject.substr(0, delimiter_location);
}
}
return output;
}
inline std::string
Endpoint::slice_before(std::string& subject, const std::string& delimiter) const
{
size_t delimiter_location = subject.find(delimiter);
std::string output;
if (delimiter_location != std::string::npos) {
size_t start = delimiter_location + delimiter.length();
output = subject.substr(0, delimiter_location);
subject = subject.substr(start, subject.length() - start);
}
return output;
}
std::string
Endpoint::to_string() const
{
std::string ret;
if (path.empty()) {
return ret;
}
ret += "xapian://";
if (!user.empty() || !password.empty()) {
ret += user;
if (!password.empty()) {
ret += ":" + password;
}
ret += "@";
}
ret += host;
if (port > 0) {
ret += ":";
ret += std::to_string(port);
}
if (!host.empty() || port > 0) {
ret += "/";
}
ret += path;
if (!search.empty()) {
ret += "?" + search;
}
return ret;
}
bool
Endpoint::operator<(const Endpoint& other) const
{
return hash() < other.hash();
}
size_t
Endpoint::hash() const
{
static std::hash<std::string> hash_fn_string;
std::hash<int> hash_fn_int;
return (
hash_fn_string(path) ^
hash_fn_string(user) ^
hash_fn_string(password) ^
hash_fn_string(host) ^
hash_fn_int(port) ^
hash_fn_string(search)
);
}
std::string
Endpoints::to_string() const
{
std::string ret;
auto j = endpoints.cbegin();
for (int i = 0; j != endpoints.cend(); ++j, ++i) {
if (i) ret += ";";
ret += (*j).to_string();
}
return ret;
}
size_t
Endpoints::hash() const
{
size_t hash = 0;
std::hash<Endpoint> hash_fn;
auto j = endpoints.cbegin();
for (int i = 0; j != endpoints.cend(); ++j, ++i) {
hash ^= hash_fn(*j);
}
return hash;
}
bool
operator==(const Endpoint& le, const Endpoint& re)
{
std::hash<Endpoint> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool
operator==(const Endpoints& le, const Endpoints& re)
{
std::hash<Endpoints> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool
operator!=(const Endpoint& le, const Endpoint& re)
{
return !(le == re);
}
bool
operator!=(const Endpoints& le, const Endpoints& re)
{
return !(le == re);
}
size_t
std::hash<Endpoint>::operator()(const Endpoint& e) const
{
return e.hash();
}
size_t
std::hash<Endpoints>::operator()(const Endpoints& e) const
{
return e.hash();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <termios.h>
// For removing point cloud outside certain distance
// based on http://pointclouds.org/documentation/tutorials/passthrough.php tutorial
#include <pcl/point_types.h>
#include <pcl/filters/passthrough.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
// for pcl segmentation
#include <pcl/features/integral_image_normal.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/segmentation/euclidean_cluster_comparator.h>
// ros stuff
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
// include to convert from messages to pointclouds and vice versa
#include <pcl_conversions/pcl_conversions.h>
// // displaying image and reading key input
// #include <image_transport/image_transport.h>
// #include <opencv2/highgui/highgui.hpp>
// #include <cv_bridge/cv_bridge.h>
bool dist_viewer, distance_limit_enable[3];
float limitX[2],limitY[2],limitZ[2];
std::string POINTS_IN;
std::string save_directory, object_name;
int cloud_save_index;
ros::Subscriber pc_sub;
pcl::PCDWriter writer;
// function getch is from http://answers.ros.org/question/63491/keyboard-key-pressed/
int getch()
{
static struct termios oldt, newt;
tcgetattr( STDIN_FILENO, &oldt); // save old settings
newt = oldt;
newt.c_lflag &= ~(ICANON); // disable buffering
tcsetattr( STDIN_FILENO, TCSANOW, &newt); // apply new settings
int c = getchar(); // read character (non-blocking)
tcsetattr( STDIN_FILENO, TCSANOW, &oldt); // restore old settings
return c;
}
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filter_distance(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_input)
{
std::cerr << "Cloud points before distance filtering: " << cloud_input->points.size() << std::endl;
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGBA>);
pcl::PassThrough<pcl::PointXYZRGBA> pass;
*cloud_filtered = *cloud_input;
pass.setInputCloud (cloud_filtered);
pass.setKeepOrganized(true);
if (distance_limit_enable[0])
{
pass.setFilterFieldName ("x");
pass.setFilterLimits (limitX[0], limitX[1]);
pass.filter (*cloud_filtered);
}
if (distance_limit_enable[1])
{
pass.setFilterFieldName ("y");
pass.setFilterLimits (limitY[0], limitY[1]);
pass.filter (*cloud_filtered);
}
if (distance_limit_enable[2])
{
pass.setFilterFieldName ("z");
pass.setFilterLimits (limitZ[0], limitZ[1]);
pass.filter (*cloud_filtered);
}
std::cerr << "Cloud after distance filtering: " << cloud_filtered->points.size() << std::endl;
return cloud_filtered;
}
void cloud_segmenter_and_save(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr input_cloud)
{
std::cerr << "\nSegmentation process begin \n";
// Remove point outside certain distance
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGBA>);
cloud_filtered = cloud_filter_distance(input_cloud);
if (dist_viewer)
{
std::cerr << "See distance filtered cloud. Press q to quit viewer. \n";
pcl::visualization::CloudViewer viewer ("Distance Filtered Cloud Viewer");
viewer.showCloud (cloud_filtered);
while (!viewer.wasStopped ())
{
}
dist_viewer = false;
writer.write<pcl::PointXYZRGBA> (save_directory+"distance_filtered.pcd", *cloud_filtered, false);
}
// Get Normal Cloud
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::IntegralImageNormalEstimation<pcl::PointXYZRGBA, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud_filtered);
ne.compute(*normals);
// Segment planes
pcl::OrganizedMultiPlaneSegmentation< pcl::PointXYZRGBA, pcl::Normal, pcl::Label > mps;
std::vector<pcl::ModelCoefficients> model_coefficients;
std::vector<pcl::PointIndices> inlier_indices;
pcl::PointCloud<pcl::Label>::Ptr labels (new pcl::PointCloud<pcl::Label>);
std::vector<pcl::PointIndices> label_indices;
std::vector<pcl::PointIndices> boundary_indices;
mps.setMinInliers (15000);
mps.setAngularThreshold (0.017453 * 2.0); // 2 degrees
mps.setDistanceThreshold (0.02); // 2cm
mps.setInputNormals (normals);
mps.setInputCloud (cloud_filtered);
std::vector< pcl::PlanarRegion<pcl::PointXYZRGBA>, Eigen::aligned_allocator<pcl::PlanarRegion<pcl::PointXYZRGBA> > > regions;
mps.segmentAndRefine (regions, model_coefficients, inlier_indices, labels, label_indices, boundary_indices);
// Remove detected planes (table) and segment the object
std::vector<bool> plane_labels;
plane_labels.resize (label_indices.size (), false);
for (size_t i = 0; i < label_indices.size (); i++)
{
if (label_indices[i].indices.size () > 10000)
{
plane_labels[i] = true;
}
}
pcl::EuclideanClusterComparator<pcl::PointXYZRGBA, pcl::Normal, pcl::Label>::Ptr euclidean_cluster_comparator_(new pcl::EuclideanClusterComparator<pcl::PointXYZRGBA, pcl::Normal, pcl::Label> ());
euclidean_cluster_comparator_->setInputCloud (cloud_filtered);
euclidean_cluster_comparator_->setLabels (labels);
euclidean_cluster_comparator_->setExcludeLabels (plane_labels);
euclidean_cluster_comparator_->setDistanceThreshold (0.03f, false);
pcl::PointCloud<pcl::Label> euclidean_labels;
std::vector<pcl::PointIndices> euclidean_label_indices;
pcl::OrganizedConnectedComponentSegmentation<pcl::PointXYZRGBA,pcl::Label> euclidean_segmentation (euclidean_cluster_comparator_);
euclidean_segmentation.setInputCloud (cloud_filtered);
euclidean_segmentation.segment (euclidean_labels, euclidean_label_indices);
// save detected cluster data
for (size_t i = 0; i < euclidean_label_indices.size (); i++)
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGBA>);
pcl::ExtractIndices<pcl::PointXYZRGBA> extract;
pcl::PointIndices::Ptr object_cloud_indices (new pcl::PointIndices);
*object_cloud_indices = euclidean_label_indices[i];
extract.setInputCloud(cloud_filtered);
extract.setIndices(object_cloud_indices);
extract.setKeepOrganized(true);
extract.filter(*cloud_cluster);
std::stringstream ss;
ss << save_directory << object_name << cloud_save_index << ".pcd";
writer.write<pcl::PointXYZRGBA> (ss.str (), *cloud_cluster, false); //*
std::cerr << "Saved " << save_directory << object_name << cloud_save_index << ".pcd" << std::endl;
cloud_save_index++;
}
std::cerr << "Segmentation done \n. Wait for new data \n";
}
void callback(const sensor_msgs::PointCloud2 &pc)
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
// convert sensor_msgs::PointCloud2 to pcl::PointXYZRGBA
pcl::fromROSMsg(pc, *cloud);
cloud_segmenter_and_save(cloud);
}
int main (int argc, char** argv)
{
ros::init(argc,argv,"object_on_table_segmenter_Node");
ros::NodeHandle nh("~");
//getting subscriber parameters
nh.param("POINTS_IN", POINTS_IN,std::string("/camera/depth_registered/points"));
//getting save parameters
nh.param("save_directory",save_directory,std::string("./result"));
nh.param("object",object_name,std::string("cloud_cluster_"));
nh.param("pcl_viewer",dist_viewer,false);
nh.param("save_index",cloud_save_index,0);
//getting other parameters
nh.param("limit_X",distance_limit_enable[0],false);
nh.param("limit_Y",distance_limit_enable[1],false);
nh.param("limit_Z",distance_limit_enable[2],true);
nh.param("xMin",limitX[0],0.0f);
nh.param("yMin",limitY[0],0.0f);
nh.param("zMin",limitZ[0],0.0f);
nh.param("xMax",limitX[1],0.0f);
nh.param("yMax",limitY[1],0.0f);
nh.param("zMax",limitZ[1],1.5f);
pc_sub = nh.subscribe(POINTS_IN,1,callback);
std::cerr << "Press 'q' key to exit \n";
std::cerr << "Press 's' key to do object on table segmentation \n";
ros::Rate r(10); // 10 hz
int key = 0;
while (ros::ok())
{
key = getch();
if ((key == 's') || (key == 'S'))
ros::spinOnce();
else if ((key == 'q') || (key == 'Q'))
break;
r.sleep();
}
ros::shutdown();
return (0);
}
<commit_msg>Fix parameter from float to double<commit_after>#include <iostream>
#include <termios.h>
// For removing point cloud outside certain distance
// based on http://pointclouds.org/documentation/tutorials/passthrough.php tutorial
#include <pcl/point_types.h>
#include <pcl/filters/passthrough.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
// for pcl segmentation
#include <pcl/features/integral_image_normal.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/segmentation/euclidean_cluster_comparator.h>
// ros stuff
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
// include to convert from messages to pointclouds and vice versa
#include <pcl_conversions/pcl_conversions.h>
// // displaying image and reading key input
// #include <image_transport/image_transport.h>
// #include <opencv2/highgui/highgui.hpp>
// #include <cv_bridge/cv_bridge.h>
bool dist_viewer, distance_limit_enable[3];
double limitX[2],limitY[2],limitZ[2];
std::string POINTS_IN;
std::string save_directory, object_name;
int cloud_save_index;
ros::Subscriber pc_sub;
pcl::PCDWriter writer;
// function getch is from http://answers.ros.org/question/63491/keyboard-key-pressed/
int getch()
{
static struct termios oldt, newt;
tcgetattr( STDIN_FILENO, &oldt); // save old settings
newt = oldt;
newt.c_lflag &= ~(ICANON); // disable buffering
tcsetattr( STDIN_FILENO, TCSANOW, &newt); // apply new settings
int c = getchar(); // read character (non-blocking)
tcsetattr( STDIN_FILENO, TCSANOW, &oldt); // restore old settings
return c;
}
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filter_distance(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_input)
{
std::cerr << "Cloud points before distance filtering: " << cloud_input->points.size() << std::endl;
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGBA>);
pcl::PassThrough<pcl::PointXYZRGBA> pass;
*cloud_filtered = *cloud_input;
pass.setInputCloud (cloud_filtered);
pass.setKeepOrganized(true);
if (distance_limit_enable[0])
{
pass.setFilterFieldName ("x");
pass.setFilterLimits (limitX[0], limitX[1]);
pass.filter (*cloud_filtered);
}
if (distance_limit_enable[1])
{
pass.setFilterFieldName ("y");
pass.setFilterLimits (limitY[0], limitY[1]);
pass.filter (*cloud_filtered);
}
if (distance_limit_enable[2])
{
pass.setFilterFieldName ("z");
pass.setFilterLimits (limitZ[0], limitZ[1]);
pass.filter (*cloud_filtered);
}
std::cerr << "Cloud after distance filtering: " << cloud_filtered->points.size() << std::endl;
return cloud_filtered;
}
void cloud_segmenter_and_save(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr input_cloud)
{
std::cerr << "\nSegmentation process begin \n";
// Remove point outside certain distance
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGBA>);
cloud_filtered = cloud_filter_distance(input_cloud);
if (dist_viewer)
{
std::cerr << "See distance filtered cloud. Press q to quit viewer. \n";
pcl::visualization::CloudViewer viewer ("Distance Filtered Cloud Viewer");
viewer.showCloud (cloud_filtered);
while (!viewer.wasStopped ())
{
}
dist_viewer = false;
writer.write<pcl::PointXYZRGBA> (save_directory+"distance_filtered.pcd", *cloud_filtered, false);
}
// Get Normal Cloud
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::IntegralImageNormalEstimation<pcl::PointXYZRGBA, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.AVERAGE_3D_GRADIENT);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud_filtered);
ne.compute(*normals);
// Segment planes
pcl::OrganizedMultiPlaneSegmentation< pcl::PointXYZRGBA, pcl::Normal, pcl::Label > mps;
std::vector<pcl::ModelCoefficients> model_coefficients;
std::vector<pcl::PointIndices> inlier_indices;
pcl::PointCloud<pcl::Label>::Ptr labels (new pcl::PointCloud<pcl::Label>);
std::vector<pcl::PointIndices> label_indices;
std::vector<pcl::PointIndices> boundary_indices;
mps.setMinInliers (15000);
mps.setAngularThreshold (0.017453 * 2.0); // 2 degrees
mps.setDistanceThreshold (0.02); // 2cm
mps.setInputNormals (normals);
mps.setInputCloud (cloud_filtered);
std::vector< pcl::PlanarRegion<pcl::PointXYZRGBA>, Eigen::aligned_allocator<pcl::PlanarRegion<pcl::PointXYZRGBA> > > regions;
mps.segmentAndRefine (regions, model_coefficients, inlier_indices, labels, label_indices, boundary_indices);
// Remove detected planes (table) and segment the object
std::vector<bool> plane_labels;
plane_labels.resize (label_indices.size (), false);
for (size_t i = 0; i < label_indices.size (); i++)
{
if (label_indices[i].indices.size () > 10000)
{
plane_labels[i] = true;
}
}
pcl::EuclideanClusterComparator<pcl::PointXYZRGBA, pcl::Normal, pcl::Label>::Ptr euclidean_cluster_comparator_(new pcl::EuclideanClusterComparator<pcl::PointXYZRGBA, pcl::Normal, pcl::Label> ());
euclidean_cluster_comparator_->setInputCloud (cloud_filtered);
euclidean_cluster_comparator_->setLabels (labels);
euclidean_cluster_comparator_->setExcludeLabels (plane_labels);
euclidean_cluster_comparator_->setDistanceThreshold (0.03f, false);
pcl::PointCloud<pcl::Label> euclidean_labels;
std::vector<pcl::PointIndices> euclidean_label_indices;
pcl::OrganizedConnectedComponentSegmentation<pcl::PointXYZRGBA,pcl::Label> euclidean_segmentation (euclidean_cluster_comparator_);
euclidean_segmentation.setInputCloud (cloud_filtered);
euclidean_segmentation.segment (euclidean_labels, euclidean_label_indices);
// save detected cluster data
for (size_t i = 0; i < euclidean_label_indices.size (); i++)
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGBA>);
pcl::ExtractIndices<pcl::PointXYZRGBA> extract;
pcl::PointIndices::Ptr object_cloud_indices (new pcl::PointIndices);
*object_cloud_indices = euclidean_label_indices[i];
extract.setInputCloud(cloud_filtered);
extract.setIndices(object_cloud_indices);
extract.setKeepOrganized(true);
extract.filter(*cloud_cluster);
std::stringstream ss;
ss << save_directory << object_name << cloud_save_index << ".pcd";
writer.write<pcl::PointXYZRGBA> (ss.str (), *cloud_cluster, false); //*
std::cerr << "Saved " << save_directory << object_name << cloud_save_index << ".pcd" << std::endl;
cloud_save_index++;
}
std::cerr << "Segmentation done \n. Wait for new data \n";
}
void callback(const sensor_msgs::PointCloud2 &pc)
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
// convert sensor_msgs::PointCloud2 to pcl::PointXYZRGBA
pcl::fromROSMsg(pc, *cloud);
cloud_segmenter_and_save(cloud);
}
int main (int argc, char** argv)
{
ros::init(argc,argv,"object_on_table_segmenter_Node");
ros::NodeHandle nh("~");
//getting subscriber parameters
nh.param("POINTS_IN", POINTS_IN,std::string("/camera/depth_registered/points"));
//getting save parameters
nh.param("save_directory",save_directory,std::string("./result"));
nh.param("object",object_name,std::string("cloud_cluster_"));
nh.param("pcl_viewer",dist_viewer,false);
nh.param("save_index",cloud_save_index,0);
//getting other parameters
nh.param("limit_X",distance_limit_enable[0],false);
nh.param("limit_Y",distance_limit_enable[1],false);
nh.param("limit_Z",distance_limit_enable[2],true);
nh.param("xMin",limitX[0],0.0d);
nh.param("yMin",limitY[0],0.0d);
nh.param("zMin",limitZ[0],0.0d);
nh.param("xMax",limitX[1],0.0d);
nh.param("yMax",limitY[1],0.0d);
nh.param("zMax",limitZ[1],1.5d);
pc_sub = nh.subscribe(POINTS_IN,1,callback);
std::cerr << "Press 'q' key to exit \n";
std::cerr << "Press 's' key to do object on table segmentation \n";
ros::Rate r(10); // 10 hz
int key = 0;
while (ros::ok())
{
key = getch();
if ((key == 's') || (key == 'S'))
ros::spinOnce();
else if ((key == 'q') || (key == 'Q'))
break;
r.sleep();
}
ros::shutdown();
return (0);
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file shuffle_op.cc
* \brief Operator to shuffle elements of an NDArray
*/
#if ((__GNUC__ > 4 && !defined(__clang__major__)) || (__clang_major__ > 4 && __linux__)) && \
defined(_OPENMP) && !defined(__ANDROID__)
#define USE_GNU_PARALLEL_SHUFFLE
#endif
#include <mxnet/operator_util.h>
#include <algorithm>
#include <random>
#include <vector>
#include <cstring>
#ifdef USE_GNU_PARALLEL_SHUFFLE
#include <unistd.h>
#include <parallel/algorithm>
#endif
#include "../elemwise_op_common.h"
namespace mxnet {
namespace op {
namespace {
template <typename DType, typename Rand>
void Shuffle1D(DType* const out, const index_t size, Rand* const prnd) {
#ifdef USE_GNU_PARALLEL_SHUFFLE
/*
* See issue #15029: the data type of n needs to be compatible with
* the gcc library: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B\
* -v3/include/parallel/random_shuffle.h#L384
*/
auto rand_n = [prnd](uint32_t n) {
std::uniform_int_distribution<uint32_t> dist(0, n - 1);
return dist(*prnd);
};
__gnu_parallel::random_shuffle(out, out + size, rand_n);
#else
std::shuffle(out, out + size, *prnd);
#endif
}
template <typename DType, typename Rand>
void ShuffleND(DType* const out,
const index_t size,
const index_t first_axis_len,
Rand* const prnd,
const OpContext& ctx) {
// Fisher-Yates shuffling
using namespace mxnet_op;
const index_t stride = size / first_axis_len;
auto rand_n = [prnd](index_t n) {
std::uniform_int_distribution<index_t> dist(0, n - 1);
return dist(*prnd);
};
CHECK_GT(first_axis_len, 0U);
const size_t stride_bytes = sizeof(DType) * stride;
Tensor<cpu, 1, char> buf =
ctx.requested[1].get_space_typed<cpu, 1, char>(Shape1(stride_bytes), ctx.get_stream<cpu>());
for (index_t i = first_axis_len - 1; i > 0; --i) {
const index_t j = rand_n(i + 1);
if (i != j) {
#pragma GCC diagnostic push
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
std::memcpy(buf.dptr_, out + stride * i, stride_bytes);
std::memcpy(out + stride * i, out + stride * j, stride_bytes);
std::memcpy(out + stride * j, buf.dptr_, stride_bytes);
#pragma GCC diagnostic pop
}
}
}
} // namespace
void ShuffleForwardCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) {
return;
}
CHECK_NE(req[0], kAddTo) << "Shuffle does not support AddTo";
const mxnet::TShape& input_shape = inputs[0].shape_;
const index_t size = inputs[0].Size();
const index_t first_axis_len = input_shape[0];
Stream<cpu>* s = ctx.get_stream<cpu>();
MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, {
Tensor<cpu, 1, DType> in = inputs[0].get_with_shape<cpu, 1, DType>(Shape1(size), s);
Tensor<cpu, 1, DType> out = outputs[0].get_with_shape<cpu, 1, DType>(Shape1(size), s);
auto& prnd = ctx.requested[0].get_random<cpu, index_t>(ctx.get_stream<cpu>())->GetRndEngine();
if (req[0] != kWriteInplace) {
std::copy(in.dptr_, in.dptr_ + size, out.dptr_);
}
if (input_shape.ndim() == 1) {
Shuffle1D(out.dptr_, size, &prnd);
} else {
ShuffleND(out.dptr_, size, first_axis_len, &prnd, ctx);
}
});
}
// No parameter is declared.
// No backward computation is registered. Shuffling is not differentiable.
NNVM_REGISTER_OP(_shuffle)
.add_alias("shuffle")
.add_alias("_npi_shuffle")
.describe(R"code(Randomly shuffle the elements.
This shuffles the array along the first axis.
The order of the elements in each subarray does not change.
For example, if a 2D array is given, the order of the rows randomly changes,
but the order of the elements in each row does not change.
)code")
.set_num_inputs(1)
.set_num_outputs(1)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<1, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kRandom,
ResourceRequest::kTempSpace};
})
.set_attr<nnvm::FInplaceOption>("FInplaceOption",
[](const NodeAttrs& attrs) {
return std::vector<std::pair<int, int>>{{0, 0}};
})
.set_attr<FCompute>("FCompute<cpu>", ShuffleForwardCPU)
.add_argument("data", "NDArray-or-Symbol", "Data to be shuffled.");
} // namespace op
} // namespace mxnet
<commit_msg>[PERFORMANCE] Improve shuffle implementation (#20928)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file shuffle_op.cc
* \brief Operator to shuffle elements of an NDArray
*/
#if ((__GNUC__ > 4 && !defined(__clang__major__)) || (__clang_major__ > 4 && __linux__)) && \
defined(_OPENMP) && !defined(__ANDROID__)
#define USE_GNU_PARALLEL_SHUFFLE
#endif
#include <mxnet/operator_util.h>
#include <numeric>
#include <algorithm>
#include <random>
#include <vector>
#include <cstring>
#ifdef USE_GNU_PARALLEL_SHUFFLE
#include <unistd.h>
#include <parallel/algorithm>
#endif
#include "../elemwise_op_common.h"
namespace mxnet {
namespace op {
namespace {
template <typename DType, typename Rand>
void Shuffle1D(DType* const out, const index_t size, Rand* const prnd) {
#ifdef USE_GNU_PARALLEL_SHUFFLE
/*
* See issue #15029: the data type of n needs to be compatible with
* the gcc library: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B\
* -v3/include/parallel/random_shuffle.h#L384
*/
auto rand_n = [prnd](uint32_t n) {
std::uniform_int_distribution<uint32_t> dist(0, n - 1);
return dist(*prnd);
};
__gnu_parallel::random_shuffle(out, out + size, rand_n);
#else
std::shuffle(out, out + size, *prnd);
#endif
}
template <typename DType, typename Rand>
void ShuffleND(DType* const out,
DType* const in,
const index_t size,
const index_t first_axis_len,
Rand* const prnd,
const OpContext& ctx,
OpReqType reqT) {
// Optimized Fisher-Yates shuffling
using namespace mxnet_op;
const index_t stride = size / first_axis_len;
CHECK_GT(first_axis_len, 0U);
const size_t stride_bytes = sizeof(DType) * stride;
std::vector<index_t> index(first_axis_len);
std::iota(index.begin(), index.end(), 0);
std::shuffle(index.begin(), index.end(), *prnd);
if (reqT != kWriteInplace) {
for (index_t i = 0; i < first_axis_len; ++i) {
auto j = index[i];
void* const dst = static_cast<void* const>(out + stride * j);
void* const src = static_cast<void* const>(in + stride * i);
std::memcpy(dst, src, stride_bytes);
}
} else {
assert(in == out);
std::vector<bool> done(first_axis_len, false);
Tensor<cpu, 1, DType> tmp_buf =
ctx.requested[1].get_space_typed<cpu, 1, DType>(Shape1(stride), ctx.get_stream<cpu>());
void* const tmp = static_cast<void*>(tmp_buf.dptr_);
for (index_t i = 0; i < first_axis_len; ++i) {
if (!done[i]) {
index_t pos = index[i];
if (pos != i) {
void* const dst = static_cast<void*>(out + stride * i);
void* const src = static_cast<void*>(out + stride * pos);
std::memcpy(tmp, dst, stride_bytes);
std::memcpy(dst, src, stride_bytes);
done[i] = true;
void* dst_loop = static_cast<void*>(out + stride * pos);
// go through indexes until return to the starting one
while (index[pos] != i) {
const index_t next_pos = index[pos];
void* src_loop = static_cast<void*>(out + stride * next_pos);
std::memcpy(dst_loop, src_loop, stride_bytes);
done[pos] = true;
dst_loop = src_loop;
pos = next_pos;
}
std::memcpy(dst_loop, tmp, stride_bytes);
done[pos] = true;
}
}
}
}
}
} // namespace
void ShuffleForwardCPU(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) {
return;
}
CHECK_NE(req[0], kAddTo) << "Shuffle does not support AddTo";
const mxnet::TShape& input_shape = inputs[0].shape_;
const index_t size = inputs[0].Size();
const index_t first_axis_len = input_shape[0];
Stream<cpu>* s = ctx.get_stream<cpu>();
MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, {
Tensor<cpu, 1, DType> in = inputs[0].get_with_shape<cpu, 1, DType>(Shape1(size), s);
Tensor<cpu, 1, DType> out = outputs[0].get_with_shape<cpu, 1, DType>(Shape1(size), s);
auto& prnd = ctx.requested[0].get_random<cpu, index_t>(ctx.get_stream<cpu>())->GetRndEngine();
if (input_shape.ndim() == 1) {
if (req[0] != kWriteInplace) {
std::copy(in.dptr_, in.dptr_ + size, out.dptr_);
}
Shuffle1D(out.dptr_, size, &prnd);
} else {
ShuffleND(out.dptr_, in.dptr_, size, first_axis_len, &prnd, ctx, req[0]);
}
});
}
// No parameter is declared.
// No backward computation is registered. Shuffling is not differentiable.
NNVM_REGISTER_OP(_shuffle)
.add_alias("shuffle")
.add_alias("_npi_shuffle")
.describe(R"code(Randomly shuffle the elements.
This shuffles the array along the first axis.
The order of the elements in each subarray does not change.
For example, if a 2D array is given, the order of the rows randomly changes,
but the order of the elements in each row does not change.
)code")
.set_num_inputs(1)
.set_num_outputs(1)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<1, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kRandom,
ResourceRequest::kTempSpace};
})
.set_attr<nnvm::FInplaceOption>("FInplaceOption",
[](const NodeAttrs& attrs) {
return std::vector<std::pair<int, int>>{{0, 0}};
})
.set_attr<FCompute>("FCompute<cpu>", ShuffleForwardCPU)
.add_argument("data", "NDArray-or-Symbol", "Data to be shuffled.");
} // namespace op
} // namespace mxnet
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
#include <algorithm>
using ::osvr::client::ClientInterfacePtr;
using ::osvr::client::ClientInterface;
using ::osvr::make_shared;
OSVR_ClientContextObject::OSVR_ClientContextObject(const char appId[])
: m_appId(appId) {
OSVR_DEV_VERBOSE("Client context initialized for " << m_appId);
}
OSVR_ClientContextObject::~OSVR_ClientContextObject() {}
std::string const &OSVR_ClientContextObject::getAppId() const {
return m_appId;
}
void OSVR_ClientContextObject::update() {
m_update();
std::for_each(begin(m_interfaces), end(m_interfaces),
[](ClientInterfacePtr const &iface) { iface->update(); });
}
ClientInterfacePtr OSVR_ClientContextObject::getInterface(const char path[]) {
ClientInterfacePtr ret;
if (!path) {
return ret;
}
std::string p(path);
if (p.empty()) {
return ret;
}
ret = make_shared<ClientInterface>(this, path,
ClientInterface::PrivateConstructor());
m_interfaces.push_back(ret);
return ret;
}
ClientInterfacePtr
OSVR_ClientContextObject::releaseInterface(ClientInterface *iface) {
ClientInterfacePtr ret;
if (!iface) {
return ret;
}
InterfaceList::iterator it =
std::find_if(begin(m_interfaces), end(m_interfaces),
[&](ClientInterfacePtr const &ptr) {
if (ptr.get() == iface) {
ret = ptr;
return true;
}
return false;
});
BOOST_ASSERT_MSG(
(it == end(m_interfaces)) == (!ret),
"We should have a pointer if and only if we have the iterator");
if (ret) {
// Erase it from our list
m_interfaces.erase(it);
}
return ret;
}
std::string
OSVR_ClientContextObject::getStringParameter(std::string const &path) const {
auto it = m_params.find(path);
std::string ret;
if (it != m_params.end()) {
ret = it->second;
}
return ret;
}
void OSVR_ClientContextObject::setParameter(std::string const &path,
std::string const &value) {
OSVR_DEV_VERBOSE("Parameter set for " << path);
m_params[path] = value;
}<commit_msg>Replace a lambda with a range-for<commit_after>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
#include <algorithm>
using ::osvr::client::ClientInterfacePtr;
using ::osvr::client::ClientInterface;
using ::osvr::make_shared;
OSVR_ClientContextObject::OSVR_ClientContextObject(const char appId[])
: m_appId(appId) {
OSVR_DEV_VERBOSE("Client context initialized for " << m_appId);
}
OSVR_ClientContextObject::~OSVR_ClientContextObject() {}
std::string const &OSVR_ClientContextObject::getAppId() const {
return m_appId;
}
void OSVR_ClientContextObject::update() {
m_update();
for (auto const &iface : m_interfaces) {
iface->update();
}
}
ClientInterfacePtr OSVR_ClientContextObject::getInterface(const char path[]) {
ClientInterfacePtr ret;
if (!path) {
return ret;
}
std::string p(path);
if (p.empty()) {
return ret;
}
ret = make_shared<ClientInterface>(this, path,
ClientInterface::PrivateConstructor());
m_interfaces.push_back(ret);
return ret;
}
ClientInterfacePtr
OSVR_ClientContextObject::releaseInterface(ClientInterface *iface) {
ClientInterfacePtr ret;
if (!iface) {
return ret;
}
InterfaceList::iterator it =
std::find_if(begin(m_interfaces), end(m_interfaces),
[&](ClientInterfacePtr const &ptr) {
if (ptr.get() == iface) {
ret = ptr;
return true;
}
return false;
});
BOOST_ASSERT_MSG(
(it == end(m_interfaces)) == (!ret),
"We should have a pointer if and only if we have the iterator");
if (ret) {
// Erase it from our list
m_interfaces.erase(it);
}
return ret;
}
std::string
OSVR_ClientContextObject::getStringParameter(std::string const &path) const {
auto it = m_params.find(path);
std::string ret;
if (it != m_params.end()) {
ret = it->second;
}
return ret;
}
void OSVR_ClientContextObject::setParameter(std::string const &path,
std::string const &value) {
OSVR_DEV_VERBOSE("Parameter set for " << path);
m_params[path] = value;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "src/perfetto_cmd/packet_writer.h"
#include <array>
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/ext/base/paged_memory.h"
#include "perfetto/ext/base/utils.h"
#include "perfetto/ext/tracing/core/trace_packet.h"
#include "perfetto/protozero/proto_utils.h"
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
#include <zlib.h>
#endif
namespace perfetto {
namespace {
using protozero::proto_utils::kMessageLengthFieldSize;
using protozero::proto_utils::MakeTagLengthDelimited;
using protozero::proto_utils::WriteRedundantVarInt;
using protozero::proto_utils::WriteVarInt;
using Preamble = std::array<char, 16>;
// ID of the |packet| field in trace.proto. Hardcoded as this we don't
// want to depend on protos/trace:lite for binary size saving reasons.
constexpr uint32_t kPacketId = 1;
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
// ID of |compressed_packets| in trace_packet.proto.
constexpr uint32_t kCompressedPacketsId = 50;
// Maximum allowable size for a single packet.
const size_t kMaxPacketSize = 500 * 1024;
// After every kPendingBytesLimit we do a Z_SYNC_FLUSH in the zlib stream.
const size_t kPendingBytesLimit = 32 * 1024;
#endif // PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
template <uint32_t id>
size_t GetPreamble(size_t sz, Preamble* preamble) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(preamble->data());
constexpr uint32_t tag = MakeTagLengthDelimited(id);
ptr = WriteVarInt(tag, ptr);
ptr = WriteVarInt(sz, ptr);
size_t preamble_size = reinterpret_cast<uintptr_t>(ptr) -
reinterpret_cast<uintptr_t>(preamble->data());
PERFETTO_DCHECK(preamble_size < preamble->size());
return preamble_size;
}
class FilePacketWriter : public PacketWriter {
public:
FilePacketWriter(FILE* fd);
~FilePacketWriter() override;
bool WritePackets(const std::vector<TracePacket>& packets) override;
private:
FILE* fd_;
};
FilePacketWriter::FilePacketWriter(FILE* fd) : fd_(fd) {}
FilePacketWriter::~FilePacketWriter() {
fflush(fd_);
}
bool FilePacketWriter::WritePackets(const std::vector<TracePacket>& packets) {
for (const TracePacket& packet : packets) {
Preamble preamble;
size_t size = GetPreamble<kPacketId>(packet.size(), &preamble);
if (fwrite(preamble.data(), 1, size, fd_) != size)
return false;
for (const Slice& slice : packet.slices()) {
if (fwrite(reinterpret_cast<const char*>(slice.start), 1, slice.size,
fd_) != slice.size) {
return false;
}
}
}
return true;
}
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
class ZipPacketWriter : public PacketWriter {
public:
ZipPacketWriter(std::unique_ptr<PacketWriter>);
~ZipPacketWriter() override;
bool WritePackets(const std::vector<TracePacket>& packets) override;
private:
bool WritePacket(const TracePacket& packet);
void CheckEq(int actual_code, int expected_code);
bool FinalizeCompressedPacket();
inline void Deflate(const char* ptr, size_t size) {
return Deflate(reinterpret_cast<const uint8_t*>(ptr), size);
}
inline void Deflate(const void* ptr, size_t size) {
return Deflate(reinterpret_cast<const uint8_t*>(ptr), size);
}
void Deflate(const uint8_t* ptr, size_t size);
std::unique_ptr<PacketWriter> writer_;
z_stream stream_{};
base::PagedMemory buf_;
uint8_t* const start_;
uint8_t* const end_;
bool is_compressing_ = false;
size_t pending_bytes_ = 0;
};
ZipPacketWriter::ZipPacketWriter(std::unique_ptr<PacketWriter> writer)
: writer_(std::move(writer)),
buf_(base::PagedMemory::Allocate(kMaxPacketSize)),
start_(static_cast<uint8_t*>(buf_.Get())),
end_(start_ + buf_.size()) {}
ZipPacketWriter::~ZipPacketWriter() {
if (is_compressing_)
FinalizeCompressedPacket();
}
bool ZipPacketWriter::WritePackets(const std::vector<TracePacket>& packets) {
for (const TracePacket& packet : packets) {
if (!WritePacket(packet))
return false;
}
return true;
}
bool ZipPacketWriter::WritePacket(const TracePacket& packet) {
// If we have already written one compressed packet, check whether we should
// flush the buffer.
if (is_compressing_) {
// We have two goals:
// - Fit as much data as possible into each packet
// - Ensure each packet is under 512KB
// We keep track of two numbers:
// - the number of remaining bytes in the output buffer
// - the number of (pending) uncompressed bytes written since the last flush
// The pending bytes may or may not have appeared in output buffer.
// Assuming in the worst case each uncompressed input byte can turn into
// two compressed bytes we can ensure we don't go over 512KB by not letting
// the number of pending bytes go over remaining bytes/2 - however often
// each input byte will not turn into 2 output bytes but less than 1 output
// byte - so this underfills the packet. To avoid this every 32kb we deflate
// with Z_SYNC_FLUSH ensuring all pending bytes are present in the output
// buffer.
if (pending_bytes_ > kPendingBytesLimit) {
CheckEq(deflate(&stream_, Z_SYNC_FLUSH), Z_OK);
pending_bytes_ = 0;
}
PERFETTO_DCHECK(end_ >= stream_.next_out);
size_t remaining = static_cast<size_t>(end_ - stream_.next_out);
if ((pending_bytes_ + packet.size() + 1024) * 2 > remaining) {
if (!FinalizeCompressedPacket()) {
return false;
}
}
}
// Reinitialize the compresser if needed:
if (!is_compressing_) {
memset(&stream_, 0, sizeof(stream_));
CheckEq(deflateInit(&stream_, 9), Z_OK);
is_compressing_ = true;
stream_.next_out = start_;
stream_.avail_out = static_cast<unsigned int>(end_ - start_);
}
// Compress the trace packet header:
Preamble packet_hdr;
size_t packet_hdr_size = GetPreamble<kPacketId>(packet.size(), &packet_hdr);
Deflate(packet_hdr.data(), packet_hdr_size);
// Compress the trace packet itself:
for (const Slice& slice : packet.slices()) {
Deflate(slice.start, slice.size);
}
return true;
}
bool ZipPacketWriter::FinalizeCompressedPacket() {
PERFETTO_DCHECK(is_compressing_);
CheckEq(deflate(&stream_, Z_FINISH), Z_STREAM_END);
size_t size = static_cast<size_t>(stream_.next_out - start_);
Preamble preamble;
size_t preamble_size = GetPreamble<kCompressedPacketsId>(size, &preamble);
std::vector<TracePacket> out_packets(1);
TracePacket& out_packet = out_packets[0];
out_packet.AddSlice(preamble.data(), preamble_size);
out_packet.AddSlice(start_, size);
if (!writer_->WritePackets(out_packets))
return false;
is_compressing_ = false;
pending_bytes_ = 0;
CheckEq(deflateEnd(&stream_), Z_OK);
return true;
}
void ZipPacketWriter::CheckEq(int actual_code, int expected_code) {
if (actual_code == expected_code)
return;
PERFETTO_FATAL("Expected %d got %d: %s", actual_code, expected_code,
stream_.msg);
}
void ZipPacketWriter::Deflate(const uint8_t* ptr, size_t size) {
PERFETTO_CHECK(is_compressing_);
stream_.next_in = const_cast<uint8_t*>(ptr);
stream_.avail_in = static_cast<unsigned int>(size);
CheckEq(deflate(&stream_, Z_NO_FLUSH), Z_OK);
PERFETTO_CHECK(stream_.avail_in == 0);
pending_bytes_ += size;
}
#endif // PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
} // namespace
PacketWriter::PacketWriter() {}
PacketWriter::~PacketWriter() {}
std::unique_ptr<PacketWriter> CreateFilePacketWriter(FILE* fd) {
return std::unique_ptr<PacketWriter>(new FilePacketWriter(fd));
}
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
std::unique_ptr<PacketWriter> CreateZipPacketWriter(
std::unique_ptr<PacketWriter> writer) {
return std::unique_ptr<PacketWriter>(new ZipPacketWriter(std::move(writer)));
}
#endif
} // namespace perfetto
<commit_msg>perfetto-cmd: Reduce compression quality to 6<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "src/perfetto_cmd/packet_writer.h"
#include <array>
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/ext/base/paged_memory.h"
#include "perfetto/ext/base/utils.h"
#include "perfetto/ext/tracing/core/trace_packet.h"
#include "perfetto/protozero/proto_utils.h"
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
#include <zlib.h>
#endif
namespace perfetto {
namespace {
using protozero::proto_utils::kMessageLengthFieldSize;
using protozero::proto_utils::MakeTagLengthDelimited;
using protozero::proto_utils::WriteRedundantVarInt;
using protozero::proto_utils::WriteVarInt;
using Preamble = std::array<char, 16>;
// ID of the |packet| field in trace.proto. Hardcoded as this we don't
// want to depend on protos/trace:lite for binary size saving reasons.
constexpr uint32_t kPacketId = 1;
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
// ID of |compressed_packets| in trace_packet.proto.
constexpr uint32_t kCompressedPacketsId = 50;
// Maximum allowable size for a single packet.
const size_t kMaxPacketSize = 500 * 1024;
// After every kPendingBytesLimit we do a Z_SYNC_FLUSH in the zlib stream.
const size_t kPendingBytesLimit = 32 * 1024;
#endif // PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
template <uint32_t id>
size_t GetPreamble(size_t sz, Preamble* preamble) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(preamble->data());
constexpr uint32_t tag = MakeTagLengthDelimited(id);
ptr = WriteVarInt(tag, ptr);
ptr = WriteVarInt(sz, ptr);
size_t preamble_size = reinterpret_cast<uintptr_t>(ptr) -
reinterpret_cast<uintptr_t>(preamble->data());
PERFETTO_DCHECK(preamble_size < preamble->size());
return preamble_size;
}
class FilePacketWriter : public PacketWriter {
public:
FilePacketWriter(FILE* fd);
~FilePacketWriter() override;
bool WritePackets(const std::vector<TracePacket>& packets) override;
private:
FILE* fd_;
};
FilePacketWriter::FilePacketWriter(FILE* fd) : fd_(fd) {}
FilePacketWriter::~FilePacketWriter() {
fflush(fd_);
}
bool FilePacketWriter::WritePackets(const std::vector<TracePacket>& packets) {
for (const TracePacket& packet : packets) {
Preamble preamble;
size_t size = GetPreamble<kPacketId>(packet.size(), &preamble);
if (fwrite(preamble.data(), 1, size, fd_) != size)
return false;
for (const Slice& slice : packet.slices()) {
if (fwrite(reinterpret_cast<const char*>(slice.start), 1, slice.size,
fd_) != slice.size) {
return false;
}
}
}
return true;
}
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
class ZipPacketWriter : public PacketWriter {
public:
ZipPacketWriter(std::unique_ptr<PacketWriter>);
~ZipPacketWriter() override;
bool WritePackets(const std::vector<TracePacket>& packets) override;
private:
bool WritePacket(const TracePacket& packet);
void CheckEq(int actual_code, int expected_code);
bool FinalizeCompressedPacket();
inline void Deflate(const char* ptr, size_t size) {
return Deflate(reinterpret_cast<const uint8_t*>(ptr), size);
}
inline void Deflate(const void* ptr, size_t size) {
return Deflate(reinterpret_cast<const uint8_t*>(ptr), size);
}
void Deflate(const uint8_t* ptr, size_t size);
std::unique_ptr<PacketWriter> writer_;
z_stream stream_{};
base::PagedMemory buf_;
uint8_t* const start_;
uint8_t* const end_;
bool is_compressing_ = false;
size_t pending_bytes_ = 0;
};
ZipPacketWriter::ZipPacketWriter(std::unique_ptr<PacketWriter> writer)
: writer_(std::move(writer)),
buf_(base::PagedMemory::Allocate(kMaxPacketSize)),
start_(static_cast<uint8_t*>(buf_.Get())),
end_(start_ + buf_.size()) {}
ZipPacketWriter::~ZipPacketWriter() {
if (is_compressing_)
FinalizeCompressedPacket();
}
bool ZipPacketWriter::WritePackets(const std::vector<TracePacket>& packets) {
for (const TracePacket& packet : packets) {
if (!WritePacket(packet))
return false;
}
return true;
}
bool ZipPacketWriter::WritePacket(const TracePacket& packet) {
// If we have already written one compressed packet, check whether we should
// flush the buffer.
if (is_compressing_) {
// We have two goals:
// - Fit as much data as possible into each packet
// - Ensure each packet is under 512KB
// We keep track of two numbers:
// - the number of remaining bytes in the output buffer
// - the number of (pending) uncompressed bytes written since the last flush
// The pending bytes may or may not have appeared in output buffer.
// Assuming in the worst case each uncompressed input byte can turn into
// two compressed bytes we can ensure we don't go over 512KB by not letting
// the number of pending bytes go over remaining bytes/2 - however often
// each input byte will not turn into 2 output bytes but less than 1 output
// byte - so this underfills the packet. To avoid this every 32kb we deflate
// with Z_SYNC_FLUSH ensuring all pending bytes are present in the output
// buffer.
if (pending_bytes_ > kPendingBytesLimit) {
CheckEq(deflate(&stream_, Z_SYNC_FLUSH), Z_OK);
pending_bytes_ = 0;
}
PERFETTO_DCHECK(end_ >= stream_.next_out);
size_t remaining = static_cast<size_t>(end_ - stream_.next_out);
if ((pending_bytes_ + packet.size() + 1024) * 2 > remaining) {
if (!FinalizeCompressedPacket()) {
return false;
}
}
}
// Reinitialize the compresser if needed:
if (!is_compressing_) {
memset(&stream_, 0, sizeof(stream_));
CheckEq(deflateInit(&stream_, 6), Z_OK);
is_compressing_ = true;
stream_.next_out = start_;
stream_.avail_out = static_cast<unsigned int>(end_ - start_);
}
// Compress the trace packet header:
Preamble packet_hdr;
size_t packet_hdr_size = GetPreamble<kPacketId>(packet.size(), &packet_hdr);
Deflate(packet_hdr.data(), packet_hdr_size);
// Compress the trace packet itself:
for (const Slice& slice : packet.slices()) {
Deflate(slice.start, slice.size);
}
return true;
}
bool ZipPacketWriter::FinalizeCompressedPacket() {
PERFETTO_DCHECK(is_compressing_);
CheckEq(deflate(&stream_, Z_FINISH), Z_STREAM_END);
size_t size = static_cast<size_t>(stream_.next_out - start_);
Preamble preamble;
size_t preamble_size = GetPreamble<kCompressedPacketsId>(size, &preamble);
std::vector<TracePacket> out_packets(1);
TracePacket& out_packet = out_packets[0];
out_packet.AddSlice(preamble.data(), preamble_size);
out_packet.AddSlice(start_, size);
if (!writer_->WritePackets(out_packets))
return false;
is_compressing_ = false;
pending_bytes_ = 0;
CheckEq(deflateEnd(&stream_), Z_OK);
return true;
}
void ZipPacketWriter::CheckEq(int actual_code, int expected_code) {
if (actual_code == expected_code)
return;
PERFETTO_FATAL("Expected %d got %d: %s", actual_code, expected_code,
stream_.msg);
}
void ZipPacketWriter::Deflate(const uint8_t* ptr, size_t size) {
PERFETTO_CHECK(is_compressing_);
stream_.next_in = const_cast<uint8_t*>(ptr);
stream_.avail_in = static_cast<unsigned int>(size);
CheckEq(deflate(&stream_, Z_NO_FLUSH), Z_OK);
PERFETTO_CHECK(stream_.avail_in == 0);
pending_bytes_ += size;
}
#endif // PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
} // namespace
PacketWriter::PacketWriter() {}
PacketWriter::~PacketWriter() {}
std::unique_ptr<PacketWriter> CreateFilePacketWriter(FILE* fd) {
return std::unique_ptr<PacketWriter>(new FilePacketWriter(fd));
}
#if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
std::unique_ptr<PacketWriter> CreateZipPacketWriter(
std::unique_ptr<PacketWriter> writer) {
return std::unique_ptr<PacketWriter>(new ZipPacketWriter(std::move(writer)));
}
#endif
} // namespace perfetto
<|endoftext|>
|
<commit_before>/*
ESP8266 Simple Service Discovery
Copyright (c) 2015 Hristo Gochkov
Original (Arduino) version by Filippo Sallemi, July 23, 2014.
Can be found at: https://github.com/nomadnt/uSSDP
License (MIT license):
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.
*/
#define LWIP_OPEN_SRC
#include <functional>
#include "ESP8266SSDP.h"
#include "WiFiUdp.h"
#include "debug.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "user_interface.h"
}
#include "lwip/opt.h"
#include "lwip/udp.h"
#include "lwip/inet.h"
#include "lwip/igmp.h"
#include "lwip/mem.h"
#include "include/UdpContext.h"
// #define DEBUG_SSDP Serial
#define SSDP_INTERVAL 1200
#define SSDP_PORT 1900
#define SSDP_METHOD_SIZE 10
#define SSDP_URI_SIZE 2
#define SSDP_BUFFER_SIZE 64
#define SSDP_MULTICAST_TTL 2
static const IPAddress SSDP_MULTICAST_ADDR(239, 255, 255, 250);
static const char* _ssdp_response_template =
"HTTP/1.1 200 OK\r\n"
"EXT:\r\n"
"ST: upnp:rootdevice\r\n";
static const char* _ssdp_notify_template =
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"NT: upnp:rootdevice\r\n"
"NTS: ssdp:alive\r\n";
static const char* _ssdp_packet_template =
"%s" // _ssdp_response_template / _ssdp_notify_template
"CACHE-CONTROL: max-age=%u\r\n" // SSDP_INTERVAL
"SERVER: Arduino/1.0 UPNP/1.1 %s/%s\r\n" // _modelName, _modelNumber
"USN: uuid:%s\r\n" // _uuid
"LOCATION: http://%u.%u.%u.%u:%u/%s\r\n" // WiFi.localIP(), _port, _schemaURL
"\r\n";
static const char* _ssdp_schema_template =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/xml\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n"
"<?xml version=\"1.0\"?>"
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
"<specVersion>"
"<major>1</major>"
"<minor>0</minor>"
"</specVersion>"
"<URLBase>http://%u.%u.%u.%u:%u/</URLBase>" // WiFi.localIP(), _port
"<device>"
"<deviceType>%s</deviceType>"
"<friendlyName>%s</friendlyName>"
"<presentationURL>%s</presentationURL>"
"<serialNumber>%s</serialNumber>"
"<modelName>%s</modelName>"
"<modelNumber>%s</modelNumber>"
"<modelURL>%s</modelURL>"
"<manufacturer>%s</manufacturer>"
"<manufacturerURL>%s</manufacturerURL>"
"<UDN>uuid:%s</UDN>"
"</device>"
// "<iconList>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>48</height>"
// "<width>48</width>"
// "<depth>24</depth>"
// "<url>icon48.png</url>"
// "</icon>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>120</height>"
// "<width>120</width>"
// "<depth>24</depth>"
// "<url>icon120.png</url>"
// "</icon>"
// "</iconList>"
"</root>\r\n"
"\r\n";
struct SSDPTimer {
ETSTimer timer;
};
SSDPClass::SSDPClass() :
_server(0),
_timer(new SSDPTimer),
_port(80),
_ttl(SSDP_MULTICAST_TTL),
_respondToPort(0),
_pending(false),
_delay(0),
_process_time(0),
_notify_time(0)
{
_uuid[0] = '\0';
_modelNumber[0] = '\0';
sprintf(_deviceType, "urn:schemas-upnp-org:device:Basic:1");
_friendlyName[0] = '\0';
_presentationURL[0] = '\0';
_serialNumber[0] = '\0';
_modelName[0] = '\0';
_modelURL[0] = '\0';
_manufacturer[0] = '\0';
_manufacturerURL[0] = '\0';
sprintf(_schemaURL, "ssdp/schema.xml");
}
SSDPClass::~SSDPClass(){
delete _timer;
}
bool SSDPClass::begin(){
_pending = false;
uint32_t chipId = ESP.getChipId();
sprintf(_uuid, "38323636-4558-4dda-9188-cda0e6%02x%02x%02x",
(uint16_t) ((chipId >> 16) & 0xff),
(uint16_t) ((chipId >> 8) & 0xff),
(uint16_t) chipId & 0xff );
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("SSDP UUID: %s\n", (char *)_uuid);
#endif
if (_server) {
_server->unref();
_server = 0;
}
_server = new UdpContext;
_server->ref();
ip_addr_t ifaddr;
ifaddr.addr = WiFi.localIP();
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t) SSDP_MULTICAST_ADDR;
if (igmp_joingroup(&ifaddr, &multicast_addr) != ERR_OK ) {
DEBUGV("SSDP failed to join igmp group");
return false;
}
if (!_server->listen(*IP_ADDR_ANY, SSDP_PORT)) {
return false;
}
_server->setMulticastInterface(ifaddr);
_server->setMulticastTTL(_ttl);
_server->onRx(std::bind(&SSDPClass::_update, this));
if (!_server->connect(multicast_addr, SSDP_PORT)) {
return false;
}
_startTimer();
return true;
}
void SSDPClass::_send(ssdp_method_t method){
char buffer[1460];
uint32_t ip = WiFi.localIP();
int len = snprintf(buffer, sizeof(buffer),
_ssdp_packet_template,
(method == NONE)?_ssdp_response_template:_ssdp_notify_template,
SSDP_INTERVAL,
_modelName, _modelNumber,
_uuid,
IP2STR(&ip), _port, _schemaURL
);
_server->append(buffer, len);
ip_addr_t remoteAddr;
uint16_t remotePort;
if(method == NONE) {
remoteAddr.addr = _respondToAddr;
remotePort = _respondToPort;
#ifdef DEBUG_SSDP
DEBUG_SSDP.print("Sending Response to ");
#endif
} else {
remoteAddr.addr = SSDP_MULTICAST_ADDR;
remotePort = SSDP_PORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.println("Sending Notify to ");
#endif
}
#ifdef DEBUG_SSDP
DEBUG_SSDP.print(IPAddress(remoteAddr.addr));
DEBUG_SSDP.print(":");
DEBUG_SSDP.println(remotePort);
#endif
_server->send(&remoteAddr, remotePort);
}
void SSDPClass::schema(WiFiClient client){
uint32_t ip = WiFi.localIP();
client.printf(_ssdp_schema_template,
IP2STR(&ip), _port,
_deviceType,
_friendlyName,
_presentationURL,
_serialNumber,
_modelName,
_modelNumber,
_modelURL,
_manufacturer,
_manufacturerURL,
_uuid
);
}
void SSDPClass::_update(){
if(!_pending && _server->next()) {
ssdp_method_t method = NONE;
_respondToAddr = _server->getRemoteAddress();
_respondToPort = _server->getRemotePort();
typedef enum {METHOD, URI, PROTO, KEY, VALUE, ABORT} states;
states state = METHOD;
typedef enum {START, MAN, ST, MX} headers;
headers header = START;
uint8_t cursor = 0;
uint8_t cr = 0;
char buffer[SSDP_BUFFER_SIZE] = {0};
while(_server->getSize() > 0){
char c = _server->read();
(c == '\r' || c == '\n') ? cr++ : cr = 0;
switch(state){
case METHOD:
if(c == ' '){
if(strcmp(buffer, "M-SEARCH") == 0) method = SEARCH;
else if(strcmp(buffer, "NOTIFY") == 0) method = NOTIFY;
if(method == NONE) state = ABORT;
else state = URI;
cursor = 0;
} else if(cursor < SSDP_METHOD_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case URI:
if(c == ' '){
if(strcmp(buffer, "*")) state = ABORT;
else state = PROTO;
cursor = 0;
} else if(cursor < SSDP_URI_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case PROTO:
if(cr == 2){ state = KEY; cursor = 0; }
break;
case KEY:
if(cr == 4){ _pending = true; _process_time = millis(); }
else if(c == ' '){ cursor = 0; state = VALUE; }
else if(c != '\r' && c != '\n' && c != ':' && cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case VALUE:
if(cr == 2){
switch(header){
case START:
break;
case MAN:
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("MAN: %s\n", (char *)buffer);
#endif
break;
case ST:
if(strcmp(buffer, "ssdp:all")){
state = ABORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("REJECT: %s\n", (char *)buffer);
#endif
}
if(strcmp(buffer, "ssdp:discovery")){
_send(NONE);
state = ABORT;
}
break;
case MX:
_delay = random(0, atoi(buffer)) * 1000L;
break;
}
if(state != ABORT){ state = KEY; header = START; cursor = 0; }
} else if(c != '\r' && c != '\n'){
if(header == START){
if(strncmp(buffer, "MA", 2) == 0) header = MAN;
else if(strcmp(buffer, "ST") == 0) header = ST;
else if(strcmp(buffer, "MX") == 0) header = MX;
}
if(cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
}
break;
case ABORT:
_pending = false; _delay = 0;
break;
}
}
}
if(_pending && (millis() - _process_time) > _delay){
_pending = false; _delay = 0;
_send(NONE);
} else if(_notify_time == 0 || (millis() - _notify_time) > (SSDP_INTERVAL * 1000L)){
_notify_time = millis();
_send(NOTIFY);
}
if (_pending) {
while (_server->next())
_server->flush();
}
}
void SSDPClass::setSchemaURL(const char *url){
strlcpy(_schemaURL, url, sizeof(_schemaURL));
}
void SSDPClass::setHTTPPort(uint16_t port){
_port = port;
}
void SSDPClass::setDeviceType(const char *deviceType){
strlcpy(_deviceType, deviceType, sizeof(_deviceType));
}
void SSDPClass::setName(const char *name){
strlcpy(_friendlyName, name, sizeof(_friendlyName));
}
void SSDPClass::setURL(const char *url){
strlcpy(_presentationURL, url, sizeof(_presentationURL));
}
void SSDPClass::setSerialNumber(const char *serialNumber){
strlcpy(_serialNumber, serialNumber, sizeof(_serialNumber));
}
void SSDPClass::setSerialNumber(const uint32_t serialNumber){
snprintf(_serialNumber, sizeof(uint32_t)*2+1, "%08X", serialNumber);
}
void SSDPClass::setModelName(const char *name){
strlcpy(_modelName, name, sizeof(_modelName));
}
void SSDPClass::setModelNumber(const char *num){
strlcpy(_modelNumber, num, sizeof(_modelNumber));
}
void SSDPClass::setModelURL(const char *url){
strlcpy(_modelURL, url, sizeof(_modelURL));
}
void SSDPClass::setManufacturer(const char *name){
strlcpy(_manufacturer, name, sizeof(_manufacturer));
}
void SSDPClass::setManufacturerURL(const char *url){
strlcpy(_manufacturerURL, url, sizeof(_manufacturerURL));
}
void SSDPClass::setTTL(const uint8_t ttl){
_ttl = ttl;
}
void SSDPClass::_onTimerStatic(SSDPClass* self) {
self->_update();
}
void SSDPClass::_startTimer() {
ETSTimer* tm = &(_timer->timer);
const int interval = 1000;
os_timer_disarm(tm);
os_timer_setfn(tm, reinterpret_cast<ETSTimerFunc*>(&SSDPClass::_onTimerStatic), reinterpret_cast<void*>(this));
os_timer_arm(tm, interval, 1 /* repeat */);
}
SSDPClass SSDP;
<commit_msg>more correctly responding to queries<commit_after>/*
ESP8266 Simple Service Discovery
Copyright (c) 2015 Hristo Gochkov
Original (Arduino) version by Filippo Sallemi, July 23, 2014.
Can be found at: https://github.com/nomadnt/uSSDP
License (MIT license):
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.
*/
#define LWIP_OPEN_SRC
#include <functional>
#include "ESP8266SSDP.h"
#include "WiFiUdp.h"
#include "debug.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "user_interface.h"
}
#include "lwip/opt.h"
#include "lwip/udp.h"
#include "lwip/inet.h"
#include "lwip/igmp.h"
#include "lwip/mem.h"
#include "include/UdpContext.h"
// #define DEBUG_SSDP Serial
#define SSDP_INTERVAL 1200
#define SSDP_PORT 1900
#define SSDP_METHOD_SIZE 10
#define SSDP_URI_SIZE 2
#define SSDP_BUFFER_SIZE 64
#define SSDP_MULTICAST_TTL 2
static const IPAddress SSDP_MULTICAST_ADDR(239, 255, 255, 250);
static const char* _ssdp_response_template =
"HTTP/1.1 200 OK\r\n"
"EXT:\r\n"
"ST: upnp:rootdevice\r\n";
static const char* _ssdp_notify_template =
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"NT: upnp:rootdevice\r\n"
"NTS: ssdp:alive\r\n";
static const char* _ssdp_packet_template =
"%s" // _ssdp_response_template / _ssdp_notify_template
"CACHE-CONTROL: max-age=%u\r\n" // SSDP_INTERVAL
"SERVER: Arduino/1.0 UPNP/1.1 %s/%s\r\n" // _modelName, _modelNumber
"USN: uuid:%s\r\n" // _uuid
"LOCATION: http://%u.%u.%u.%u:%u/%s\r\n" // WiFi.localIP(), _port, _schemaURL
"\r\n";
static const char* _ssdp_schema_template =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/xml\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n"
"<?xml version=\"1.0\"?>"
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
"<specVersion>"
"<major>1</major>"
"<minor>0</minor>"
"</specVersion>"
"<URLBase>http://%u.%u.%u.%u:%u/</URLBase>" // WiFi.localIP(), _port
"<device>"
"<deviceType>%s</deviceType>"
"<friendlyName>%s</friendlyName>"
"<presentationURL>%s</presentationURL>"
"<serialNumber>%s</serialNumber>"
"<modelName>%s</modelName>"
"<modelNumber>%s</modelNumber>"
"<modelURL>%s</modelURL>"
"<manufacturer>%s</manufacturer>"
"<manufacturerURL>%s</manufacturerURL>"
"<UDN>uuid:%s</UDN>"
"</device>"
// "<iconList>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>48</height>"
// "<width>48</width>"
// "<depth>24</depth>"
// "<url>icon48.png</url>"
// "</icon>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>120</height>"
// "<width>120</width>"
// "<depth>24</depth>"
// "<url>icon120.png</url>"
// "</icon>"
// "</iconList>"
"</root>\r\n"
"\r\n";
struct SSDPTimer {
ETSTimer timer;
};
SSDPClass::SSDPClass() :
_server(0),
_timer(new SSDPTimer),
_port(80),
_ttl(SSDP_MULTICAST_TTL),
_respondToPort(0),
_pending(false),
_delay(0),
_process_time(0),
_notify_time(0)
{
_uuid[0] = '\0';
_modelNumber[0] = '\0';
sprintf(_deviceType, "urn:schemas-upnp-org:device:Basic:1");
_friendlyName[0] = '\0';
_presentationURL[0] = '\0';
_serialNumber[0] = '\0';
_modelName[0] = '\0';
_modelURL[0] = '\0';
_manufacturer[0] = '\0';
_manufacturerURL[0] = '\0';
sprintf(_schemaURL, "ssdp/schema.xml");
}
SSDPClass::~SSDPClass(){
delete _timer;
}
bool SSDPClass::begin(){
_pending = false;
uint32_t chipId = ESP.getChipId();
sprintf(_uuid, "38323636-4558-4dda-9188-cda0e6%02x%02x%02x",
(uint16_t) ((chipId >> 16) & 0xff),
(uint16_t) ((chipId >> 8) & 0xff),
(uint16_t) chipId & 0xff );
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("SSDP UUID: %s\n", (char *)_uuid);
#endif
if (_server) {
_server->unref();
_server = 0;
}
_server = new UdpContext;
_server->ref();
ip_addr_t ifaddr;
ifaddr.addr = WiFi.localIP();
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t) SSDP_MULTICAST_ADDR;
if (igmp_joingroup(&ifaddr, &multicast_addr) != ERR_OK ) {
DEBUGV("SSDP failed to join igmp group");
return false;
}
if (!_server->listen(*IP_ADDR_ANY, SSDP_PORT)) {
return false;
}
_server->setMulticastInterface(ifaddr);
_server->setMulticastTTL(_ttl);
_server->onRx(std::bind(&SSDPClass::_update, this));
if (!_server->connect(multicast_addr, SSDP_PORT)) {
return false;
}
_startTimer();
return true;
}
void SSDPClass::_send(ssdp_method_t method){
char buffer[1460];
uint32_t ip = WiFi.localIP();
int len = snprintf(buffer, sizeof(buffer),
_ssdp_packet_template,
(method == NONE)?_ssdp_response_template:_ssdp_notify_template,
SSDP_INTERVAL,
_modelName, _modelNumber,
_uuid,
IP2STR(&ip), _port, _schemaURL
);
_server->append(buffer, len);
ip_addr_t remoteAddr;
uint16_t remotePort;
if(method == NONE) {
remoteAddr.addr = _respondToAddr;
remotePort = _respondToPort;
#ifdef DEBUG_SSDP
DEBUG_SSDP.print("Sending Response to ");
#endif
} else {
remoteAddr.addr = SSDP_MULTICAST_ADDR;
remotePort = SSDP_PORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.println("Sending Notify to ");
#endif
}
#ifdef DEBUG_SSDP
DEBUG_SSDP.print(IPAddress(remoteAddr.addr));
DEBUG_SSDP.print(":");
DEBUG_SSDP.println(remotePort);
#endif
_server->send(&remoteAddr, remotePort);
}
void SSDPClass::schema(WiFiClient client){
uint32_t ip = WiFi.localIP();
client.printf(_ssdp_schema_template,
IP2STR(&ip), _port,
_deviceType,
_friendlyName,
_presentationURL,
_serialNumber,
_modelName,
_modelNumber,
_modelURL,
_manufacturer,
_manufacturerURL,
_uuid
);
}
void SSDPClass::_update(){
if(!_pending && _server->next()) {
ssdp_method_t method = NONE;
_respondToAddr = _server->getRemoteAddress();
_respondToPort = _server->getRemotePort();
typedef enum {METHOD, URI, PROTO, KEY, VALUE, ABORT} states;
states state = METHOD;
typedef enum {START, MAN, ST, MX} headers;
headers header = START;
uint8_t cursor = 0;
uint8_t cr = 0;
char buffer[SSDP_BUFFER_SIZE] = {0};
while(_server->getSize() > 0){
char c = _server->read();
(c == '\r' || c == '\n') ? cr++ : cr = 0;
switch(state){
case METHOD:
if(c == ' '){
if(strcmp(buffer, "M-SEARCH") == 0) method = SEARCH;
else if(strcmp(buffer, "NOTIFY") == 0) method = NOTIFY;
if(method == NONE) state = ABORT;
else state = URI;
cursor = 0;
} else if(cursor < SSDP_METHOD_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case URI:
if(c == ' '){
if(strcmp(buffer, "*")) state = ABORT;
else state = PROTO;
cursor = 0;
} else if(cursor < SSDP_URI_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case PROTO:
if(cr == 2){ state = KEY; cursor = 0; }
break;
case KEY:
if(cr == 4){ _pending = true; _process_time = millis(); }
else if(c == ' '){ cursor = 0; state = VALUE; }
else if(c != '\r' && c != '\n' && c != ':' && cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case VALUE:
if(cr == 2){
switch(header){
case START:
break;
case MAN:
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("MAN: %s\n", (char *)buffer);
#endif
break;
case ST:
if(strcmp(buffer, "ssdp:all")){
state = ABORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("REJECT: %s\n", (char *)buffer);
#endif
}
// if the search type matches our type, we should respond
if(strcmp(buffer, _deviceType)){
_pending = true;
_process_time = millis();
state = KEY;
cursor += strlen(_deviceType);
}
break;
case MX:
_delay = random(0, atoi(buffer)) * 1000L;
break;
}
if(state != ABORT){ state = KEY; header = START; cursor = 0; }
} else if(c != '\r' && c != '\n'){
if(header == START){
if(strncmp(buffer, "MA", 2) == 0) header = MAN;
else if(strcmp(buffer, "ST") == 0) header = ST;
else if(strcmp(buffer, "MX") == 0) header = MX;
}
if(cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
}
break;
case ABORT:
_pending = false; _delay = 0;
break;
}
}
}
if(_pending && (millis() - _process_time) > _delay){
_pending = false; _delay = 0;
_send(NONE);
} else if(_notify_time == 0 || (millis() - _notify_time) > (SSDP_INTERVAL * 1000L)){
_notify_time = millis();
_send(NOTIFY);
}
if (_pending) {
while (_server->next())
_server->flush();
}
}
void SSDPClass::setSchemaURL(const char *url){
strlcpy(_schemaURL, url, sizeof(_schemaURL));
}
void SSDPClass::setHTTPPort(uint16_t port){
_port = port;
}
void SSDPClass::setDeviceType(const char *deviceType){
strlcpy(_deviceType, deviceType, sizeof(_deviceType));
}
void SSDPClass::setName(const char *name){
strlcpy(_friendlyName, name, sizeof(_friendlyName));
}
void SSDPClass::setURL(const char *url){
strlcpy(_presentationURL, url, sizeof(_presentationURL));
}
void SSDPClass::setSerialNumber(const char *serialNumber){
strlcpy(_serialNumber, serialNumber, sizeof(_serialNumber));
}
void SSDPClass::setSerialNumber(const uint32_t serialNumber){
snprintf(_serialNumber, sizeof(uint32_t)*2+1, "%08X", serialNumber);
}
void SSDPClass::setModelName(const char *name){
strlcpy(_modelName, name, sizeof(_modelName));
}
void SSDPClass::setModelNumber(const char *num){
strlcpy(_modelNumber, num, sizeof(_modelNumber));
}
void SSDPClass::setModelURL(const char *url){
strlcpy(_modelURL, url, sizeof(_modelURL));
}
void SSDPClass::setManufacturer(const char *name){
strlcpy(_manufacturer, name, sizeof(_manufacturer));
}
void SSDPClass::setManufacturerURL(const char *url){
strlcpy(_manufacturerURL, url, sizeof(_manufacturerURL));
}
void SSDPClass::setTTL(const uint8_t ttl){
_ttl = ttl;
}
void SSDPClass::_onTimerStatic(SSDPClass* self) {
self->_update();
}
void SSDPClass::_startTimer() {
ETSTimer* tm = &(_timer->timer);
const int interval = 1000;
os_timer_disarm(tm);
os_timer_setfn(tm, reinterpret_cast<ETSTimerFunc*>(&SSDPClass::_onTimerStatic), reinterpret_cast<void*>(this));
os_timer_arm(tm, interval, 1 /* repeat */);
}
SSDPClass SSDP;
<|endoftext|>
|
<commit_before>/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Analyzer part of inline assembly.
*/
#include <libsolidity/inlineasm/AsmAnalysis.h>
#include <libsolidity/inlineasm/AsmData.h>
#include <libsolidity/inlineasm/AsmScopeFiller.h>
#include <libsolidity/inlineasm/AsmScope.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/interface/Utils.h>
#include <boost/range/adaptor/reversed.hpp>
#include <memory>
#include <functional>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;
AsmAnalyzer::AsmAnalyzer(
AsmAnalyzer::Scopes& _scopes,
ErrorList& _errors,
ExternalIdentifierAccess::Resolver const& _resolver
):
m_resolver(_resolver), m_scopes(_scopes), m_errors(_errors)
{
}
bool AsmAnalyzer::analyze(Block const& _block)
{
if (!(ScopeFiller(m_scopes, m_errors))(_block))
return false;
return (*this)(_block);
}
bool AsmAnalyzer::operator()(assembly::Instruction const& _instruction)
{
auto const& info = instructionInfo(_instruction.instruction);
m_stackHeight += info.ret - info.args;
return true;
}
bool AsmAnalyzer::operator()(assembly::Literal const& _literal)
{
++m_stackHeight;
if (!_literal.isNumber && _literal.value.size() > 32)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"String literal too long (" + boost::lexical_cast<std::string>(_literal.value.size()) + " > 32)",
_literal.location
));
return false;
}
return true;
}
bool AsmAnalyzer::operator()(assembly::Identifier const& _identifier)
{
bool success = true;
if (m_currentScope->lookup(_identifier.name, Scope::Visitor(
[&](Scope::Variable const& _var)
{
if (!_var.active)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable " + _identifier.name + " used before it was declared.",
_identifier.location
));
success = false;
}
++m_stackHeight;
},
[&](Scope::Label const&)
{
++m_stackHeight;
},
[&](Scope::Function const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Function " + _identifier.name + " used without being called.",
_identifier.location
));
success = false;
}
)))
{
}
else
{
size_t stackSize(-1);
if (m_resolver)
stackSize = m_resolver(_identifier, IdentifierContext::RValue);
if (stackSize == size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Identifier not found.",
_identifier.location
));
success = false;
}
m_stackHeight += stackSize == size_t(-1) ? 1 : stackSize;
}
return success;
}
bool AsmAnalyzer::operator()(FunctionalInstruction const& _instr)
{
bool success = true;
for (auto const& arg: _instr.arguments | boost::adaptors::reversed)
{
int const stackHeight = m_stackHeight;
if (!boost::apply_visitor(*this, arg))
success = false;
if (!expectDeposit(1, stackHeight, locationOf(arg)))
success = false;
}
// Parser already checks that the number of arguments is correct.
solAssert(instructionInfo(_instr.instruction.instruction).args == int(_instr.arguments.size()), "");
if (!(*this)(_instr.instruction))
success = false;
return success;
}
bool AsmAnalyzer::operator()(assembly::Assignment const& _assignment)
{
return checkAssignment(_assignment.variableName, size_t(-1));
}
bool AsmAnalyzer::operator()(FunctionalAssignment const& _assignment)
{
int const stackHeight = m_stackHeight;
bool success = boost::apply_visitor(*this, *_assignment.value);
solAssert(m_stackHeight >= stackHeight, "Negative value size.");
if (!checkAssignment(_assignment.variableName, m_stackHeight - stackHeight))
success = false;
return success;
}
bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl)
{
bool success = boost::apply_visitor(*this, *_varDecl.value);
boost::get<Scope::Variable>(m_currentScope->identifiers.at(_varDecl.name)).active = true;
return success;
}
bool AsmAnalyzer::operator()(assembly::FunctionDefinition const& _funDef)
{
Scope& bodyScope = scope(&_funDef.body);
for (auto const& var: _funDef.arguments + _funDef.returns)
boost::get<Scope::Variable>(bodyScope.identifiers.at(var)).active = true;
int const stackHeight = m_stackHeight;
m_stackHeight = _funDef.arguments.size() + _funDef.returns.size();
m_virtualVariablesInNextBlock = m_stackHeight;
bool success = (*this)(_funDef.body);
m_stackHeight = stackHeight;
return success;
}
bool AsmAnalyzer::operator()(assembly::FunctionCall const& _funCall)
{
bool success = true;
size_t arguments = 0;
size_t returns = 0;
if (!m_currentScope->lookup(_funCall.functionName.name, Scope::Visitor(
[&](Scope::Variable const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Attempt to call variable instead of function.",
_funCall.functionName.location
));
success = false;
},
[&](Scope::Label const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Attempt to call label instead of function.",
_funCall.functionName.location
));
success = false;
},
[&](Scope::Function const& _fun)
{
arguments = _fun.arguments;
returns = _fun.returns;
}
)))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Function not found.",
_funCall.functionName.location
));
success = false;
}
if (success)
{
if (_funCall.arguments.size() != arguments)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Expected " +
boost::lexical_cast<string>(arguments) +
" arguments but got " +
boost::lexical_cast<string>(_funCall.arguments.size()) +
".",
_funCall.functionName.location
));
success = false;
}
}
for (auto const& arg: _funCall.arguments | boost::adaptors::reversed)
{
int const stackHeight = m_stackHeight;
if (!boost::apply_visitor(*this, arg))
success = false;
if (!expectDeposit(1, stackHeight, locationOf(arg)))
success = false;
}
m_stackHeight += int(returns) - int(arguments);
return success;
}
bool AsmAnalyzer::operator()(Block const& _block)
{
bool success = true;
m_currentScope = &scope(&_block);
int const initialStackHeight = m_stackHeight - m_virtualVariablesInNextBlock;
m_virtualVariablesInNextBlock = 0;
for (auto const& s: _block.statements)
if (!boost::apply_visitor(*this, s))
success = false;
for (auto const& identifier: scope(&_block).identifiers)
if (identifier.second.type() == typeid(Scope::Variable))
--m_stackHeight;
int const stackDiff = m_stackHeight - initialStackHeight;
if (stackDiff != 0)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Unbalanced stack at the end of a block: " +
(
stackDiff > 0 ?
to_string(stackDiff) + string(" surplus item(s).") :
to_string(-stackDiff) + string(" missing item(s).")
),
_block.location
));
success = false;
}
m_currentScope = m_currentScope->superScope;
return success;
}
bool AsmAnalyzer::checkAssignment(assembly::Identifier const& _variable, size_t _valueSize)
{
bool success = true;
size_t variableSize(-1);
if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name))
{
// Check that it is a variable
if (var->type() != typeid(Scope::Variable))
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Assignment requires variable.",
_variable.location
));
success = false;
}
else if (!boost::get<Scope::Variable>(*var).active)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable " + _variable.name + " used before it was declared.",
_variable.location
));
success = false;
}
variableSize = 1;
}
else if (m_resolver)
variableSize = m_resolver(_variable, IdentifierContext::LValue);
if (variableSize == size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable not found or variable not lvalue.",
_variable.location
));
success = false;
}
if (_valueSize == size_t(-1))
_valueSize = variableSize == size_t(-1) ? 1 : variableSize;
m_stackHeight -= _valueSize;
if (_valueSize != variableSize && variableSize != size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Variable size (" +
to_string(variableSize) +
") and value size (" +
to_string(_valueSize) +
") do not match.",
_variable.location
));
success = false;
}
return success;
}
bool AsmAnalyzer::expectDeposit(int const _deposit, int const _oldHeight, SourceLocation const& _location)
{
int stackDiff = m_stackHeight - _oldHeight;
if (stackDiff != _deposit)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Expected instruction(s) to deposit " +
boost::lexical_cast<string>(_deposit) +
" item(s) to the stack, but did deposit " +
boost::lexical_cast<string>(stackDiff) +
" item(s).",
_location
));
return false;
}
else
return true;
}
Scope& AsmAnalyzer::scope(Block const* _block)
{
auto scopePtr = m_scopes.at(_block);
solAssert(scopePtr, "Scope requested but not present.");
return *scopePtr;
}
<commit_msg>Another stack check.<commit_after>/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Analyzer part of inline assembly.
*/
#include <libsolidity/inlineasm/AsmAnalysis.h>
#include <libsolidity/inlineasm/AsmData.h>
#include <libsolidity/inlineasm/AsmScopeFiller.h>
#include <libsolidity/inlineasm/AsmScope.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/interface/Utils.h>
#include <boost/range/adaptor/reversed.hpp>
#include <memory>
#include <functional>
using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;
AsmAnalyzer::AsmAnalyzer(
AsmAnalyzer::Scopes& _scopes,
ErrorList& _errors,
ExternalIdentifierAccess::Resolver const& _resolver
):
m_resolver(_resolver), m_scopes(_scopes), m_errors(_errors)
{
}
bool AsmAnalyzer::analyze(Block const& _block)
{
if (!(ScopeFiller(m_scopes, m_errors))(_block))
return false;
return (*this)(_block);
}
bool AsmAnalyzer::operator()(assembly::Instruction const& _instruction)
{
auto const& info = instructionInfo(_instruction.instruction);
m_stackHeight += info.ret - info.args;
return true;
}
bool AsmAnalyzer::operator()(assembly::Literal const& _literal)
{
++m_stackHeight;
if (!_literal.isNumber && _literal.value.size() > 32)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"String literal too long (" + boost::lexical_cast<std::string>(_literal.value.size()) + " > 32)",
_literal.location
));
return false;
}
return true;
}
bool AsmAnalyzer::operator()(assembly::Identifier const& _identifier)
{
bool success = true;
if (m_currentScope->lookup(_identifier.name, Scope::Visitor(
[&](Scope::Variable const& _var)
{
if (!_var.active)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable " + _identifier.name + " used before it was declared.",
_identifier.location
));
success = false;
}
++m_stackHeight;
},
[&](Scope::Label const&)
{
++m_stackHeight;
},
[&](Scope::Function const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Function " + _identifier.name + " used without being called.",
_identifier.location
));
success = false;
}
)))
{
}
else
{
size_t stackSize(-1);
if (m_resolver)
stackSize = m_resolver(_identifier, IdentifierContext::RValue);
if (stackSize == size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Identifier not found.",
_identifier.location
));
success = false;
}
m_stackHeight += stackSize == size_t(-1) ? 1 : stackSize;
}
return success;
}
bool AsmAnalyzer::operator()(FunctionalInstruction const& _instr)
{
bool success = true;
for (auto const& arg: _instr.arguments | boost::adaptors::reversed)
{
int const stackHeight = m_stackHeight;
if (!boost::apply_visitor(*this, arg))
success = false;
if (!expectDeposit(1, stackHeight, locationOf(arg)))
success = false;
}
// Parser already checks that the number of arguments is correct.
solAssert(instructionInfo(_instr.instruction.instruction).args == int(_instr.arguments.size()), "");
if (!(*this)(_instr.instruction))
success = false;
return success;
}
bool AsmAnalyzer::operator()(assembly::Assignment const& _assignment)
{
return checkAssignment(_assignment.variableName, size_t(-1));
}
bool AsmAnalyzer::operator()(FunctionalAssignment const& _assignment)
{
int const stackHeight = m_stackHeight;
bool success = boost::apply_visitor(*this, *_assignment.value);
solAssert(m_stackHeight >= stackHeight, "Negative value size.");
if (!checkAssignment(_assignment.variableName, m_stackHeight - stackHeight))
success = false;
return success;
}
bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl)
{
int const stackHeight = m_stackHeight;
bool success = boost::apply_visitor(*this, *_varDecl.value);
solAssert(m_stackHeight - stackHeight == 1, "Invalid value size.");
boost::get<Scope::Variable>(m_currentScope->identifiers.at(_varDecl.name)).active = true;
return success;
}
bool AsmAnalyzer::operator()(assembly::FunctionDefinition const& _funDef)
{
Scope& bodyScope = scope(&_funDef.body);
for (auto const& var: _funDef.arguments + _funDef.returns)
boost::get<Scope::Variable>(bodyScope.identifiers.at(var)).active = true;
int const stackHeight = m_stackHeight;
m_stackHeight = _funDef.arguments.size() + _funDef.returns.size();
m_virtualVariablesInNextBlock = m_stackHeight;
bool success = (*this)(_funDef.body);
m_stackHeight = stackHeight;
return success;
}
bool AsmAnalyzer::operator()(assembly::FunctionCall const& _funCall)
{
bool success = true;
size_t arguments = 0;
size_t returns = 0;
if (!m_currentScope->lookup(_funCall.functionName.name, Scope::Visitor(
[&](Scope::Variable const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Attempt to call variable instead of function.",
_funCall.functionName.location
));
success = false;
},
[&](Scope::Label const&)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Attempt to call label instead of function.",
_funCall.functionName.location
));
success = false;
},
[&](Scope::Function const& _fun)
{
arguments = _fun.arguments;
returns = _fun.returns;
}
)))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Function not found.",
_funCall.functionName.location
));
success = false;
}
if (success)
{
if (_funCall.arguments.size() != arguments)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Expected " +
boost::lexical_cast<string>(arguments) +
" arguments but got " +
boost::lexical_cast<string>(_funCall.arguments.size()) +
".",
_funCall.functionName.location
));
success = false;
}
}
for (auto const& arg: _funCall.arguments | boost::adaptors::reversed)
{
int const stackHeight = m_stackHeight;
if (!boost::apply_visitor(*this, arg))
success = false;
if (!expectDeposit(1, stackHeight, locationOf(arg)))
success = false;
}
m_stackHeight += int(returns) - int(arguments);
return success;
}
bool AsmAnalyzer::operator()(Block const& _block)
{
bool success = true;
m_currentScope = &scope(&_block);
int const initialStackHeight = m_stackHeight - m_virtualVariablesInNextBlock;
m_virtualVariablesInNextBlock = 0;
for (auto const& s: _block.statements)
if (!boost::apply_visitor(*this, s))
success = false;
for (auto const& identifier: scope(&_block).identifiers)
if (identifier.second.type() == typeid(Scope::Variable))
--m_stackHeight;
int const stackDiff = m_stackHeight - initialStackHeight;
if (stackDiff != 0)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Unbalanced stack at the end of a block: " +
(
stackDiff > 0 ?
to_string(stackDiff) + string(" surplus item(s).") :
to_string(-stackDiff) + string(" missing item(s).")
),
_block.location
));
success = false;
}
m_currentScope = m_currentScope->superScope;
return success;
}
bool AsmAnalyzer::checkAssignment(assembly::Identifier const& _variable, size_t _valueSize)
{
bool success = true;
size_t variableSize(-1);
if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name))
{
// Check that it is a variable
if (var->type() != typeid(Scope::Variable))
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Assignment requires variable.",
_variable.location
));
success = false;
}
else if (!boost::get<Scope::Variable>(*var).active)
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable " + _variable.name + " used before it was declared.",
_variable.location
));
success = false;
}
variableSize = 1;
}
else if (m_resolver)
variableSize = m_resolver(_variable, IdentifierContext::LValue);
if (variableSize == size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::DeclarationError,
"Variable not found or variable not lvalue.",
_variable.location
));
success = false;
}
if (_valueSize == size_t(-1))
_valueSize = variableSize == size_t(-1) ? 1 : variableSize;
m_stackHeight -= _valueSize;
if (_valueSize != variableSize && variableSize != size_t(-1))
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Variable size (" +
to_string(variableSize) +
") and value size (" +
to_string(_valueSize) +
") do not match.",
_variable.location
));
success = false;
}
return success;
}
bool AsmAnalyzer::expectDeposit(int const _deposit, int const _oldHeight, SourceLocation const& _location)
{
int stackDiff = m_stackHeight - _oldHeight;
if (stackDiff != _deposit)
{
m_errors.push_back(make_shared<Error>(
Error::Type::TypeError,
"Expected instruction(s) to deposit " +
boost::lexical_cast<string>(_deposit) +
" item(s) to the stack, but did deposit " +
boost::lexical_cast<string>(stackDiff) +
" item(s).",
_location
));
return false;
}
else
return true;
}
Scope& AsmAnalyzer::scope(Block const* _block)
{
auto scopePtr = m_scopes.at(_block);
solAssert(scopePtr, "Scope requested but not present.");
return *scopePtr;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2014 P.L. Lucas <selairi@gmail.com>
Copyright (C) 2014 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
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 "monitorwidget.h"
#include <QComboBox>
#include <QStringBuilder>
#include <QDialogButtonBox>
#include <KScreen/EDID>
QString modeToString(KScreen::ModePtr mode)
{
// mode->name() can be anything, not just widthxheight. eg if added with cvt.
return QString("%1x%2").arg(mode->size().width()).arg(mode->size().height());
}
KScreen::OutputPtr getOutputById(int id, KScreen::OutputList outputs)
{
for (const KScreen::OutputPtr &output : outputs)
if (output->id() == id)
return output;
return KScreen::OutputPtr(nullptr);
}
KScreen::ModePtr getModeById(QString id, KScreen::ModeList modes)
{
for (const KScreen::ModePtr &mode : modes)
if (mode->id() == id)
return mode;
return KScreen::ModePtr(NULL);
}
static bool sizeBiggerThan(const KScreen::ModePtr &modeA, const KScreen::ModePtr &modeB)
{
QSize sizeA = modeA->size();
QSize sizeB = modeB->size();
return sizeA.width() * sizeA.height() > sizeB.width() * sizeB.height();
}
MonitorWidget::MonitorWidget(KScreen::OutputPtr output, KScreen::ConfigPtr config, QWidget* parent) :
QGroupBox(parent)
{
this->output = output;
this->config = config;
ui.setupUi(this);
ui.enabledCheckbox->setChecked(output->isEnabled());
QList <KScreen::ModePtr> modeList = output->modes().values();
// Remove duplicate sizes
QMap<QString, KScreen::ModePtr> noDuplicateModes;
foreach(const KScreen::ModePtr &mode, modeList)
{
if( noDuplicateModes.keys().contains(modeToString(mode)) )
{
KScreen::ModePtr actual = noDuplicateModes[modeToString(mode)];
bool isActualPreferred = output->preferredModes().contains(actual->id());
bool isModePreferred = output->preferredModes().contains(mode->id());
if( ( mode->refreshRate() > actual->refreshRate() && !isActualPreferred ) || isModePreferred )
noDuplicateModes[modeToString(mode)] = mode;
}
else
noDuplicateModes[modeToString(mode)] = mode;
}
// Sort modes by size
modeList = noDuplicateModes.values();
qSort(modeList.begin(), modeList.end(), sizeBiggerThan);
// Add each mode to the list
foreach (const KScreen::ModePtr &mode, modeList)
{
ui.resolutionCombo->addItem(modeToString(mode), mode->id());
if(output->preferredModes().contains(mode->id()))
{
// Make bold preferredModes
QFont font = ui.resolutionCombo->font();
font.setBold(true);
ui.resolutionCombo->setItemData(ui.resolutionCombo->count()-1, font, Qt::FontRole);
}
}
connect(ui.resolutionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onResolutionChanged(int)));
// Select actual mode in list
if (output->currentMode())
{
// Set the current mode in dropdown
int idx = ui.resolutionCombo->findData(output->currentMode()->id());
if (idx < 0)
{
// Select mode with same size
foreach (const KScreen::ModePtr &mode, modeList)
{
if( mode->size() == output->currentMode()->size() )
idx = ui.resolutionCombo->findData(output->currentMode()->id());
}
}
if(idx < 0)
idx = ui.resolutionCombo->findData(output->preferredMode()->id());
if (idx >= 0)
ui.resolutionCombo->setCurrentIndex(idx);
}
updateRefreshRates();
// Update EDID information
// KScreen doesn't make much public but that's ok...
KScreen::Edid* edid = output->edid();
if (edid && edid->isValid())
{
ui.outputInfoLabel->setText(
tr("Name: %1\n").arg(edid->name()) %
tr("Vendor: %1\n").arg(edid->vendor()) %
tr("Serial: %1\n").arg(edid->serial()) %
tr("Display size: %1cm x %2cm\n").arg(edid->width()).arg(edid->height()) %
tr("Serial number: %1\n").arg(edid->serial()) %
tr("EISA device ID: %1\n").arg(edid->eisaId())
);
}
if (config->connectedOutputs().count() == 1)
{
setOnlyMonitor(true);
// There isn't always a primary output. Gross.
output->setPrimary(true);
}
ui.xPosSpinBox->setValue(output->pos().x());
ui.yPosSpinBox->setValue(output->pos().y());
// Behavior chooser
if (output->isPrimary())
ui.behaviorCombo->setCurrentIndex(PrimaryDisplay);
// Insert orientations
ui.orientationCombo->addItem(tr("None"), KScreen::Output::None);
ui.orientationCombo->addItem(tr("Left"), KScreen::Output::Left);
ui.orientationCombo->addItem(tr("Right"), KScreen::Output::Right);
ui.orientationCombo->addItem(tr("Inverted"), KScreen::Output::Inverted);
switch(output->rotation())
{
case KScreen::Output::None:
ui.orientationCombo->setCurrentIndex(0);
break;
case KScreen::Output::Left:
ui.orientationCombo->setCurrentIndex(1);
break;
case KScreen::Output::Right:
ui.orientationCombo->setCurrentIndex(2);
break;
case KScreen::Output::Inverted:
ui.orientationCombo->setCurrentIndex(3);
break;
}
connect(ui.enabledCheckbox, SIGNAL(toggled(bool)), this, SLOT(onEnabledChanged(bool)));
connect(ui.behaviorCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onBehaviorChanged(int)));
connect(ui.xPosSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onPositionChanged(int)));
connect(ui.yPosSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onPositionChanged(int)));
connect(ui.orientationCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onOrientationChanged(int)));
// Force update behavior visibility
onBehaviorChanged(ui.behaviorCombo->currentIndex());
}
MonitorWidget::~MonitorWidget()
{
}
void MonitorWidget::onEnabledChanged(bool enabled)
{
output->setEnabled(enabled);
// If we're enabling a disabled output for the first time
if (enabled && !output->currentMode())
{
// order here matters
onResolutionChanged(ui.resolutionCombo->currentIndex());
onOrientationChanged(ui.orientationCombo->currentIndex());
onBehaviorChanged(ui.behaviorCombo->currentIndex());
}
}
void MonitorWidget::onOrientationChanged(int idx)
{
output->setRotation((KScreen::Output::Rotation) ui.orientationCombo->currentData().toInt(0));
}
void MonitorWidget::onBehaviorChanged(int idx)
{
// Behavior should match the index of the selected element
ui.xPosSpinBox->setVisible(idx == ExtendDisplay);
ui.yPosSpinBox->setVisible(idx == ExtendDisplay);
output->setPrimary(idx == PrimaryDisplay);
if(idx == PrimaryDisplay)
emit primaryOutputChanged(this);
}
void MonitorWidget::onPositionChanged(int value)
{
output->setPos(QPoint(ui.xPosSpinBox->value(), ui.yPosSpinBox->value()));
}
void MonitorWidget::onResolutionChanged(int index)
{
output->setCurrentModeId(ui.resolutionCombo->currentData().toString());
updateRefreshRates();
}
void MonitorWidget::onRateChanged(int index)
{
output->setCurrentModeId(ui.rateCombo->currentData().toString());
}
void MonitorWidget::updateRefreshRates()
{
disconnect(ui.rateCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onRateChanged(int)));
ui.rateCombo->clear();
if (output->modes().size() < 0)
return;
KScreen::ModePtr selectedMode = output->currentMode();
if (selectedMode)
{
for (const KScreen::ModePtr &mode : output->modes())
if (mode->size() == selectedMode->size())
ui.rateCombo->addItem(tr("%1 Hz").arg(mode->refreshRate()), mode->id());
int idx = ui.rateCombo->findData(selectedMode->id());
if (idx >= 0)
ui.rateCombo->setCurrentIndex(idx);
}
connect(ui.rateCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onRateChanged(int)));
}
void MonitorWidget::setOnlyMonitor(bool isOnlyMonitor)
{
ui.enabledCheckbox->setEnabled(!isOnlyMonitor);
ui.behaviorCombo->setEnabled(!isOnlyMonitor);
ui.xPosSpinBox->setVisible(!isOnlyMonitor);
ui.yPosSpinBox->setVisible(!isOnlyMonitor);
if(isOnlyMonitor)
{
ui.xPosSpinBox->setValue(0);
ui.yPosSpinBox->setValue(0);
}
}
void MonitorWidget::onPrimaryOutputChanged(MonitorWidget *widget)
{
if(widget == this)
return;
ui.behaviorCombo->setCurrentIndex(ExtendDisplay);
}
<commit_msg>Show non-primary screens in UI. (#116)<commit_after>/*
Copyright (C) 2014 P.L. Lucas <selairi@gmail.com>
Copyright (C) 2014 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
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 "monitorwidget.h"
#include <QComboBox>
#include <QStringBuilder>
#include <QDialogButtonBox>
#include <KScreen/EDID>
QString modeToString(KScreen::ModePtr mode)
{
// mode->name() can be anything, not just widthxheight. eg if added with cvt.
return QString("%1x%2").arg(mode->size().width()).arg(mode->size().height());
}
KScreen::OutputPtr getOutputById(int id, KScreen::OutputList outputs)
{
for (const KScreen::OutputPtr &output : outputs)
if (output->id() == id)
return output;
return KScreen::OutputPtr(nullptr);
}
KScreen::ModePtr getModeById(QString id, KScreen::ModeList modes)
{
for (const KScreen::ModePtr &mode : modes)
if (mode->id() == id)
return mode;
return KScreen::ModePtr(NULL);
}
static bool sizeBiggerThan(const KScreen::ModePtr &modeA, const KScreen::ModePtr &modeB)
{
QSize sizeA = modeA->size();
QSize sizeB = modeB->size();
return sizeA.width() * sizeA.height() > sizeB.width() * sizeB.height();
}
MonitorWidget::MonitorWidget(KScreen::OutputPtr output, KScreen::ConfigPtr config, QWidget* parent) :
QGroupBox(parent)
{
this->output = output;
this->config = config;
ui.setupUi(this);
ui.enabledCheckbox->setChecked(output->isEnabled());
QList <KScreen::ModePtr> modeList = output->modes().values();
// Remove duplicate sizes
QMap<QString, KScreen::ModePtr> noDuplicateModes;
foreach(const KScreen::ModePtr &mode, modeList)
{
if( noDuplicateModes.keys().contains(modeToString(mode)) )
{
KScreen::ModePtr actual = noDuplicateModes[modeToString(mode)];
bool isActualPreferred = output->preferredModes().contains(actual->id());
bool isModePreferred = output->preferredModes().contains(mode->id());
if( ( mode->refreshRate() > actual->refreshRate() && !isActualPreferred ) || isModePreferred )
noDuplicateModes[modeToString(mode)] = mode;
}
else
noDuplicateModes[modeToString(mode)] = mode;
}
// Sort modes by size
modeList = noDuplicateModes.values();
qSort(modeList.begin(), modeList.end(), sizeBiggerThan);
// Add each mode to the list
foreach (const KScreen::ModePtr &mode, modeList)
{
ui.resolutionCombo->addItem(modeToString(mode), mode->id());
if(output->preferredModes().contains(mode->id()))
{
// Make bold preferredModes
QFont font = ui.resolutionCombo->font();
font.setBold(true);
ui.resolutionCombo->setItemData(ui.resolutionCombo->count()-1, font, Qt::FontRole);
}
}
connect(ui.resolutionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onResolutionChanged(int)));
// Select actual mode in list
if (output->currentMode())
{
// Set the current mode in dropdown
int idx = ui.resolutionCombo->findData(output->currentMode()->id());
if (idx < 0)
{
// Select mode with same size
foreach (const KScreen::ModePtr &mode, modeList)
{
if( mode->size() == output->currentMode()->size() )
idx = ui.resolutionCombo->findData(output->currentMode()->id());
}
}
if(idx < 0)
idx = ui.resolutionCombo->findData(output->preferredMode()->id());
if (idx >= 0)
ui.resolutionCombo->setCurrentIndex(idx);
}
updateRefreshRates();
// Update EDID information
// KScreen doesn't make much public but that's ok...
KScreen::Edid* edid = output->edid();
if (edid && edid->isValid())
{
ui.outputInfoLabel->setText(
tr("Name: %1\n").arg(edid->name()) %
tr("Vendor: %1\n").arg(edid->vendor()) %
tr("Serial: %1\n").arg(edid->serial()) %
tr("Display size: %1cm x %2cm\n").arg(edid->width()).arg(edid->height()) %
tr("Serial number: %1\n").arg(edid->serial()) %
tr("EISA device ID: %1\n").arg(edid->eisaId())
);
}
if (config->connectedOutputs().count() == 1)
{
setOnlyMonitor(true);
// There isn't always a primary output. Gross.
output->setPrimary(true);
}
ui.xPosSpinBox->setValue(output->pos().x());
ui.yPosSpinBox->setValue(output->pos().y());
// Behavior chooser
if (output->isPrimary())
ui.behaviorCombo->setCurrentIndex(PrimaryDisplay);
else
ui.behaviorCombo->setCurrentIndex(ExtendDisplay);
// Insert orientations
ui.orientationCombo->addItem(tr("None"), KScreen::Output::None);
ui.orientationCombo->addItem(tr("Left"), KScreen::Output::Left);
ui.orientationCombo->addItem(tr("Right"), KScreen::Output::Right);
ui.orientationCombo->addItem(tr("Inverted"), KScreen::Output::Inverted);
switch(output->rotation())
{
case KScreen::Output::None:
ui.orientationCombo->setCurrentIndex(0);
break;
case KScreen::Output::Left:
ui.orientationCombo->setCurrentIndex(1);
break;
case KScreen::Output::Right:
ui.orientationCombo->setCurrentIndex(2);
break;
case KScreen::Output::Inverted:
ui.orientationCombo->setCurrentIndex(3);
break;
}
connect(ui.enabledCheckbox, SIGNAL(toggled(bool)), this, SLOT(onEnabledChanged(bool)));
connect(ui.behaviorCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onBehaviorChanged(int)));
connect(ui.xPosSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onPositionChanged(int)));
connect(ui.yPosSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onPositionChanged(int)));
connect(ui.orientationCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onOrientationChanged(int)));
// Force update behavior visibility
onBehaviorChanged(ui.behaviorCombo->currentIndex());
}
MonitorWidget::~MonitorWidget()
{
}
void MonitorWidget::onEnabledChanged(bool enabled)
{
output->setEnabled(enabled);
// If we're enabling a disabled output for the first time
if (enabled && !output->currentMode())
{
// order here matters
onResolutionChanged(ui.resolutionCombo->currentIndex());
onOrientationChanged(ui.orientationCombo->currentIndex());
onBehaviorChanged(ui.behaviorCombo->currentIndex());
}
}
void MonitorWidget::onOrientationChanged(int idx)
{
output->setRotation((KScreen::Output::Rotation) ui.orientationCombo->currentData().toInt(0));
}
void MonitorWidget::onBehaviorChanged(int idx)
{
// Behavior should match the index of the selected element
ui.xPosSpinBox->setVisible(idx == ExtendDisplay);
ui.yPosSpinBox->setVisible(idx == ExtendDisplay);
output->setPrimary(idx == PrimaryDisplay);
if(idx == PrimaryDisplay)
emit primaryOutputChanged(this);
}
void MonitorWidget::onPositionChanged(int value)
{
output->setPos(QPoint(ui.xPosSpinBox->value(), ui.yPosSpinBox->value()));
}
void MonitorWidget::onResolutionChanged(int index)
{
output->setCurrentModeId(ui.resolutionCombo->currentData().toString());
updateRefreshRates();
}
void MonitorWidget::onRateChanged(int index)
{
output->setCurrentModeId(ui.rateCombo->currentData().toString());
}
void MonitorWidget::updateRefreshRates()
{
disconnect(ui.rateCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onRateChanged(int)));
ui.rateCombo->clear();
if (output->modes().size() < 0)
return;
KScreen::ModePtr selectedMode = output->currentMode();
if (selectedMode)
{
for (const KScreen::ModePtr &mode : output->modes())
if (mode->size() == selectedMode->size())
ui.rateCombo->addItem(tr("%1 Hz").arg(mode->refreshRate()), mode->id());
int idx = ui.rateCombo->findData(selectedMode->id());
if (idx >= 0)
ui.rateCombo->setCurrentIndex(idx);
}
connect(ui.rateCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onRateChanged(int)));
}
void MonitorWidget::setOnlyMonitor(bool isOnlyMonitor)
{
ui.enabledCheckbox->setEnabled(!isOnlyMonitor);
ui.behaviorCombo->setEnabled(!isOnlyMonitor);
ui.xPosSpinBox->setVisible(!isOnlyMonitor);
ui.yPosSpinBox->setVisible(!isOnlyMonitor);
if(isOnlyMonitor)
{
ui.xPosSpinBox->setValue(0);
ui.yPosSpinBox->setValue(0);
}
}
void MonitorWidget::onPrimaryOutputChanged(MonitorWidget *widget)
{
if(widget == this)
return;
ui.behaviorCombo->setCurrentIndex(ExtendDisplay);
}
<|endoftext|>
|
<commit_before>// Copyright 2020 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 "google/cloud/spanner/client.h"
#include <iostream>
#include <stdexcept>
#include <chrono>
namespace {
namespace spanner = ::google::cloud::spanner;
using google::cloud::StatusOr;
const std::int64_t DEFAULTGAP = 100;
const std::int64_t BATCHSIZE = 1000;
void batchUpdateData(spanner::Client readClient, spanner::Client writeClient,
std::int64_t batchSize) {
auto rows = readClient.Read("TestModels", spanner::KeySet::All(),
{"CdsId", "TrainingTime"});
using RowType = std::tuple<std::int64_t, spanner::Timestamp>;
// A helper to read a single Timestamp.
const auto& get_expiration_time =
[](spanner::Client client, std::int64_t cdsId)
-> StatusOr<spanner::Timestamp> {
auto key = spanner::KeySet().AddKey(spanner::MakeKey(cdsId));
auto rows = client.Read("TestModels", std::move(key),
{"ExpirationTime"});
using RowType = std::tuple<spanner::Timestamp>;
auto row = spanner::GetSingularRow(spanner::StreamOf<RowType>(rows));
if (!row) return std::move(row).status();
return std::get<0>(*std::move(row));
};
spanner::Mutations mutations;
std::int64_t i = 0;
for(const auto& row : spanner::StreamOf<RowType>(rows)) {
if(!row) throw std::runtime_error(row.status().message());
i += 1;
std::int64_t cdsId = std::get<0>(*row);
spanner::Timestamp trainingTime = std::get<1>(*row);
// auto expirationTime = get_expiration_time(readClient, cdsId);
// if(!expirationTime) {
spanner::sys_time<std::chrono::nanoseconds> expirationNS =
trainingTime.get<spanner::sys_time<std::chrono::nanoseconds>>().value()
+ 60*std::chrono::hours(24);
spanner::Timestamp newExpirationTime = spanner::MakeTimestamp(expirationNS).value();
mutations.push_back(spanner::UpdateMutationBuilder(
"TestModels", {"CdsId", "ExpirationTime", "TrainingTime"})
.EmplaceRow(cdsId, newExpirationTime, trainingTime)
.Build());
if(i % batchSize == 0) {
auto commit_result = writeClient.Commit(mutations);
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
mutations.clear();
i = 0;
}
// }
// else: check validity
}
}
void batchInsertData(google::cloud::spanner::Client client, std::int64_t batchSize) {
namespace spanner = ::google::cloud::spanner;
using ::google::cloud::StatusOr;
auto commit_result = client.Commit(
[&client, &batchSize](
spanner::Transaction const& txn) -> StatusOr<spanner::Mutations> {
spanner::Mutations mutations;
spanner::sys_time<std::chrono::nanoseconds> trainingNS = std::chrono::system_clock::now();
spanner::Timestamp trainingTime = spanner::MakeTimestamp(trainingNS).value();
for(std::int64_t i = 3; i <= batchSize; i++) {
mutations.push_back(spanner::InsertMutationBuilder(
"TestModels", {"CdsId", "TrainingTime"})
.EmplaceRow(i, trainingTime)
.Build());
}
return mutations;
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
}
} // namespace
int main(int argc, char* argv[]) try {
if (argc != 4) {
std::cerr << "Usage: " << argv[0]
<< " project-id instance-id database-id\n";
return 1;
}
spanner::Client readClient(
spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3])));
spanner::Client writeClient(
spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3])));
auto start = std::chrono::high_resolution_clock::now();
batchUpdateData(readClient, writeClient, BATCHSIZE);
// batchInsertData(writeClient, BATCHSIZE);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start);
std::cout <<
"Time taken : " << duration.count() << " milliseconds" << std::endl;
return 1;
} catch (std::exception const& ex) {
std::cerr << "Standard exception raised: " << ex.what() << "\n";
return 1;
}<commit_msg>update with check<commit_after>// Copyright 2020 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 "google/cloud/spanner/client.h"
#include <iostream>
#include <stdexcept>
#include <chrono>
namespace {
namespace spanner = ::google::cloud::spanner;
using google::cloud::StatusOr;
const std::int64_t DEFAULTGAP = 100;
const std::int64_t BATCHSIZE = 1000;
void batchUpdateData(spanner::Client readClient, spanner::Client writeClient,
std::int64_t batchSize) {
auto rows = readClient.Read("TestModels", spanner::KeySet::All(),
{"CdsId", "ExpirationTime", "TrainingTime"});
spanner::Mutations mutations;
std::int64_t i = 0;
for(const auto& row : rows) {
if(!row) throw std::runtime_error(row.status().message());
spanner::Value cds = (*row).get(0).value();
spanner::Value expiration = (*row).get(1).value();
spanner::Value training = (*row).get(2).value();
std::int64_t cdsId = cds.get<std::int64_t>().value();
StatusOr<spanner::Timestamp> expirationTime = expiration.get<spanner::Timestamp>();
StatusOr<spanner::Timestamp> trainingTime = training.get<spanner::Timestamp>();
if(!trainingTime) {
throw std::runtime_error("TrainingTime shouldn't be null.");
}
if(expirationTime) {
spanner::sys_time<std::chrono::nanoseconds> trainingNS =
(*expirationTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value()
- 60*std::chrono::hours(24);
spanner::Timestamp supposedTraining = spanner::MakeTimestamp(trainingNS).value();
if(*trainingTime != supposedTraining) {
throw std::runtime_error("Time gap for " + std::to_string(cdsId) + " is not correct.");
}
}
else {
spanner::sys_time<std::chrono::nanoseconds> expirationNS =
(*trainingTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value()
+ 60*std::chrono::hours(24);
spanner::Timestamp newExpiration = spanner::MakeTimestamp(expirationNS).value();
mutations.push_back(spanner::UpdateMutationBuilder(
"TestModels", {"CdsId", "ExpirationTime", "TrainingTime"})
.EmplaceRow(cdsId, newExpiration, *trainingTime)
.Build());
++i;
if(i % batchSize == 0) {
auto commit_result = writeClient.Commit(mutations);
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
mutations.clear();
i = 0;
}
}
}
}
void batchInsertData(google::cloud::spanner::Client client, std::int64_t batchSize) {
namespace spanner = ::google::cloud::spanner;
using ::google::cloud::StatusOr;
auto commit_result = client.Commit(
[&client, &batchSize](
spanner::Transaction const& txn) -> StatusOr<spanner::Mutations> {
spanner::Mutations mutations;
spanner::sys_time<std::chrono::nanoseconds> trainingNS = std::chrono::system_clock::now();
spanner::Timestamp trainingTime = spanner::MakeTimestamp(trainingNS).value();
for(std::int64_t i = 3; i <= batchSize; i++) {
mutations.push_back(spanner::InsertMutationBuilder(
"TestModels", {"CdsId", "TrainingTime"})
.EmplaceRow(i, trainingTime)
.Build());
}
return mutations;
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
}
} // namespace
int main(int argc, char* argv[]) try {
if (argc != 4) {
std::cerr << "Usage: " << argv[0]
<< " project-id instance-id database-id\n";
return 1;
}
spanner::Client readClient(
spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3])));
spanner::Client writeClient(
spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3])));
auto start = std::chrono::high_resolution_clock::now();
batchUpdateData(readClient, writeClient, BATCHSIZE);
// batchInsertData(writeClient, BATCHSIZE);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start);
std::cout <<
"Time taken : " << duration.count() << " milliseconds" << std::endl;
return 1;
} catch (std::exception const& ex) {
std::cerr << "Standard exception raised: " << ex.what() << "\n";
return 1;
}<|endoftext|>
|
<commit_before>// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDFEOS5CFMissLLArray.cc
/// \brief The implementation of the retrieval of the missing lat/lon values for HDF-EOS5 products
///
/// \author Kent Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
#include "config_hdf5.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <BESDebug.h>
#include "InternalErr.h"
#include <Array.h>
#include "HDFEOS5CFMissLLArray.h"
BaseType *HDFEOS5CFMissLLArray::ptr_duplicate()
{
return new HDFEOS5CFMissLLArray(*this);
}
bool HDFEOS5CFMissLLArray::read()
{
BESDEBUG("h5","Coming to HDFEOS5CFMissLLArray read "<<endl);
int nelms = -1;
vector<int>offset;
vector<int>count;
vector<int>step;
if (eos5_projcode != HE5_GCTP_GEO)
throw InternalErr (__FILE__, __LINE__,"The projection is not supported.");
if (rank <= 0)
throw InternalErr (__FILE__, __LINE__,
"The number of dimension of this variable should be greater than 0");
else {
offset.resize(rank);
count.resize(rank);
step.resize(rank);
nelms = format_constraint (&offset[0], &step[0], &count[0]);
}
if (nelms <= 0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments is negative.");
float start = 0.0;
float end = 0.0;
vector<float>val;
val.resize(nelms);
if (CV_LAT_MISS == cvartype) {
if (HE5_HDFE_GD_UL == eos5_origin || HE5_HDFE_GD_UR == eos5_origin) {
start = point_upper;
end = point_lower;
}
else {// (gridorigin == HE5_HDFE_GD_LL || gridorigin == HE5_HDFE_GD_LR)
start = point_lower;
end = point_upper;
}
if(ydimsize <=0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments should be greater than 0.");
float lat_step = (end - start) /ydimsize;
// Now offset,step and val will always be valid. line 74 and 85 assure this.
if ( HE5_HDFE_CENTER == eos5_pixelreg ) {
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i*step[0] + 0.5f) * lat_step + start) / 1000000.0;
}
else { // HE5_HDFE_CORNER
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i * step[0])*lat_step + start) / 1000000.0;
}
}
if (CV_LON_MISS == cvartype) {
if (HE5_HDFE_GD_UL == eos5_origin || HE5_HDFE_GD_LL == eos5_origin) {
start = point_left;
end = point_right;
}
else {// (gridorigin == HE5_HDFE_GD_UR || gridorigin == HE5_HDFE_GD_LR)
start = point_right;
end = point_left;
}
if(xdimsize <=0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments should be greater than 0.");
float lon_step = (end - start) /xdimsize;
if (HE5_HDFE_CENTER == eos5_pixelreg) {
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0] + i *step[0] + 0.5f) * lon_step + start ) / 1000000.0;
}
else { // HE5_HDFE_CORNER
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i*step[0]) * lon_step + start) / 1000000.0;
}
}
#if 0
for (int i =0; i <nelms; i++)
"h5","final data val "<< i <<" is " << val[i] <<endl;
#endif
set_value ((dods_float32 *) &val[0], nelms);
return true;
}
// parse constraint expr. and make hdf5 coordinate point location.
// return number of elements to read.
int
HDFEOS5CFMissLLArray::format_constraint (int *offset, int *step, int *count)
{
long nels = 1;
int id = 0;
Dim_iter p = dim_begin ();
while (p != dim_end ()) {
int start = dimension_start (p, true);
int stride = dimension_stride (p, true);
int stop = dimension_stop (p, true);
// Check for illegical constraint
if (stride < 0 || start < 0 || stop < 0 || start > stop) {
ostringstream oss;
oss << "Array/Grid hyperslab indices are bad: [" << start <<
":" << stride << ":" << stop << "]";
throw Error (malformed_expr, oss.str ());
}
// Check for an empty constraint and use the whole dimension if so.
if (start == 0 && stop == 0 && stride == 0) {
start = dimension_start (p, false);
stride = dimension_stride (p, false);
stop = dimension_stop (p, false);
}
offset[id] = start;
step[id] = stride;
count[id] = ((stop - start) / stride) + 1; // count of elements
nels *= count[id]; // total number of values for variable
BESDEBUG ("h5",
"=format_constraint():"
<< "id=" << id << " offset=" << offset[id]
<< " step=" << step[id]
<< " count=" << count[id]
<< endl);
id++;
p++;
}
return nels;
}
<commit_msg>HDVHANDLER-183, fix the 0-length array handling and the format_constraint index checking.<commit_after>// This file is part of the hdf5_handler implementing for the CF-compliant
// Copyright (c) 2011-2016 The HDF Group, Inc. and OPeNDAP, Inc.
//
// This is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This software is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// You can contact The HDF Group, Inc. at 1800 South Oak Street,
// Suite 203, Champaign, IL 61820
/////////////////////////////////////////////////////////////////////////////
/// \file HDFEOS5CFMissLLArray.cc
/// \brief The implementation of the retrieval of the missing lat/lon values for HDF-EOS5 products
///
/// \author Kent Yang <myang6@hdfgroup.org>
///
/// Copyright (C) 2011-2016 The HDF Group
///
/// All rights reserved.
#include "config_hdf5.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <BESDebug.h>
#include "InternalErr.h"
#include <Array.h>
#include "HDFEOS5CFMissLLArray.h"
BaseType *HDFEOS5CFMissLLArray::ptr_duplicate()
{
return new HDFEOS5CFMissLLArray(*this);
}
bool HDFEOS5CFMissLLArray::read()
{
BESDEBUG("h5","Coming to HDFEOS5CFMissLLArray read "<<endl);
int nelms = -1;
vector<int>offset;
vector<int>count;
vector<int>step;
if (eos5_projcode != HE5_GCTP_GEO)
throw InternalErr (__FILE__, __LINE__,"The projection is not supported.");
if (rank <= 0)
throw InternalErr (__FILE__, __LINE__,
"The number of dimension of this variable should be greater than 0");
else {
offset.resize(rank);
count.resize(rank);
step.resize(rank);
nelms = format_constraint (&offset[0], &step[0], &count[0]);
}
if (nelms <= 0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments is negative.");
float start = 0.0;
float end = 0.0;
vector<float>val;
val.resize(nelms);
if (CV_LAT_MISS == cvartype) {
if (HE5_HDFE_GD_UL == eos5_origin || HE5_HDFE_GD_UR == eos5_origin) {
start = point_upper;
end = point_lower;
}
else {// (gridorigin == HE5_HDFE_GD_LL || gridorigin == HE5_HDFE_GD_LR)
start = point_lower;
end = point_upper;
}
if(ydimsize <=0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments should be greater than 0.");
float lat_step = (end - start) /ydimsize;
// Now offset,step and val will always be valid. line 74 and 85 assure this.
if ( HE5_HDFE_CENTER == eos5_pixelreg ) {
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i*step[0] + 0.5f) * lat_step + start) / 1000000.0;
}
else { // HE5_HDFE_CORNER
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i * step[0])*lat_step + start) / 1000000.0;
}
}
if (CV_LON_MISS == cvartype) {
if (HE5_HDFE_GD_UL == eos5_origin || HE5_HDFE_GD_LL == eos5_origin) {
start = point_left;
end = point_right;
}
else {// (gridorigin == HE5_HDFE_GD_UR || gridorigin == HE5_HDFE_GD_LR)
start = point_right;
end = point_left;
}
if(xdimsize <=0)
throw InternalErr (__FILE__, __LINE__,
"The number of elments should be greater than 0.");
float lon_step = (end - start) /xdimsize;
if (HE5_HDFE_CENTER == eos5_pixelreg) {
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0] + i *step[0] + 0.5f) * lon_step + start ) / 1000000.0;
}
else { // HE5_HDFE_CORNER
for (int i = 0; i < nelms; i++)
val[i] = ((float)(offset[0]+i*step[0]) * lon_step + start) / 1000000.0;
}
}
#if 0
for (int i =0; i <nelms; i++)
"h5","final data val "<< i <<" is " << val[i] <<endl;
#endif
set_value ((dods_float32 *) &val[0], nelms);
return true;
}
// parse constraint expr. and make hdf5 coordinate point location.
// return number of elements to read.
int
HDFEOS5CFMissLLArray::format_constraint (int *offset, int *step, int *count)
{
long nels = 1;
int id = 0;
Dim_iter p = dim_begin ();
while (p != dim_end ()) {
int start = dimension_start (p, true);
int stride = dimension_stride (p, true);
int stop = dimension_stop (p, true);
// Check for illegal constraint
if (start > stop) {
ostringstream oss;
oss << "Array/Grid hyperslab start point "<< start <<
" is greater than stop point " << stop <<".";
throw Error(malformed_expr, oss.str());
}
offset[id] = start;
step[id] = stride;
count[id] = ((stop - start) / stride) + 1; // count of elements
nels *= count[id]; // total number of values for variable
BESDEBUG ("h5",
"=format_constraint():"
<< "id=" << id << " offset=" << offset[id]
<< " step=" << step[id]
<< " count=" << count[id]
<< endl);
id++;
p++;
}
return nels;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <atomic>
#include <chrono>
#include <future> // for async()
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include "helper.h"
#include "route_guide.grpc_cb.pb.h"
using grpc_cb::Channel;
using grpc_cb::ChannelSptr;
using grpc_cb::ClientAsyncReader;
using grpc_cb::ClientAsyncReaderWriter;
using grpc_cb::ClientAsyncWriter;
using grpc_cb::ClientSyncReader;
using grpc_cb::ClientSyncReaderWriter;
using grpc_cb::ClientSyncWriter;
using grpc_cb::Status;
using routeguide::Point;
using routeguide::Feature;
using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide::Stub;
const float kCoordFactor = 10000000.0;
static unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count();
static std::default_random_engine generator(seed);
Point MakePoint(long latitude, long longitude) {
Point p;
p.set_latitude(latitude);
p.set_longitude(longitude);
return p;
}
routeguide::Rectangle MakeRect(const Point& lo, const Point& hi) {
routeguide::Rectangle rect;
*rect.mutable_lo() = lo;
*rect.mutable_hi() = hi;
return rect;
}
routeguide::Rectangle MakeRect(long lo_latitude, long lo_longitude,
long hi_latitude, long hi_longitude) {
return MakeRect(MakePoint(lo_latitude, lo_longitude),
MakePoint(hi_latitude, hi_longitude));
}
Feature MakeFeature(const std::string& name,
long latitude, long longitude) {
Feature f;
f.set_name(name);
f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return f;
}
RouteNote MakeRouteNote(const std::string& message,
long latitude, long longitude) {
RouteNote n;
n.set_message(message);
n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return n;
}
void PrintFeature(const Feature& feature) {
if (!feature.has_location()) {
std::cout << "Server returns incomplete feature." << std::endl;
return;
}
if (feature.name().empty()) {
std::cout << "Found no feature at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
else {
std::cout << "Found feature called " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
} // PrintFeature()
void PrintServerNote(const RouteNote& server_note) {
std::cout << "Got message " << server_note.message()
<< " at " << server_note.location().latitude() << ", "
<< server_note.location().longitude() << std::endl;
}
void RandomSleep() {
std::uniform_int_distribution<int> delay_distribution(500, 1500);
std::this_thread::sleep_for(std::chrono::milliseconds(
delay_distribution(generator)));
}
void RunWriteRouteNote(ClientSyncReaderWriter<RouteNote, RouteNote>
sync_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
sync_reader_writer.Write(note);
// RandomSleep();
}
sync_reader_writer.CloseWriting();
}
class RouteGuideClient {
public:
RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
: stub_(routeguide::RouteGuide::NewStub(channel)) {
routeguide::ParseDb(db, &feature_list_);
assert(!feature_list_.empty());
}
void BlockingGetFeature() {
Point point;
Feature feature;
point = MakePoint(409146138, -746188906);
BlockingGetOneFeature(point, &feature);
point = MakePoint(0, 0);
BlockingGetOneFeature(point, &feature);
}
void BlockingListFeatures() {
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
Feature feature;
std::cout << "Looking for features between 40, -75 and 42, -73"
<< std::endl;
auto reader(stub_->SyncListFeatures(rect));
while (reader.ReadOne(&feature)) {
std::cout << "Found feature called "
<< feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
Status status = reader.RecvStatus();
if (status.ok()) {
std::cout << "ListFeatures rpc succeeded." << std::endl;
} else {
std::cout << "ListFeatures rpc failed." << std::endl;
}
}
void BlockingRecordRoute() {
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list_.size() - 1);
auto writer(stub_->SyncRecordRoute());
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list_[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
RouteSummary stats;
// Recv reponse and status.
Status status = writer.Close(&stats); // Todo: timeout
if (status.ok()) {
std::cout << "Finished trip with " << stats.point_count() << " points\n"
<< "Passed " << stats.feature_count() << " features\n"
<< "Traveled " << stats.distance() << " meters\n"
<< "It took " << stats.elapsed_time() << " seconds"
<< std::endl;
} else {
std::cout << "RecordRoute rpc failed." << std::endl;
}
}
// Todo: Callback on client stream response and status.
void BlockingRouteChat() {
ClientSyncReaderWriter<RouteNote, RouteNote> sync_reader_writer(
stub_->SyncRouteChat());
auto f = std::async(std::launch::async, [sync_reader_writer]() {
RunWriteRouteNote(sync_reader_writer);
});
RouteNote server_note;
while (sync_reader_writer.ReadOne(&server_note))
PrintServerNote(server_note);
f.wait();
// Todo: Close() should auto close writing.
Status status = sync_reader_writer.RecvStatus();
if (!status.ok()) {
std::cout << "RouteChat rpc failed." << std::endl;
}
}
private:
bool BlockingGetOneFeature(const Point& point, Feature* feature) {
Status status = stub_->BlockingGetFeature(point, feature);
if (!status.ok()) {
std::cout << "GetFeature rpc failed." << std::endl;
return false;
}
PrintFeature(*feature);
return feature->has_location();
}
std::unique_ptr<Stub> stub_;
std::vector<Feature> feature_list_;
};
void GetFeatureAsync(const ChannelSptr& channel) {
Stub stub(channel);
// Ignore error status.
stub.AsyncGetFeature(MakePoint(0, 0),
[](const Feature& feature) { PrintFeature(feature); });
// Ignore response.
stub.AsyncGetFeature(MakePoint(0, 0));
Point point1 = MakePoint(409146138, -746188906);
stub.AsyncGetFeature(point1,
[&stub](const Feature& feature) {
PrintFeature(feature);
stub.Shutdown();
},
[&stub](const Status& err) {
std::cout << "AsyncGetFeature rpc failed. "
<< err.GetDetails() << std::endl;
stub.Shutdown();
}); // AsyncGetFeature()
stub.BlockingRun(); // until stub.Shutdown()
}
void ListFeaturesAsync(const ChannelSptr& channel) {
Stub stub(channel);
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl;
stub.AsyncListFeatures(rect,
[](const Feature& feature){
std::cout << "Got feature " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
},
[&stub](const Status& status){
std::cout << "End status: (" << status.GetCode() << ") "
<< status.GetDetails() << std::endl;
stub.Shutdown(); // To break BlockingRun().
});
stub.BlockingRun(); // until stub.Shutdown()
}
void RecordRouteAsync(const ChannelSptr& channel,
const std::string& db) {
assert(!db.empty());
std::vector<Feature> feature_list;
routeguide::ParseDb(db, &feature_list);
assert(!feature_list.empty());
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list.size() - 1);
Stub stub(channel);
auto f = std::async(std::launch::async, [&stub]() { stub.BlockingRun(); });
// ClientAsyncWriter<Point, RouteSummary> writer;
auto writer = stub.AsyncRecordRoute();
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
// Recv reponse and status.
writer.Close([](const Status& status, const RouteSummary& resp) {
if (!status.ok()) {
std::cout << "RecordRoute rpc failed." << std::endl;
return;
}
std::cout << "Finished trip with " << resp.point_count() << " points\n"
<< "Passed " << resp.feature_count() << " features\n"
<< "Traveled " << resp.distance() << " meters\n"
<< "It took " << resp.elapsed_time() << " seconds" << std::endl;
});
// Todo: timeout
stub.Shutdown();
} // RecordRouteAsync()
void AsyncWriteRouteNotes(ClientAsyncReaderWriter<RouteNote, RouteNote>
async_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
async_reader_writer.Write(note);
// RandomSleep();
}
async_reader_writer.CloseWriting(); // Optional.
}
void RouteChatAsync(const ChannelSptr& channel) {
Stub stub(channel);
std::atomic_bool bReaderDone = false;
ClientAsyncReaderWriter<RouteNote, RouteNote> async_reader_writer(
stub.AsyncRouteChat([&bReaderDone](const Status& status) {
if (!status.ok()) {
std::cout << "RouteChat rpc failed. " << status.GetDetails()
<< std::endl;
}
bReaderDone = true;
}));
async_reader_writer.ReadEach(
[](const RouteNote& note) { PrintServerNote(note); });
AsyncWriteRouteNotes(async_reader_writer);
auto f = std::async(std::launch::async, [&stub]() {
stub.BlockingRun();
});
while (!bReaderDone)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
stub.Shutdown(); // To break BlockingRun().
} // RouteChatAsync()
int main(int argc, char** argv) {
// Expect only arg: --db_path=path/to/route_guide_db.json.
std::string db = routeguide::GetDbFileContent(argc, argv);
assert(!db.empty());
ChannelSptr channel(new Channel("localhost:50051"));
RouteGuideClient guide(channel, db);
std::cout << "---- BlockingGetFeature --------------" << std::endl;
guide.BlockingGetFeature();
std::cout << "---- BlockingListFeatures --------------" << std::endl;
guide.BlockingListFeatures();
std::cout << "---- BlockingRecordRoute --------------" << std::endl;
guide.BlockingRecordRoute();
std::cout << "---- BlockingRouteChat --------------" << std::endl;
guide.BlockingRouteChat();
std::cout << "---- GetFeatureAsync ----" << std::endl;
GetFeatureAsync(channel);
std::cout << "---- ListFeaturesAsync ----" << std::endl;
ListFeaturesAsync(channel);
std::cout << "---- RecordRouteAsnyc ----" << std::endl;
RecordRouteAsync(channel, db);
std::cout << "---- RouteChatAsync ---" << std::endl;
RouteChatAsync(channel);
return 0;
}
<commit_msg>Use Stub internal types.<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <atomic>
#include <chrono>
#include <future> // for async()
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include "helper.h"
#include "route_guide.grpc_cb.pb.h"
using grpc_cb::Channel;
using grpc_cb::ChannelSptr;
using grpc_cb::Status;
using routeguide::Point;
using routeguide::Feature;
using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide::Stub;
const float kCoordFactor = 10000000.0;
static unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count();
static std::default_random_engine generator(seed);
Point MakePoint(long latitude, long longitude) {
Point p;
p.set_latitude(latitude);
p.set_longitude(longitude);
return p;
}
routeguide::Rectangle MakeRect(const Point& lo, const Point& hi) {
routeguide::Rectangle rect;
*rect.mutable_lo() = lo;
*rect.mutable_hi() = hi;
return rect;
}
routeguide::Rectangle MakeRect(long lo_latitude, long lo_longitude,
long hi_latitude, long hi_longitude) {
return MakeRect(MakePoint(lo_latitude, lo_longitude),
MakePoint(hi_latitude, hi_longitude));
}
Feature MakeFeature(const std::string& name,
long latitude, long longitude) {
Feature f;
f.set_name(name);
f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return f;
}
RouteNote MakeRouteNote(const std::string& message,
long latitude, long longitude) {
RouteNote n;
n.set_message(message);
n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return n;
}
void PrintFeature(const Feature& feature) {
if (!feature.has_location()) {
std::cout << "Server returns incomplete feature." << std::endl;
return;
}
if (feature.name().empty()) {
std::cout << "Found no feature at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
else {
std::cout << "Found feature called " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
} // PrintFeature()
void PrintServerNote(const RouteNote& server_note) {
std::cout << "Got message " << server_note.message()
<< " at " << server_note.location().latitude() << ", "
<< server_note.location().longitude() << std::endl;
}
void RandomSleep() {
std::uniform_int_distribution<int> delay_distribution(500, 1500);
std::this_thread::sleep_for(std::chrono::milliseconds(
delay_distribution(generator)));
}
void RunWriteRouteNote(Stub::RouteChat_SyncReaderWriter sync_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
sync_reader_writer.Write(note);
// RandomSleep();
}
sync_reader_writer.CloseWriting();
}
class RouteGuideClient {
public:
RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
: stub_(routeguide::RouteGuide::NewStub(channel)) {
routeguide::ParseDb(db, &feature_list_);
assert(!feature_list_.empty());
}
void BlockingGetFeature() {
Point point;
Feature feature;
point = MakePoint(409146138, -746188906);
BlockingGetOneFeature(point, &feature);
point = MakePoint(0, 0);
BlockingGetOneFeature(point, &feature);
}
void BlockingListFeatures() {
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
Feature feature;
std::cout << "Looking for features between 40, -75 and 42, -73"
<< std::endl;
auto reader(stub_->SyncListFeatures(rect));
while (reader.ReadOne(&feature)) {
std::cout << "Found feature called "
<< feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
Status status = reader.RecvStatus();
if (status.ok()) {
std::cout << "ListFeatures rpc succeeded." << std::endl;
} else {
std::cout << "ListFeatures rpc failed." << std::endl;
}
}
void BlockingRecordRoute() {
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list_.size() - 1);
auto writer(stub_->SyncRecordRoute());
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list_[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
RouteSummary stats;
// Recv reponse and status.
Status status = writer.Close(&stats); // Todo: timeout
if (status.ok()) {
std::cout << "Finished trip with " << stats.point_count() << " points\n"
<< "Passed " << stats.feature_count() << " features\n"
<< "Traveled " << stats.distance() << " meters\n"
<< "It took " << stats.elapsed_time() << " seconds"
<< std::endl;
} else {
std::cout << "RecordRoute rpc failed." << std::endl;
}
}
// Todo: Callback on client stream response and status.
void BlockingRouteChat() {
auto sync_reader_writer(stub_->SyncRouteChat());
auto f = std::async(std::launch::async, [sync_reader_writer]() {
RunWriteRouteNote(sync_reader_writer);
});
RouteNote server_note;
while (sync_reader_writer.ReadOne(&server_note))
PrintServerNote(server_note);
f.wait();
// Todo: Close() should auto close writing.
Status status = sync_reader_writer.RecvStatus();
if (!status.ok()) {
std::cout << "RouteChat rpc failed." << std::endl;
}
}
private:
bool BlockingGetOneFeature(const Point& point, Feature* feature) {
Status status = stub_->BlockingGetFeature(point, feature);
if (!status.ok()) {
std::cout << "GetFeature rpc failed." << std::endl;
return false;
}
PrintFeature(*feature);
return feature->has_location();
}
std::unique_ptr<Stub> stub_;
std::vector<Feature> feature_list_;
};
void GetFeatureAsync(const ChannelSptr& channel) {
Stub stub(channel);
// Ignore error status.
stub.AsyncGetFeature(MakePoint(0, 0),
[](const Feature& feature) { PrintFeature(feature); });
// Ignore response.
stub.AsyncGetFeature(MakePoint(0, 0));
Point point1 = MakePoint(409146138, -746188906);
stub.AsyncGetFeature(point1,
[&stub](const Feature& feature) {
PrintFeature(feature);
stub.Shutdown();
},
[&stub](const Status& err) {
std::cout << "AsyncGetFeature rpc failed. "
<< err.GetDetails() << std::endl;
stub.Shutdown();
}); // AsyncGetFeature()
stub.BlockingRun(); // until stub.Shutdown()
}
void ListFeaturesAsync(const ChannelSptr& channel) {
Stub stub(channel);
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl;
stub.AsyncListFeatures(rect,
[](const Feature& feature){
std::cout << "Got feature " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
},
[&stub](const Status& status){
std::cout << "End status: (" << status.GetCode() << ") "
<< status.GetDetails() << std::endl;
stub.Shutdown(); // To break BlockingRun().
});
stub.BlockingRun(); // until stub.Shutdown()
}
void RecordRouteAsync(const ChannelSptr& channel,
const std::string& db) {
assert(!db.empty());
std::vector<Feature> feature_list;
routeguide::ParseDb(db, &feature_list);
assert(!feature_list.empty());
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list.size() - 1);
Stub stub(channel);
auto f = std::async(std::launch::async, [&stub]() { stub.BlockingRun(); });
// ClientAsyncWriter<Point, RouteSummary> writer;
auto writer = stub.AsyncRecordRoute();
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
// Recv reponse and status.
writer.Close([](const Status& status, const RouteSummary& resp) {
if (!status.ok()) {
std::cout << "RecordRoute rpc failed." << std::endl;
return;
}
std::cout << "Finished trip with " << resp.point_count() << " points\n"
<< "Passed " << resp.feature_count() << " features\n"
<< "Traveled " << resp.distance() << " meters\n"
<< "It took " << resp.elapsed_time() << " seconds" << std::endl;
});
// Todo: timeout
stub.Shutdown();
} // RecordRouteAsync()
void AsyncWriteRouteNotes(Stub::RouteChat_AsyncReaderWriter async_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
async_reader_writer.Write(note);
// RandomSleep();
}
async_reader_writer.CloseWriting(); // Optional.
}
void RouteChatAsync(const ChannelSptr& channel) {
Stub stub(channel);
std::atomic_bool bReaderDone = false;
auto async_reader_writer(
stub.AsyncRouteChat([&bReaderDone](const Status& status) {
if (!status.ok()) {
std::cout << "RouteChat rpc failed. " << status.GetDetails()
<< std::endl;
}
bReaderDone = true;
}));
async_reader_writer.ReadEach(
[](const RouteNote& note) { PrintServerNote(note); });
AsyncWriteRouteNotes(async_reader_writer);
auto f = std::async(std::launch::async, [&stub]() {
stub.BlockingRun();
});
while (!bReaderDone)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
stub.Shutdown(); // To break BlockingRun().
} // RouteChatAsync()
int main(int argc, char** argv) {
// Expect only arg: --db_path=path/to/route_guide_db.json.
std::string db = routeguide::GetDbFileContent(argc, argv);
assert(!db.empty());
ChannelSptr channel(new Channel("localhost:50051"));
RouteGuideClient guide(channel, db);
std::cout << "---- BlockingGetFeature --------------" << std::endl;
guide.BlockingGetFeature();
std::cout << "---- BlockingListFeatures --------------" << std::endl;
guide.BlockingListFeatures();
std::cout << "---- BlockingRecordRoute --------------" << std::endl;
guide.BlockingRecordRoute();
std::cout << "---- BlockingRouteChat --------------" << std::endl;
guide.BlockingRouteChat();
std::cout << "---- GetFeatureAsync ----" << std::endl;
GetFeatureAsync(channel);
std::cout << "---- ListFeaturesAsync ----" << std::endl;
ListFeaturesAsync(channel);
std::cout << "---- RecordRouteAsnyc ----" << std::endl;
RecordRouteAsync(channel, db);
std::cout << "---- RouteChatAsync ---" << std::endl;
RouteChatAsync(channel);
return 0;
}
<|endoftext|>
|
<commit_before>#include "stochastic.h"
#include "accumulator.h"
#include "sampler.h"
#include "file/logger.h"
#include "util/log_search.hpp"
#include "util/random.hpp"
#include "util/thread_pool.h"
#include "util/timer.h"
#include "optimize.h"
namespace ncv
{
namespace detail
{
static opt_state_t tune(
trainer_data_t& data,
stochastic_optimizer optimizer, scalar_t alpha0, scalar_t decay)
{
const samples_t tsamples = data.m_tsampler.get();
const size_t epochs = 1;
// construct the optimization problem (NB: one random sample at the time)
size_t index = 0;
auto fn_size = ncv::make_opsize(data);
auto fn_fval = ncv::make_opfval(data, tsamples, index);
auto fn_grad = ncv::make_opgrad(data, tsamples, index);
auto fn_wlog = nullptr;
auto fn_elog = nullptr;
auto fn_ulog = nullptr;
// assembly optimization problem & optimize the model
opt_state_t opt = ncv::minimize(
fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog,
data.m_x0, optimizer, epochs, tsamples.size(), alpha0, decay);
// OK, cumulate the loss value
data.m_lacc.reset(opt.x);
data.m_lacc.update(data.m_task, tsamples, data.m_loss);
opt.f = data.m_lacc.value();
return opt;
}
static trainer_result_t train(
trainer_data_t& data,
stochastic_optimizer optimizer, size_t epochs, scalar_t alpha0, scalar_t decay,
thread_pool_t::mutex_t& mutex)
{
samples_t tsamples = data.m_tsampler.get();
samples_t vsamples = data.m_vsampler.get();
trainer_result_t result;
const ncv::timer_t timer;
// construct the optimization problem (NB: one random sample at the time)
size_t index = 0, epoch = 0;
auto fn_size = ncv::make_opsize(data);
auto fn_fval = ncv::make_opfval(data, tsamples, index);
auto fn_grad = ncv::make_opgrad(data, tsamples, index);
auto fn_wlog = ncv::make_opwlog();
auto fn_elog = ncv::make_opelog();
auto fn_ulog = [&] (const opt_state_t& state)
{
// shuffle randomly the training samples after each epoch
random_t<size_t> xrng(0, tsamples.size());
random_index_t<size_t> xrnd(xrng);
std::random_shuffle(tsamples.begin(), tsamples.end(), xrnd);
// evaluate training samples
data.m_lacc.reset(state.x);
data.m_lacc.update(data.m_task, tsamples, data.m_loss);
const scalar_t tvalue = data.m_lacc.value();
const scalar_t terror_avg = data.m_lacc.avg_error();
const scalar_t terror_var = data.m_lacc.var_error();
// evaluate validation samples
data.m_lacc.reset(state.x);
data.m_lacc.update(data.m_task, vsamples, data.m_loss);
const scalar_t vvalue = data.m_lacc.value();
const scalar_t verror_avg = data.m_lacc.avg_error();
const scalar_t verror_var = data.m_lacc.var_error();
epoch ++;
// OK, update the optimum solution
const thread_pool_t::lock_t lock(mutex);
result.update(state.x, tvalue, terror_avg, terror_var, vvalue, verror_avg, verror_var,
epoch, scalars_t({ alpha0, decay, data.m_lacc.lambda() }));
log_info()
<< "[train = " << tvalue << "/" << terror_avg
<< ", valid = " << vvalue << "/" << verror_avg
<< ", xnorm = " << state.x.lpNorm<Eigen::Infinity>()
<< ", alpha = " << alpha0
<< ", decay = " << decay
<< ", epoch = " << epoch << "/" << epochs
<< ", lambda = " << data.m_lacc.lambda()
<< "] done in " << timer.elapsed() << ".";
};
// assembly optimization problem & optimize the model
ncv::minimize(fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog,
data.m_x0, optimizer, epochs, tsamples.size(), alpha0, decay);
// OK
return result;
}
}
trainer_result_t stochastic_train(
const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,
const loss_t& loss, const string_t& criterion,
stochastic_optimizer optimizer, size_t epochs)
{
thread_pool_t::mutex_t mutex;
// operator to train for a given regularization factor
const auto op = [&] (scalar_t lambda)
{
vector_t x0;
model.save_params(x0);
opt_state_t opt_state;
scalar_t opt_alpha = 1.00;
scalar_t opt_decay = 0.50;
// operator to tune the learning rate
const auto op_lrate = [&] (scalar_t alpha)
{
accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);
accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);
trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);
const scalars_t decays = { 0.50, 0.75, 1.00 };
// also tune the decay rate
std::set<std::pair<opt_state_t, scalar_t> > states;
for (scalar_t decay : decays)
{
const ncv::timer_t timer;
const opt_state_t state = detail::tune(data, optimizer, alpha, decay);
const thread_pool_t::lock_t lock(mutex);
log_info()
<< "[tuning: loss = " << state.f
<< ", alpha = " << alpha
<< ", decay = " << decay
<< ", lambda = " << data.m_lacc.lambda()
<< "] done in " << timer.elapsed() << ".";
states.insert(std::make_pair(state, decay));
}
if (states.begin()->first < opt_state)
{
opt_state = states.begin()->first;
opt_alpha = alpha;
opt_decay = states.begin()->second;
}
return states.begin()->first;
};
thread_pool_t wpool(nthreads);
log_min_search_mt(op_lrate, wpool, -6.0, 0.0, 0.5, nthreads);
// train the model using the tuned learning rate & decay rate
{
accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);
accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);
trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);
return detail::train(data, optimizer, epochs, opt_alpha, opt_decay, mutex);
}
};
// tune the regularization factor (if needed)
if (accumulator_t::can_regularize(criterion))
{
thread_pool_t wpool(nthreads);
return log_min_search_mt(op, wpool, -4.0, +4.0, 0.5, nthreads).first;
}
else
{
return op(0.0);
}
}
}
<commit_msg>tune learning rate for all epochs (miss-leading results for a single epoch)<commit_after>#include "stochastic.h"
#include "accumulator.h"
#include "sampler.h"
#include "file/logger.h"
#include "util/log_search.hpp"
#include "util/random.hpp"
#include "util/thread_pool.h"
#include "util/timer.h"
#include "optimize.h"
namespace ncv
{
namespace detail
{
static void train(
trainer_data_t& data,
stochastic_optimizer optimizer, size_t epochs, scalar_t alpha0, scalar_t decay,
trainer_result_t& result, thread_pool_t::mutex_t& mutex)
{
samples_t tsamples = data.m_tsampler.get();
samples_t vsamples = data.m_vsampler.get();
const ncv::timer_t timer;
// construct the optimization problem (NB: one random sample at the time)
size_t index = 0, epoch = 0;
auto fn_size = ncv::make_opsize(data);
auto fn_fval = ncv::make_opfval(data, tsamples, index);
auto fn_grad = ncv::make_opgrad(data, tsamples, index);
auto fn_wlog = ncv::make_opwlog();
auto fn_elog = ncv::make_opelog();
auto fn_ulog = [&] (const opt_state_t& state)
{
// shuffle randomly the training samples after each epoch
random_t<size_t> xrng(0, tsamples.size());
random_index_t<size_t> xrnd(xrng);
std::random_shuffle(tsamples.begin(), tsamples.end(), xrnd);
// evaluate training samples
data.m_lacc.reset(state.x);
data.m_lacc.update(data.m_task, tsamples, data.m_loss);
const scalar_t tvalue = data.m_lacc.value();
const scalar_t terror_avg = data.m_lacc.avg_error();
const scalar_t terror_var = data.m_lacc.var_error();
// evaluate validation samples
data.m_lacc.reset(state.x);
data.m_lacc.update(data.m_task, vsamples, data.m_loss);
const scalar_t vvalue = data.m_lacc.value();
const scalar_t verror_avg = data.m_lacc.avg_error();
const scalar_t verror_var = data.m_lacc.var_error();
epoch ++;
// OK, update the optimum solution
const thread_pool_t::lock_t lock(mutex);
result.update(state.x, tvalue, terror_avg, terror_var, vvalue, verror_avg, verror_var,
epoch, scalars_t({ alpha0, decay, data.m_lacc.lambda() }));
log_info()
<< "[train = " << tvalue << "/" << terror_avg
<< ", valid = " << vvalue << "/" << verror_avg
<< ", xnorm = " << state.x.lpNorm<Eigen::Infinity>()
<< ", alpha = " << alpha0
<< ", decay = " << decay
<< ", epoch = " << epoch << "/" << epochs
<< ", lambda = " << data.m_lacc.lambda()
<< "] done in " << timer.elapsed() << ".";
};
// assembly optimization problem & optimize the model
ncv::minimize(fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog,
data.m_x0, optimizer, epochs, tsamples.size(), alpha0, decay);
}
}
trainer_result_t stochastic_train(
const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,
const loss_t& loss, const string_t& criterion,
stochastic_optimizer optimizer, size_t epochs)
{
thread_pool_t::mutex_t mutex;
// operator to train for a given regularization factor
const auto op = [&] (scalar_t lambda)
{
vector_t x0;
model.save_params(x0);
// operator to tune the learning rate
const auto op_lrate = [&] (scalar_t alpha)
{
accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);
accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);
trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);
// also tune the decay rate (if possible)
const scalars_t decays = (optimizer == stochastic_optimizer::NAG) ?
scalars_t({ 1.00 }) : scalars_t({ 0.50, 0.75, 1.00 });
trainer_result_t result;
for (scalar_t decay : decays)
{
detail::train(data, optimizer, epochs, alpha, decay, result, mutex);
}
return result;
};
thread_pool_t wpool(nthreads);
return log_min_search_mt(op_lrate, wpool, -6.0, 0.0, 0.5, nthreads).first;
};
// tune the regularization factor (if needed)
if (accumulator_t::can_regularize(criterion))
{
thread_pool_t wpool(nthreads);
return log_min_search_mt(op, wpool, -4.0, +4.0, 0.5, nthreads).first;
}
else
{
return op(0.0);
}
}
}
<|endoftext|>
|
<commit_before>// SimpleGraph.cpp : implementation file
//
#include "stdafx.h"
#include "HexEditView.h"
#include "SimpleGraph.h"
#include "misc.h"
// CSimpleGraph
IMPLEMENT_DYNAMIC(CSimpleGraph, CWnd)
CSimpleGraph::CSimpleGraph()
{
m_pdc = NULL;
m_bar = -1;
}
void CSimpleGraph::SetData(FILE_ADDRESS maximum, std::vector<FILE_ADDRESS> val, std::vector<COLORREF> col)
{
if (val == m_val && col == m_col)
return; // no change
ASSERT(val.size() == col.size());
m_max = maximum;
m_val.swap(val);
m_col.swap(col);
update();
}
void CSimpleGraph::update()
{
CRect rct;
GetClientRect(rct);
// If the graph has been resized we need a new DC/bitmap
if (m_rct != rct)
{
m_rct = rct;
// Delete old DC/bitmap
if (m_pdc != NULL)
{
delete m_pdc;
m_pdc = NULL;
m_bm.DeleteObject();
m_hfnt.DeleteObject();
m_vfnt.DeleteObject();
}
// Recreate DC/bitmap for drawing into
CDC* pDC = GetDC();
m_pdc = new CDC();
m_pdc->CreateCompatibleDC(pDC);
m_bm.CreateCompatibleBitmap(pDC, rct.Width(), rct.Height());
m_pdc->SelectObject(&m_bm);
// Set up text including creating the font
LOGFONT lf;
memset(&lf, '\0', sizeof(lf));
lf.lfHeight = 12;
strcpy(lf.lfFaceName, "Tahoma"); // Simple font face for small digits
m_hfnt.CreateFontIndirect(&lf);
lf.lfEscapement = 900; // text at 90 degrees
m_vfnt.CreateFontIndirect(&lf);
m_pdc->SetBkMode(TRANSPARENT);
m_pdc->SetTextColor(m_axes); // use same colour as axes for now
}
// Get adjusted colours
COLORREF *pc = new COLORREF[m_col.size()];
for (int ii = 0; ii < m_col.size(); ++ii)
pc[ii] = add_contrast(m_col[ii], m_back);
// Draw background
m_pdc->FillSolidRect(0, 0, m_rct.Width(), m_rct.Height(), m_back);
draw_axes();
int width = m_rct.Width() - m_left - m_right; // width of the actual graph area
int height = m_rct.Height() - m_top - m_bottom; // height of the graph
int ypos = m_rct.Height() - m_bottom; // bottom of the graph (dist. from rect top)
// Draw bars of graph
ASSERT(m_val.size() == m_col.size());
int xpos = m_left;
for (int ii = 0; ii < m_val.size(); ++ii)
{
int next_xpos = m_left + (width*(ii+1))/m_val.size();
int cy = int((m_val[ii]*height)/m_max);
m_pdc->FillSolidRect(xpos, ypos - cy, next_xpos - xpos, cy, pc[ii]); // draw bar for this byte value
//m_pdc->FillSolidRect(xpos, ypos - cy, next_xpos - xpos, 1, RGB(0, 0, 0)); // add black tip to all bars
// Add ticks
if (ii % 16 == 0)
{
int siz;
if (ii %64 == 0)
siz = 4;
else
siz = 2;
m_pdc->FillSolidRect(xpos - 1, ypos + 1, 1, siz, m_axes);
}
xpos = next_xpos;
}
m_pdc->FillSolidRect(xpos - 1, ypos + 1, 1, 4, m_axes); // Right end tick
delete[] pc;
Invalidate();
}
void CSimpleGraph::draw_axes()
{
int width = m_rct.Width() - m_left - m_right;
int height = m_rct.Height() - m_top - m_bottom;
m_pdc->FillSolidRect(m_left - 1, m_top - 1, 1, height + 1, m_axes); // vert axis
// Calculate tick interval, units etc for the vertical axis
int max; // scaled max value
CString ustr; // scaling unit
if (m_max >= 2000000000)
{
max = int(m_max/1000000000);
ustr = "Billions";
}
else if (m_max >= 2000000)
{
max = int(m_max/1000000);
ustr = "Millions";
}
else if (m_max >= 2000)
{
max = int(m_max/1000);
ustr = "Thousands";
}
else
{
max = int(m_max);
ustr = "";
}
int max_ticks = height/20; // leave at least 20 pixels between ticks
int min_spacing = max_ticks == 0 ? max : max/max_ticks + 1; // min tick distance in graph units
char buf[10];
sprintf(buf, "%d", min_spacing);
double mag = pow(10.0, double(strlen(buf) - 1)); // max magnitude
double vv = min_spacing/mag;
int tick; // how far apart are ticks in scaled units
if (vv > 5.0)
tick = 10 * int(mag);
else if (vv > 2.0)
tick = 5 * int(mag);
else if (vv > 1.0)
tick = 2 * int(mag);
else
tick = int(mag);
CRect rct;
m_pdc->SelectObject(&m_hfnt);
for (int tt = 0; tt < max; tt += tick)
{
int ypos = m_rct.Height() - m_bottom - (tt*height)/max; // xxx is this right as max is rounded??
m_pdc->FillSolidRect(m_left - 3, ypos, 3, 1, m_axes);
// Draw units next to tick
//if (tt < (max*7)/8) // don't draw near the top so we have room for the "Show" button
{
sprintf(buf, "%d", tt);
rct.left = 0;
rct.right = 28;
rct.bottom = ypos + 7;
rct.top = rct.bottom - 20;
m_pdc->DrawText(buf, strlen(buf), rct, DT_SINGLELINE | DT_BOTTOM | DT_RIGHT | DT_NOCLIP);
//m_pdc->ExtTextOut(14, ypos-7, 0, NULL, buf, strlen(buf), NULL);
}
}
// Vertical unit scaling text
m_pdc->SelectObject(&m_vfnt);
m_pdc->ExtTextOutA(0, m_rct.Height() - m_bottom, 0, NULL, ustr, strlen(ustr), NULL);
// Draw horizontal axis
m_pdc->FillSolidRect(m_left - 1, m_rct.Height() - m_bottom, width + 1, 1, m_axes);
}
void CSimpleGraph::track_mouse(unsigned long flag)
{
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = flag;
tme.dwHoverTime = 0;
tme.hwndTrack = m_hWnd;
VERIFY(::_TrackMouseEvent(&tme));
}
int CSimpleGraph::get_bar(CPoint pt)
{
++pt.x; // mouse posn seems to be out by 1 pixel
if (pt.y <= m_top || pt.y >= m_rct.Height() - m_bottom ||
pt.x < m_left || pt.x > m_rct.Width() - m_right)
{
// Outside graph area so return
return -1;
}
int retval = ((pt.x - m_left)*m_val.size())/(m_rct.Width() - m_left - m_right);
if (retval >= m_val.size())
retval = m_val.size() - 1;
return retval;
}
BEGIN_MESSAGE_MAP(CSimpleGraph, CWnd)
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_SETCURSOR()
ON_WM_MOUSEMOVE()
ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover)
ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
END_MESSAGE_MAP()
// CSimpleGraph message handlers
void CSimpleGraph::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rct;
GetClientRect(rct);
// Just BLT the current graph into the display
dc.BitBlt(rct.left, rct.top, rct.Width(), rct.Height(), m_pdc, 0, 0, SRCCOPY);
}
void CSimpleGraph::OnSize(UINT nType, int cx, int cy)
{
__super::OnSize(nType, cx, cy);
update();
}
BOOL CSimpleGraph::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
CPoint pt;
::GetCursorPos(&pt); // get mouse location (screen coords)
ScreenToClient(&pt);
if (get_bar(pt) > -1)
::SetCursor(theApp.LoadCursor(IDC_INFO)); // show info cursor if over the graph
else
::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
return TRUE;
}
void CSimpleGraph::OnMouseMove(UINT nFlags, CPoint point)
{
CWnd::OnMouseMove(nFlags, point);
// Check for hover if no tip window is visible
if (!m_tip.IsWindowVisible())
track_mouse(TME_HOVER);
else if (get_bar(point) != m_bar && !m_tip.FadingOut())
m_tip.Hide(300);
}
LRESULT CSimpleGraph::OnMouseHover(WPARAM, LPARAM lp)
{
CPoint pt(LOWORD(lp), HIWORD(lp)); // client window coords
CHexEditView *pv = GetView();
ASSERT(pv != NULL);
m_bar = get_bar(pt);
if (m_bar > -1 && !m_tip.IsWindowVisible())
{
// Update the tip info
m_tip.Clear();
CString ss;
if (theApp.hex_ucase_)
ss.Format("Byte: %d [%02.2Xh] %s", m_bar, m_bar, pv->DescChar(m_bar));
else
ss.Format("Byte: %d [%02.2xh] %s", m_bar, m_bar, pv->DescChar(m_bar));
m_tip.AddString(ss);
char buf[32]; // used with sprintf (CString::Format can't handle __int64)
sprintf(buf, "%I64d", m_val[m_bar]);
ss = buf;
AddCommas(ss);
m_tip.AddString("Count: " +ss);
// Work out the tip window display position and move the tip window there
CPoint tip_pt = pt + CSize(16, 16);
ClientToScreen(&tip_pt);
m_tip.Move(tip_pt, false);
m_tip.Show();
track_mouse(TME_LEAVE);
return 0; // return 0 to say we processed it
}
return 1;
}
LRESULT CSimpleGraph::OnMouseLeave(WPARAM, LPARAM lp)
{
// Make sure we hide the tip window when the mouse leave the window (no more move messages are received)
m_tip.Hide(300);
return 0;
}
<commit_msg>Avoid divide by zero in Count property page when the file is empty<commit_after>// SimpleGraph.cpp : implementation file
//
#include "stdafx.h"
#include "HexEditView.h"
#include "SimpleGraph.h"
#include "misc.h"
// CSimpleGraph
IMPLEMENT_DYNAMIC(CSimpleGraph, CWnd)
CSimpleGraph::CSimpleGraph()
{
m_pdc = NULL;
m_bar = -1;
}
void CSimpleGraph::SetData(FILE_ADDRESS maximum, std::vector<FILE_ADDRESS> val, std::vector<COLORREF> col)
{
if (val == m_val && col == m_col)
return; // no change
ASSERT(val.size() == col.size());
m_max = maximum;
if (m_max < 1) m_max = 1; // avoid divide by zero
m_val.swap(val);
m_col.swap(col);
update();
}
void CSimpleGraph::update()
{
CRect rct;
GetClientRect(rct);
// If the graph has been resized we need a new DC/bitmap
if (m_rct != rct)
{
m_rct = rct;
// Delete old DC/bitmap
if (m_pdc != NULL)
{
delete m_pdc;
m_pdc = NULL;
m_bm.DeleteObject();
m_hfnt.DeleteObject();
m_vfnt.DeleteObject();
}
// Recreate DC/bitmap for drawing into
CDC* pDC = GetDC();
m_pdc = new CDC();
m_pdc->CreateCompatibleDC(pDC);
m_bm.CreateCompatibleBitmap(pDC, rct.Width(), rct.Height());
m_pdc->SelectObject(&m_bm);
// Set up text including creating the font
LOGFONT lf;
memset(&lf, '\0', sizeof(lf));
lf.lfHeight = 12;
strcpy(lf.lfFaceName, "Tahoma"); // Simple font face for small digits
m_hfnt.CreateFontIndirect(&lf);
lf.lfEscapement = 900; // text at 90 degrees
m_vfnt.CreateFontIndirect(&lf);
m_pdc->SetBkMode(TRANSPARENT);
m_pdc->SetTextColor(m_axes); // use same colour as axes for now
}
// Get adjusted colours
COLORREF *pc = new COLORREF[m_col.size()];
for (int ii = 0; ii < m_col.size(); ++ii)
pc[ii] = add_contrast(m_col[ii], m_back);
// Draw background
m_pdc->FillSolidRect(0, 0, m_rct.Width(), m_rct.Height(), m_back);
draw_axes();
int width = m_rct.Width() - m_left - m_right; // width of the actual graph area
int height = m_rct.Height() - m_top - m_bottom; // height of the graph
int ypos = m_rct.Height() - m_bottom; // bottom of the graph (dist. from rect top)
// Draw bars of graph
ASSERT(m_val.size() == m_col.size());
int xpos = m_left;
for (int ii = 0; ii < m_val.size(); ++ii)
{
int next_xpos = m_left + (width*(ii+1))/m_val.size();
int cy = int((m_val[ii]*height)/m_max);
m_pdc->FillSolidRect(xpos, ypos - cy, next_xpos - xpos, cy, pc[ii]); // draw bar for this byte value
//m_pdc->FillSolidRect(xpos, ypos - cy, next_xpos - xpos, 1, RGB(0, 0, 0)); // add black tip to all bars
// Add ticks
if (ii % 16 == 0)
{
int siz;
if (ii %64 == 0)
siz = 4;
else
siz = 2;
m_pdc->FillSolidRect(xpos - 1, ypos + 1, 1, siz, m_axes);
}
xpos = next_xpos;
}
m_pdc->FillSolidRect(xpos - 1, ypos + 1, 1, 4, m_axes); // Right end tick
delete[] pc;
Invalidate();
}
void CSimpleGraph::draw_axes()
{
int width = m_rct.Width() - m_left - m_right;
int height = m_rct.Height() - m_top - m_bottom;
m_pdc->FillSolidRect(m_left - 1, m_top - 1, 1, height + 1, m_axes); // vert axis
// Calculate tick interval, units etc for the vertical axis
int max; // scaled max value
CString ustr; // scaling unit
if (m_max >= 2000000000)
{
max = int(m_max/1000000000);
ustr = "Billions";
}
else if (m_max >= 2000000)
{
max = int(m_max/1000000);
ustr = "Millions";
}
else if (m_max >= 2000)
{
max = int(m_max/1000);
ustr = "Thousands";
}
else
{
max = int(m_max);
ustr = "";
}
int max_ticks = height/20; // leave at least 20 pixels between ticks
int min_spacing = max_ticks == 0 ? max : max/max_ticks + 1; // min tick distance in graph units
char buf[10];
sprintf(buf, "%d", min_spacing);
double mag = pow(10.0, double(strlen(buf) - 1)); // max magnitude
double vv = min_spacing/mag;
int tick; // how far apart are ticks in scaled units
if (vv > 5.0)
tick = 10 * int(mag);
else if (vv > 2.0)
tick = 5 * int(mag);
else if (vv > 1.0)
tick = 2 * int(mag);
else
tick = int(mag);
CRect rct;
m_pdc->SelectObject(&m_hfnt);
for (int tt = 0; tt < max; tt += tick)
{
int ypos = m_rct.Height() - m_bottom - (tt*height)/max; // xxx is this right as max is rounded??
m_pdc->FillSolidRect(m_left - 3, ypos, 3, 1, m_axes);
// Draw units next to tick
//if (tt < (max*7)/8) // don't draw near the top so we have room for the "Show" button
{
sprintf(buf, "%d", tt);
rct.left = 0;
rct.right = 28;
rct.bottom = ypos + 7;
rct.top = rct.bottom - 20;
m_pdc->DrawText(buf, strlen(buf), rct, DT_SINGLELINE | DT_BOTTOM | DT_RIGHT | DT_NOCLIP);
//m_pdc->ExtTextOut(14, ypos-7, 0, NULL, buf, strlen(buf), NULL);
}
}
// Vertical unit scaling text
m_pdc->SelectObject(&m_vfnt);
m_pdc->ExtTextOutA(0, m_rct.Height() - m_bottom, 0, NULL, ustr, strlen(ustr), NULL);
// Draw horizontal axis
m_pdc->FillSolidRect(m_left - 1, m_rct.Height() - m_bottom, width + 1, 1, m_axes);
}
void CSimpleGraph::track_mouse(unsigned long flag)
{
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = flag;
tme.dwHoverTime = 0;
tme.hwndTrack = m_hWnd;
VERIFY(::_TrackMouseEvent(&tme));
}
int CSimpleGraph::get_bar(CPoint pt)
{
++pt.x; // mouse posn seems to be out by 1 pixel
if (pt.y <= m_top || pt.y >= m_rct.Height() - m_bottom ||
pt.x < m_left || pt.x > m_rct.Width() - m_right)
{
// Outside graph area so return
return -1;
}
int retval = ((pt.x - m_left)*m_val.size())/(m_rct.Width() - m_left - m_right);
if (retval >= m_val.size())
retval = m_val.size() - 1;
return retval;
}
BEGIN_MESSAGE_MAP(CSimpleGraph, CWnd)
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_SETCURSOR()
ON_WM_MOUSEMOVE()
ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover)
ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
END_MESSAGE_MAP()
// CSimpleGraph message handlers
void CSimpleGraph::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rct;
GetClientRect(rct);
// Just BLT the current graph into the display
dc.BitBlt(rct.left, rct.top, rct.Width(), rct.Height(), m_pdc, 0, 0, SRCCOPY);
}
void CSimpleGraph::OnSize(UINT nType, int cx, int cy)
{
__super::OnSize(nType, cx, cy);
update();
}
BOOL CSimpleGraph::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
CPoint pt;
::GetCursorPos(&pt); // get mouse location (screen coords)
ScreenToClient(&pt);
if (get_bar(pt) > -1)
::SetCursor(theApp.LoadCursor(IDC_INFO)); // show info cursor if over the graph
else
::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
return TRUE;
}
void CSimpleGraph::OnMouseMove(UINT nFlags, CPoint point)
{
CWnd::OnMouseMove(nFlags, point);
// Check for hover if no tip window is visible
if (!m_tip.IsWindowVisible())
track_mouse(TME_HOVER);
else if (get_bar(point) != m_bar && !m_tip.FadingOut())
m_tip.Hide(300);
}
LRESULT CSimpleGraph::OnMouseHover(WPARAM, LPARAM lp)
{
CPoint pt(LOWORD(lp), HIWORD(lp)); // client window coords
CHexEditView *pv = GetView();
ASSERT(pv != NULL);
m_bar = get_bar(pt);
if (m_bar > -1 && !m_tip.IsWindowVisible())
{
// Update the tip info
m_tip.Clear();
CString ss;
if (theApp.hex_ucase_)
ss.Format("Byte: %d [%02.2Xh] %s", m_bar, m_bar, pv->DescChar(m_bar));
else
ss.Format("Byte: %d [%02.2xh] %s", m_bar, m_bar, pv->DescChar(m_bar));
m_tip.AddString(ss);
char buf[32]; // used with sprintf (CString::Format can't handle __int64)
sprintf(buf, "%I64d", m_val[m_bar]);
ss = buf;
AddCommas(ss);
m_tip.AddString("Count: " +ss);
// Work out the tip window display position and move the tip window there
CPoint tip_pt = pt + CSize(16, 16);
ClientToScreen(&tip_pt);
m_tip.Move(tip_pt, false);
m_tip.Show();
track_mouse(TME_LEAVE);
return 0; // return 0 to say we processed it
}
return 1;
}
LRESULT CSimpleGraph::OnMouseLeave(WPARAM, LPARAM lp)
{
// Make sure we hide the tip window when the mouse leave the window (no more move messages are received)
m_tip.Hide(300);
return 0;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <atomic>
#include <chrono>
#include <future> // for async()
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include "helper.h"
#include "route_guide.grpc_cb.pb.h"
using grpc_cb::Channel;
using grpc_cb::ChannelSptr;
using grpc_cb::Status;
using routeguide::Point;
using routeguide::Feature;
using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide::Stub;
const float kCoordFactor = 10000000.0;
static unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count();
static std::default_random_engine generator(seed);
Point MakePoint(long latitude, long longitude) {
Point p;
p.set_latitude(latitude);
p.set_longitude(longitude);
return p;
}
routeguide::Rectangle MakeRect(const Point& lo, const Point& hi) {
routeguide::Rectangle rect;
*rect.mutable_lo() = lo;
*rect.mutable_hi() = hi;
return rect;
}
routeguide::Rectangle MakeRect(long lo_latitude, long lo_longitude,
long hi_latitude, long hi_longitude) {
return MakeRect(MakePoint(lo_latitude, lo_longitude),
MakePoint(hi_latitude, hi_longitude));
}
Feature MakeFeature(const std::string& name,
long latitude, long longitude) {
Feature f;
f.set_name(name);
f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return f;
}
RouteNote MakeRouteNote(const std::string& message,
long latitude, long longitude) {
RouteNote n;
n.set_message(message);
n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return n;
}
void PrintFeature(const Feature& feature) {
if (!feature.has_location()) {
std::cout << "Server returns incomplete feature." << std::endl;
return;
}
if (feature.name().empty()) {
std::cout << "Found no feature at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
else {
std::cout << "Found feature called " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
} // PrintFeature()
void PrintServerNote(const RouteNote& server_note) {
std::cout << "Got message " << server_note.message()
<< " at " << server_note.location().latitude() << ", "
<< server_note.location().longitude() << std::endl;
}
void RandomSleep() {
std::uniform_int_distribution<int> delay_distribution(500, 1500);
std::this_thread::sleep_for(std::chrono::milliseconds(
delay_distribution(generator)));
}
void RunWriteRouteNote(Stub::RouteChat_SyncReaderWriter sync_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
sync_reader_writer.Write(note);
// RandomSleep();
}
sync_reader_writer.CloseWriting();
}
class RouteGuideClient {
public:
RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
: stub_(new Stub(channel)) {
routeguide::ParseDb(db, &feature_list_);
assert(!feature_list_.empty());
}
void SyncGetFeature() {
Point point;
Feature feature;
point = MakePoint(409146138, -746188906);
SyncGetOneFeature(point, &feature);
point = MakePoint(0, 0);
SyncGetOneFeature(point, &feature);
}
void SyncListFeatures() {
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
Feature feature;
std::cout << "Looking for features between 40, -75 and 42, -73"
<< std::endl;
auto sync_reader(stub_->Sync_ListFeatures(rect));
while (sync_reader.ReadOne(&feature)) {
std::cout << "Found feature called "
<< feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
Status status = sync_reader.RecvStatus();
if (status.ok()) {
std::cout << "ListFeatures rpc succeeded." << std::endl;
} else {
std::cout << "ListFeatures rpc failed." << std::endl;
}
}
void SyncRecordRoute() {
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list_.size() - 1);
auto sync_writer(stub_->Sync_RecordRoute());
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list_[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!sync_writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
RouteSummary stats;
// Recv reponse and status.
Status status = sync_writer.Close(&stats); // Todo: timeout
if (status.ok()) {
std::cout << "Finished trip with " << stats.point_count() << " points\n"
<< "Passed " << stats.feature_count() << " features\n"
<< "Traveled " << stats.distance() << " meters\n"
<< "It took " << stats.elapsed_time() << " seconds"
<< std::endl;
} else {
std::cout << "RecordRoute rpc failed." << std::endl;
}
}
// Todo: Callback on client stream response and status.
void SyncRouteChat() {
auto sync_reader_writer(stub_->Sync_RouteChat());
auto f = std::async(std::launch::async, [sync_reader_writer]() {
RunWriteRouteNote(sync_reader_writer);
});
RouteNote server_note;
while (sync_reader_writer.ReadOne(&server_note))
PrintServerNote(server_note);
f.wait();
// Todo: Close() should auto close writing.
Status status = sync_reader_writer.RecvStatus();
if (!status.ok()) {
std::cout << "RouteChat rpc failed." << std::endl;
}
}
private:
bool SyncGetOneFeature(const Point& point, Feature* feature) {
Status status = stub_->Sync_GetFeature(point, feature);
if (!status.ok()) {
std::cout << "GetFeature rpc failed." << std::endl;
return false;
}
PrintFeature(*feature);
return feature->has_location();
}
std::unique_ptr<Stub> stub_;
std::vector<Feature> feature_list_;
};
void GetFeatureAsync(const ChannelSptr& channel) {
Stub stub(channel);
// Ignore error status.
stub.Async_GetFeature(MakePoint(0, 0),
[](const Feature& feature) { PrintFeature(feature); });
// Ignore response.
stub.Async_GetFeature(MakePoint(0, 0));
Point point1 = MakePoint(409146138, -746188906);
stub.Async_GetFeature(point1,
[&stub](const Feature& feature) {
PrintFeature(feature);
stub.Shutdown();
},
[&stub](const Status& err) {
std::cout << "AsyncGetFeature rpc failed. "
<< err.GetDetails() << std::endl;
stub.Shutdown();
}); // AsyncGetFeature()
stub.Run(); // until stub.Shutdown()
}
void ListFeaturesAsync(const ChannelSptr& channel) {
Stub stub(channel);
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl;
stub.Async_ListFeatures(rect,
[](const Feature& feature) {
std::cout << "Got feature " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
},
[&stub](const Status& status) {
std::cout << "End status: (" << status.GetCode() << ") "
<< status.GetDetails() << std::endl;
stub.Shutdown(); // To break Run().
});
stub.Run(); // until stub.Shutdown()
}
void RecordRouteAsync(const ChannelSptr& channel,
const std::string& db) {
assert(!db.empty());
std::vector<Feature> feature_list;
routeguide::ParseDb(db, &feature_list);
assert(!feature_list.empty());
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list.size() - 1);
Stub stub(channel);
auto f = std::async(std::launch::async, [&stub]() { stub.Run(); });
// ClientAsyncWriter<Point, RouteSummary> async_writer;
auto async_writer = stub.Async_RecordRoute();
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!async_writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
// Recv reponse and status.
async_writer.Close([](const Status& status, const RouteSummary& resp) {
if (!status.ok()) {
std::cout << "RecordRoute rpc failed." << std::endl;
return;
}
std::cout << "Finished trip with " << resp.point_count() << " points\n"
<< "Passed " << resp.feature_count() << " features\n"
<< "Traveled " << resp.distance() << " meters\n"
<< "It took " << resp.elapsed_time() << " seconds" << std::endl;
});
// Todo: timeout
stub.Shutdown();
} // RecordRouteAsync()
void AsyncWriteRouteNotes(Stub::RouteChat_AsyncReaderWriter async_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
async_reader_writer.Write(note);
RandomSleep();
}
async_reader_writer.CloseWriting(); // Optional.
}
void RouteChatAsync(const ChannelSptr& channel) {
Stub stub(channel);
auto f_run = std::async(std::launch::async, [&stub]() {
stub.Run();
});
std::atomic_bool bReaderDone = false;
auto async_reader_writer(
stub.Async_RouteChat([&bReaderDone](const Status& status) {
if (!status.ok()) {
std::cout << "RouteChat rpc failed. " << status.GetDetails()
<< std::endl;
}
bReaderDone = true;
}));
async_reader_writer.ReadEach(
[](const RouteNote& note) { PrintServerNote(note); });
AsyncWriteRouteNotes(async_reader_writer);
while (!bReaderDone)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
stub.Shutdown(); // To break Run().
} // RouteChatAsync()
void TestRpcTimeout(const ChannelSptr& channel) {
Stub stub(channel);
stub.SetCallTimeoutMs(INT64_MIN);
Point point = MakePoint(0, 0);
Feature feature;
Status status = stub.Sync_GetFeature(point, &feature);
assert(status.GetCode() == GRPC_STATUS_DEADLINE_EXCEEDED);
}
int main(int argc, char** argv) {
// Expect only arg: --db_path=path/to/route_guide_db.json.
std::string db = routeguide::GetDbFileContent(argc, argv);
assert(!db.empty());
ChannelSptr channel(new Channel("localhost:50051"));
RouteGuideClient guide(channel, db);
TestRpcTimeout(channel);
std::cout << "---- SyncGetFeature --------------" << std::endl;
guide.SyncGetFeature();
std::cout << "---- SyncListFeatures --------------" << std::endl;
guide.SyncListFeatures();
std::cout << "---- SyncRecordRoute --------------" << std::endl;
guide.SyncRecordRoute();
std::cout << "---- SyncRouteChat --------------" << std::endl;
guide.SyncRouteChat();
std::cout << "---- GetFeatureAsync ----" << std::endl;
GetFeatureAsync(channel);
std::cout << "---- ListFeaturesAsync ----" << std::endl;
ListFeaturesAsync(channel);
std::cout << "---- RecordRouteAsnyc ----" << std::endl;
RecordRouteAsync(channel, db);
std::cout << "---- RouteChatAsync ---" << std::endl;
RouteChatAsync(channel);
return 0;
}
<commit_msg>Update example output.<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <atomic>
#include <chrono>
#include <future> // for async()
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include "helper.h"
#include "route_guide.grpc_cb.pb.h"
using grpc_cb::Channel;
using grpc_cb::ChannelSptr;
using grpc_cb::Status;
using routeguide::Point;
using routeguide::Feature;
using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide::Stub;
const float kCoordFactor = 10000000.0;
static unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count();
static std::default_random_engine generator(seed);
Point MakePoint(long latitude, long longitude) {
Point p;
p.set_latitude(latitude);
p.set_longitude(longitude);
return p;
}
routeguide::Rectangle MakeRect(const Point& lo, const Point& hi) {
routeguide::Rectangle rect;
*rect.mutable_lo() = lo;
*rect.mutable_hi() = hi;
return rect;
}
routeguide::Rectangle MakeRect(long lo_latitude, long lo_longitude,
long hi_latitude, long hi_longitude) {
return MakeRect(MakePoint(lo_latitude, lo_longitude),
MakePoint(hi_latitude, hi_longitude));
}
Feature MakeFeature(const std::string& name,
long latitude, long longitude) {
Feature f;
f.set_name(name);
f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return f;
}
RouteNote MakeRouteNote(const std::string& message,
long latitude, long longitude) {
RouteNote n;
n.set_message(message);
n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return n;
}
void PrintFeature(const Feature& feature) {
if (!feature.has_location()) {
std::cout << "Server returns incomplete feature." << std::endl;
return;
}
if (feature.name().empty()) {
std::cout << "Found no feature at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
else {
std::cout << "Found feature called " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
} // PrintFeature()
void PrintServerNote(const RouteNote& server_note) {
std::cout << "Got message " << server_note.message()
<< " at " << server_note.location().latitude() << ", "
<< server_note.location().longitude() << std::endl;
}
void RandomSleep() {
std::uniform_int_distribution<int> delay_distribution(500, 1500);
std::this_thread::sleep_for(std::chrono::milliseconds(
delay_distribution(generator)));
}
void RunWriteRouteNote(Stub::RouteChat_SyncReaderWriter sync_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
sync_reader_writer.Write(note);
// RandomSleep();
}
sync_reader_writer.CloseWriting();
}
class RouteGuideClient {
public:
RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
: stub_(new Stub(channel)) {
routeguide::ParseDb(db, &feature_list_);
assert(!feature_list_.empty());
}
void SyncGetFeature() {
Point point;
Feature feature;
point = MakePoint(409146138, -746188906);
SyncGetOneFeature(point, &feature);
point = MakePoint(0, 0);
SyncGetOneFeature(point, &feature);
}
void SyncListFeatures() {
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
Feature feature;
std::cout << "Looking for features between 40, -75 and 42, -73"
<< std::endl;
auto sync_reader(stub_->Sync_ListFeatures(rect));
while (sync_reader.ReadOne(&feature)) {
std::cout << "Found feature called "
<< feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
}
Status status = sync_reader.RecvStatus();
if (status.ok()) {
std::cout << "ListFeatures rpc succeeded." << std::endl;
} else {
std::cout << "ListFeatures rpc failed." << std::endl;
}
}
void SyncRecordRoute() {
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list_.size() - 1);
auto sync_writer(stub_->Sync_RecordRoute());
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list_[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!sync_writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
RouteSummary stats;
// Recv reponse and status.
Status status = sync_writer.Close(&stats); // Todo: timeout
if (status.ok()) {
std::cout << "Finished trip with " << stats.point_count() << " points\n"
<< "Passed " << stats.feature_count() << " features\n"
<< "Traveled " << stats.distance() << " meters\n"
<< "It took " << stats.elapsed_time() << " seconds"
<< std::endl;
} else {
std::cout << "RecordRoute rpc failed." << std::endl;
}
}
// Todo: Callback on client stream response and status.
void SyncRouteChat() {
auto sync_reader_writer(stub_->Sync_RouteChat());
auto f = std::async(std::launch::async, [sync_reader_writer]() {
RunWriteRouteNote(sync_reader_writer);
});
RouteNote server_note;
while (sync_reader_writer.ReadOne(&server_note))
PrintServerNote(server_note);
f.wait();
// Todo: Close() should auto close writing.
Status status = sync_reader_writer.RecvStatus();
if (!status.ok()) {
std::cout << "RouteChat rpc failed." << std::endl;
}
}
private:
bool SyncGetOneFeature(const Point& point, Feature* feature) {
Status status = stub_->Sync_GetFeature(point, feature);
if (!status.ok()) {
std::cout << "GetFeature rpc failed." << std::endl;
return false;
}
PrintFeature(*feature);
return feature->has_location();
}
std::unique_ptr<Stub> stub_;
std::vector<Feature> feature_list_;
};
void GetFeatureAsync(const ChannelSptr& channel) {
Stub stub(channel);
// Ignore error status.
stub.Async_GetFeature(MakePoint(0, 0),
[](const Feature& feature) { PrintFeature(feature); });
// Ignore response.
stub.Async_GetFeature(MakePoint(0, 0));
Point point1 = MakePoint(409146138, -746188906);
stub.Async_GetFeature(point1,
[&stub](const Feature& feature) {
PrintFeature(feature);
stub.Shutdown();
},
[&stub](const Status& err) {
std::cout << "AsyncGetFeature rpc failed. "
<< err.GetDetails() << std::endl;
stub.Shutdown();
}); // AsyncGetFeature()
stub.Run(); // until stub.Shutdown()
}
void ListFeaturesAsync(const ChannelSptr& channel) {
Stub stub(channel);
routeguide::Rectangle rect = MakeRect(
400000000, -750000000, 420000000, -730000000);
std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl;
stub.Async_ListFeatures(rect,
[](const Feature& feature) {
std::cout << "Found feature called " << feature.name() << " at "
<< feature.location().latitude()/kCoordFactor << ", "
<< feature.location().longitude()/kCoordFactor << std::endl;
},
[&stub](const Status& status) {
if (status.ok()) {
std::cout << "ListFeatures rpc succeeded." << std::endl;
} else {
std::cout << "ListFeatures rpc failed." << std::endl;
}
stub.Shutdown(); // To break Run().
});
stub.Run(); // until stub.Shutdown()
}
void RecordRouteAsync(const ChannelSptr& channel,
const std::string& db) {
assert(!db.empty());
std::vector<Feature> feature_list;
routeguide::ParseDb(db, &feature_list);
assert(!feature_list.empty());
Point point;
const int kPoints = 10;
std::uniform_int_distribution<int> feature_distribution(
0, feature_list.size() - 1);
Stub stub(channel);
auto f = std::async(std::launch::async, [&stub]() { stub.Run(); });
// ClientAsyncWriter<Point, RouteSummary> async_writer;
auto async_writer = stub.Async_RecordRoute();
for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list[feature_distribution(generator)];
std::cout << "Visiting point "
<< f.location().latitude()/kCoordFactor << ", "
<< f.location().longitude()/kCoordFactor << std::endl;
if (!async_writer.Write(f.location())) {
// Broken stream.
break;
}
RandomSleep();
}
// Recv reponse and status.
async_writer.Close([](const Status& status, const RouteSummary& resp) {
if (!status.ok()) {
std::cout << "RecordRoute rpc failed." << std::endl;
return;
}
std::cout << "Finished trip with " << resp.point_count() << " points\n"
<< "Passed " << resp.feature_count() << " features\n"
<< "Traveled " << resp.distance() << " meters\n"
<< "It took " << resp.elapsed_time() << " seconds" << std::endl;
});
// Todo: timeout
stub.Shutdown();
} // RecordRouteAsync()
void AsyncWriteRouteNotes(Stub::RouteChat_AsyncReaderWriter async_reader_writer) {
std::vector<RouteNote> notes{
MakeRouteNote("First message", 0, 0),
MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message()
<< " at " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl;
async_reader_writer.Write(note);
RandomSleep();
}
async_reader_writer.CloseWriting(); // Optional.
}
void RouteChatAsync(const ChannelSptr& channel) {
Stub stub(channel);
auto f_run = std::async(std::launch::async, [&stub]() {
stub.Run();
});
std::atomic_bool bReaderDone = false;
auto async_reader_writer(
stub.Async_RouteChat([&bReaderDone](const Status& status) {
if (!status.ok()) {
std::cout << "RouteChat rpc failed. " << status.GetDetails()
<< std::endl;
}
bReaderDone = true;
}));
async_reader_writer.ReadEach(
[](const RouteNote& note) { PrintServerNote(note); });
AsyncWriteRouteNotes(async_reader_writer);
while (!bReaderDone)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
stub.Shutdown(); // To break Run().
} // RouteChatAsync()
void TestRpcTimeout(const ChannelSptr& channel) {
Stub stub(channel);
stub.SetCallTimeoutMs(INT64_MIN);
Point point = MakePoint(0, 0);
Feature feature;
Status status = stub.Sync_GetFeature(point, &feature);
assert(status.GetCode() == GRPC_STATUS_DEADLINE_EXCEEDED);
}
int main(int argc, char** argv) {
// Expect only arg: --db_path=path/to/route_guide_db.json.
std::string db = routeguide::GetDbFileContent(argc, argv);
assert(!db.empty());
ChannelSptr channel(new Channel("localhost:50051"));
RouteGuideClient guide(channel, db);
TestRpcTimeout(channel);
std::cout << "---- SyncGetFeature --------------" << std::endl;
guide.SyncGetFeature();
std::cout << "---- SyncListFeatures --------------" << std::endl;
guide.SyncListFeatures();
std::cout << "---- SyncRecordRoute --------------" << std::endl;
guide.SyncRecordRoute();
std::cout << "---- SyncRouteChat --------------" << std::endl;
guide.SyncRouteChat();
std::cout << "---- GetFeatureAsync ----" << std::endl;
GetFeatureAsync(channel);
std::cout << "---- ListFeaturesAsync ----" << std::endl;
ListFeaturesAsync(channel);
std::cout << "---- RecordRouteAsnyc ----" << std::endl;
RecordRouteAsync(channel, db);
std::cout << "---- RouteChatAsync ---" << std::endl;
RouteChatAsync(channel);
return 0;
}
<|endoftext|>
|
<commit_before>#include "lineedit.h"
#include <qml.h>
LineEditExtension::LineEditExtension(QObject *object)
: QObject(object), m_lineedit(static_cast<QLineEdit *>(object))
{
}
int LineEditExtension::leftMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return l;
}
int LineEditExtension::setLeftMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(m, t, r, b);
}
int LineEditExtension::rightMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return r;
}
int LineEditExtension::setRightMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, t, m, b);
}
int LineEditExtension::topMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return t;
}
int LineEditExtension::setTopMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, m, r, b);
}
int LineEditExtension::bottomMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return b;
}
int LineEditExtension::setBottomMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, t, r, m);
}
QML_DECLARE_TYPE(QLineEdit);
QML_DEFINE_EXTENDED_TYPE(QLineEdit, QLineEdit, LineEditExtension);
<commit_msg>Fix QML_DEFINE_EXTENDED_TYPE use in extending/extended example.<commit_after>#include "lineedit.h"
#include <qml.h>
LineEditExtension::LineEditExtension(QObject *object)
: QObject(object), m_lineedit(static_cast<QLineEdit *>(object))
{
}
int LineEditExtension::leftMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return l;
}
int LineEditExtension::setLeftMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(m, t, r, b);
}
int LineEditExtension::rightMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return r;
}
int LineEditExtension::setRightMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, t, m, b);
}
int LineEditExtension::topMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return t;
}
int LineEditExtension::setTopMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, m, r, b);
}
int LineEditExtension::bottomMargin() const
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
return b;
}
int LineEditExtension::setBottomMargin(int m)
{
int l, r, t, b;
m_lineedit->getTextMargins(&l, &t, &r, &b);
m_lineedit->setTextMargins(l, t, r, m);
}
QML_DECLARE_TYPE(QLineEdit);
QML_DEFINE_EXTENDED_TYPE(People, 1, 0, 0, QLineEdit, QLineEdit, LineEditExtension);
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: slide.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2007-07-17 15:15:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SLIDESHOW_SLIDE_HXX
#define INCLUDED_SLIDESHOW_SLIDE_HXX
#include "shapemanager.hxx"
#include "subsettableshapemanager.hxx"
#include "unoviewcontainer.hxx"
#include "slidebitmap.hxx"
#include "shapemaps.hxx"
#include <boost/shared_ptr.hpp>
namespace com { namespace sun { namespace star {
namespace drawing {
class XDrawPage;
}
namespace uno {
class XComponentContext;
}
namespace animations {
class XAnimationNode;
} } } }
namespace basegfx
{
class B2IVector;
}
/* Definition of Slide interface */
namespace slideshow
{
namespace internal
{
class RGBColor;
class ScreenUpdater;
class Slide
{
public:
// Showing
// -------------------------------------------------------------------
/** Prepares to show slide.
Call this method to reduce the timeout show(), and
getInitialSlideBitmap() need to complete. If
prefetch() is not called explicitely, the named
methods will call it implicitely.
*/
virtual bool prefetch() = 0;
/** Shows the slide on all registered views
After this call, the slide will render itself to the
views, and start its animations.
@param bSlideBackgoundPainted
When true, the initial slide content on the background
layer is already rendered (e.g. from a previous slide
transition). When false, Slide renders initial content of
slide.
*/
virtual bool show( bool bSlideBackgoundPainted ) = 0;
/** Force-ends the slide
After this call, the slide has stopped all animations,
and ceased rendering/visualization on all views.
*/
virtual void hide() = 0;
// Queries
// -------------------------------------------------------------------
/** Query the size of this slide in user coordinates
This value is retrieved from the XDrawPage properties.
*/
virtual basegfx::B2IVector getSlideSize() const = 0;
/// Gets the underlying API page
virtual ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XDrawPage > getXDrawPage() const = 0;
/// Gets the animation node.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > getXAnimationNode() const = 0;
// Slide bitmaps
// -------------------------------------------------------------------
/** Request bitmap for current slide appearance.
The bitmap returned by this method depends on the
current state of the slide and the contained
animations. A newly generated slide will return the
initial slide content here (e.g. with all 'appear'
effect shapes invisible), a slide whose effects are
currently running will return a bitmap corresponding
to the current position on the animation timeline, and
a slide whose effects have all been run will generate
a bitmap with the final slide appearance (e.g. with
all 'hide' effect shapes invisible).
@param rView
View to retrieve bitmap for (note that the bitmap will
have device-pixel equivalence to the content that
would have been rendered onto the given view). Note
that the view must have been added to this slide
before via viewAdded().
*/
virtual SlideBitmapSharedPtr
getCurrentSlideBitmap( const UnoViewSharedPtr& rView ) const = 0;
};
typedef ::boost::shared_ptr< Slide > SlideSharedPtr;
class EventQueue;
class CursorManager;
class EventMultiplexer;
class ActivitiesQueue;
class UserEventQueue;
class RGBColor;
/** Construct from XDrawPage
The Slide object generally works in XDrawPage model
coordinates, that is, the page will have the width and
height as specified in the XDrawPage's property
set. The top, left corner of the page will be rendered
at (0,0) in the given canvas' view coordinate system.
Does not render anything initially
@param xDrawPage
Page to display on this slide
@param xRootNode
Root of the SMIL animation tree. Used to animate the slide.
@param rEventQueue
EventQueue. Used to post events.
@param rActivitiesQueue
ActivitiesQueue. Used to run animations.
@param rEventMultiplexer
Event source
@param rUserEventQueue
UserEeventQueue
*/
SlideSharedPtr createSlide( const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XDrawPage >& xDrawPage,
const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& xRootNode,
EventQueue& rEventQueue,
EventMultiplexer& rEventMultiplexer,
ScreenUpdater& rScreenUpdater,
ActivitiesQueue& rActivitiesQueue,
UserEventQueue& rUserEventQueue,
CursorManager& rCursorManager,
const UnoViewContainer& rViewContainer,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext >& xContext,
const ShapeEventListenerMap& rShapeListenerMap,
const ShapeCursorMap& rShapeCursorMap,
RGBColor const& aUserPaintColor,
bool bUserPaintEnabled,
bool bIntrinsicAnimationsAllowed,
bool bDisableAnimationZOrder );
}
}
#endif /* INCLUDED_SLIDESHOW_SLIDE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.9.46); FILE MERGED 2008/03/31 14:00:30 rt 1.9.46.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: slide.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SLIDESHOW_SLIDE_HXX
#define INCLUDED_SLIDESHOW_SLIDE_HXX
#include "shapemanager.hxx"
#include "subsettableshapemanager.hxx"
#include "unoviewcontainer.hxx"
#include "slidebitmap.hxx"
#include "shapemaps.hxx"
#include <boost/shared_ptr.hpp>
namespace com { namespace sun { namespace star {
namespace drawing {
class XDrawPage;
}
namespace uno {
class XComponentContext;
}
namespace animations {
class XAnimationNode;
} } } }
namespace basegfx
{
class B2IVector;
}
/* Definition of Slide interface */
namespace slideshow
{
namespace internal
{
class RGBColor;
class ScreenUpdater;
class Slide
{
public:
// Showing
// -------------------------------------------------------------------
/** Prepares to show slide.
Call this method to reduce the timeout show(), and
getInitialSlideBitmap() need to complete. If
prefetch() is not called explicitely, the named
methods will call it implicitely.
*/
virtual bool prefetch() = 0;
/** Shows the slide on all registered views
After this call, the slide will render itself to the
views, and start its animations.
@param bSlideBackgoundPainted
When true, the initial slide content on the background
layer is already rendered (e.g. from a previous slide
transition). When false, Slide renders initial content of
slide.
*/
virtual bool show( bool bSlideBackgoundPainted ) = 0;
/** Force-ends the slide
After this call, the slide has stopped all animations,
and ceased rendering/visualization on all views.
*/
virtual void hide() = 0;
// Queries
// -------------------------------------------------------------------
/** Query the size of this slide in user coordinates
This value is retrieved from the XDrawPage properties.
*/
virtual basegfx::B2IVector getSlideSize() const = 0;
/// Gets the underlying API page
virtual ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XDrawPage > getXDrawPage() const = 0;
/// Gets the animation node.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > getXAnimationNode() const = 0;
// Slide bitmaps
// -------------------------------------------------------------------
/** Request bitmap for current slide appearance.
The bitmap returned by this method depends on the
current state of the slide and the contained
animations. A newly generated slide will return the
initial slide content here (e.g. with all 'appear'
effect shapes invisible), a slide whose effects are
currently running will return a bitmap corresponding
to the current position on the animation timeline, and
a slide whose effects have all been run will generate
a bitmap with the final slide appearance (e.g. with
all 'hide' effect shapes invisible).
@param rView
View to retrieve bitmap for (note that the bitmap will
have device-pixel equivalence to the content that
would have been rendered onto the given view). Note
that the view must have been added to this slide
before via viewAdded().
*/
virtual SlideBitmapSharedPtr
getCurrentSlideBitmap( const UnoViewSharedPtr& rView ) const = 0;
};
typedef ::boost::shared_ptr< Slide > SlideSharedPtr;
class EventQueue;
class CursorManager;
class EventMultiplexer;
class ActivitiesQueue;
class UserEventQueue;
class RGBColor;
/** Construct from XDrawPage
The Slide object generally works in XDrawPage model
coordinates, that is, the page will have the width and
height as specified in the XDrawPage's property
set. The top, left corner of the page will be rendered
at (0,0) in the given canvas' view coordinate system.
Does not render anything initially
@param xDrawPage
Page to display on this slide
@param xRootNode
Root of the SMIL animation tree. Used to animate the slide.
@param rEventQueue
EventQueue. Used to post events.
@param rActivitiesQueue
ActivitiesQueue. Used to run animations.
@param rEventMultiplexer
Event source
@param rUserEventQueue
UserEeventQueue
*/
SlideSharedPtr createSlide( const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XDrawPage >& xDrawPage,
const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& xRootNode,
EventQueue& rEventQueue,
EventMultiplexer& rEventMultiplexer,
ScreenUpdater& rScreenUpdater,
ActivitiesQueue& rActivitiesQueue,
UserEventQueue& rUserEventQueue,
CursorManager& rCursorManager,
const UnoViewContainer& rViewContainer,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext >& xContext,
const ShapeEventListenerMap& rShapeListenerMap,
const ShapeCursorMap& rShapeCursorMap,
RGBColor const& aUserPaintColor,
bool bUserPaintEnabled,
bool bIntrinsicAnimationsAllowed,
bool bDisableAnimationZOrder );
}
}
#endif /* INCLUDED_SLIDESHOW_SLIDE_HXX */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/rt/DynamicObject.h"
#include "db/rt/DynamicObjectIterator.h"
#include "db/rt/DynamicObjectIterators.h"
#include <cstdlib>
using namespace db::rt;
DynamicObject::DynamicObject() :
Collectable<DynamicObjectImpl>(new DynamicObjectImpl())
{
}
DynamicObject::DynamicObject(DynamicObjectImpl* impl) :
Collectable<DynamicObjectImpl>(impl)
{
}
DynamicObject::DynamicObject(const DynamicObject& rhs) :
Collectable<DynamicObjectImpl>(rhs)
{
}
DynamicObject::~DynamicObject()
{
}
bool DynamicObject::operator==(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && !lhs.isNull() && !rhs.isNull())
{
// compare heap objects
rval = (*lhs == *rhs);
}
return rval;
}
bool DynamicObject::operator!=(const DynamicObject& rhs)
{
return !(*this == rhs);
}
bool DynamicObject::operator<(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
// NULL is always less than anything other than NULL
if(lhs.isNull())
{
rval = !rhs.isNull();
}
// lhs is not NULL, but rhs is, so rhs is not less
else if(rhs.isNull())
{
rval = false;
}
// neither lhs or rhs is NULL, compare heap objects
else
{
rval = (*lhs < *rhs);
}
return rval;
}
void DynamicObject::operator=(const char* value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(bool value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(double value)
{
*mReference->ptr = value;
}
DynamicObject& DynamicObject::operator[](const char* name)
{
return (*mReference->ptr)[name];
}
DynamicObject& DynamicObject::operator[](int index)
{
return (*mReference->ptr)[index];
}
DynamicObjectIterator DynamicObject::getIterator() const
{
DynamicObjectIteratorImpl* i;
switch((*this)->getType())
{
case Map:
i = new DynamicObjectIteratorMap((DynamicObject&)*this);
break;
case Array:
i = new DynamicObjectIteratorArray((DynamicObject&)*this);
break;
default:
i = new DynamicObjectIteratorSingle((DynamicObject&)*this);
break;
}
return DynamicObjectIterator(i);
}
DynamicObject DynamicObject::clone()
{
DynamicObject rval;
if(isNull())
{
rval.setNull();
}
else
{
int index = 0;
rval->setType((*this)->getType());
DynamicObjectIterator i = getIterator();
while(i->hasNext())
{
DynamicObject dyno = i->next();
switch((*this)->getType())
{
case String:
rval = dyno->getString();
break;
case Boolean:
rval = dyno->getBoolean();
break;
case Int32:
rval = dyno->getInt32();
break;
case UInt32:
rval = dyno->getUInt32();
break;
case Int64:
rval = dyno->getInt64();
break;
case UInt64:
rval = dyno->getUInt64();
break;
case Double:
rval = dyno->getDouble();
break;
case Map:
rval[i->getName()] = dyno.clone();
break;
case Array:
rval[index++] = dyno.clone();
break;
}
}
}
return rval;
}
void DynamicObject::merge(DynamicObject& rhs, bool append)
{
switch(rhs->getType())
{
case String:
case Boolean:
case Int32:
case UInt32:
case Int64:
case UInt64:
case Double:
*this = rhs.clone();
break;
case Map:
{
(*this)->setType(Map);
DynamicObjectIterator i = rhs.getIterator();
while(i->hasNext())
{
DynamicObject next = i->next();
(*this)[i->getName()].merge(next, append);
}
break;
}
case Array:
(*this)->setType(Array);
DynamicObjectIterator i = rhs.getIterator();
int offset = (append ? (*this)->length() : 0);
for(int ii = 0; i->hasNext(); ii++)
{
(*this)[offset + ii].merge(i->next(), append);
}
break;
}
}
bool DynamicObject::isSubset(const DynamicObject& rhs) const
{
bool rval;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && (*this)->getType() == Map && rhs->getType() == Map)
{
// ensure right map has same or greater length
if((*this)->length() <= rhs->length())
{
rval = true;
DynamicObjectIterator i = this->getIterator();
while(rval && i->hasNext())
{
DynamicObject& leftDyno = i->next();
if(rhs->hasMember(i->getName()))
{
DynamicObject& rightDyno = (*rhs)[i->getName()];
if(leftDyno->getType() == Map && rightDyno->getType() == Map)
{
rval = leftDyno.isSubset(rightDyno);
}
else
{
rval = (leftDyno == rightDyno);
}
}
else
{
rval = false;
}
}
}
}
return rval;
}
const char* DynamicObject::descriptionForType(DynamicObjectType type)
{
const char* rval;
switch(type)
{
case String:
rval = "string";
break;
case Boolean:
rval = "boolean";
break;
case Int32:
rval = "32 bit integer";
break;
case UInt32:
rval = "32 bit unsigned integer";
break;
case Int64:
rval = "64 bit integer";
break;
case UInt64:
rval = "64 bit unsigned integer";
break;
case Double:
rval = "floating point";
break;
case Map:
rval = "map";
break;
case Array:
rval = "array";
break;
}
return rval;
}
DynamicObjectType DynamicObject::determineType(const char* str)
{
DynamicObjectType rval = String;
// FIXME: this code might interpret hex/octal strings as integers
// (and other code for that matter!) and we might not want to do that
// if string starts with whitespace, forget about it
if(!isspace(str[0]))
{
// see if the number is an unsigned int
// then check signed int
// then check doubles
char* end;
strtoull(str, &end, 10);
if(end[0] == 0 && str[0] != '-')
{
// if end is NULL (and not negative) then the whole string was an int
rval = UInt64;
}
else
{
// the number may be a signed int
strtoll(str, &end, 10);
if(end[0] == 0)
{
// if end is NULL then the whole string was an int
rval = Int64;
}
else
{
// the number may be a double
strtod(str, &end);
if(end[0] == 0)
{
// end is NULL, so we've got a double,
// else we've assume a String
rval = Double;
}
}
}
}
return rval;
}
<commit_msg>Small optimization.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/rt/DynamicObject.h"
#include "db/rt/DynamicObjectIterator.h"
#include "db/rt/DynamicObjectIterators.h"
#include <cstdlib>
using namespace db::rt;
DynamicObject::DynamicObject() :
Collectable<DynamicObjectImpl>(new DynamicObjectImpl())
{
}
DynamicObject::DynamicObject(DynamicObjectImpl* impl) :
Collectable<DynamicObjectImpl>(impl)
{
}
DynamicObject::DynamicObject(const DynamicObject& rhs) :
Collectable<DynamicObjectImpl>(rhs)
{
}
DynamicObject::~DynamicObject()
{
}
bool DynamicObject::operator==(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && !lhs.isNull() && !rhs.isNull())
{
// compare heap objects
rval = (*lhs == *rhs);
}
return rval;
}
bool DynamicObject::operator!=(const DynamicObject& rhs)
{
return !(*this == rhs);
}
bool DynamicObject::operator<(const DynamicObject& rhs) const
{
bool rval;
const DynamicObject& lhs = *this;
// NULL is always less than anything other than NULL
if(lhs.isNull())
{
rval = !rhs.isNull();
}
// lhs is not NULL, but rhs is, so rhs is not less
else if(rhs.isNull())
{
rval = false;
}
// neither lhs or rhs is NULL, compare heap objects
else
{
rval = (*lhs < *rhs);
}
return rval;
}
void DynamicObject::operator=(const char* value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(bool value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint32_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(int64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(uint64_t value)
{
*mReference->ptr = value;
}
void DynamicObject::operator=(double value)
{
*mReference->ptr = value;
}
DynamicObject& DynamicObject::operator[](const char* name)
{
return (*mReference->ptr)[name];
}
DynamicObject& DynamicObject::operator[](int index)
{
return (*mReference->ptr)[index];
}
DynamicObjectIterator DynamicObject::getIterator() const
{
DynamicObjectIteratorImpl* i;
switch((*this)->getType())
{
case Map:
i = new DynamicObjectIteratorMap((DynamicObject&)*this);
break;
case Array:
i = new DynamicObjectIteratorArray((DynamicObject&)*this);
break;
default:
i = new DynamicObjectIteratorSingle((DynamicObject&)*this);
break;
}
return DynamicObjectIterator(i);
}
DynamicObject DynamicObject::clone()
{
DynamicObject rval;
if(isNull())
{
rval.setNull();
}
else
{
int index = 0;
rval->setType((*this)->getType());
DynamicObjectIterator i = getIterator();
while(i->hasNext())
{
DynamicObject dyno = i->next();
switch((*this)->getType())
{
case String:
rval = dyno->getString();
break;
case Boolean:
rval = dyno->getBoolean();
break;
case Int32:
rval = dyno->getInt32();
break;
case UInt32:
rval = dyno->getUInt32();
break;
case Int64:
rval = dyno->getInt64();
break;
case UInt64:
rval = dyno->getUInt64();
break;
case Double:
rval = dyno->getDouble();
break;
case Map:
rval[i->getName()] = dyno.clone();
break;
case Array:
rval[index++] = dyno.clone();
break;
}
}
}
return rval;
}
void DynamicObject::merge(DynamicObject& rhs, bool append)
{
switch(rhs->getType())
{
case String:
case Boolean:
case Int32:
case UInt32:
case Int64:
case UInt64:
case Double:
*this = rhs.clone();
break;
case Map:
{
(*this)->setType(Map);
DynamicObjectIterator i = rhs.getIterator();
while(i->hasNext())
{
DynamicObject& next = i->next();
(*this)[i->getName()].merge(next, append);
}
break;
}
case Array:
(*this)->setType(Array);
DynamicObjectIterator i = rhs.getIterator();
int offset = (append ? (*this)->length() : 0);
for(int ii = 0; i->hasNext(); ii++)
{
(*this)[offset + ii].merge(i->next(), append);
}
break;
}
}
bool DynamicObject::isSubset(const DynamicObject& rhs) const
{
bool rval;
rval = Collectable<DynamicObjectImpl>::operator==(rhs);
if(!rval && (*this)->getType() == Map && rhs->getType() == Map)
{
// ensure right map has same or greater length
if((*this)->length() <= rhs->length())
{
rval = true;
DynamicObjectIterator i = this->getIterator();
while(rval && i->hasNext())
{
DynamicObject& leftDyno = i->next();
if(rhs->hasMember(i->getName()))
{
DynamicObject& rightDyno = (*rhs)[i->getName()];
if(leftDyno->getType() == Map && rightDyno->getType() == Map)
{
rval = leftDyno.isSubset(rightDyno);
}
else
{
rval = (leftDyno == rightDyno);
}
}
else
{
rval = false;
}
}
}
}
return rval;
}
const char* DynamicObject::descriptionForType(DynamicObjectType type)
{
const char* rval;
switch(type)
{
case String:
rval = "string";
break;
case Boolean:
rval = "boolean";
break;
case Int32:
rval = "32 bit integer";
break;
case UInt32:
rval = "32 bit unsigned integer";
break;
case Int64:
rval = "64 bit integer";
break;
case UInt64:
rval = "64 bit unsigned integer";
break;
case Double:
rval = "floating point";
break;
case Map:
rval = "map";
break;
case Array:
rval = "array";
break;
}
return rval;
}
DynamicObjectType DynamicObject::determineType(const char* str)
{
DynamicObjectType rval = String;
// FIXME: this code might interpret hex/octal strings as integers
// (and other code for that matter!) and we might not want to do that
// if string starts with whitespace, forget about it
if(!isspace(str[0]))
{
// see if the number is an unsigned int
// then check signed int
// then check doubles
char* end;
strtoull(str, &end, 10);
if(end[0] == 0 && str[0] != '-')
{
// if end is NULL (and not negative) then the whole string was an int
rval = UInt64;
}
else
{
// the number may be a signed int
strtoll(str, &end, 10);
if(end[0] == 0)
{
// if end is NULL then the whole string was an int
rval = Int64;
}
else
{
// the number may be a double
strtod(str, &end);
if(end[0] == 0)
{
// end is NULL, so we've got a double,
// else we've assume a String
rval = Double;
}
}
}
}
return rval;
}
<|endoftext|>
|
<commit_before>#include "LargeRAWFile.h"
using namespace std;
#define BLOCK_COPY_SIZE (UINT64(128*1024*1024))
LargeRAWFile::LargeRAWFile(const std::string& strFilename, UINT64 iHeaderSize) :
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, UINT64 iHeaderSize) :
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(LargeRAWFile &other) :
m_strFilename(other.m_strFilename+"~"),
m_bIsOpen(other.m_bIsOpen),
m_iHeaderSize(other.m_iHeaderSize)
{
if (m_bIsOpen) {
UINT64 iDataSize = other.GetCurrentSize();
Create(iDataSize);
other.SeekStart();
unsigned char* pData = new unsigned char[size_t(min(iDataSize, BLOCK_COPY_SIZE))];
for (UINT64 i = 0;i<iDataSize;i+=BLOCK_COPY_SIZE) {
UINT64 iCopySize = min(BLOCK_COPY_SIZE, iDataSize-i);
other.ReadRAW(pData, iCopySize);
WriteRAW(pData, iCopySize);
}
delete [] pData;
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "w+b" : "rb");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(UINT64 iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) {
SeekPos(iInitialSize);
SeekStart();
}
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
UINT64 LargeRAWFile::GetCurrentSize() {
UINT64 iPrevPos = GetPos();
SeekStart();
UINT64 ulStart = GetPos();
UINT64 ulEnd = SeekEnd();
UINT64 ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart(){
SeekPos(0);
}
UINT64 LargeRAWFile::SeekEnd(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
else
return 0;
#endif
}
UINT64 LargeRAWFile::GetPos(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
#endif
}
void LargeRAWFile::SeekPos(UINT64 iPos){
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
<commit_msg>Potential uninitialized var: copy writable flag from source.<commit_after>#include "LargeRAWFile.h"
using namespace std;
#define BLOCK_COPY_SIZE (UINT64(128*1024*1024))
LargeRAWFile::LargeRAWFile(const std::string& strFilename, UINT64 iHeaderSize) :
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, UINT64 iHeaderSize) :
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(LargeRAWFile &other) :
m_strFilename(other.m_strFilename+"~"),
m_bIsOpen(other.m_bIsOpen),
m_iHeaderSize(other.m_iHeaderSize),
m_bWritable(other.m_bWritable)
{
if (m_bIsOpen) {
UINT64 iDataSize = other.GetCurrentSize();
Create(iDataSize);
other.SeekStart();
unsigned char* pData = new unsigned char[size_t(min(iDataSize, BLOCK_COPY_SIZE))];
for (UINT64 i = 0;i<iDataSize;i+=BLOCK_COPY_SIZE) {
UINT64 iCopySize = min(BLOCK_COPY_SIZE, iDataSize-i);
other.ReadRAW(pData, iCopySize);
WriteRAW(pData, iCopySize);
}
delete [] pData;
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "w+b" : "rb");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(UINT64 iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) {
SeekPos(iInitialSize);
SeekStart();
}
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
UINT64 LargeRAWFile::GetCurrentSize() {
UINT64 iPrevPos = GetPos();
SeekStart();
UINT64 ulStart = GetPos();
UINT64 ulEnd = SeekEnd();
UINT64 ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart(){
SeekPos(0);
}
UINT64 LargeRAWFile::SeekEnd(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
else
return 0;
#endif
}
UINT64 LargeRAWFile::GetPos(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
#endif
}
void LargeRAWFile::SeekPos(UINT64 iPos){
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
<|endoftext|>
|
<commit_before>#ifndef MYPARSER_AST_HPP
#define MYPARSER_AST_HPP
#include "myparser_str.hpp"
#include "myparser_pass.hpp"
namespace myparser {
using Input = std::string::const_iterator;
using BuiltinRoot = MP_STR("root", 4);
using BuiltinSpace = MP_STR("space", 5);
using BuiltinKeyword = MP_STR("keyword", 7);
using BuiltinError = MP_STR("error", 5);
template <class TX = void> // actually not a template
class Node {
private:
const Input pos;
inline Node() = delete;
protected:
inline Node(
const Input &input
): pos(input) {}
public:
virtual ~Node() {} // destructable (public)
virtual void free() {
delete this;
}
virtual bool empty() const = 0;
virtual void runPass(PassBase<> *pass) const = 0;
virtual const std::string &getRuleName() const = 0;
virtual size_t getLen() const = 0;
virtual void getFullText(std::ostream &out) const = 0;
inline const std::string asFullText() const {
std::ostringstream result;
getFullText(result);
return result.str();
}
inline const Input &getPos() const {
return pos;
}
inline const Input getTail() const {
return pos + getLen();
}
inline Node<> *challengeLonger(Node<> *target) {
if (!target) {
return this;
}
if (getTail() > target->getTail()) {
target->free();
return this;
} else {
this->free();
return target;
}
}
};
template <class TX = void> // actually not a template
class NodeList: public Node<> {
private:
std::vector<Node<> *> children;
size_t basepos;
NodeList<> *brother = nullptr;
protected:
inline NodeList(
const Input &input
): Node<>(input), children() {}
public:
virtual ~NodeList() {
for (size_t i = basepos; i < children.size(); ++i) {
children[i]->free();
}
}
virtual void free() {
if (brother) {
brother->basepos = 0;
brother->brother = nullptr;
}
delete this;
}
virtual bool empty() const {
for (Node<> *child: children) {
if (!child->empty()) {
return false;
}
}
return true;
}
inline void bind(NodeList<> *target, const size_t pos) {
brother = target;
basepos = pos;
}
inline void putChild(Node<> *value) {
children.push_back(value);
}
virtual size_t getLen() const {
size_t result = 0;
for (Node<> *child: children) {
result += child->getLen();
}
return result;
}
virtual void getFullText(std::ostream &out) const {
for (Node<> *child: children) {
child->getFullText(out);
}
}
inline const std::vector<Node<> *> &getChildren() const {
return children;
}
};
template <size_t I>
class NodeListIndexed: public NodeList<> {
public:
inline NodeListIndexed(
const Input &input
): NodeList<>(input) {}
// virtual ~NodeListIndexed() {}
inline size_t getIndex() const {
return I;
}
};
template <class TX = void> // actually not a template
class NodeText: public Node<> {
private:
const std::string text;
protected:
inline NodeText(
const Input &input, std::string &&value
): Node<>(input), text(std::move(value)) {}
inline NodeText(
const Input &input, const std::string &value
): Node<>(input), text(value) {}
public:
// virtual ~NodeText() {}
virtual bool accepted() const {
return true;
}
virtual bool empty() const {
return accepted() && text.size() == 0;
}
virtual size_t getLen() const {
return text.size();
}
virtual void getFullText(std::ostream &out) const {
out << text;
}
inline const std::string &getText() const {
return text;
}
};
template <class TX = void> // actually not a template
class NodeTextPure: public NodeText<> {
public:
inline NodeTextPure(
const Input &input, std::string &&value
): NodeText<>(input, std::move(value)) {}
// virtual ~NodeTextPure() {}
};
template <class E>
class NodeTextOrError: public NodeText<> {
public:
inline NodeTextOrError(
const Input &input, std::string &&value
): NodeText<>(input, std::move(value)) {}
// virtual ~NodeTextOrError() {}
};
template <class E>
class NodeError: public Node<> {
public:
inline NodeError(
const Input &input
): Node<>(input) {}
// virtual ~NodeError() {}
virtual bool empty() const {
return false;
}
virtual size_t getLen() const {
return 0;
}
virtual void getFullText(std::ostream &out) const {
// nothing
(void) out;
}
};
// could specialize
template <class N>
class NodeBaseList {
public:
template <size_t I>
using Type = NodeListIndexed<I>;
};
// could specialize
template <class N>
class NodeBaseText {
public:
template <class TX = void> // actually not a template
using Type = NodeTextPure<>;
};
// could specialize
template <class N>
class NodeBaseError {
public:
template <class E>
using Type = NodeError<E>;
};
template <class N, class T, size_t I = 0 /* bind later */>
class NodeTyped: public T {
public:
using T::T;
virtual void runPass(PassBase<> *pass) const {
Pass<I>::call(pass, pass->getId(), this);
}
virtual const std::string &getRuleName() const {
return N::getStr();
}
};
template <class N, size_t I>
using NodeTypedList = NodeTyped<N, typename NodeBaseList<N>::template Type<I>>;
template <class N>
using NodeTypedText = NodeTyped<N, typename NodeBaseText<N>::template Type<>>;
template <class N, class E>
using NodeTypedError = NodeTyped<N, typename NodeBaseError<N>::template Type<E>>;
}
#endif
<commit_msg>simplify getTail()<commit_after>#ifndef MYPARSER_AST_HPP
#define MYPARSER_AST_HPP
#include "myparser_str.hpp"
#include "myparser_pass.hpp"
namespace myparser {
using Input = std::string::const_iterator;
using BuiltinRoot = MP_STR("root", 4);
using BuiltinSpace = MP_STR("space", 5);
using BuiltinKeyword = MP_STR("keyword", 7);
using BuiltinError = MP_STR("error", 5);
template <class TX = void> // actually not a template
class Node {
private:
inline Node() = delete;
protected:
inline Node(
const Input &input
): pos(input), tail(input) {}
const Input pos;
Input tail;
public:
virtual ~Node() {} // destructable (public)
virtual void free() {
delete this;
}
virtual bool empty() const = 0;
virtual void runPass(PassBase<> *pass) const = 0;
virtual const std::string &getRuleName() const = 0;
virtual void getFullText(std::ostream &out) const = 0;
inline const std::string asFullText() const {
std::ostringstream result;
getFullText(result);
return result.str();
}
inline const Input &getPos() const {
return pos;
}
inline const Input &getTail() const {
return tail;
}
inline Node<> *challengeLonger(Node<> *target) {
if (!target) {
return this;
}
if (getTail() > target->getTail()) {
target->free();
return this;
} else {
this->free();
return target;
}
}
};
template <class TX = void> // actually not a template
class NodeList: public Node<> {
private:
std::vector<Node<> *> children;
size_t basepos;
NodeList<> *brother = nullptr;
protected:
inline NodeList(
const Input &input
): Node<>(input), children() {}
public:
virtual ~NodeList() {
for (size_t i = basepos; i < children.size(); ++i) {
children[i]->free();
}
}
virtual void free() {
if (brother) {
brother->basepos = 0;
brother->brother = nullptr;
}
delete this;
}
virtual bool empty() const {
for (Node<> *child: children) {
if (!child->empty()) {
return false;
}
}
return true;
}
inline void bind(NodeList<> *target, const size_t pos) {
brother = target;
basepos = pos;
}
inline void putChild(Node<> *value) {
children.push_back(value);
tail = value->getTail();
}
virtual void getFullText(std::ostream &out) const {
for (Node<> *child: children) {
child->getFullText(out);
}
}
inline const std::vector<Node<> *> &getChildren() const {
return children;
}
};
template <size_t I>
class NodeListIndexed: public NodeList<> {
public:
inline NodeListIndexed(
const Input &input
): NodeList<>(input) {}
// virtual ~NodeListIndexed() {}
inline size_t getIndex() const {
return I;
}
};
template <class TX = void> // actually not a template
class NodeText: public Node<> {
private:
const std::string text;
protected:
inline NodeText(
const Input &input, std::string &&value
): Node<>(input), text(std::move(value)) {
tail = tail + text.size();
}
inline NodeText(
const Input &input, const std::string &value
): Node<>(input), text(value) {
tail = tail + text.size();
}
public:
// virtual ~NodeText() {}
virtual bool accepted() const {
return true;
}
virtual bool empty() const {
return accepted() && text.size() == 0;
}
virtual void getFullText(std::ostream &out) const {
out << text;
}
inline const std::string &getText() const {
return text;
}
};
template <class TX = void> // actually not a template
class NodeTextPure: public NodeText<> {
public:
inline NodeTextPure(
const Input &input, std::string &&value
): NodeText<>(input, std::move(value)) {}
// virtual ~NodeTextPure() {}
};
template <class E>
class NodeTextOrError: public NodeText<> {
public:
inline NodeTextOrError(
const Input &input, std::string &&value
): NodeText<>(input, std::move(value)) {}
// virtual ~NodeTextOrError() {}
};
template <class E>
class NodeError: public Node<> {
public:
inline NodeError(
const Input &input
): Node<>(input) {}
// virtual ~NodeError() {}
virtual bool empty() const {
return false;
}
virtual void getFullText(std::ostream &out) const {
// nothing
(void) out;
}
};
// could specialize
template <class N>
class NodeBaseList {
public:
template <size_t I>
using Type = NodeListIndexed<I>;
};
// could specialize
template <class N>
class NodeBaseText {
public:
template <class TX = void> // actually not a template
using Type = NodeTextPure<>;
};
// could specialize
template <class N>
class NodeBaseError {
public:
template <class E>
using Type = NodeError<E>;
};
template <class N, class T, size_t I = 0 /* bind later */>
class NodeTyped: public T {
public:
using T::T;
virtual void runPass(PassBase<> *pass) const {
Pass<I>::call(pass, pass->getId(), this);
}
virtual const std::string &getRuleName() const {
return N::getStr();
}
};
template <class N, size_t I>
using NodeTypedList = NodeTyped<N, typename NodeBaseList<N>::template Type<I>>;
template <class N>
using NodeTypedText = NodeTyped<N, typename NodeBaseText<N>::template Type<>>;
template <class N, class E>
using NodeTypedError = NodeTyped<N, typename NodeBaseError<N>::template Type<E>>;
}
#endif
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef XENSTORE_HH_
#define XENSTORE_HH_
extern "C" {
#include <xenstore.h>
}
class xenstore {
public:
class xenstore_transaction {
private:
xenstore *_x;
protected:
xs_transaction_t _t = 0;
public:
explicit xenstore_transaction(xenstore *x) : _x(x)
, _t(x->start_transaction()) {}
explicit xenstore_transaction() {}
~xenstore_transaction() { if (_t) { _x->end_transaction(_t); } }
xs_transaction_t t() { return _t; }
friend class xenstore;
};
protected:
xs_transaction_t start_transaction();
void end_transaction(xs_transaction_t t);
static xenstore_transaction _xs_null; // having it here simplify forward decls
private:
static xenstore *_instance;
struct xs_handle *_h;
explicit xenstore();
~xenstore();
public:
static xenstore *instance();
virtual void write(std::string path, std::string value, xenstore_transaction &t = _xs_null);
virtual void remove(std::string path, xenstore_transaction &t = _xs_null);
virtual std::string read(std::string path, xenstore_transaction &t = _xs_null);
virtual std::list<std::string> ls(std::string path, xenstore_transaction &t = _xs_null);
template <typename T>
T read(std::string path, xenstore_transaction &t = _xs_null) { return boost::lexical_cast<T>(read(path, t)); }
template <typename T>
T read_or_default(std::string path, T deflt = T(), xenstore_transaction &t = _xs_null) {
auto val = read(path, t);
if (val.empty()) {
return deflt;
} else {
return boost::lexical_cast<T>(val);
}
}
template <typename T>
void write(std::string path, T val, xenstore_transaction &t = _xs_null) { return write(path, std::to_string(val), t); }
};
#endif /* XENSTORE_HH_ */
<commit_msg>fix xenstore compilation<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef XENSTORE_HH_
#define XENSTORE_HH_
#include <list>
extern "C" {
#include <xenstore.h>
}
class xenstore {
public:
class xenstore_transaction {
private:
xenstore *_x;
protected:
xs_transaction_t _t = 0;
public:
explicit xenstore_transaction(xenstore *x) : _x(x)
, _t(x->start_transaction()) {}
explicit xenstore_transaction() {}
~xenstore_transaction() { if (_t) { _x->end_transaction(_t); } }
xs_transaction_t t() { return _t; }
friend class xenstore;
};
protected:
xs_transaction_t start_transaction();
void end_transaction(xs_transaction_t t);
static xenstore_transaction _xs_null; // having it here simplify forward decls
private:
static xenstore *_instance;
struct xs_handle *_h;
explicit xenstore();
~xenstore();
public:
static xenstore *instance();
virtual void write(std::string path, std::string value, xenstore_transaction &t = _xs_null);
virtual void remove(std::string path, xenstore_transaction &t = _xs_null);
virtual std::string read(std::string path, xenstore_transaction &t = _xs_null);
virtual std::list<std::string> ls(std::string path, xenstore_transaction &t = _xs_null);
template <typename T>
T read(std::string path, xenstore_transaction &t = _xs_null) { return boost::lexical_cast<T>(read(path, t)); }
template <typename T>
T read_or_default(std::string path, T deflt = T(), xenstore_transaction &t = _xs_null) {
auto val = read(path, t);
if (val.empty()) {
return deflt;
} else {
return boost::lexical_cast<T>(val);
}
}
template <typename T>
void write(std::string path, T val, xenstore_transaction &t = _xs_null) { return write(path, std::to_string(val), t); }
};
#endif /* XENSTORE_HH_ */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32TextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to Matt Turek who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkWin32TextMapper.h"
#include "vtkWin32ImageWindow.h"
int vtkWin32TextMapper::GetCompositingMode(vtkActor2D* actor)
{
vtkProperty2D* tempProp = actor->GetProperty();
int compositeMode = tempProp->GetCompositingOperator();
switch (compositeMode)
{
case VTK_BLACK:
return R2_BLACK;
break;
case VTK_NOT_DEST:
return R2_NOT;
break;
case VTK_SRC_AND_DEST:
return R2_MASKPEN;
break;
case VTK_SRC_OR_DEST:
return R2_MERGEPEN;
break;
case VTK_NOT_SRC:
return R2_NOTCOPYPEN;
break;
case VTK_SRC_XOR_DEST:
return R2_XORPEN;
break;
case VTK_SRC_AND_notDEST:
return R2_MASKPENNOT;
break;
case VTK_SRC:
return R2_COPYPEN;
break;
case VTK_WHITE:
return R2_WHITE;
break;
default:
return R2_COPYPEN;
break;
}
}
void vtkWin32TextMapper::Render(vtkViewport* viewport, vtkActor2D* actor)
{
vtkDebugMacro (<< "vtkWin32TextMapper::Render");
// Check for input
if (this->Input == NULL)
{
vtkErrorMacro (<<"vtkWin32TextMapper::Render - No input");
}
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
HWND windowId = (HWND) window->GetGenericWindowId();
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Get the position of the text actor
POINT ptDestOff;
int xOffset = 0;
int yOffset = 0;
// Get the position of the text actor
int* actorPos =
actor->GetPositionCoordinate()->GetComputedLocalDisplayValue(viewport);
xOffset = actorPos[0];
yOffset = actorPos[1];
ptDestOff.x = xOffset;
ptDestOff.y = yOffset;
// Set up the font color from the text actor
unsigned char red = 0;
unsigned char green = 0;
unsigned char blue = 0;
float* actorColor = actor->GetProperty()->GetColor();
red = (unsigned char) (actorColor[0] * 255.0);
green = (unsigned char) (actorColor[1] * 255.0);
blue = (unsigned char) (actorColor[2] * 255.0);
// Set up the shadow color
float intensity;
intensity = (red + green + blue)/3.0;
unsigned char shadowRed, shadowGreen, shadowBlue;
if (intensity > 128)
{
shadowRed = shadowBlue = shadowGreen = 0;
}
else
{
shadowRed = shadowBlue = shadowGreen = 255;
}
// Create the font
LOGFONT fontStruct;
char fontname[32];
DWORD family;
switch (this->FontFamily)
{
case VTK_ARIAL:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
case VTK_TIMES:
strcpy(fontname, "Times Roman");
family = FF_ROMAN;
break;
case VTK_COURIER:
strcpy(fontname, "Courier");
family = FF_MODERN;
break;
default:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
}
fontStruct.lfHeight = MulDiv(this->FontSize,
GetDeviceCaps(hdc, LOGPIXELSY), 72);
// height in logical units
fontStruct.lfWidth = 0; // default width
fontStruct.lfEscapement = 0;
fontStruct.lfOrientation = 0;
if (this->Bold == 1)
{
fontStruct.lfWeight = FW_BOLD;
}
else
{
fontStruct.lfWeight = FW_NORMAL;
}
fontStruct.lfItalic = this->Italic;
fontStruct.lfUnderline = 0;
fontStruct.lfStrikeOut = 0;
fontStruct.lfCharSet = ANSI_CHARSET;
fontStruct.lfOutPrecision = OUT_DEFAULT_PRECIS;
fontStruct.lfClipPrecision = CLIP_DEFAULT_PRECIS;
fontStruct.lfQuality = DEFAULT_QUALITY;
fontStruct.lfPitchAndFamily = DEFAULT_PITCH | family;
strcpy(fontStruct.lfFaceName, fontname);
HFONT hFont = CreateFontIndirect(&fontStruct);
HFONT hOldFont = (HFONT) SelectObject(hdc, hFont);
// Set the compositing operator
int compositeMode = this->GetCompositingMode(actor);
SetROP2(hdc, compositeMode);
// For Debug
int op = GetROP2(hdc);
if (op != compositeMode)
{
vtkErrorMacro(<<"vtkWin32TextMapper::Render - ROP not set!");
}
// Define bounding rectangle
RECT rect;
rect.left = ptDestOff.x;
rect.top = ptDestOff.y;
rect.bottom = ptDestOff.y;
rect.right = ptDestOff.x;
// Calculate the size of the bounding rectangle
DrawText(hdc, this->Input, strlen(this->Input), &rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX);
// Set the colors for the shadow
long status;
if (this->Shadow)
{
status = SetTextColor(hdc, RGB(shadowRed, shadowGreen, shadowBlue));
if (status == CLR_INVALID)
vtkErrorMacro(<<"vtkWin32TextMapper::Render - Set shadow color failed!");
// Set the background mode to transparent
SetBkMode(hdc, TRANSPARENT);
// Draw the shadow text
rect.left++; rect.top++; rect.bottom++; rect.right++;
DrawText(hdc, this->Input, strlen(this->Input), &rect,DT_LEFT|DT_NOPREFIX);
rect.left--; rect.top--; rect.bottom--; rect.right--;
}
// set the colors for the foreground
status = SetTextColor(hdc, RGB(red, green, blue));
if (status == CLR_INVALID)
vtkErrorMacro(<<"vtkWin32TextMapper::Render - SetTextColor failed!");
// Set the background mode to transparent
SetBkMode(hdc, TRANSPARENT);
// Draw the text
DrawText(hdc, this->Input, strlen(this->Input), &rect, DT_LEFT|DT_NOPREFIX);
SelectObject(hdc, hOldFont);
DeleteObject(hFont);
}
<commit_msg>BUG: fixed positioning of text<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32TextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to Matt Turek who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkWin32TextMapper.h"
#include "vtkWin32ImageWindow.h"
int vtkWin32TextMapper::GetCompositingMode(vtkActor2D* actor)
{
vtkProperty2D* tempProp = actor->GetProperty();
int compositeMode = tempProp->GetCompositingOperator();
switch (compositeMode)
{
case VTK_BLACK:
return R2_BLACK;
break;
case VTK_NOT_DEST:
return R2_NOT;
break;
case VTK_SRC_AND_DEST:
return R2_MASKPEN;
break;
case VTK_SRC_OR_DEST:
return R2_MERGEPEN;
break;
case VTK_NOT_SRC:
return R2_NOTCOPYPEN;
break;
case VTK_SRC_XOR_DEST:
return R2_XORPEN;
break;
case VTK_SRC_AND_notDEST:
return R2_MASKPENNOT;
break;
case VTK_SRC:
return R2_COPYPEN;
break;
case VTK_WHITE:
return R2_WHITE;
break;
default:
return R2_COPYPEN;
break;
}
}
void vtkWin32TextMapper::Render(vtkViewport* viewport, vtkActor2D* actor)
{
vtkDebugMacro (<< "vtkWin32TextMapper::Render");
// Check for input
if (this->Input == NULL)
{
vtkErrorMacro (<<"vtkWin32TextMapper::Render - No input");
}
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
HWND windowId = (HWND) window->GetGenericWindowId();
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Get the position of the text actor
POINT ptDestOff;
int xOffset = 0;
int yOffset = 0;
// Get the position of the text actor
int* actorPos =
actor->GetPositionCoordinate()->GetComputedLocalDisplayValue(viewport);
xOffset = actorPos[0];
yOffset = actorPos[1];
ptDestOff.x = xOffset;
ptDestOff.y = yOffset;
// Set up the font color from the text actor
unsigned char red = 0;
unsigned char green = 0;
unsigned char blue = 0;
float* actorColor = actor->GetProperty()->GetColor();
red = (unsigned char) (actorColor[0] * 255.0);
green = (unsigned char) (actorColor[1] * 255.0);
blue = (unsigned char) (actorColor[2] * 255.0);
// Set up the shadow color
float intensity;
intensity = (red + green + blue)/3.0;
unsigned char shadowRed, shadowGreen, shadowBlue;
if (intensity > 128)
{
shadowRed = shadowBlue = shadowGreen = 0;
}
else
{
shadowRed = shadowBlue = shadowGreen = 255;
}
// Create the font
LOGFONT fontStruct;
char fontname[32];
DWORD family;
switch (this->FontFamily)
{
case VTK_ARIAL:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
case VTK_TIMES:
strcpy(fontname, "Times Roman");
family = FF_ROMAN;
break;
case VTK_COURIER:
strcpy(fontname, "Courier");
family = FF_MODERN;
break;
default:
strcpy(fontname, "Arial");
family = FF_SWISS;
break;
}
fontStruct.lfHeight = MulDiv(this->FontSize,
GetDeviceCaps(hdc, LOGPIXELSY), 72);
// height in logical units
fontStruct.lfWidth = 0; // default width
fontStruct.lfEscapement = 0;
fontStruct.lfOrientation = 0;
if (this->Bold == 1)
{
fontStruct.lfWeight = FW_BOLD;
}
else
{
fontStruct.lfWeight = FW_NORMAL;
}
fontStruct.lfItalic = this->Italic;
fontStruct.lfUnderline = 0;
fontStruct.lfStrikeOut = 0;
fontStruct.lfCharSet = ANSI_CHARSET;
fontStruct.lfOutPrecision = OUT_DEFAULT_PRECIS;
fontStruct.lfClipPrecision = CLIP_DEFAULT_PRECIS;
fontStruct.lfQuality = DEFAULT_QUALITY;
fontStruct.lfPitchAndFamily = DEFAULT_PITCH | family;
strcpy(fontStruct.lfFaceName, fontname);
HFONT hFont = CreateFontIndirect(&fontStruct);
HFONT hOldFont = (HFONT) SelectObject(hdc, hFont);
// Set the compositing operator
int compositeMode = this->GetCompositingMode(actor);
SetROP2(hdc, compositeMode);
// For Debug
int op = GetROP2(hdc);
if (op != compositeMode)
{
vtkErrorMacro(<<"vtkWin32TextMapper::Render - ROP not set!");
}
// Define bounding rectangle
RECT rect;
rect.left = ptDestOff.x;
rect.top = ptDestOff.y;
rect.bottom = ptDestOff.y;
rect.right = ptDestOff.x;
// Calculate the size of the bounding rectangle
DrawText(hdc, this->Input, strlen(this->Input), &rect,
DT_CALCRECT|DT_LEFT|DT_NOPREFIX);
// adjust the rectangle to account for lower left origin
rect.top = 2*rect.top - rect.bottom;
rect.bottom = ptDestOff.y;
// Set the colors for the shadow
long status;
if (this->Shadow)
{
status = SetTextColor(hdc, RGB(shadowRed, shadowGreen, shadowBlue));
if (status == CLR_INVALID)
vtkErrorMacro(<<"vtkWin32TextMapper::Render - Set shadow color failed!");
// Set the background mode to transparent
SetBkMode(hdc, TRANSPARENT);
// Draw the shadow text
rect.left++; rect.top++; rect.bottom++; rect.right++;
DrawText(hdc, this->Input, strlen(this->Input), &rect,DT_LEFT|DT_NOPREFIX);
rect.left--; rect.top--; rect.bottom--; rect.right--;
}
// set the colors for the foreground
status = SetTextColor(hdc, RGB(red, green, blue));
if (status == CLR_INVALID)
vtkErrorMacro(<<"vtkWin32TextMapper::Render - SetTextColor failed!");
// Set the background mode to transparent
SetBkMode(hdc, TRANSPARENT);
// Draw the text
DrawText(hdc, this->Input, strlen(this->Input), &rect, DT_LEFT|DT_NOPREFIX);
SelectObject(hdc, hOldFont);
DeleteObject(hFont);
}
<|endoftext|>
|
<commit_before>// -*-c++-*-
/*
* demonstrates usage of osg::TextureRectangle.
*
* Actually there isn't much difference to the rest of the osg::Texture*
* bunch only this:
* - texture coordinates for texture rectangles must be in image
* coordinates instead of normalized coordinates (0-1). So for a 500x250
* image the coordinates for the entire image would be
* 0,250 0,0 500,0 500,250 instead of 0,1 0,0 1,0 1,1
* - only the following wrap modes are supported (but not enforced)
* CLAMP, CLAMP_TO_EDGE, CLAMP_TO_BORDER
* - a border is not supported
* - mipmap is not supported
*/
#include <osg/Notify>
#include <osg/TextureRectangle>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Projection>
#include <osg/MatrixTransform>
#include <osgText/Text>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
/**********************************************************************
*
* Texture pan animation callback
*
**********************************************************************/
class TexturePanCallback : public osg::NodeCallback
{
public:
TexturePanCallback(osg::Geometry* geom, osg::Image* img,
double delay = 0.05) :
_geom(geom),
_img(img),
_phaseS(35.0f),
_phaseT(18.0f),
_phaseScale(5.0f),
_delay(delay),
_prevTime(0.0)
{
}
virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
{
if (!_geom || !_img)
return;
if (nv->getFrameStamp()) {
double currTime = nv->getFrameStamp()->getReferenceTime();
if (currTime - _prevTime > _delay) {
float rad = osg::DegreesToRadians(currTime);
// zoom scale (0.2 - 1.0)
float scale = sin(rad * _phaseScale) * 0.4f + 0.6f;
float scaleR = 1.0f - scale;
// calculate new texture coordinates
float s, t;
s = ((sin(rad * _phaseS) + 1) * 0.5f) * (_img->s() * scaleR);
t = ((sin(rad * _phaseT) + 1) * 0.5f) * (_img->t() * scaleR);
// set new texture coordinate array
osg::Vec2Array* texcoords = (osg::Vec2Array*) _geom->getTexCoordArray(0);
float w = _img->s() * scale, h = _img->t() * scale;
(*texcoords)[0].set(s, t+h);
(*texcoords)[1].set(s, t);
(*texcoords)[2].set(s+w, t);
(*texcoords)[3].set(s+w, t+h);
// record time
_prevTime = currTime;
}
}
}
private:
osg::Geometry* _geom;
osg::Image* _img;
float _phaseS, _phaseT, _phaseScale;
double _delay;
double _prevTime;
};
osg::Node* createRectangle(osg::BoundingBox& bb,
const std::string& filename)
{
osg::Vec3 top_left(bb.xMin(),bb.yMax(),bb.zMax());
osg::Vec3 bottom_left(bb.xMin(),bb.yMax(),bb.zMin());
osg::Vec3 bottom_right(bb.xMax(),bb.yMax(),bb.zMin());
osg::Vec3 top_right(bb.xMax(),bb.yMax(),bb.zMax());
// create geometry
osg::Geometry* geom = new osg::Geometry;
osg::Vec3Array* vertices = new osg::Vec3Array(4);
(*vertices)[0] = top_left;
(*vertices)[1] = bottom_left;
(*vertices)[2] = bottom_right;
(*vertices)[3] = top_right;
geom->setVertexArray(vertices);
osg::Vec2Array* texcoords = new osg::Vec2Array(4);
(*texcoords)[0].set(0.0f, 0.0f);
(*texcoords)[1].set(1.0f, 0.0f);
(*texcoords)[2].set(1.0f, 1.0f);
(*texcoords)[3].set(0.0f, 1.0f);
geom->setTexCoordArray(0,texcoords);
osg::Vec3Array* normals = new osg::Vec3Array(1);
(*normals)[0].set(-1.0f,0.0f,0.0f);
geom->setNormalArray(normals);
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
osg::Vec4Array* colors = new osg::Vec4Array(1);
(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
geom->setColorArray(colors);
geom->setColorBinding(osg::Geometry::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4));
// disable display list so our modified tex coordinates show up
geom->setUseDisplayList(false);
// setup texture
osg::TextureRectangle* texture = new osg::TextureRectangle;
// load image
osg::Image* img = osgDB::readImageFile(filename);
texture->setImage(img);
// setup state
osg::StateSet* state = geom->getOrCreateStateSet();
state->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
// turn off lighting
state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
// install 'update' callback
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
geode->setUpdateCallback(new TexturePanCallback(geom, img));
return geode;
}
osg::Geode* createText(const std::string& str,
const osg::Vec3& pos)
{
static std::string font("fonts/arial.ttf");
osg::Geode* geode = new osg::Geode;
osgText::Text* text = new osgText::Text;
geode->addDrawable(text);
text->setFont(font);
text->setPosition(pos);
text->setText(str);
return geode;
}
osg::Node* createHUD()
{
osg::Group* group = new osg::Group;
// turn off lighting and depth test
osg::StateSet* state = group->getOrCreateStateSet();
state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
state->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
// add text
osg::Vec3 pos(120.0f, 800.0f, 0.0f);
const osg::Vec3 delta(0.0f, -80.0f, 0.0f);
const char* text[] = {
"TextureRectangle Mini-HOWTO",
"- essentially behaves like Texture2D, *except* that:",
"- tex coords must be non-normalized (0..pixel) instead of (0..1)",
"- wrap modes must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER\n repeating wrap modes are not supported",
"- filter modes must be NEAREST or LINEAR since\n mipmaps are not supported",
"- texture borders are not supported",
"- defaults should be fine",
NULL
};
const char** t = text;
while (*t) {
group->addChild(createText(*t++, pos));
pos += delta;
}
// create HUD
osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
modelview_abs->setMatrix(osg::Matrix::identity());
modelview_abs->addChild(group);
osg::Projection* projection = new osg::Projection;
projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
projection->addChild(modelview_abs);
return projection;
}
osg::Node* createModel(const std::string& filename)
{
osg::Group* root = new osg::Group;
if (filename != "X") {
osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f);
root->addChild(createRectangle(bb, filename)); // XXX
}
root->addChild(createHUD());
return root;
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a demo which demonstrates use of osg::TextureRectangle.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] <image> ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// create a model from the images.
osg::Node* rootNode = createModel((arguments.argc() > 1 ? arguments[1] : "lz.rgb"));
// add model to viewer.
viewer.setSceneData(rootNode);
// create the windows and run the threads.
viewer.realize();
while (!viewer.done())
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added Images/ infront of lz.rgb path.<commit_after>// -*-c++-*-
/*
* demonstrates usage of osg::TextureRectangle.
*
* Actually there isn't much difference to the rest of the osg::Texture*
* bunch only this:
* - texture coordinates for texture rectangles must be in image
* coordinates instead of normalized coordinates (0-1). So for a 500x250
* image the coordinates for the entire image would be
* 0,250 0,0 500,0 500,250 instead of 0,1 0,0 1,0 1,1
* - only the following wrap modes are supported (but not enforced)
* CLAMP, CLAMP_TO_EDGE, CLAMP_TO_BORDER
* - a border is not supported
* - mipmap is not supported
*/
#include <osg/Notify>
#include <osg/TextureRectangle>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Projection>
#include <osg/MatrixTransform>
#include <osgText/Text>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
/**********************************************************************
*
* Texture pan animation callback
*
**********************************************************************/
class TexturePanCallback : public osg::NodeCallback
{
public:
TexturePanCallback(osg::Geometry* geom, osg::Image* img,
double delay = 0.05) :
_geom(geom),
_img(img),
_phaseS(35.0f),
_phaseT(18.0f),
_phaseScale(5.0f),
_delay(delay),
_prevTime(0.0)
{
}
virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
{
if (!_geom || !_img)
return;
if (nv->getFrameStamp()) {
double currTime = nv->getFrameStamp()->getReferenceTime();
if (currTime - _prevTime > _delay) {
float rad = osg::DegreesToRadians(currTime);
// zoom scale (0.2 - 1.0)
float scale = sin(rad * _phaseScale) * 0.4f + 0.6f;
float scaleR = 1.0f - scale;
// calculate new texture coordinates
float s, t;
s = ((sin(rad * _phaseS) + 1) * 0.5f) * (_img->s() * scaleR);
t = ((sin(rad * _phaseT) + 1) * 0.5f) * (_img->t() * scaleR);
// set new texture coordinate array
osg::Vec2Array* texcoords = (osg::Vec2Array*) _geom->getTexCoordArray(0);
float w = _img->s() * scale, h = _img->t() * scale;
(*texcoords)[0].set(s, t+h);
(*texcoords)[1].set(s, t);
(*texcoords)[2].set(s+w, t);
(*texcoords)[3].set(s+w, t+h);
// record time
_prevTime = currTime;
}
}
}
private:
osg::Geometry* _geom;
osg::Image* _img;
float _phaseS, _phaseT, _phaseScale;
double _delay;
double _prevTime;
};
osg::Node* createRectangle(osg::BoundingBox& bb,
const std::string& filename)
{
osg::Vec3 top_left(bb.xMin(),bb.yMax(),bb.zMax());
osg::Vec3 bottom_left(bb.xMin(),bb.yMax(),bb.zMin());
osg::Vec3 bottom_right(bb.xMax(),bb.yMax(),bb.zMin());
osg::Vec3 top_right(bb.xMax(),bb.yMax(),bb.zMax());
// create geometry
osg::Geometry* geom = new osg::Geometry;
osg::Vec3Array* vertices = new osg::Vec3Array(4);
(*vertices)[0] = top_left;
(*vertices)[1] = bottom_left;
(*vertices)[2] = bottom_right;
(*vertices)[3] = top_right;
geom->setVertexArray(vertices);
osg::Vec2Array* texcoords = new osg::Vec2Array(4);
(*texcoords)[0].set(0.0f, 0.0f);
(*texcoords)[1].set(1.0f, 0.0f);
(*texcoords)[2].set(1.0f, 1.0f);
(*texcoords)[3].set(0.0f, 1.0f);
geom->setTexCoordArray(0,texcoords);
osg::Vec3Array* normals = new osg::Vec3Array(1);
(*normals)[0].set(-1.0f,0.0f,0.0f);
geom->setNormalArray(normals);
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
osg::Vec4Array* colors = new osg::Vec4Array(1);
(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
geom->setColorArray(colors);
geom->setColorBinding(osg::Geometry::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4));
// disable display list so our modified tex coordinates show up
geom->setUseDisplayList(false);
// setup texture
osg::TextureRectangle* texture = new osg::TextureRectangle;
// load image
osg::Image* img = osgDB::readImageFile(filename);
texture->setImage(img);
// setup state
osg::StateSet* state = geom->getOrCreateStateSet();
state->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
// turn off lighting
state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
// install 'update' callback
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
geode->setUpdateCallback(new TexturePanCallback(geom, img));
return geode;
}
osg::Geode* createText(const std::string& str,
const osg::Vec3& pos)
{
static std::string font("fonts/arial.ttf");
osg::Geode* geode = new osg::Geode;
osgText::Text* text = new osgText::Text;
geode->addDrawable(text);
text->setFont(font);
text->setPosition(pos);
text->setText(str);
return geode;
}
osg::Node* createHUD()
{
osg::Group* group = new osg::Group;
// turn off lighting and depth test
osg::StateSet* state = group->getOrCreateStateSet();
state->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
state->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
// add text
osg::Vec3 pos(120.0f, 800.0f, 0.0f);
const osg::Vec3 delta(0.0f, -80.0f, 0.0f);
const char* text[] = {
"TextureRectangle Mini-HOWTO",
"- essentially behaves like Texture2D, *except* that:",
"- tex coords must be non-normalized (0..pixel) instead of (0..1)",
"- wrap modes must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER\n repeating wrap modes are not supported",
"- filter modes must be NEAREST or LINEAR since\n mipmaps are not supported",
"- texture borders are not supported",
"- defaults should be fine",
NULL
};
const char** t = text;
while (*t) {
group->addChild(createText(*t++, pos));
pos += delta;
}
// create HUD
osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
modelview_abs->setMatrix(osg::Matrix::identity());
modelview_abs->addChild(group);
osg::Projection* projection = new osg::Projection;
projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
projection->addChild(modelview_abs);
return projection;
}
osg::Node* createModel(const std::string& filename)
{
osg::Group* root = new osg::Group;
if (filename != "X") {
osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f);
root->addChild(createRectangle(bb, filename)); // XXX
}
root->addChild(createHUD());
return root;
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a demo which demonstrates use of osg::TextureRectangle.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] <image> ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// create a model from the images.
osg::Node* rootNode = createModel((arguments.argc() > 1 ? arguments[1] : "Images/lz.rgb"));
// add model to viewer.
viewer.setSceneData(rootNode);
// create the windows and run the threads.
viewer.realize();
while (!viewer.done())
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: gi_parse.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: np $ $Date: 2001-06-11 16:04:51 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <gi_parse.hxx>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <gilacces.hxx>
using namespace std;
const char * C_sLineEnd = "\r\n";
inline void
WriteStr( ostream & o_rOut, const Simstr & i_rStr )
{
o_rOut.write( i_rStr.str(), i_rStr.l() );
}
inline void
WriteStr( ostream & o_rOut, const char * i_rStr )
{
o_rOut.write( i_rStr, strlen(i_rStr) );
}
inline void
GenericInfo_Parser::SetError( E_Error i_eError )
{
eErrorCode = i_eError;
nErrorLine = nCurLine;
}
GenericInfo_Parser::GenericInfo_Parser()
: sCurParsePosition(""),
nCurLine(0),
nLevel(0),
bGoon(false),
// sCurComment,
eErrorCode(ok),
nErrorLine(0),
pResult(0),
pResource(0)
{
}
GenericInfo_Parser::~GenericInfo_Parser()
{
}
bool
GenericInfo_Parser::LoadList( GenericInfoList_Builder & o_rResult,
const Simstr & i_sSourceFileName )
{
ifstream aFile( i_sSourceFileName.str() );
if ( aFile.fail() )
{
SetError(cannot_open);
return false;
}
ResetState(o_rResult);
for ( ReadLine(aFile); bGoon; ReadLine(aFile) )
{
bool bOk = InterpretLine();
if ( !bOk)
{
SetError(syntax_error);
break;
}
}
if ( nLevel > 0 && eErrorCode == ok)
{
SetError(unexpected_eof);
}
else if ( nLevel < 0 )
{
SetError(unexpected_list_end);
}
aFile.close();
return eErrorCode == ok;
}
bool
GenericInfo_Parser::SaveList( const Simstr & i_rOutputFile,
GenericInfoList_Browser & io_rListBrowser )
{
ofstream aFile( i_rOutputFile.str() );
if ( aFile.fail() )
{
SetError(cannot_open);
return false;
}
ResetState(io_rListBrowser);
WriteList(aFile);
aFile.close();
return eErrorCode == ok;
}
void
GenericInfo_Parser::ResetState( GenericInfoList_Builder & io_rResult )
{
sCurParsePosition = "";
nCurLine = 0;
nLevel = 0;
bGoon = true;
sCurComment = "";
eErrorCode = ok;
nErrorLine = 0;
pResult = &io_rResult;
pResource = 0;
}
void
GenericInfo_Parser::ResetState( GenericInfoList_Browser & io_rSrc )
{
sCurParsePosition = "";
nCurLine = 0;
nLevel = 0;
bGoon = false;
sCurComment = "";
eErrorCode = ok;
nErrorLine = 0;
pResult = 0;
pResource = &io_rSrc;
}
void
GenericInfo_Parser::ReadLine( istream & i_rSrc )
{
const int nInputSize = 32000;
static char sInput[nInputSize];
i_rSrc.get(sInput, nInputSize);
UINT32 nGot = UINT32(i_rSrc.gcount());
if (nGot == 0)
{
bGoon = false;
return;
}
nCurLine++;
#if 0
if ( sInput[ nGot-1 ] == '\r' )
sInput[ nGot-1 ] = '\0';
#endif
i_rSrc.get();
for ( sCurParsePosition = &sInput[0]; *sCurParsePosition > 0 && *sCurParsePosition <= 32; ++sCurParsePosition );
for ( char * sEnd = const_cast< char* >(strchr(sCurParsePosition,'\0'));
sEnd != sCurParsePosition
? *(sEnd-1) <= 32
: false;
--sEnd )
{
*(sEnd-1) = '\0';
}
}
bool
GenericInfo_Parser::InterpretLine()
{
switch ( ClassifyLine() )
{
case lt_key: ReadKey();
break;
case lt_open_list: PushLevel_Read();
break;
case lt_close_list: PopLevel_Read();
break;
case lt_comment: AddCurLine2CurComment();
break;
case lt_empty: AddCurLine2CurComment();
break;
default:
return false;
}
return true;
}
GenericInfo_Parser::E_LineType
GenericInfo_Parser::ClassifyLine()
{
switch ( *sCurParsePosition )
{
case '{': return lt_open_list;
case '}': return lt_close_list;
case '#': return lt_comment;
case '0': return lt_empty;
}
return lt_key;
}
void
GenericInfo_Parser::ReadKey()
{
const char * pSearch = sCurParsePosition;
for ( ; *pSearch > 32; ++pSearch );
UINT32 nKeyLength = pSearch - sCurParsePosition;
for ( ; *pSearch <= 32 && *pSearch > '\0'; ++pSearch );
pResult->AddKey( sCurParsePosition, nKeyLength,
pSearch, strlen(pSearch),
sCurComment.str(), sCurComment.l()
);
}
void
GenericInfo_Parser::PushLevel_Read()
{
nLevel++;
pResult->OpenList();
}
void
GenericInfo_Parser::PopLevel_Read()
{
nLevel--;
pResult->CloseList();
}
void
GenericInfo_Parser::AddCurLine2CurComment()
{
sCurComment += sCurParsePosition;
sCurComment += C_sLineEnd;
}
void
GenericInfo_Parser::WriteList( ostream & o_rFile )
{
static char sBuffer[32000];
for ( bGoon = pResource->Start_CurList();
bGoon;
bGoon = pResource->NextOf_CurList() )
{
pResource->Get_CurComment(&sBuffer[0]);
WriteComment(o_rFile,sBuffer);
pResource->Get_CurKey(&sBuffer[0]);
WriteKey(o_rFile,sBuffer);
pResource->Get_CurValue(&sBuffer[0]);
WriteValue(o_rFile,sBuffer);
if ( pResource->HasSubList_CurKey() )
{
PushLevel_Write();
/*
WriteIndentation();
o_rFile.write("{",1);
o_rFile.write(C_sLineEnd, C_nLineEndLength);
*/
WriteList(o_rFile);
/*
WriteIndentation();
o_rFile.write("}",1);
o_rFile.write(C_sLineEnd, C_nLineEndLength);
*/
PopLevel_Write();
}
} // end for
}
void
GenericInfo_Parser::PushLevel_Write()
{
nLevel++;
pResource->Push_CurList();
}
void
GenericInfo_Parser::PopLevel_Write()
{
nLevel--;
pResource->Pop_CurList();
}
void
GenericInfo_Parser::WriteComment( ostream & o_rFile,
const char * i_sStr )
{
WriteStr( o_rFile, i_sStr );
if ( i_sStr[ strlen(i_sStr)-1 ] != '\n' )
WriteStr( o_rFile, C_sLineEnd );
}
void
GenericInfo_Parser::WriteKey( ostream & o_rFile,
const char * i_sStr )
{
WriteIndentation(o_rFile);
WriteStr( o_rFile, i_sStr );
}
void
GenericInfo_Parser::WriteValue( ostream & o_rFile,
const char * i_sStr )
{
if ( i_sStr != 0 ? strlen(i_sStr) > 0 : false )
{
WriteStr(o_rFile," ");
WriteStr(o_rFile,i_sStr);
}
WriteStr(o_rFile,C_sLineEnd);
}
void
GenericInfo_Parser::WriteIndentation( ostream & o_rFile )
{
const int nIndentBound = 60;
static const char sIndentation[nIndentBound+1] =
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
if ( nLevel == 0 )
return;
if ( nLevel <= nIndentBound )
o_rFile.write( sIndentation, nLevel );
else
{
INT16 iLevel = nLevel;
for ( ; iLevel > nIndentBound; iLevel-=nIndentBound )
o_rFile.write( sIndentation, nIndentBound );
o_rFile.write( sIndentation, iLevel );
}
}
<commit_msg>Fix handling of empty ines.<commit_after>/*************************************************************************
*
* $RCSfile: gi_parse.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: np $ $Date: 2001-06-12 14:38:15 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <gi_parse.hxx>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <gilacces.hxx>
using namespace std;
const char * C_sLineEnd = "\r\n";
inline void
WriteStr( ostream & o_rOut, const Simstr & i_rStr )
{
o_rOut.write( i_rStr.str(), i_rStr.l() );
}
inline void
WriteStr( ostream & o_rOut, const char * i_rStr )
{
o_rOut.write( i_rStr, strlen(i_rStr) );
}
inline void
GenericInfo_Parser::SetError( E_Error i_eError )
{
eErrorCode = i_eError;
nErrorLine = nCurLine;
}
GenericInfo_Parser::GenericInfo_Parser()
: sCurParsePosition(""),
nCurLine(0),
nLevel(0),
bGoon(false),
// sCurComment,
eErrorCode(ok),
nErrorLine(0),
pResult(0),
pResource(0)
{
}
GenericInfo_Parser::~GenericInfo_Parser()
{
}
bool
GenericInfo_Parser::LoadList( GenericInfoList_Builder & o_rResult,
const Simstr & i_sSourceFileName )
{
ifstream aFile( i_sSourceFileName.str() );
if ( aFile.fail() )
{
SetError(cannot_open);
return false;
}
ResetState(o_rResult);
for ( ReadLine(aFile); bGoon; ReadLine(aFile) )
{
bool bOk = InterpretLine();
if ( !bOk)
{
SetError(syntax_error);
break;
}
}
if ( nLevel > 0 && eErrorCode == ok)
{
SetError(unexpected_eof);
}
else if ( nLevel < 0 )
{
SetError(unexpected_list_end);
}
aFile.close();
return eErrorCode == ok;
}
bool
GenericInfo_Parser::SaveList( const Simstr & i_rOutputFile,
GenericInfoList_Browser & io_rListBrowser )
{
ofstream aFile( i_rOutputFile.str() );
if ( aFile.fail() )
{
SetError(cannot_open);
return false;
}
ResetState(io_rListBrowser);
WriteList(aFile);
aFile.close();
return eErrorCode == ok;
}
void
GenericInfo_Parser::ResetState( GenericInfoList_Builder & io_rResult )
{
sCurParsePosition = "";
nCurLine = 0;
nLevel = 0;
bGoon = true;
sCurComment = "";
eErrorCode = ok;
nErrorLine = 0;
pResult = &io_rResult;
pResource = 0;
}
void
GenericInfo_Parser::ResetState( GenericInfoList_Browser & io_rSrc )
{
sCurParsePosition = "";
nCurLine = 0;
nLevel = 0;
bGoon = false;
sCurComment = "";
eErrorCode = ok;
nErrorLine = 0;
pResult = 0;
pResource = &io_rSrc;
}
void
GenericInfo_Parser::ReadLine( istream & i_rSrc )
{
const int nInputSize = 32000;
static char sInput[nInputSize];
i_rSrc.get(sInput, nInputSize);
UINT32 nGot = UINT32(i_rSrc.gcount());
if (nGot == 0 && i_rSrc.eof())
{
bGoon = false;
return;
}
nCurLine++;
#if 0
if ( sInput[ nGot-1 ] == '\r' )
sInput[ nGot-1 ] = '\0';
#endif
i_rSrc.get();
for ( sCurParsePosition = &sInput[0]; *sCurParsePosition > 0 && *sCurParsePosition <= 32; ++sCurParsePosition );
for ( char * sEnd = const_cast< char* >(strchr(sCurParsePosition,'\0'));
sEnd != sCurParsePosition
? *(sEnd-1) <= 32
: false;
--sEnd )
{
*(sEnd-1) = '\0';
}
}
bool
GenericInfo_Parser::InterpretLine()
{
switch ( ClassifyLine() )
{
case lt_key: ReadKey();
break;
case lt_open_list: PushLevel_Read();
break;
case lt_close_list: PopLevel_Read();
break;
case lt_comment: AddCurLine2CurComment();
break;
case lt_empty: AddCurLine2CurComment();
break;
default:
return false;
}
return true;
}
GenericInfo_Parser::E_LineType
GenericInfo_Parser::ClassifyLine()
{
switch ( *sCurParsePosition )
{
case '{': return lt_open_list;
case '}': return lt_close_list;
case '#': return lt_comment;
case '\0': return lt_empty;
}
return lt_key;
}
void
GenericInfo_Parser::ReadKey()
{
const char * pSearch = sCurParsePosition;
for ( ; *pSearch > 32; ++pSearch );
UINT32 nKeyLength = pSearch - sCurParsePosition;
for ( ; *pSearch <= 32 && *pSearch > '\0'; ++pSearch );
pResult->AddKey( sCurParsePosition, nKeyLength,
pSearch, strlen(pSearch),
sCurComment.str(), sCurComment.l()
);
sCurComment = "";
}
void
GenericInfo_Parser::PushLevel_Read()
{
nLevel++;
pResult->OpenList();
}
void
GenericInfo_Parser::PopLevel_Read()
{
nLevel--;
pResult->CloseList();
}
void
GenericInfo_Parser::AddCurLine2CurComment()
{
sCurComment += sCurParsePosition;
sCurComment += C_sLineEnd;
}
void
GenericInfo_Parser::WriteList( ostream & o_rFile )
{
static char sBuffer[32000];
for ( bGoon = pResource->Start_CurList();
bGoon;
bGoon = pResource->NextOf_CurList() )
{
pResource->Get_CurComment(&sBuffer[0]);
WriteComment(o_rFile,sBuffer);
pResource->Get_CurKey(&sBuffer[0]);
WriteKey(o_rFile,sBuffer);
pResource->Get_CurValue(&sBuffer[0]);
WriteValue(o_rFile,sBuffer);
if ( pResource->HasSubList_CurKey() )
{
PushLevel_Write();
/*
WriteIndentation();
o_rFile.write("{",1);
o_rFile.write(C_sLineEnd, C_nLineEndLength);
*/
WriteList(o_rFile);
/*
WriteIndentation();
o_rFile.write("}",1);
o_rFile.write(C_sLineEnd, C_nLineEndLength);
*/
PopLevel_Write();
}
} // end for
}
void
GenericInfo_Parser::PushLevel_Write()
{
nLevel++;
pResource->Push_CurList();
}
void
GenericInfo_Parser::PopLevel_Write()
{
nLevel--;
pResource->Pop_CurList();
}
void
GenericInfo_Parser::WriteComment( ostream & o_rFile,
const char * i_sStr )
{
WriteStr( o_rFile, i_sStr );
if ( i_sStr[ strlen(i_sStr)-1 ] != '\n' )
WriteStr( o_rFile, C_sLineEnd );
}
void
GenericInfo_Parser::WriteKey( ostream & o_rFile,
const char * i_sStr )
{
WriteIndentation(o_rFile);
WriteStr( o_rFile, i_sStr );
}
void
GenericInfo_Parser::WriteValue( ostream & o_rFile,
const char * i_sStr )
{
if ( i_sStr != 0 ? strlen(i_sStr) > 0 : false )
{
WriteStr(o_rFile," ");
WriteStr(o_rFile,i_sStr);
}
WriteStr(o_rFile,C_sLineEnd);
}
void
GenericInfo_Parser::WriteIndentation( ostream & o_rFile )
{
const int nIndentBound = 60;
static const char sIndentation[nIndentBound+1] =
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
if ( nLevel == 0 )
return;
if ( nLevel <= nIndentBound )
o_rFile.write( sIndentation, nLevel );
else
{
INT16 iLevel = nLevel;
for ( ; iLevel > nIndentBound; iLevel-=nIndentBound )
o_rFile.write( sIndentation, nIndentBound );
o_rFile.write( sIndentation, iLevel );
}
}
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2016 Gagan Kumar(scopeInfinity)
Complete License at https://raw.githubusercontent.com/scopeInfinity/NaturalSort/master/LICENSE.md
*/
/**********************************************************************
Calling Methods :
//For Natural Sorting
void SI::natural::sort(Container<String>);
void SI::natural::sort(IteratorBegin<String>,IteratorEnd<String>);
void SI::natural::sort<String,CArraySize>(CArray<String>);
//For Natural Comparision
bool SI::natural::compare<String>(String lhs,String rhs);
bool SI::natural::compare<String>(char *const lhs,char *const rhs);
Here we can have
std::vector<std::string> as Container<String>
String as std::string
CArray<String> as std::string[CArraySize]
***********************************************************************/
#ifndef SI_sort_HPP
#define SI_sort_HPP
#include <cctype>
#include <algorithm>
#include <vector>
namespace SI
{
namespace natural
{
namespace detail
{
/********** Compare Two Character CaseInsensitive ********/
template<typename ElementType>
bool natural_less(const ElementType &lhs,const ElementType &rhs)
{
if(tolower(lhs)<tolower(rhs))
return true;
return false;
}
template<typename ElementType>
bool is_not_digit(const ElementType &x)
{
return !isdigit(x);
}
/********** Compare Two Iterators CaseInsensitive ********/
template<typename ElementType,typename Iterator>
struct comp_over_iterator
{
int operator()(const Iterator &lhs,const Iterator &rhs) const
{
if(natural_less<ElementType>(*lhs,*rhs))
return -1;
if(natural_less<ElementType>(*rhs,*lhs))
return +1;
}
};
/****************************************************
Comparing two SubString from (Begin,End Iterator each)
with only digits.
Usage :
int compare_number()(\
FirstNumberBeginIterator,FirstNumberEndIterator,isFirstNumberFractionalPart\
SecondNumberBeginIterator,SecondNumberEndIterator,isSecondNumberFractionalPart\
);
Returns :
-1 - Number1 < Number2
0 - Number1 == Number2
1 - Number1 > Number2
***************************************************/
template<typename ValueType, typename Iterator>
struct compare_number
{
private:
//If Number is Itself fractional Part
int fractional(Iterator lhsBegin,Iterator lhsEnd, Iterator rhsBegin,Iterator rhsEnd)
{
while(lhsBegin<lhsEnd && rhsBegin<rhsEnd)
{
int local_compare = comp_over_iterator<ValueType, Iterator>()(lhsBegin,rhsBegin);
if(local_compare!=0)
return local_compare;
lhsBegin++;
rhsBegin++;
}
while(lhsBegin<lhsEnd && *lhsBegin=='0') lhsBegin++;
while(rhsBegin<rhsEnd && *rhsBegin=='0') rhsBegin++;
if(lhsBegin==lhsEnd && rhsBegin!=rhsEnd)
return -1;
else if(lhsBegin!=lhsEnd && rhsBegin==rhsEnd)
return +1;
else //lhsBegin==lhsEnd && rhsBegin==rhsEnd
return 0;
}
int non_fractional(Iterator lhsBegin,Iterator lhsEnd, Iterator rhsBegin,Iterator rhsEnd)
{
//Skip Inital Zero's
while(lhsBegin<lhsEnd && *lhsBegin=='0') lhsBegin++;
while(rhsBegin<rhsEnd && *rhsBegin=='0') rhsBegin++;
//Comparing By Length of Both String
if(lhsEnd-lhsBegin<rhsEnd-rhsBegin)
return -1;
if(lhsEnd-lhsBegin>rhsEnd-rhsBegin)
return +1;
//Equal In length
while(lhsBegin<lhsEnd)
{
int local_compare = comp_over_iterator<ValueType, Iterator>()(lhsBegin,rhsBegin);
if(local_compare!=0)
return local_compare;
lhsBegin++;
rhsBegin++;
}
return 0;
}
public:
int operator()(\
Iterator lhsBegin,Iterator lhsEnd,bool isFractionalPart1,\
Iterator rhsBegin,Iterator rhsEnd,bool isFractionalPart2)
{
if(isFractionalPart1 && !isFractionalPart2)
return true; //0<num1<1 && num2>=1
if(!isFractionalPart1 && isFractionalPart2)
return false; //0<num2<1 && num1>=1
//isFractionPart1 == isFactionalPart2
if(isFractionalPart1)
return fractional(lhsBegin,lhsEnd,rhsBegin,rhsEnd);
else
return non_fractional(lhsBegin,lhsEnd,rhsBegin,rhsEnd);
}
};
}// namespace detail
/***********************************************************************
Natural Comparision of Two String using both's (Begin and End Iterator)
Returns :
-1 - String1 < String2
0 - String1 == String2
1 - String1 > String2
Suffix 1 represents for components of 1st String
Suffix 2 represents for components of 2nd String
************************************************************************/
template<typename ElementType, typename Iterator>
bool _compare(\
const Iterator &lhsBegin,const Iterator &lhsEnd,\
const Iterator &rhsBegin,const Iterator &rhsEnd)
{
Iterator current1 = lhsBegin,current2 = rhsBegin;
//Flag for Space Found Check
bool flag_found_space1 = false,flag_found_space2 = false;
while(current1!=lhsEnd && current2!=rhsEnd)
{
//Ignore More than One Continous Space
/******************************************
For HandlingComparision Like
Hello 9
Hello 10
Hello 123
******************************************/
while(flag_found_space1 && current1!=lhsEnd && *current1==' ') current1++;
flag_found_space1=false;
if(*current1==' ') flag_found_space1 = true;
while(flag_found_space2 && current2!=rhsEnd && *current2==' ') current2++;
flag_found_space2=false;
if(*current2==' ') flag_found_space2 = true;
if( !isdigit(*current1 ) && !isdigit(*current2))
{
//If Both Are Non Digits do Normal Comparision
if(detail::natural_less<ElementType>(*current1,*current2))
return true;
if(detail::natural_less<ElementType>(*current2,*current1))
return false;
current1++;
current2++;
}
else
{
/*********************************
Capture Numeric Part of Both String
and then using it to compare Both
***********************************/
Iterator last_nondigit1 = std::find_if(current1,lhsEnd,detail::is_not_digit<ElementType>);
Iterator last_nondigit2 = std::find_if(current2,rhsEnd,detail::is_not_digit<ElementType>);
int result = detail::compare_number<ElementType, Iterator>()(\
current1,last_nondigit1,(current1>lhsBegin && *(current1-1)=='.'), \
current2,last_nondigit2,(current2>rhsBegin && *(current2-1)=='.'));
if(result<0)
return true;
if(result>0)
return false;
current1 = last_nondigit1;
current2 = last_nondigit2;
}
}
}
template<typename String>
inline bool compare(const String &first ,const String &second)
{
return _compare<typename String::value_type,typename String::const_iterator>(first.begin(),first.end(),second.begin(),second.end());
}
template<>
inline bool compare(char *const &first ,char *const &second)
{
char* it1 = first;
while(*it1!='\0')it1++;
char* it2 = second;
while(*it2!='\0')it2++;
return _compare<char,char*>(first,it1,second,it2);
}
template<typename Container>
inline bool sort(Container &container)
{
std::sort(container.begin(),container.end(),compare<typename Container::value_type>);
}
template<typename Iterator>
inline bool sort(const Iterator &first,const Iterator &end)
{
std::sort(first,end,compare<typename Iterator::value_type>);
}
template<typename ValueType>
inline bool sort(ValueType* const first,ValueType* const end)
{
std::sort(first,end,compare<ValueType>);
}
template<typename ValueType,int N>
inline bool sort(ValueType container[N])
{
std::sort(&container[0],&container[0]+N,compare<ValueType>);
}
}//namespace natural
}//namespace SI
#endif
<commit_msg>Return properly value when lfs == rhs in comp_over_iterator().<commit_after>/*
The MIT License (MIT)
Copyright (c) 2016 Gagan Kumar(scopeInfinity)
Complete License at https://raw.githubusercontent.com/scopeInfinity/NaturalSort/master/LICENSE.md
*/
/**********************************************************************
Calling Methods :
//For Natural Sorting
void SI::natural::sort(Container<String>);
void SI::natural::sort(IteratorBegin<String>,IteratorEnd<String>);
void SI::natural::sort<String,CArraySize>(CArray<String>);
//For Natural Comparision
bool SI::natural::compare<String>(String lhs,String rhs);
bool SI::natural::compare<String>(char *const lhs,char *const rhs);
Here we can have
std::vector<std::string> as Container<String>
String as std::string
CArray<String> as std::string[CArraySize]
***********************************************************************/
#ifndef SI_sort_HPP
#define SI_sort_HPP
#include <cctype>
#include <algorithm>
#include <vector>
namespace SI
{
namespace natural
{
namespace detail
{
/********** Compare Two Character CaseInsensitive ********/
template<typename ElementType>
bool natural_less(const ElementType &lhs,const ElementType &rhs)
{
if(tolower(lhs)<tolower(rhs))
return true;
return false;
}
template<typename ElementType>
bool is_not_digit(const ElementType &x)
{
return !isdigit(x);
}
/********** Compare Two Iterators CaseInsensitive ********/
template<typename ElementType,typename Iterator>
struct comp_over_iterator
{
int operator()(const Iterator &lhs,const Iterator &rhs) const
{
if(natural_less<ElementType>(*lhs,*rhs))
return -1;
if(natural_less<ElementType>(*rhs,*lhs))
return +1;
return 0;
}
};
/****************************************************
Comparing two SubString from (Begin,End Iterator each)
with only digits.
Usage :
int compare_number()(\
FirstNumberBeginIterator,FirstNumberEndIterator,isFirstNumberFractionalPart\
SecondNumberBeginIterator,SecondNumberEndIterator,isSecondNumberFractionalPart\
);
Returns :
-1 - Number1 < Number2
0 - Number1 == Number2
1 - Number1 > Number2
***************************************************/
template<typename ValueType, typename Iterator>
struct compare_number
{
private:
//If Number is Itself fractional Part
int fractional(Iterator lhsBegin,Iterator lhsEnd, Iterator rhsBegin,Iterator rhsEnd)
{
while(lhsBegin<lhsEnd && rhsBegin<rhsEnd)
{
int local_compare = comp_over_iterator<ValueType, Iterator>()(lhsBegin,rhsBegin);
if(local_compare!=0)
return local_compare;
lhsBegin++;
rhsBegin++;
}
while(lhsBegin<lhsEnd && *lhsBegin=='0') lhsBegin++;
while(rhsBegin<rhsEnd && *rhsBegin=='0') rhsBegin++;
if(lhsBegin==lhsEnd && rhsBegin!=rhsEnd)
return -1;
else if(lhsBegin!=lhsEnd && rhsBegin==rhsEnd)
return +1;
else //lhsBegin==lhsEnd && rhsBegin==rhsEnd
return 0;
}
int non_fractional(Iterator lhsBegin,Iterator lhsEnd, Iterator rhsBegin,Iterator rhsEnd)
{
//Skip Inital Zero's
while(lhsBegin<lhsEnd && *lhsBegin=='0') lhsBegin++;
while(rhsBegin<rhsEnd && *rhsBegin=='0') rhsBegin++;
//Comparing By Length of Both String
if(lhsEnd-lhsBegin<rhsEnd-rhsBegin)
return -1;
if(lhsEnd-lhsBegin>rhsEnd-rhsBegin)
return +1;
//Equal In length
while(lhsBegin<lhsEnd)
{
int local_compare = comp_over_iterator<ValueType, Iterator>()(lhsBegin,rhsBegin);
if(local_compare!=0)
return local_compare;
lhsBegin++;
rhsBegin++;
}
return 0;
}
public:
int operator()(\
Iterator lhsBegin,Iterator lhsEnd,bool isFractionalPart1,\
Iterator rhsBegin,Iterator rhsEnd,bool isFractionalPart2)
{
if(isFractionalPart1 && !isFractionalPart2)
return true; //0<num1<1 && num2>=1
if(!isFractionalPart1 && isFractionalPart2)
return false; //0<num2<1 && num1>=1
//isFractionPart1 == isFactionalPart2
if(isFractionalPart1)
return fractional(lhsBegin,lhsEnd,rhsBegin,rhsEnd);
else
return non_fractional(lhsBegin,lhsEnd,rhsBegin,rhsEnd);
}
};
}// namespace detail
/***********************************************************************
Natural Comparision of Two String using both's (Begin and End Iterator)
Returns :
-1 - String1 < String2
0 - String1 == String2
1 - String1 > String2
Suffix 1 represents for components of 1st String
Suffix 2 represents for components of 2nd String
************************************************************************/
template<typename ElementType, typename Iterator>
bool _compare(\
const Iterator &lhsBegin,const Iterator &lhsEnd,\
const Iterator &rhsBegin,const Iterator &rhsEnd)
{
Iterator current1 = lhsBegin,current2 = rhsBegin;
//Flag for Space Found Check
bool flag_found_space1 = false,flag_found_space2 = false;
while(current1!=lhsEnd && current2!=rhsEnd)
{
//Ignore More than One Continous Space
/******************************************
For HandlingComparision Like
Hello 9
Hello 10
Hello 123
******************************************/
while(flag_found_space1 && current1!=lhsEnd && *current1==' ') current1++;
flag_found_space1=false;
if(*current1==' ') flag_found_space1 = true;
while(flag_found_space2 && current2!=rhsEnd && *current2==' ') current2++;
flag_found_space2=false;
if(*current2==' ') flag_found_space2 = true;
if( !isdigit(*current1 ) && !isdigit(*current2))
{
//If Both Are Non Digits do Normal Comparision
if(detail::natural_less<ElementType>(*current1,*current2))
return true;
if(detail::natural_less<ElementType>(*current2,*current1))
return false;
current1++;
current2++;
}
else
{
/*********************************
Capture Numeric Part of Both String
and then using it to compare Both
***********************************/
Iterator last_nondigit1 = std::find_if(current1,lhsEnd,detail::is_not_digit<ElementType>);
Iterator last_nondigit2 = std::find_if(current2,rhsEnd,detail::is_not_digit<ElementType>);
int result = detail::compare_number<ElementType, Iterator>()(\
current1,last_nondigit1,(current1>lhsBegin && *(current1-1)=='.'), \
current2,last_nondigit2,(current2>rhsBegin && *(current2-1)=='.'));
if(result<0)
return true;
if(result>0)
return false;
current1 = last_nondigit1;
current2 = last_nondigit2;
}
}
}
template<typename String>
inline bool compare(const String &first ,const String &second)
{
return _compare<typename String::value_type,typename String::const_iterator>(first.begin(),first.end(),second.begin(),second.end());
}
template<>
inline bool compare(char *const &first ,char *const &second)
{
char* it1 = first;
while(*it1!='\0')it1++;
char* it2 = second;
while(*it2!='\0')it2++;
return _compare<char,char*>(first,it1,second,it2);
}
template<typename Container>
inline bool sort(Container &container)
{
std::sort(container.begin(),container.end(),compare<typename Container::value_type>);
}
template<typename Iterator>
inline bool sort(const Iterator &first,const Iterator &end)
{
std::sort(first,end,compare<typename Iterator::value_type>);
}
template<typename ValueType>
inline bool sort(ValueType* const first,ValueType* const end)
{
std::sort(first,end,compare<ValueType>);
}
template<typename ValueType,int N>
inline bool sort(ValueType container[N])
{
std::sort(&container[0],&container[0]+N,compare<ValueType>);
}
}//namespace natural
}//namespace SI
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_TEMPORARY_BINARY_EXPR_HPP
#define ETL_TEMPORARY_BINARY_EXPR_HPP
#include <iostream> //For stream support
#include <ostream>
#include <memory> //For shared_ptr
#include "traits_lite.hpp"
#include "iterator.hpp"
#include "tmp.hpp"
// CRTP classes
#include "crtp/comparable.hpp"
#include "crtp/iterable.hpp"
namespace etl {
template <typename D, typename V>
struct temporary_expr : comparable<D>, iterable<D> {
using derived_t = D;
using value_type = V;
using memory_type = value_type*;
using const_memory_type = const value_type*;
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
//Apply the expression
value_type operator[](std::size_t i) const {
return as_derived().result()[i];
}
template<typename... S, cpp_enable_if(sizeof...(S) == sub_size_compare<derived_t>::value)>
value_type operator()(S... args) const {
static_assert(cpp::all_convertible_to<std::size_t, S...>::value, "Invalid size types");
return as_derived().result()(args...);
}
template<typename DD = D, cpp_enable_if((sub_size_compare<DD>::value > 1))>
auto operator()(std::size_t i) const {
return sub(as_derived(), i);
}
//{{{ Iterator
iterator<const derived_t> begin() const noexcept {
return {as_derived(), 0};
}
iterator<const derived_t> end() const noexcept {
return {as_derived(), size(as_derived())};
}
// Direct memory access
memory_type memory_start() noexcept {
return as_derived().result().memory_start();
}
const_memory_type memory_start() const noexcept {
return as_derived().result().memory_start();
}
memory_type memory_end() noexcept {
return as_derived().result().memory_end();
}
const_memory_type memory_end() const noexcept {
return as_derived().result().memory_end();
}
};
template <typename T, typename AExpr, typename Op, typename Forced>
struct temporary_unary_expr final : temporary_expr<temporary_unary_expr<T, AExpr, Op, Forced>, T> {
using value_type = T;
using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr>, Forced>;
using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>;
private:
static_assert(is_etl_expr<AExpr>::value, "The argument must be an ETL expr");
using this_type = temporary_unary_expr<T, AExpr, Op, Forced>;
AExpr _a;
data_type _c;
bool evaluated = false;
bool allocated = false;
public:
//Construct a new expression
explicit temporary_unary_expr(AExpr a) : _a(a) {
//Nothing else to init
}
//Construct a new expression
temporary_unary_expr(AExpr a, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _c(c) {
//Nothing else to init
}
//Copy an expression
temporary_unary_expr(const temporary_unary_expr& e) : _a(e._a), _c(e._c) {
//Nothing else to init
}
//Move an expression
temporary_unary_expr(temporary_unary_expr&& e) : _a(e._a), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) {
e.evaluated = false;
}
//Expressions are invariant
temporary_unary_expr& operator=(const temporary_unary_expr& /*e*/) = delete;
temporary_unary_expr& operator=(temporary_unary_expr&& /*e*/) = delete;
//Accessors
std::add_lvalue_reference_t<AExpr> a(){
return _a;
}
cpp::add_const_lvalue_t<AExpr> a() const {
return _a;
}
void evaluate(){
if(!evaluated){
Op::apply(_a, result());
evaluated = true;
}
}
template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& r){
evaluate();
r = result();
}
template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& result){
Op::apply(_a, std::forward<Result>(result));
}
template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void allocate_temporary() const {
allocated = true;
}
template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void allocate_temporary(){
if(!_c){
_c.reset(Op::allocate(_a));
}
allocated = true;
}
using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>;
result_type& result(){
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
const result_type& result() const {
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
};
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
struct temporary_binary_expr final : temporary_expr<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>, T> {
using value_type = T;
using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr, BExpr>, Forced>;
using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>;
private:
static_assert(is_etl_expr<AExpr>::value && is_etl_expr<BExpr>::value, "Both arguments must be ETL expr");
using this_type = temporary_binary_expr<T, AExpr, BExpr, Op, Forced>;
AExpr _a;
BExpr _b;
data_type _c;
bool evaluated = false;
public:
//Construct a new expression
temporary_binary_expr(AExpr a, BExpr b) : _a(a), _b(b) {
//Nothing else to init
}
//Construct a new expression
temporary_binary_expr(AExpr a, BExpr b, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _b(b), _c(c) {
//Nothing else to init
}
//Copy an expression
temporary_binary_expr(const temporary_binary_expr& e) : _a(e._a), _b(e._b), _c(e._c) {
//Nothing else to init
}
//Move an expression
temporary_binary_expr(temporary_binary_expr&& e) : _a(e._a), _b(e._b), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) {
e.evaluated = false;
}
//Expressions are invariant
temporary_binary_expr& operator=(const temporary_binary_expr& /*e*/) = delete;
temporary_binary_expr& operator=(temporary_binary_expr&& /*e*/) = delete;
//Accessors
std::add_lvalue_reference_t<AExpr> a(){
return _a;
}
cpp::add_const_lvalue_t<AExpr> a() const {
return _a;
}
std::add_lvalue_reference_t<BExpr> b(){
return _b;
}
cpp::add_const_lvalue_t<BExpr> b() const {
return _b;
}
void evaluate(){
if(!evaluated){
Op::apply(_a, _b, result());
evaluated = true;
}
}
template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& r){
evaluate();
//TODO Normally, this should not be necessary
if(&r != &result()){
r = result();
}
}
template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& result){
Op::apply(_a, _b, std::forward<Result>(result));
}
template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void allocate_temporary() const {
//NOP
}
template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void allocate_temporary(){
if(!_c){
_c.reset(Op::allocate(_a, _b));
}
}
using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>;
result_type& result(){
return get_result_op::apply(_c);
}
const result_type& result() const {
return get_result_op::apply(_c);
}
};
template <typename T, typename AExpr, typename Op, typename Forced>
std::ostream& operator<<(std::ostream& os, const temporary_unary_expr<T, AExpr, Op, Forced>& expr){
return os << Op::desc() << "(" << expr.a() << ")";
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
std::ostream& operator<<(std::ostream& os, const temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& expr){
return os << Op::desc() << "(" << expr.a() << ", " << expr.b() << ")";
}
} //end of namespace etl
#endif
<commit_msg>Add assertions<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_TEMPORARY_BINARY_EXPR_HPP
#define ETL_TEMPORARY_BINARY_EXPR_HPP
#include <iostream> //For stream support
#include <ostream>
#include <memory> //For shared_ptr
#include "traits_lite.hpp"
#include "iterator.hpp"
#include "tmp.hpp"
// CRTP classes
#include "crtp/comparable.hpp"
#include "crtp/iterable.hpp"
namespace etl {
template <typename D, typename V>
struct temporary_expr : comparable<D>, iterable<D> {
using derived_t = D;
using value_type = V;
using memory_type = value_type*;
using const_memory_type = const value_type*;
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
//Apply the expression
value_type operator[](std::size_t i) const {
return as_derived().result()[i];
}
template<typename... S, cpp_enable_if(sizeof...(S) == sub_size_compare<derived_t>::value)>
value_type operator()(S... args) const {
static_assert(cpp::all_convertible_to<std::size_t, S...>::value, "Invalid size types");
return as_derived().result()(args...);
}
template<typename DD = D, cpp_enable_if((sub_size_compare<DD>::value > 1))>
auto operator()(std::size_t i) const {
return sub(as_derived(), i);
}
//{{{ Iterator
iterator<const derived_t> begin() const noexcept {
return {as_derived(), 0};
}
iterator<const derived_t> end() const noexcept {
return {as_derived(), size(as_derived())};
}
// Direct memory access
memory_type memory_start() noexcept {
return as_derived().result().memory_start();
}
const_memory_type memory_start() const noexcept {
return as_derived().result().memory_start();
}
memory_type memory_end() noexcept {
return as_derived().result().memory_end();
}
const_memory_type memory_end() const noexcept {
return as_derived().result().memory_end();
}
};
template <typename T, typename AExpr, typename Op, typename Forced>
struct temporary_unary_expr final : temporary_expr<temporary_unary_expr<T, AExpr, Op, Forced>, T> {
using value_type = T;
using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr>, Forced>;
using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>;
private:
static_assert(is_etl_expr<AExpr>::value, "The argument must be an ETL expr");
using this_type = temporary_unary_expr<T, AExpr, Op, Forced>;
AExpr _a;
data_type _c;
bool evaluated = false;
bool allocated = false;
public:
//Construct a new expression
explicit temporary_unary_expr(AExpr a) : _a(a) {
//Nothing else to init
}
//Construct a new expression
temporary_unary_expr(AExpr a, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _c(c) {
//Nothing else to init
}
//Copy an expression
temporary_unary_expr(const temporary_unary_expr& e) : _a(e._a), _c(e._c) {
//Nothing else to init
}
//Move an expression
temporary_unary_expr(temporary_unary_expr&& e) : _a(e._a), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) {
e.evaluated = false;
}
//Expressions are invariant
temporary_unary_expr& operator=(const temporary_unary_expr& /*e*/) = delete;
temporary_unary_expr& operator=(temporary_unary_expr&& /*e*/) = delete;
//Accessors
std::add_lvalue_reference_t<AExpr> a(){
return _a;
}
cpp::add_const_lvalue_t<AExpr> a() const {
return _a;
}
void evaluate(){
if(!evaluated){
Op::apply(_a, result());
evaluated = true;
}
}
template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& r){
evaluate();
r = result();
}
template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& result){
Op::apply(_a, std::forward<Result>(result));
}
template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void allocate_temporary() const {
allocated = true;
}
template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void allocate_temporary(){
if(!_c){
_c.reset(Op::allocate(_a));
}
allocated = true;
}
using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>;
result_type& result(){
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
const result_type& result() const {
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
};
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
struct temporary_binary_expr final : temporary_expr<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>, T> {
using value_type = T;
using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr, BExpr>, Forced>;
using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>;
private:
static_assert(is_etl_expr<AExpr>::value && is_etl_expr<BExpr>::value, "Both arguments must be ETL expr");
using this_type = temporary_binary_expr<T, AExpr, BExpr, Op, Forced>;
AExpr _a;
BExpr _b;
data_type _c;
bool evaluated = false;
bool allocated = false;
public:
//Construct a new expression
temporary_binary_expr(AExpr a, BExpr b) : _a(a), _b(b) {
//Nothing else to init
}
//Construct a new expression
temporary_binary_expr(AExpr a, BExpr b, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _b(b), _c(c) {
//Nothing else to init
}
//Copy an expression
temporary_binary_expr(const temporary_binary_expr& e) : _a(e._a), _b(e._b), _c(e._c) {
//Nothing else to init
}
//Move an expression
temporary_binary_expr(temporary_binary_expr&& e) : _a(e._a), _b(e._b), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) {
e.evaluated = false;
}
//Expressions are invariant
temporary_binary_expr& operator=(const temporary_binary_expr& /*e*/) = delete;
temporary_binary_expr& operator=(temporary_binary_expr&& /*e*/) = delete;
//Accessors
std::add_lvalue_reference_t<AExpr> a(){
return _a;
}
cpp::add_const_lvalue_t<AExpr> a() const {
return _a;
}
std::add_lvalue_reference_t<BExpr> b(){
return _b;
}
cpp::add_const_lvalue_t<BExpr> b() const {
return _b;
}
void evaluate(){
if(!evaluated){
Op::apply(_a, _b, result());
evaluated = true;
}
}
template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& r){
evaluate();
//TODO Normally, this should not be necessary
if(&r != &result()){
r = result();
}
}
template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void direct_evaluate(Result&& result){
Op::apply(_a, _b, std::forward<Result>(result));
}
template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)>
void allocate_temporary() const {
allocated = true;
}
template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)>
void allocate_temporary(){
if(!_c){
_c.reset(Op::allocate(_a, _b));
}
allocated = true;
}
using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>;
result_type& result(){
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
const result_type& result() const {
cpp_assert(evaluated, "The result has not been evaluated");
cpp_assert(allocated, "The result has not been allocated");
return get_result_op::apply(_c);
}
};
template <typename T, typename AExpr, typename Op, typename Forced>
std::ostream& operator<<(std::ostream& os, const temporary_unary_expr<T, AExpr, Op, Forced>& expr){
return os << Op::desc() << "(" << expr.a() << ")";
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
std::ostream& operator<<(std::ostream& os, const temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& expr){
return os << Op::desc() << "(" << expr.a() << ", " << expr.b() << ")";
}
} //end of namespace etl
#endif
<|endoftext|>
|
<commit_before>#include "entity_system.h"
#include "cmapclient.h"
#include "enumerate.h"
#include "itemdb.h"
#include <entt.hpp>
#include "components/basic_info.h"
#include "components/client.h"
#include "components/computed_values.h"
#include "components/faction.h"
#include "components/character_graphics.h"
#include "components/guild.h"
#include "components/hotbar.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"
#include "components/npc.h"
#include "components/owner.h"
#include "components/position.h"
#include "components/skills.h"
#include "components/stamina.h"
#include "components/stats.h"
#include "components/status_effects.h"
#include "components/wishlist.h"
#include "chat/normal_chat.h"
EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate), nearby(*this) {
logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
// dispatcher registration
register_dispatcher(std::function{Chat::normal_chat});
}
void EntitySystem::stop() {
work_queue.kill();
}
bool EntitySystem::dispatch_packet(RoseCommon::Entity entity, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {
if (!packet) {
return false;
}
if (!dispatcher.is_supported(*packet.get())) {
return false;
}
add_task(std::move([this, entity, packet = std::move(packet)](EntitySystem& entitySystem) mutable {
dispatcher.dispatch(entitySystem, entity, std::move(packet));
}));
return true;
}
void EntitySystem::run() {
for (auto [res, task] = work_queue.pop_front(); res;) {
{
std::lock_guard<std::mutex> lock(access);
std::invoke(std::move(task), *this);
}
auto [tmp_res, tmp_task] = work_queue.pop_front();
res = tmp_res;
task = std::move(tmp_task);
}
}
void EntitySystem::send_map(const RoseCommon::CRosePacket& packet) {
registry.view<Component::Client>().each([](auto entity, auto &client_ptr) {
(void)entity;
if (auto client = client_ptr.client.lock()) {
client->send(packet);
}
});
}
void EntitySystem::send_nearby(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) {
registry.view<Component::Client>().each([entity, this](auto other, auto &client_ptr) {
if (!nearby.is_nearby(entity, other)) return;
if (auto client = client_ptr.client.lock()) {
client->send(packet);
}
});
}
void EntitySystem::sent_to(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) {
if (auto client_ptr = registry.try_get<Component::Client>(entity)) {
if (auto client = client_ptr->client.lock()) {
client->send(packet);
}
}
}
void EntitySystem::delete_entity(RoseCommon::Entity entity) {
add_task([entity](EntitySystem& entitySystem) {
entitySystem.registry.destroy(entity);
});
}
RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium, uint32_t sessionId, std::weak_ptr<CMapClient> client) {
using namespace Component;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters{};
Core::InventoryTable inventoryTable{};
Core::SkillTable skillsTable{};
Core::WishTable wish{};
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters).where(characters.id == charId));
if (static_cast<long>(charRes.front().count) != 1L) {
return entt::null;
}
const auto& charRow = charRes.front();
entt::prototype prototype(registry);
auto& basicInfo = prototype.set<BasicInfo>();
basicInfo.name = charRow.name;
basicInfo.id = idManager.get_free_id();
basicInfo.tag = sessionId;
basicInfo.teamId = basicInfo.id;
basicInfo.job = charRow.job;
basicInfo.statPoints = charRow.statPoints;
basicInfo.skillPoints = charRow.skillPoints;
basicInfo.pkFlag = charRow.pkFlag;
basicInfo.stone = charRow.stone;
auto& component_client = prototype.set<Client>();
component_client.client = client;
auto& computedValues = prototype.set<ComputedValues>();
computedValues.command = RoseCommon::Command::STOP;
computedValues.isOnMap.store(false);
computedValues.moveMode = RoseCommon::MoveMode::WALK;
computedValues.runSpeed = 0;
computedValues.atkSpeed = 0;
computedValues.weightRate = 0;
auto& faction = prototype.set<Faction>();
faction.id = charRow.factionid;
faction.rank = charRow.factionRank;
faction.fame = charRow.fame;
faction.factionFame[0] = charRow.factionFame1;
faction.factionFame[1] = charRow.factionFame2;
faction.points[0] = charRow.factionPoints1;
faction.points[1] = charRow.factionPoints2;
faction.points[2] = charRow.factionPoints3;
auto& characterGraphics = prototype.set<CharacterGraphics>();
characterGraphics.face = charRow.face;
characterGraphics.hair = charRow.hair;
characterGraphics.race = charRow.race;
auto& guild = prototype.set<Guild>();
guild.id = charRow.clanid;
guild.contribution = charRow.clanContribution;
guild.rank = charRow.clanRank;
prototype.set<Hotbar>();
auto invRes =
conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
auto& inventory = prototype.set<Inventory>();
for (const auto& row : invRes) {
if (row.slot >= RoseCommon::MAX_ITEMS) {
continue;
}
Item item;
item.isCreated = false;
item.life = 1000;
item.hasSocket = row.socket;
item.isAppraised = true;
item.refine = row.refine;
item.count = row.amount;
item.gemOpt = row.gemOpt;
item.price = 0;
inventory.items[row.slot] = load_item(row.itemtype, row.itemid, item);
}
auto& level = prototype.set<Level>();
level.xp = charRow.exp;
level.level = charRow.level;
level.penaltyXp = charRow.penaltyExp;
auto& life = prototype.set<Life>();
life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in
life.maxHp = charRow.maxHp;
auto& magic = prototype.set<Magic>();
magic.mp = charRow.maxMp / 3;
magic.maxMp = charRow.maxMp;
auto& pos = prototype.set<Position>();
pos.x = charRow.x;
pos.y = charRow.y;
pos.z = 0;
pos.spawn = charRow.reviveMap;
pos.map = charRow.map;
auto skillRes =
conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
auto& skills = prototype.set<Skills>();
for (const auto& [i, row] : Core::enumerate(skillRes)) {
skills.skills[i].set_id(row.id);
skills.skills[i].set_level(row.level);
}
auto& stamina = prototype.set<Stamina>();
stamina.stamina = charRow.stamina;
auto& stats = prototype.set<Stats>();
stats.str = charRow.str;
stats.dex = charRow.dex;
stats.int_ = charRow.int_;
stats.con = charRow.con;
stats.charm = charRow.charm;
stats.sense = charRow.sense;
stats.bodySize = 100;
stats.headSize = 100;
prototype.set<StatusEffects>();
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
auto& wishlist = prototype.set<Wishlist>();
for (const auto& row : wishRes) {
if (row.slot >= RoseCommon::MAX_WISHLIST) {
continue;
}
Item item;
item.isCreated = false;
item.life = 1000;
item.hasSocket = row.socket;
item.isAppraised = true;
item.refine = row.refine;
item.count = row.amount;
item.gemOpt = row.gemOpt;
item.price = row.price;
wishlist.items[row.slot] = load_item(row.itemtype, row.itemid, item);
}
std::lock_guard<std::mutex> lock(access);
return prototype();
}
void EntitySystem::save_character(RoseCommon::Entity character) const {
//TODO: should be done as a task
}
RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {
using namespace Component;
entt::prototype prototype(registry);
const auto &itemDb = RoseCommon::ItemDatabase::getInstance();
if (!itemDb.itemExists(type, id)) {
return entt::null;
}
const auto& def = itemDb.getItemDef(type, id);
auto& item = prototype.set<Item>();
item.isCreated = false;
item.life = 1000;
item.durability = 100;
item.hasSocket = false;
item.isAppraised = false;
item.refine = 0;
item.count = 0;
item.gemOpt = 0;
item.price = 0;
prototype.set<RoseCommon::ItemDef>(def);
std::lock_guard<std::mutex> lock(access);
return prototype();
}
RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) {
auto entity = create_item(type, id);
if (entity == entt::null) {
return entt::null;
}
registry.replace<Component::Item>(entity, item);
return entity;
}
void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const {
// TODO: should be done as a task???
}
<commit_msg>Update entity_system.cpp<commit_after>#include "entity_system.h"
#include "cmapclient.h"
#include "enumerate.h"
#include "itemdb.h"
#include <entt.hpp>
#include "components/basic_info.h"
#include "components/client.h"
#include "components/computed_values.h"
#include "components/faction.h"
#include "components/character_graphics.h"
#include "components/guild.h"
#include "components/hotbar.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"
#include "components/npc.h"
#include "components/owner.h"
#include "components/position.h"
#include "components/skills.h"
#include "components/stamina.h"
#include "components/stats.h"
#include "components/status_effects.h"
#include "components/wishlist.h"
#include "chat/normal_chat.h"
EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate), nearby(*this) {
logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
// callback for nearby calculations
registry.construction<Component::Position>().connect<&Nearby::add_entity>(&nearby);
registry.destruction<Component::Position>().connect<&Nearby::remove_entity>(&nearby);
// dispatcher registration
register_dispatcher(std::function{Chat::normal_chat});
}
void EntitySystem::stop() {
work_queue.kill();
registry.construction<Component::Position>().disconnect<&Nearby::add_entity>(&nearby);
registry.destruction<Component::Position>().disconnect<&Nearby::remove_entity>(&nearby);
}
bool EntitySystem::dispatch_packet(RoseCommon::Entity entity, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {
if (!packet) {
return false;
}
if (!dispatcher.is_supported(*packet.get())) {
return false;
}
add_task(std::move([this, entity, packet = std::move(packet)](EntitySystem& entitySystem) mutable {
dispatcher.dispatch(entitySystem, entity, std::move(packet));
}));
return true;
}
void EntitySystem::run() {
for (auto [res, task] = work_queue.pop_front(); res;) {
{
std::lock_guard<std::mutex> lock(access);
std::invoke(std::move(task), *this);
}
auto [tmp_res, tmp_task] = work_queue.pop_front();
res = tmp_res;
task = std::move(tmp_task);
}
}
void EntitySystem::send_map(const RoseCommon::CRosePacket& packet) {
registry.view<Component::Client>().each([](auto entity, auto &client_ptr) {
(void)entity;
if (auto client = client_ptr.client.lock()) {
client->send(packet);
}
});
}
void EntitySystem::send_nearby(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) {
registry.view<Component::Client>().each([entity, this](auto other, auto &client_ptr) {
if (!nearby.is_nearby(entity, other)) return;
if (auto client = client_ptr.client.lock()) {
client->send(packet);
}
});
}
void EntitySystem::sent_to(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) {
if (auto client_ptr = registry.try_get<Component::Client>(entity)) {
if (auto client = client_ptr->client.lock()) {
client->send(packet);
}
}
}
void EntitySystem::delete_entity(RoseCommon::Entity entity) {
add_task([entity](EntitySystem& entitySystem) {
entitySystem.registry.destroy(entity);
});
}
RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium, uint32_t sessionId, std::weak_ptr<CMapClient> client) {
using namespace Component;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters{};
Core::InventoryTable inventoryTable{};
Core::SkillTable skillsTable{};
Core::WishTable wish{};
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters).where(characters.id == charId));
if (static_cast<long>(charRes.front().count) != 1L) {
return entt::null;
}
const auto& charRow = charRes.front();
entt::prototype prototype(registry);
auto& basicInfo = prototype.set<BasicInfo>();
basicInfo.name = charRow.name;
basicInfo.id = idManager.get_free_id();
basicInfo.tag = sessionId;
basicInfo.teamId = basicInfo.id;
basicInfo.job = charRow.job;
basicInfo.statPoints = charRow.statPoints;
basicInfo.skillPoints = charRow.skillPoints;
basicInfo.pkFlag = charRow.pkFlag;
basicInfo.stone = charRow.stone;
auto& component_client = prototype.set<Client>();
component_client.client = client;
auto& computedValues = prototype.set<ComputedValues>();
computedValues.command = RoseCommon::Command::STOP;
computedValues.isOnMap.store(false);
computedValues.moveMode = RoseCommon::MoveMode::WALK;
computedValues.runSpeed = 0;
computedValues.atkSpeed = 0;
computedValues.weightRate = 0;
auto& faction = prototype.set<Faction>();
faction.id = charRow.factionid;
faction.rank = charRow.factionRank;
faction.fame = charRow.fame;
faction.factionFame[0] = charRow.factionFame1;
faction.factionFame[1] = charRow.factionFame2;
faction.points[0] = charRow.factionPoints1;
faction.points[1] = charRow.factionPoints2;
faction.points[2] = charRow.factionPoints3;
auto& characterGraphics = prototype.set<CharacterGraphics>();
characterGraphics.face = charRow.face;
characterGraphics.hair = charRow.hair;
characterGraphics.race = charRow.race;
auto& guild = prototype.set<Guild>();
guild.id = charRow.clanid;
guild.contribution = charRow.clanContribution;
guild.rank = charRow.clanRank;
prototype.set<Hotbar>();
auto invRes =
conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
auto& inventory = prototype.set<Inventory>();
for (const auto& row : invRes) {
if (row.slot >= RoseCommon::MAX_ITEMS) {
continue;
}
Item item;
item.isCreated = false;
item.life = 1000;
item.hasSocket = row.socket;
item.isAppraised = true;
item.refine = row.refine;
item.count = row.amount;
item.gemOpt = row.gemOpt;
item.price = 0;
inventory.items[row.slot] = load_item(row.itemtype, row.itemid, item);
}
auto& level = prototype.set<Level>();
level.xp = charRow.exp;
level.level = charRow.level;
level.penaltyXp = charRow.penaltyExp;
auto& life = prototype.set<Life>();
life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in
life.maxHp = charRow.maxHp;
auto& magic = prototype.set<Magic>();
magic.mp = charRow.maxMp / 3;
magic.maxMp = charRow.maxMp;
auto& pos = prototype.set<Position>();
pos.x = charRow.x;
pos.y = charRow.y;
pos.z = 0;
pos.spawn = charRow.reviveMap;
pos.map = charRow.map;
auto skillRes =
conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
auto& skills = prototype.set<Skills>();
for (const auto& [i, row] : Core::enumerate(skillRes)) {
skills.skills[i].set_id(row.id);
skills.skills[i].set_level(row.level);
}
auto& stamina = prototype.set<Stamina>();
stamina.stamina = charRow.stamina;
auto& stats = prototype.set<Stats>();
stats.str = charRow.str;
stats.dex = charRow.dex;
stats.int_ = charRow.int_;
stats.con = charRow.con;
stats.charm = charRow.charm;
stats.sense = charRow.sense;
stats.bodySize = 100;
stats.headSize = 100;
prototype.set<StatusEffects>();
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
auto& wishlist = prototype.set<Wishlist>();
for (const auto& row : wishRes) {
if (row.slot >= RoseCommon::MAX_WISHLIST) {
continue;
}
Item item;
item.isCreated = false;
item.life = 1000;
item.hasSocket = row.socket;
item.isAppraised = true;
item.refine = row.refine;
item.count = row.amount;
item.gemOpt = row.gemOpt;
item.price = row.price;
wishlist.items[row.slot] = load_item(row.itemtype, row.itemid, item);
}
std::lock_guard<std::mutex> lock(access);
return prototype();
}
void EntitySystem::save_character(RoseCommon::Entity character) const {
//TODO: should be done as a task
}
RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {
using namespace Component;
entt::prototype prototype(registry);
const auto &itemDb = RoseCommon::ItemDatabase::getInstance();
if (!itemDb.itemExists(type, id)) {
return entt::null;
}
const auto& def = itemDb.getItemDef(type, id);
auto& item = prototype.set<Item>();
item.isCreated = false;
item.life = 1000;
item.durability = 100;
item.hasSocket = false;
item.isAppraised = false;
item.refine = 0;
item.count = 0;
item.gemOpt = 0;
item.price = 0;
prototype.set<RoseCommon::ItemDef>(def);
std::lock_guard<std::mutex> lock(access);
return prototype();
}
RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) {
auto entity = create_item(type, id);
if (entity == entt::null) {
return entt::null;
}
registry.replace<Component::Item>(entity, item);
return entity;
}
void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const {
// TODO: should be done as a task???
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains traits for wrapper expressions
*/
#pragma once
namespace etl {
/*!
* \brief Traits for wrapper expressions
*/
template <typename T>
struct wrapper_traits {
using expr_t = T;
using sub_expr_t = std::decay_t<typename T::expr_t>;
using sub_traits = etl_traits<sub_expr_t>;
static constexpr const bool is_etl = sub_traits::is_etl; ///< Indicates if the type is an ETL expression
static constexpr const bool is_transformer = sub_traits::is_transformer; ///< Indicates if the type is a transformer
static constexpr const bool is_view = sub_traits::is_view; ///< Indicates if the type is a view
static constexpr const bool is_magic_view = sub_traits::is_magic_view; ///< Indicates if the type is a magic view
static constexpr const bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr const bool is_value = sub_traits::is_value; ///< Indicates if the expression is of value type
static constexpr const bool is_direct = sub_traits::is_direct; ///< Indicates if the expression has direct memory access
static constexpr const bool is_linear = sub_traits::is_linear; ///< Indicates if the expression is linear
static constexpr const bool is_generator = sub_traits::is_generator; ///< Indicates if the expression is a generator expression
static constexpr const bool needs_temporary_visitor = sub_traits::needs_temporary_visitor; ///< Indicates if the expression needs a temporary visitor
static constexpr const bool needs_evaluator_visitor = sub_traits::needs_evaluator_visitor; ///< Indicaes if the expression needs an evaluator visitor
static constexpr const order storage_order = sub_traits::storage_order; ///< The expression storage order
/*!
* The vectorization type for V
*/
template <vector_mode_t V>
using vectorizable = typename sub_traits::template vectorizable<V>;
/*!
* \brief Returns the size of the given expression
* \param v The expression to get the size for
* \returns the size of the given expression
*/
static std::size_t size(const expr_t& v) {
return sub_traits::size(v.value());
}
/*!
* \brief Returns the dth dimension of the given expression
* \param v The expression
* \param d The dimension to get
* \return The dth dimension of the given expression
*/
static std::size_t dim(const expr_t& v, std::size_t d) {
return sub_traits::dim(v.value(), d);
}
/*!
* \brief Returns the size of an expression of this fast type.
* \returns the size of an expression of this fast type.
*/
static constexpr std::size_t size() {
return sub_traits::size();
}
/*!
* \brief Returns the Dth dimension of an expression of this type
* \tparam D The dimension to get
* \return the Dth dimension of an expression of this type
*/
template <std::size_t D>
static constexpr std::size_t dim() {
return sub_traits::template dim<D>();
}
/*!
* \brief Returns the number of expressions for this type
* \return the number of dimensions of this type
*/
static constexpr std::size_t dimensions() {
return sub_traits::dimensions();
}
};
} //end of namespace etl
<commit_msg>Add is_thread_safe to wrapper traits<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains traits for wrapper expressions
*/
#pragma once
namespace etl {
/*!
* \brief Traits for wrapper expressions
*/
template <typename T>
struct wrapper_traits {
using expr_t = T;
using sub_expr_t = std::decay_t<typename T::expr_t>;
using sub_traits = etl_traits<sub_expr_t>;
static constexpr const bool is_etl = sub_traits::is_etl; ///< Indicates if the type is an ETL expression
static constexpr const bool is_transformer = sub_traits::is_transformer; ///< Indicates if the type is a transformer
static constexpr const bool is_view = sub_traits::is_view; ///< Indicates if the type is a view
static constexpr const bool is_magic_view = sub_traits::is_magic_view; ///< Indicates if the type is a magic view
static constexpr const bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr const bool is_value = sub_traits::is_value; ///< Indicates if the expression is of value type
static constexpr const bool is_direct = sub_traits::is_direct; ///< Indicates if the expression has direct memory access
static constexpr const bool is_linear = sub_traits::is_linear; ///< Indicates if the expression is linear
static constexpr const bool is_thread_safe = sub_traits::is_thread_safe; ///< Indicates if the expression is thread safe
static constexpr const bool is_generator = sub_traits::is_generator; ///< Indicates if the expression is a generator expression
static constexpr const bool needs_temporary_visitor = sub_traits::needs_temporary_visitor; ///< Indicates if the expression needs a temporary visitor
static constexpr const bool needs_evaluator_visitor = sub_traits::needs_evaluator_visitor; ///< Indicaes if the expression needs an evaluator visitor
static constexpr const order storage_order = sub_traits::storage_order; ///< The expression storage order
/*!
* The vectorization type for V
*/
template <vector_mode_t V>
using vectorizable = typename sub_traits::template vectorizable<V>;
/*!
* \brief Returns the size of the given expression
* \param v The expression to get the size for
* \returns the size of the given expression
*/
static std::size_t size(const expr_t& v) {
return sub_traits::size(v.value());
}
/*!
* \brief Returns the dth dimension of the given expression
* \param v The expression
* \param d The dimension to get
* \return The dth dimension of the given expression
*/
static std::size_t dim(const expr_t& v, std::size_t d) {
return sub_traits::dim(v.value(), d);
}
/*!
* \brief Returns the size of an expression of this fast type.
* \returns the size of an expression of this fast type.
*/
static constexpr std::size_t size() {
return sub_traits::size();
}
/*!
* \brief Returns the Dth dimension of an expression of this type
* \tparam D The dimension to get
* \return the Dth dimension of an expression of this type
*/
template <std::size_t D>
static constexpr std::size_t dim() {
return sub_traits::template dim<D>();
}
/*!
* \brief Returns the number of expressions for this type
* \return the number of dimensions of this type
*/
static constexpr std::size_t dimensions() {
return sub_traits::dimensions();
}
};
} //end of namespace etl
<|endoftext|>
|
<commit_before>#include "script_loader.h"
using namespace LuaScript;
ScriptLoader::File::File(std::string const& path) : path_(path) {
//TODO: find filename
//prob split on '/' and take latest, then split on '.' and take everything but the last one if there's more than one
}
ScriptLoader::ScriptLoader(std::shared_ptr<EntitySystem> entity_system, uint16_t map_id, std::string const& path):
entity_system_(entity_system),
logger_(Core::CLog::GetLogger(Core::log_type::SCRIPTLOADER).lock()),
path_(path), map_id_(map_id) {
state_.open_libraries(); //FIXME: check if we need all libs
state_.set_function("include", [this](std::string path) {
load_script(path);
});
}
void ScriptLoader::load_script() {
reload_scripts(path_);
}
void ScriptLoader::load_npcs() {
for (auto& [file, entities] : npc_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_warpgates() {
for (auto& [file, entities] : warpgate_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_spawners() {
for (auto& [file, entities] : spawner_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_script(std::string const& path) {
try {
File file = File{path};
sol::environment env{state_, sol::create, state_.globals()};
auto warpgate_file = warpgate_files_.find(files);
std::vector<Entity> warpgates;
if (warpgate_file != warpgate_files_.end()) {
warpgates = std::move(warpgate_file->second);
}
env.set_function("warp_gate", [warpgates](std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) {
warpgates.push_back(entity_system_->create_warpgate(alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale));
});
auto npc_file = npc_files_.find(file);
std::vector<Entity> npcs;
if (npc_file != npc_files_.end()) {
npcs = std::move(npc_file->second);
}
env.set_function("npc", [npc_file](std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
npc_file->second.push_back(entity_system_->create_npc(npc_lua, npc_id, map_id, x, y, z, angle));
});
auto spawner_file = spawner_files_.find(file);
std::vector<Entity> spawners;
if (spawner_file != spawner_files_.end()) {
spawners = std::move(spawners_file->second);
}
env.set_function("mob", [spawners](std::string alias, int mob_id, int mob_count, int limit, int interval, int range, int map_id, float x, float y, float z) {
spawners.push_back(entity_system_->create_spawner(alias, mob_id, mob_count, limit, interval, range, map_id, x, y, z));
});
state_.script(path, env);
logger_->info("Finished (re)loading scripts from '{}'", path);
if (warpgates.size()) warpgate_files_.insert_or_assign(std::make_pair(file, std::move(warpgates)));
if (npcs.size()) npc_files_.insert_or_assign(std::make_pair(file, std::move(npcs)));
if (spawners.size()) spawner_files_.insert_or_assign(std::make_pair(file, std::move(spawners)));
} catch (const sol::error& e) {
logger_->error("Error (re)loading lua scripts '{}' : {}", path, e.what());
}
}
<commit_msg>Update script_loader.cpp<commit_after>#include "script_loader.h"
using namespace LuaScript;
ScriptLoader::File::File(std::string const& path) : path_(path) {
//TODO: find filename
//prob split on '/' and take latest, then split on '.' and take everything but the last one if there's more than one
}
ScriptLoader::ScriptLoader(std::shared_ptr<EntitySystem> entity_system, uint16_t map_id, std::string const& path):
entity_system_(entity_system),
logger_(Core::CLog::GetLogger(Core::log_type::SCRIPTLOADER).lock()),
path_(path), map_id_(map_id) {
state_.open_libraries(); //FIXME: check if we need all libs
state_.set_function("include", [this](std::string path) {
load_script(path);
});
}
void ScriptLoader::load_script() {
load_script(path_);
}
void ScriptLoader::load_npcs() {
for (auto& [file, entities] : npc_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_warpgates() {
for (auto& [file, entities] : warpgate_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_spawners() {
for (auto& [file, entities] : spawner_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_script(std::string const& path) {
try {
File file = File{path};
sol::environment env{state_, sol::create, state_.globals()};
auto warpgate_file = warpgate_files_.find(file);
std::vector<Entity> warpgates;
if (warpgate_file != warpgate_files_.end()) {
warpgates = std::move(warpgate_file->second);
}
env.set_function("warp_gate", [warpgates](std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) {
warpgates.push_back(entity_system_->create_warpgate(alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale));
});
auto npc_file = npc_files_.find(file);
std::vector<Entity> npcs;
if (npc_file != npc_files_.end()) {
npcs = std::move(npc_file->second);
}
env.set_function("npc", [npc_file](std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
npc_file->second.push_back(entity_system_->create_npc(npc_lua, npc_id, map_id, x, y, z, angle));
});
auto spawner_file = spawner_files_.find(file);
std::vector<Entity> spawners;
if (spawner_file != spawner_files_.end()) {
spawners = std::move(spawners_file->second);
}
env.set_function("mob", [spawners](std::string alias, int mob_id, int mob_count, int limit, int interval, int range, int map_id, float x, float y, float z) {
spawners.push_back(entity_system_->create_spawner(alias, mob_id, mob_count, limit, interval, range, map_id, x, y, z));
});
state_.script(path, env);
logger_->info("Finished (re)loading scripts from '{}'", path);
if (warpgates.size()) warpgate_files_.insert_or_assign(std::make_pair(file, std::move(warpgates)));
if (npcs.size()) npc_files_.insert_or_assign(std::make_pair(file, std::move(npcs)));
if (spawners.size()) spawner_files_.insert_or_assign(std::make_pair(file, std::move(spawners)));
} catch (const sol::error& e) {
logger_->error("Error (re)loading lua scripts '{}' : {}", path, e.what());
}
}
<|endoftext|>
|
<commit_before>//
// mutex.hpp
// fibio
//
// Created by Chen Xu on 14-3-4.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_mutex_hpp
#define fibio_mutex_hpp
#include <memory>
#include <chrono>
#include <mutex>
#include <fibio/fibers/detail/forward.hpp>
namespace fibio { namespace fibers {
class mutex {
public:
/// constructor
mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
mutex(const mutex&) = delete;
void operator=(const mutex&) = delete;
std::shared_ptr<detail::mutex_object> impl_;
friend class condition_variable;
};
class timed_mutex {
public:
/// constructor
timed_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable for the specified timeout duration
*/
template<class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep,Period>& timeout_duration ) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count());
}
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable until specified time point has been reached
*/
template< class Clock, class Duration >
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time ) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_time - std::chrono::steady_clock::now()).count());
}
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
timed_mutex(const timed_mutex&) = delete;
void operator=(const timed_mutex&) = delete;
bool try_lock_usec(uint64_t usec);
std::shared_ptr<detail::timed_mutex_object> impl_;
};
class recursive_mutex {
public:
/// constructor
recursive_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
recursive_mutex(const recursive_mutex&) = delete;
void operator=(const recursive_mutex&) = delete;
std::shared_ptr<detail::recursive_mutex_object> impl_;
};
class recursive_timed_mutex {
public:
/// constructor
recursive_timed_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable for the specified timeout duration
*/
template<class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep,Period>& timeout_duration) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count());
}
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable until specified time point has been reached
*/
template<class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_time - std::chrono::steady_clock::now()).count());
}
private:
/// non-copyable
recursive_timed_mutex(const recursive_timed_mutex&) = delete;
void operator=(const recursive_timed_mutex&) = delete;
bool try_lock_usec(uint64_t usec);
std::shared_ptr<detail::recursive_timed_mutex_object> impl_;
};
}} // End of namespace fibio::fibers
namespace fibio {
using fibers::mutex;
using fibers::timed_mutex;
using fibers::recursive_mutex;
using fibers::recursive_timed_mutex;
using std::lock_guard;
using std::unique_lock;
using std::defer_lock_t;
using std::try_to_lock_t;
using std::adopt_lock_t;
using std::defer_lock;
using std::try_to_lock;
using std::adopt_lock;
using std::try_lock;
using std::lock;
} // End of namespace fibio
#endif
<commit_msg>warning<commit_after>//
// mutex.hpp
// fibio
//
// Created by Chen Xu on 14-3-4.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_mutex_hpp
#define fibio_mutex_hpp
#include <memory>
#include <chrono>
#include <mutex>
#include <fibio/fibers/detail/forward.hpp>
namespace fibio { namespace fibers {
class mutex {
public:
/// constructor
mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
mutex(const mutex&) = delete;
void operator=(const mutex&) = delete;
std::shared_ptr<detail::mutex_object> impl_;
friend struct condition_variable;
};
class timed_mutex {
public:
/// constructor
timed_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable for the specified timeout duration
*/
template<class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep,Period>& timeout_duration ) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count());
}
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable until specified time point has been reached
*/
template< class Clock, class Duration >
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time ) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_time - std::chrono::steady_clock::now()).count());
}
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
timed_mutex(const timed_mutex&) = delete;
void operator=(const timed_mutex&) = delete;
bool try_lock_usec(uint64_t usec);
std::shared_ptr<detail::timed_mutex_object> impl_;
};
class recursive_mutex {
public:
/// constructor
recursive_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
private:
/// non-copyable
recursive_mutex(const recursive_mutex&) = delete;
void operator=(const recursive_mutex&) = delete;
std::shared_ptr<detail::recursive_mutex_object> impl_;
};
class recursive_timed_mutex {
public:
/// constructor
recursive_timed_mutex();
/**
* locks the mutex, blocks if the mutex is not available
*/
void lock();
/**
* tries to lock the mutex, returns if the mutex is not available
*/
bool try_lock();
/**
* unlocks the mutex
*/
void unlock();
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable for the specified timeout duration
*/
template<class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep,Period>& timeout_duration) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_duration).count());
}
/**
* tries to lock the mutex, returns if the mutex has been
* unavailable until specified time point has been reached
*/
template<class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock,Duration>& timeout_time) {
return try_lock_usec(std::chrono::duration_cast<std::chrono::microseconds>(timeout_time - std::chrono::steady_clock::now()).count());
}
private:
/// non-copyable
recursive_timed_mutex(const recursive_timed_mutex&) = delete;
void operator=(const recursive_timed_mutex&) = delete;
bool try_lock_usec(uint64_t usec);
std::shared_ptr<detail::recursive_timed_mutex_object> impl_;
};
}} // End of namespace fibio::fibers
namespace fibio {
using fibers::mutex;
using fibers::timed_mutex;
using fibers::recursive_mutex;
using fibers::recursive_timed_mutex;
using std::lock_guard;
using std::unique_lock;
using std::defer_lock_t;
using std::try_to_lock_t;
using std::adopt_lock_t;
using std::defer_lock;
using std::try_to_lock;
using std::adopt_lock;
using std::try_lock;
using std::lock;
} // End of namespace fibio
#endif
<|endoftext|>
|
<commit_before>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015-2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <vector>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <kchashdb.h>
#include "Downloader.h"
#include "ExecUtil.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcUtil.h"
#include "MarcWriter.h"
#include "RegexMatcher.h"
#include "Semaphore.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "TimeLimit.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname
<< "[--max-record-count count] [--skip-count count] [--process-count-low-and-high-watermarks low:high] "
<< "marc_input marc_output full_text_db\n"
<< " --process-count-low-and-high-watermarks sets the maximum and minimum number of spawned\n"
<< " child processes. When we hit the high water mark we wait for child processes to exit\n"
<< " until we reach the low watermark.\n\n";
std::exit(EXIT_FAILURE);
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto &_3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->value_, "Rezension"))
return true;
} else {
const auto &z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->value_, "Rezension"))
return true;
}
return false;
}
bool FoundAtLeastOneNonReviewLink(const MarcRecord &record) {
for (size_t _856_index(record.getFieldIndex("856")); record.getTag(_856_index) == "856"; ++_856_index) {
const Subfields subfields(record.getSubfields(_856_index));
if (subfields.getIndicator1() == '7' or not subfields.hasSubfield('u'))
continue;
if (not IsProbablyAReview(subfields))
return true;
}
return false;
}
// Returns the number of child processes that returned a non-zero exit code.
unsigned CleanUpZombies(const unsigned zombies_to_collect) {
unsigned child_reported_failure_count(0);
for (unsigned zombie_no(0); zombie_no < zombies_to_collect; ++zombie_no) {
int exit_code;
::wait(&exit_code);
if (exit_code != 0)
++child_reported_failure_count;
}
return child_reported_failure_count;
}
void ProcessRecords(const unsigned max_record_count, const unsigned skip_count, MarcReader * const marc_reader,
MarcWriter * const marc_writer, const std::string &db_filename,
const unsigned process_count_low_watermark, const unsigned process_count_high_watermark)
{
Semaphore semaphore("/full_text_cached_counter", Semaphore::CREATE);
std::string err_msg;
unsigned total_record_count(0), spawn_count(0), active_child_count(0), child_reported_failure_count(0);
const std::string UPDATE_FULL_TEXT_DB_PATH("/usr/local/bin/update_full_text_db");
std::cout << "Skip " << skip_count << " records\n";
while (MarcRecord record = marc_reader->read()) {
if (total_record_count == max_record_count)
break;
++total_record_count;
if (total_record_count <= skip_count)
continue;
const bool insert_in_cache(FoundAtLeastOneNonReviewLink(record)
or (not MarcUtil::HasTagAndSubfield(record, "856", 'u')
and MarcUtil::HasTagAndSubfield(record, "520", 'a')));
if (not insert_in_cache) {
MarcUtil::FileLockedComposeAndWriteRecord(marc_writer, &record);
continue;
}
ExecUtil::Spawn(UPDATE_FULL_TEXT_DB_PATH,
{ std::to_string(marc_reader->tell()), marc_reader->getPath(),
marc_writer->getFile().getPath(), db_filename });
++active_child_count;
++spawn_count;
if (active_child_count > process_count_high_watermark) {
child_reported_failure_count += CleanUpZombies(active_child_count - process_count_low_watermark);
active_child_count = process_count_low_watermark;
}
}
// Wait for stragglers:
child_reported_failure_count += CleanUpZombies(active_child_count);
if (not err_msg.empty())
Error(err_msg);
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Spawned " << spawn_count << " subprocesses.\n";
std::cerr << semaphore.getValue()
<< " documents were not downloaded because their cached values had not yet expired.\n";
std::cerr << child_reported_failure_count << " children reported a failure!\n";
}
constexpr unsigned PROCESS_COUNT_DEFAULT_HIGH_WATERMARK(10);
constexpr unsigned PROCESS_COUNT_DEFAULT_LOW_WATERMARK(5);
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4 and argc != 6 and argc != 8 and argc != 10)
Usage();
++argv; // skip program name
// Process optional args:
unsigned max_record_count(UINT_MAX), skip_count(0);
unsigned process_count_low_watermark(PROCESS_COUNT_DEFAULT_LOW_WATERMARK),
process_count_high_watermark(PROCESS_COUNT_DEFAULT_HIGH_WATERMARK);
while (argc > 4) {
std::cout << "Arg: " << *argv << "\n";
if (std::strcmp(*argv, "--max-record-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &max_record_count) or max_record_count == 0)
Error("bad value for --max-record-count!");
++argv;
argc -= 2;
} else if (std::strcmp(*argv, "--skip-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &skip_count))
Error("bad value for --skip-count!");
std::cout << "Should skip " << skip_count << " records\n";
++argv;
argc -= 2;
} else if (std::strcmp("--process-count-low-and-high-watermarks", *argv) == 0) {
++argv;
char *arg_end(*argv + std::strlen(*argv));
char * const colon(std::find(*argv, arg_end, ':'));
if (colon == arg_end)
Error("bad argument to --process-count-low-and-high-watermarks: colon is missing!");
*colon = '\0';
if (not StringUtil::ToNumber(*argv, &process_count_low_watermark)
or not StringUtil::ToNumber(*argv, &process_count_high_watermark))
Error("low or high watermark is not an unsigned number!");
if (process_count_high_watermark > process_count_low_watermark)
Error("the high watermark must be larger than the low watermark!");
++argv;
argc -= 2;
} else
Error("unknown flag: " + std::string(*argv));
}
const std::string marc_input_filename(*argv++);
const std::string marc_output_filename(*argv++);
if (marc_input_filename == marc_output_filename)
Error("input filename must not equal output filename!");
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY));
const std::string db_filename(*argv);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE))
Error("Failed to create the key/valuedatabase \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
db.close();
const std::string UPDATE_DB_LOG_DIR_PATH(
"/var/log/" + std::string(FileUtil::Exists("/var/log/krimdok") ? "krimdok" : "ixtheo")
+ "/update_full_text_db");
if (not FileUtil::MakeDirectory(UPDATE_DB_LOG_DIR_PATH, /* recursive = */ true))
Error("failed to create directory: " + UPDATE_DB_LOG_DIR_PATH);
try {
ProcessRecords(max_record_count, skip_count, marc_reader.get(), marc_writer.get(), db_filename,
process_count_low_watermark, process_count_high_watermark);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<commit_msg>Reverted a bad change.<commit_after>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015-2017 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <vector>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <kchashdb.h>
#include "Downloader.h"
#include "ExecUtil.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcUtil.h"
#include "MarcWriter.h"
#include "RegexMatcher.h"
#include "Semaphore.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "TimeLimit.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname
<< "[--max-record-count count] [--skip-count count] [--process-count-low-and-high-watermarks low:high] "
<< "marc_input marc_output full_text_db\n"
<< " --process-count-low-and-high-watermarks sets the maximum and minimum number of spawned\n"
<< " child processes. When we hit the high water mark we wait for child processes to exit\n"
<< " until we reach the low watermark.\n\n";
std::exit(EXIT_FAILURE);
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto &_3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->value_, "Rezension"))
return true;
} else {
const auto &z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->value_, "Rezension"))
return true;
}
return false;
}
bool FoundAtLeastOneNonReviewLink(const MarcRecord &record) {
for (size_t _856_index(record.getFieldIndex("856")); record.getTag(_856_index) == "856"; ++_856_index) {
const Subfields subfields(record.getSubfields(_856_index));
if (subfields.getIndicator1() == '7' or not subfields.hasSubfield('u'))
continue;
if (not IsProbablyAReview(subfields))
return true;
}
return false;
}
// Returns the number of child processes that returned a non-zero exit code.
unsigned CleanUpZombies(const unsigned zombies_to_collect) {
unsigned child_reported_failure_count(0);
for (unsigned zombie_no(0); zombie_no < zombies_to_collect; ++zombie_no) {
int exit_code;
::wait(&exit_code);
if (exit_code != 0)
++child_reported_failure_count;
}
return child_reported_failure_count;
}
void ProcessRecords(const unsigned max_record_count, const unsigned skip_count, MarcReader * const marc_reader,
MarcWriter * const marc_writer, const std::string &db_filename,
const unsigned process_count_low_watermark, const unsigned process_count_high_watermark)
{
Semaphore semaphore("/full_text_cached_counter", Semaphore::CREATE);
std::string err_msg;
unsigned total_record_count(0), spawn_count(0), active_child_count(0), child_reported_failure_count(0);
const std::string UPDATE_FULL_TEXT_DB_PATH("/usr/local/bin/update_full_text_db");
std::cout << "Skip " << skip_count << " records\n";
off_t record_start = marc_reader->tell();
while (MarcRecord record = marc_reader->read()) {
if (total_record_count == max_record_count)
break;
++total_record_count;
if (total_record_count <= skip_count) {
record_start = marc_reader->tell();
continue;
}
const bool insert_in_cache(FoundAtLeastOneNonReviewLink(record)
or (not MarcUtil::HasTagAndSubfield(record, "856", 'u')
and MarcUtil::HasTagAndSubfield(record, "520", 'a')));
if (not insert_in_cache) {
MarcUtil::FileLockedComposeAndWriteRecord(marc_writer, &record);
record_start = marc_reader->tell();
continue;
}
ExecUtil::Spawn(UPDATE_FULL_TEXT_DB_PATH,
{ std::to_string(record_start), marc_reader->getPath(), marc_writer->getFile().getPath(),
db_filename });
++active_child_count;
++spawn_count;
if (active_child_count > process_count_high_watermark) {
child_reported_failure_count += CleanUpZombies(active_child_count - process_count_low_watermark);
active_child_count = process_count_low_watermark;
}
record_start = marc_reader->tell();
}
// Wait for stragglers:
child_reported_failure_count += CleanUpZombies(active_child_count);
if (not err_msg.empty())
Error(err_msg);
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Spawned " << spawn_count << " subprocesses.\n";
std::cerr << semaphore.getValue()
<< " documents were not downloaded because their cached values had not yet expired.\n";
std::cerr << child_reported_failure_count << " children reported a failure!\n";
}
constexpr unsigned PROCESS_COUNT_DEFAULT_HIGH_WATERMARK(10);
constexpr unsigned PROCESS_COUNT_DEFAULT_LOW_WATERMARK(5);
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 4 and argc != 6 and argc != 8 and argc != 10)
Usage();
++argv; // skip program name
// Process optional args:
unsigned max_record_count(UINT_MAX), skip_count(0);
unsigned process_count_low_watermark(PROCESS_COUNT_DEFAULT_LOW_WATERMARK),
process_count_high_watermark(PROCESS_COUNT_DEFAULT_HIGH_WATERMARK);
while (argc > 4) {
std::cout << "Arg: " << *argv << "\n";
if (std::strcmp(*argv, "--max-record-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &max_record_count) or max_record_count == 0)
Error("bad value for --max-record-count!");
++argv;
argc -= 2;
} else if (std::strcmp(*argv, "--skip-count") == 0) {
++argv;
if (not StringUtil::ToNumber(*argv, &skip_count))
Error("bad value for --skip-count!");
std::cout << "Should skip " << skip_count << " records\n";
++argv;
argc -= 2;
} else if (std::strcmp("--process-count-low-and-high-watermarks", *argv) == 0) {
++argv;
char *arg_end(*argv + std::strlen(*argv));
char * const colon(std::find(*argv, arg_end, ':'));
if (colon == arg_end)
Error("bad argument to --process-count-low-and-high-watermarks: colon is missing!");
*colon = '\0';
if (not StringUtil::ToNumber(*argv, &process_count_low_watermark)
or not StringUtil::ToNumber(*argv, &process_count_high_watermark))
Error("low or high watermark is not an unsigned number!");
if (process_count_high_watermark > process_count_low_watermark)
Error("the high watermark must be larger than the low watermark!");
++argv;
argc -= 2;
} else
Error("unknown flag: " + std::string(*argv));
}
const std::string marc_input_filename(*argv++);
const std::string marc_output_filename(*argv++);
if (marc_input_filename == marc_output_filename)
Error("input filename must not equal output filename!");
std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY));
std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY));
const std::string db_filename(*argv);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE))
Error("Failed to create the key/valuedatabase \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
db.close();
const std::string UPDATE_DB_LOG_DIR_PATH(
"/var/log/" + std::string(FileUtil::Exists("/var/log/krimdok") ? "krimdok" : "ixtheo")
+ "/update_full_text_db");
if (not FileUtil::MakeDirectory(UPDATE_DB_LOG_DIR_PATH, /* recursive = */ true))
Error("failed to create directory: " + UPDATE_DB_LOG_DIR_PATH);
try {
ProcessRecords(max_record_count, skip_count, marc_reader.get(), marc_writer.get(), db_filename,
process_count_low_watermark, process_count_high_watermark);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<|endoftext|>
|
<commit_before>/** \file translation_db_tool.cc
* \brief A tool for reading/editing of the "translations" SQL table.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <set>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "IniFile.h"
#include "SimpleXmlParser.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << " command [args]\n\n";
std::cerr << " Possible commands are:\n";
std::cerr << " get_missing language_code\n";
std::cerr << " insert token language_code text\n";
std::cerr << " insert ppn gnd_code language_code text\n";
std::exit(EXIT_FAILURE);
}
void ExecSqlOrDie(const std::string &select_statement, DbConnection * const connection) {
if (unlikely(not connection->query(select_statement)))
Error("SQL Statement failed: " + select_statement + " (" + connection->getLastErrorMessage() + ")");
}
// Replaces a comma with "\," and a slash with "\\".
std::string EscapeCommasAndBackslashes(const std::string &text) {
std::string escaped_text;
for (const auto ch : text) {
if (unlikely(ch == ',' or ch == '\\'))
escaped_text += '\\';
escaped_text += ch;
}
return escaped_text;
}
unsigned GetMissing(DbConnection * const connection, const std::string &table_name,
const std::string &table_key_name, const std::string &category,
const std::string &language_code)
{
// Find a token/ppn where "language_code" is missing:
ExecSqlOrDie("SELECT distinct " + table_key_name + " FROM " + table_name + " WHERE " + table_key_name +
" NOT IN (SELECT distinct " + table_key_name + " FROM " + table_name +
" WHERE language_code = \"" + language_code + "\") ORDER BY RAND();", connection);
DbResultSet keys_result_set(connection->getLastResultSet());
const size_t count(keys_result_set.size());
if (count == 0)
return 0;
// Print the contents of all rows with the token from the last query on stdout:
DbRow row(keys_result_set.getNextRow());
const std::string matching_key(row[table_key_name]);
ExecSqlOrDie("SELECT * FROM " + table_name + " WHERE " + table_key_name + "='" + matching_key + "';", connection);
DbResultSet result_set(connection->getLastResultSet());
if (result_set.empty())
return 0;
const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));
const bool has_gnd_code(column_names.find("gnd_code") != column_names.cend());
while (row = result_set.getNextRow())
std::cout << row[table_key_name] << ',' << count << ',' << row["language_code"] << ','
<< EscapeCommasAndBackslashes(row["translation"]) << ',' << category
<< (has_gnd_code ? "," + row["gnd_code"] : "") << '\n';
return result_set.size();
}
unsigned GetMissingVuFindTranslations(DbConnection * const connection, const std::string &language_code) {
return GetMissing(connection, "vufind_translations", "token", "vufind_translations", language_code);
}
unsigned GetMissingKeywordTranslations(DbConnection * const connection, const std::string &language_code) {
return GetMissing(connection, "keyword_translations", "ppn", "keywords", language_code);
}
void InsertIntoVuFindTranslations(DbConnection * const connection, const std::string &token,
const std::string &language_code, const std::string &text)
{
ExecSqlOrDie("INSERT INTO vufind_translations SET token=\"" + token + "\",language_code=\"" + language_code
+ "\",translation=\"" + connection->escapeString(text) + "\";", connection);
}
void InsertIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,
const std::string &gnd_code, const std::string &language_code,
const std::string &text)
{
ExecSqlOrDie("INSERT INTO keyword_translations SET ppn=\"" + ppn + ",gnd_code=\"" + gnd_code
+ "\",language_code=\"" + language_code + "\", gnd_code=\"" + gnd_code + "\",translation=\""
+ connection->escapeString(text) + "\";", connection);
}
const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");
int main(int argc, char *argv[]) {
::progname = argv[0];
try {
if (argc < 2)
Usage();
const IniFile ini_file(CONF_FILE_PATH);
const std::string sql_database(ini_file.getString("", "sql_database"));
const std::string sql_username(ini_file.getString("", "sql_username"));
const std::string sql_password(ini_file.getString("", "sql_password"));
DbConnection db_connection(sql_database, sql_username, sql_password);
if (std::strcmp(argv[1], "get_missing") == 0) {
if (argc != 3)
Error("\"get_missing\" requires exactly one argument: language_code!");
const std::string language_code(argv[2]);
if (not TranslationUtil::IsValidGerman3LetterCode(language_code))
Error("\"" + language_code + "\" is not a valid 3-letter language code!");
if (not GetMissingVuFindTranslations(&db_connection, language_code))
GetMissingKeywordTranslations(&db_connection, language_code);
} else if (std::strcmp(argv[1], "insert") == 0) {
if (argc != 5 and argc != 6)
Error("\"insert\" requires three or four arguments: token or ppn, gnd_code (if ppn), "
"language_code, and text!");
const std::string language_code(argv[(argc == 6) ? 3 : 4]);
if (not TranslationUtil::IsValidGerman3LetterCode(language_code))
Error("\"" + language_code + "\" is not a valid German 3-letter language code!");
if (argc == 5)
InsertIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4]);
else
InsertIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5]);
} else
Error("unknown command \"" + std::string(argv[1]) + "\"!");
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Improved error reporting.<commit_after>/** \file translation_db_tool.cc
* \brief A tool for reading/editing of the "translations" SQL table.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <set>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "IniFile.h"
#include "MiscUtil.h"
#include "SimpleXmlParser.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << " command [args]\n\n";
std::cerr << " Possible commands are:\n";
std::cerr << " get_missing language_code\n";
std::cerr << " insert token language_code text\n";
std::cerr << " insert ppn gnd_code language_code text\n";
std::exit(EXIT_FAILURE);
}
void ExecSqlOrDie(const std::string &select_statement, DbConnection * const connection) {
if (unlikely(not connection->query(select_statement)))
Error("SQL Statement failed: " + select_statement + " (" + connection->getLastErrorMessage() + ")");
}
// Replaces a comma with "\," and a slash with "\\".
std::string EscapeCommasAndBackslashes(const std::string &text) {
std::string escaped_text;
for (const auto ch : text) {
if (unlikely(ch == ',' or ch == '\\'))
escaped_text += '\\';
escaped_text += ch;
}
return escaped_text;
}
unsigned GetMissing(DbConnection * const connection, const std::string &table_name,
const std::string &table_key_name, const std::string &category,
const std::string &language_code)
{
// Find a token/ppn where "language_code" is missing:
ExecSqlOrDie("SELECT distinct " + table_key_name + " FROM " + table_name + " WHERE " + table_key_name +
" NOT IN (SELECT distinct " + table_key_name + " FROM " + table_name +
" WHERE language_code = \"" + language_code + "\") ORDER BY RAND();", connection);
DbResultSet keys_result_set(connection->getLastResultSet());
const size_t count(keys_result_set.size());
if (count == 0)
return 0;
// Print the contents of all rows with the token from the last query on stdout:
DbRow row(keys_result_set.getNextRow());
const std::string matching_key(row[table_key_name]);
ExecSqlOrDie("SELECT * FROM " + table_name + " WHERE " + table_key_name + "='" + matching_key + "';", connection);
DbResultSet result_set(connection->getLastResultSet());
if (result_set.empty())
return 0;
const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));
const bool has_gnd_code(column_names.find("gnd_code") != column_names.cend());
while (row = result_set.getNextRow())
std::cout << row[table_key_name] << ',' << count << ',' << row["language_code"] << ','
<< EscapeCommasAndBackslashes(row["translation"]) << ',' << category
<< (has_gnd_code ? "," + row["gnd_code"] : "") << '\n';
return result_set.size();
}
unsigned GetMissingVuFindTranslations(DbConnection * const connection, const std::string &language_code) {
return GetMissing(connection, "vufind_translations", "token", "vufind_translations", language_code);
}
unsigned GetMissingKeywordTranslations(DbConnection * const connection, const std::string &language_code) {
return GetMissing(connection, "keyword_translations", "ppn", "keywords", language_code);
}
void InsertIntoVuFindTranslations(DbConnection * const connection, const std::string &token,
const std::string &language_code, const std::string &text)
{
ExecSqlOrDie("INSERT INTO vufind_translations SET token=\"" + token + "\",language_code=\"" + language_code
+ "\",translation=\"" + connection->escapeString(text) + "\";", connection);
}
void InsertIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,
const std::string &gnd_code, const std::string &language_code,
const std::string &text)
{
ExecSqlOrDie("INSERT INTO keyword_translations SET ppn=\"" + ppn + ",gnd_code=\"" + gnd_code
+ "\",language_code=\"" + language_code + "\", gnd_code=\"" + gnd_code + "\",translation=\""
+ connection->escapeString(text) + "\";", connection);
}
const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");
int main(int argc, char *argv[]) {
::progname = argv[0];
try {
if (argc < 2)
Usage();
const IniFile ini_file(CONF_FILE_PATH);
const std::string sql_database(ini_file.getString("", "sql_database"));
const std::string sql_username(ini_file.getString("", "sql_username"));
const std::string sql_password(ini_file.getString("", "sql_password"));
DbConnection db_connection(sql_database, sql_username, sql_password);
if (std::strcmp(argv[1], "get_missing") == 0) {
if (argc != 3)
Error("\"get_missing\" requires exactly one argument: language_code!");
const std::string language_code(argv[2]);
if (not TranslationUtil::IsValidGerman3LetterCode(language_code))
Error("\"" + language_code + "\" is not a valid 3-letter language code!");
if (not GetMissingVuFindTranslations(&db_connection, language_code))
GetMissingKeywordTranslations(&db_connection, language_code);
} else if (std::strcmp(argv[1], "insert") == 0) {
if (argc != 5 and argc != 6)
Error("\"insert\" requires three or four arguments: token or ppn, gnd_code (if ppn), "
"language_code, and text!");
const std::string language_code(argv[(argc == 6) ? 3 : 4]);
if (not TranslationUtil::IsValidGerman3LetterCode(language_code))
Error("\"" + language_code + "\" is not a valid German 3-letter language code!");
if (argc == 5)
InsertIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4]);
else
InsertIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5]);
} else
Error("unknown command \"" + std::string(argv[1]) + "\"!");
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()) + " (login is " + MiscUtil::GetUserName() + ")");
}
}
<|endoftext|>
|
<commit_before>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbConnection.h"
#include "DirectoryEntry.h"
#include "ExecUtil.h"
#include "FileLocker.h"
#include "FileUtil.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "PdfUtil.h"
#include "SmartDownloader.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
#include "VuFind.h"
#include "XmlWriter.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname << " file_offset counter marc_input marc_output full_text_db\n\n"
<< " file_offset Where to start reading a MARC data set from in marc_input.\n\n";
std::exit(EXIT_FAILURE);
}
bool GetDocumentAndMediaType(const std::string &url, const unsigned timeout,
std::string * const document, std::string * const media_type)
{
if (not SmartDownload(url, timeout, document)) {
std::cerr << "Failed to download the document for " << url << " (timeout: " << timeout << " sec)\n";
return false;
}
*media_type = MediaTypeUtil::GetMediaType(*document, /* auto_simplify = */ false);
if (media_type->empty())
return false;
return true;
}
static std::map<std::string, std::string> marc_to_tesseract_language_codes_map {
{ "fre", "fra" },
{ "eng", "eng" },
{ "ger", "deu" },
{ "ita", "ita" },
{ "dut", "nld" },
{ "swe", "swe" },
{ "dan", "dan" },
{ "nor", "nor" },
{ "rus", "rus" },
{ "fin", "fin" },
{ "por", "por" },
{ "pol", "pol" },
{ "slv", "slv" },
{ "hun", "hun" },
{ "cze", "ces" },
{ "bul", "bul" },
};
std::string GetTesseractLanguageCode(const MarcUtil::Record &record) {
const auto map_iter(marc_to_tesseract_language_codes_map.find(
record.getLanguageCode()));
return (map_iter == marc_to_tesseract_language_codes_map.cend()) ? "" : map_iter->second;
}
bool GetTextFromImagePDF(const std::string &document, const std::string &media_type, const std::string &original_url,
const MarcUtil::Record &record, const std::string &pdf_images_script, std::string * const extracted_text)
{
extracted_text->clear();
if (not StringUtil::StartsWith(media_type, "application/pdf") or not PdfDocContainsNoText(document))
return false;
std::cerr << "Found a PDF w/ no text.\n";
const FileUtil::AutoTempFile auto_temp_file;
const std::string &input_filename(auto_temp_file.getFilePath());
if (not FileUtil::WriteString(input_filename, document))
Error("failed to write the PDF to a temp file!");
const FileUtil::AutoTempFile auto_temp_file2;
const std::string &output_filename(auto_temp_file2.getFilePath());
const std::string language_code(GetTesseractLanguageCode(record));
static constexpr unsigned TIMEOUT(60); // in seconds
if (ExecUtil::Exec(pdf_images_script, { input_filename, output_filename, language_code }, "", "", "", TIMEOUT)
!= 0)
{
Warning("failed to execute conversion script \"" + pdf_images_script + "\" w/in "
+ std::to_string(TIMEOUT) + " seconds ! (original Url: " + original_url + ")");
return false;
}
std::string plain_text;
if (not ReadFile(output_filename, extracted_text))
Error("failed to read OCR output!");
if (extracted_text->empty())
std::cerr << "Warning: OCR output is empty!\n";
else
std::cerr << "Whoohoo, got OCR'ed text.\n";
return true;
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto _3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension"))
return true;
} else {
const auto z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->second, "Rezension"))
return true;
}
return false;
}
/** Writes "media_type" and "document" to "db" and returns the unique key that was generated for the write. */
std::string FileLockedWriteDocumentWithMediaType(const std::string &media_type, const std::string &document,
const std::string &db_filename)
{
FileLocker file_locker(db_filename, FileLocker::WRITE_ONLY);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER))
Error("Failed to open database \"" + db_filename + "\" for writing ("
+ std::string(db.error().message()) + ")!");
const std::string key(std::to_string(db.count() + 1));
if (not db.add(key, "Content-type: " + media_type + "\r\n\r\n" + document))
Error("Failed to add key/value pair to database \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
return key;
}
bool GetExtractedTextFromDatabase(DbConnection * const db_connection, const std::string &url, const std::string &document,
std::string * const extracted_text)
{
const std::string QUERY("SELECT hash,full_text FROM full_text_cache WHERE url=\"" + url + "\"");
if (not db_connection->query(QUERY))
throw std::runtime_error("Query \"" + QUERY + "\" failed because: " + db_connection->getLastErrorMessage());
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty())
return false;
assert(result_set.size() == 1);
DbRow row(result_set.getNextRow());
const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document)));
if (unlikely(hash != row["hash"]))
return false; // The document must have changed!
*extracted_text = row["full_text"];
// Update the timestap:
const time_t now(std::time(nullptr));
const std::string current_datetime(SqlUtil::TimeTToDatetime(now));
const std::string UPDATE_STMT("UPDATE full_text_cache SET last_used=\"" + current_datetime + "\" WHERE url=\"" + url + "\"");
if (not db_connection->query(UPDATE_STMT))
throw std::runtime_error("Query \"" + UPDATE_STMT + "\" failed because: " + db_connection->getLastErrorMessage());
return true;
}
// Returns true if text has been successfully extrcated, else false.
bool ProcessRecord(File * const input, const std::string &marc_output_filename,
const std::string &pdf_images_script, const std::string &db_filename)
{
MarcUtil::Record record = MarcUtil::Record::XmlFactory(input);
ssize_t _856_index(record.getFieldIndex("856"));
if (_856_index == -1)
Error("no 856 tag found!");
constexpr unsigned PER_DOC_TIMEOUT(20);
bool succeeded(false);
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size()));
for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) {
Subfields subfields(fields[_856_index]);
const auto u_begin_end(subfields.getIterators('u'));
if (u_begin_end.first == u_begin_end.second) // No subfield 'u'.
continue;
if (IsProbablyAReview(subfields))
continue;
std::string document, media_type;
const std::string url(u_begin_end.first->second);
if (not GetDocumentAndMediaType(url, PER_DOC_TIMEOUT, &document, &media_type))
continue;
std::string mysql_url;
VuFind::GetMysqlURL(&mysql_url);
DbConnection db_connection(mysql_url);
std::string extracted_text, key;
if (GetExtractedTextFromDatabase(&db_connection, url, document, &extracted_text))
key = FileLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename);
else if (GetTextFromImagePDF(document, media_type, url, record, pdf_images_script, &extracted_text)) {
key = FileLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename);
const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document)));
const time_t now(std::time(nullptr));
const std::string current_datetime(SqlUtil::TimeTToDatetime(now));
const std::string INSERT_STMT("REPLACE INTO full_text_cache SET url=\"" + url + "\", hash=\"" + hash
+ "\", full_text=\"" + SqlUtil::EscapeBlob(&extracted_text)
+ "\", last_used=\"" + current_datetime + "\"");
if (not db_connection.query(INSERT_STMT))
throw std::runtime_error("Query \"" + INSERT_STMT + "\" failed because: " + db_connection.getLastErrorMessage());
} else
key = FileLockedWriteDocumentWithMediaType(media_type, document, db_filename);
subfields.addSubfield('e', "http://localhost/cgi-bin/full_text_lookup?id=" + key);
const std::string new_856_field(subfields.toString());
record.updateField(_856_index, new_856_field);
succeeded = true;
}
// Safely append the modified MARC data to the MARC output file:
FileLocker file_locker(marc_output_filename, FileLocker::WRITE_ONLY);
File marc_output(marc_output_filename, "ab");
if (not marc_output)
Error("can't open \"" + marc_output_filename + "\" for appending!");
XmlWriter xml_writer(&marc_output);
record.write(&xml_writer);
return succeeded;
}
const std::string BASH_HELPER("pdf_images_to_text.sh");
std::string GetPathToPdfImagesScript(const char * const argv0) {
#pragma GCC diagnostic ignored "-Wvla"
char path[std::strlen(argv0) + 1];
#pragma GCC diagnostic warning "-Wvla"
std::strcpy(path, argv0);
const std::string pdf_images_script_path(ExecUtil::Which(BASH_HELPER));
if (::access(pdf_images_script_path.c_str(), X_OK) != 0)
Error("can't execute \"" + pdf_images_script_path + "\"!");
return pdf_images_script_path;
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 5)
Usage();
long offset;
if (not StringUtil::ToNumber(argv[1], &offset))
Error("file offset must be a number!");
const std::string marc_input_filename(argv[2]);
File marc_input(marc_input_filename, "rm");
if (not marc_input)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(argv[3]);
if (not marc_input.seek(offset, SEEK_SET))
Error("failed to position " + marc_input_filename + " at offset " + std::to_string(offset)
+ "! (" + std::to_string(errno) + ")");
try {
return ProcessRecord(&marc_input, marc_output_filename, GetPathToPdfImagesScript(argv[0]), argv[4])
? EXIT_SUCCESS : EXIT_FAILURE;
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<commit_msg>Better error output when we catch an exception.<commit_after>/** \brief Utility for augmenting MARC records with links to a local full-text database.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <kchashdb.h>
#include "Compiler.h"
#include "DbConnection.h"
#include "DirectoryEntry.h"
#include "ExecUtil.h"
#include "FileLocker.h"
#include "FileUtil.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "PdfUtil.h"
#include "SmartDownloader.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
#include "VuFind.h"
#include "XmlWriter.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname << " file_offset counter marc_input marc_output full_text_db\n\n"
<< " file_offset Where to start reading a MARC data set from in marc_input.\n\n";
std::exit(EXIT_FAILURE);
}
bool GetDocumentAndMediaType(const std::string &url, const unsigned timeout,
std::string * const document, std::string * const media_type)
{
if (not SmartDownload(url, timeout, document)) {
std::cerr << "Failed to download the document for " << url << " (timeout: " << timeout << " sec)\n";
return false;
}
*media_type = MediaTypeUtil::GetMediaType(*document, /* auto_simplify = */ false);
if (media_type->empty())
return false;
return true;
}
static std::map<std::string, std::string> marc_to_tesseract_language_codes_map {
{ "fre", "fra" },
{ "eng", "eng" },
{ "ger", "deu" },
{ "ita", "ita" },
{ "dut", "nld" },
{ "swe", "swe" },
{ "dan", "dan" },
{ "nor", "nor" },
{ "rus", "rus" },
{ "fin", "fin" },
{ "por", "por" },
{ "pol", "pol" },
{ "slv", "slv" },
{ "hun", "hun" },
{ "cze", "ces" },
{ "bul", "bul" },
};
std::string GetTesseractLanguageCode(const MarcUtil::Record &record) {
const auto map_iter(marc_to_tesseract_language_codes_map.find(
record.getLanguageCode()));
return (map_iter == marc_to_tesseract_language_codes_map.cend()) ? "" : map_iter->second;
}
bool GetTextFromImagePDF(const std::string &document, const std::string &media_type, const std::string &original_url,
const MarcUtil::Record &record, const std::string &pdf_images_script, std::string * const extracted_text)
{
extracted_text->clear();
if (not StringUtil::StartsWith(media_type, "application/pdf") or not PdfDocContainsNoText(document))
return false;
std::cerr << "Found a PDF w/ no text.\n";
const FileUtil::AutoTempFile auto_temp_file;
const std::string &input_filename(auto_temp_file.getFilePath());
if (not FileUtil::WriteString(input_filename, document))
Error("failed to write the PDF to a temp file!");
const FileUtil::AutoTempFile auto_temp_file2;
const std::string &output_filename(auto_temp_file2.getFilePath());
const std::string language_code(GetTesseractLanguageCode(record));
static constexpr unsigned TIMEOUT(60); // in seconds
if (ExecUtil::Exec(pdf_images_script, { input_filename, output_filename, language_code }, "", "", "", TIMEOUT)
!= 0)
{
Warning("failed to execute conversion script \"" + pdf_images_script + "\" w/in "
+ std::to_string(TIMEOUT) + " seconds ! (original Url: " + original_url + ")");
return false;
}
std::string plain_text;
if (not ReadFile(output_filename, extracted_text))
Error("failed to read OCR output!");
if (extracted_text->empty())
std::cerr << "Warning: OCR output is empty!\n";
else
std::cerr << "Whoohoo, got OCR'ed text.\n";
return true;
}
// Checks subfields "3" and "z" to see if they start w/ "Rezension".
bool IsProbablyAReview(const Subfields &subfields) {
const auto _3_begin_end(subfields.getIterators('3'));
if (_3_begin_end.first != _3_begin_end.second) {
if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension"))
return true;
} else {
const auto z_begin_end(subfields.getIterators('z'));
if (z_begin_end.first != z_begin_end.second
and StringUtil::StartsWith(z_begin_end.first->second, "Rezension"))
return true;
}
return false;
}
/** Writes "media_type" and "document" to "db" and returns the unique key that was generated for the write. */
std::string DbLockedWriteDocumentWithMediaType(const std::string &media_type, const std::string &document,
const std::string &db_filename)
{
FileLocker file_locker(db_filename, FileLocker::WRITE_ONLY);
kyotocabinet::HashDB db;
if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER))
Error("Failed to open database \"" + db_filename + "\" for writing ("
+ std::string(db.error().message()) + ")!");
const std::string key(std::to_string(db.count() + 1));
if (not db.add(key, "Content-type: " + media_type + "\r\n\r\n" + document))
Error("Failed to add key/value pair to database \"" + db_filename + "\" ("
+ std::string(db.error().message()) + ")!");
return key;
}
bool GetExtractedTextFromDatabase(DbConnection * const db_connection, const std::string &url, const std::string &document,
std::string * const extracted_text)
{
const std::string QUERY("SELECT hash,full_text FROM full_text_cache WHERE url=\"" + url + "\"");
if (not db_connection->query(QUERY))
throw std::runtime_error("Query \"" + QUERY + "\" failed because: " + db_connection->getLastErrorMessage());
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty())
return false;
assert(result_set.size() == 1);
DbRow row(result_set.getNextRow());
const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document)));
if (unlikely(hash != row["hash"]))
return false; // The document must have changed!
*extracted_text = row["full_text"];
// Update the timestap:
const time_t now(std::time(nullptr));
const std::string current_datetime(SqlUtil::TimeTToDatetime(now));
const std::string UPDATE_STMT("UPDATE full_text_cache SET last_used=\"" + current_datetime + "\" WHERE url=\"" + url + "\"");
if (not db_connection->query(UPDATE_STMT))
throw std::runtime_error("Query \"" + UPDATE_STMT + "\" failed because: " + db_connection->getLastErrorMessage());
return true;
}
// Returns true if text has been successfully extrcated, else false.
bool ProcessRecord(File * const input, const std::string &marc_output_filename,
const std::string &pdf_images_script, const std::string &db_filename)
{
MarcUtil::Record record = MarcUtil::Record::XmlFactory(input);
ssize_t _856_index(record.getFieldIndex("856"));
if (_856_index == -1)
Error("no 856 tag found!");
constexpr unsigned PER_DOC_TIMEOUT(20);
bool succeeded(false);
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size()));
for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) {
Subfields subfields(fields[_856_index]);
const auto u_begin_end(subfields.getIterators('u'));
if (u_begin_end.first == u_begin_end.second) // No subfield 'u'.
continue;
if (IsProbablyAReview(subfields))
continue;
std::string document, media_type;
const std::string url(u_begin_end.first->second);
if (not GetDocumentAndMediaType(url, PER_DOC_TIMEOUT, &document, &media_type))
continue;
std::string mysql_url;
VuFind::GetMysqlURL(&mysql_url);
DbConnection db_connection(mysql_url);
std::string extracted_text, key;
if (GetExtractedTextFromDatabase(&db_connection, url, document, &extracted_text))
key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename);
else if (GetTextFromImagePDF(document, media_type, url, record, pdf_images_script, &extracted_text)) {
key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename);
const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document)));
const time_t now(std::time(nullptr));
const std::string current_datetime(SqlUtil::TimeTToDatetime(now));
const std::string INSERT_STMT("REPLACE INTO full_text_cache SET url=\"" + url + "\", hash=\"" + hash
+ "\", full_text=\"" + SqlUtil::EscapeBlob(&extracted_text)
+ "\", last_used=\"" + current_datetime + "\"");
if (not db_connection.query(INSERT_STMT))
throw std::runtime_error("Query \"" + INSERT_STMT + "\" failed because: " + db_connection.getLastErrorMessage());
} else
key = DbLockedWriteDocumentWithMediaType(media_type, document, db_filename);
subfields.addSubfield('e', "http://localhost/cgi-bin/full_text_lookup?id=" + key);
const std::string new_856_field(subfields.toString());
record.updateField(_856_index, new_856_field);
succeeded = true;
}
// Safely append the modified MARC data to the MARC output file:
FileLocker file_locker(marc_output_filename, FileLocker::WRITE_ONLY);
File marc_output(marc_output_filename, "ab");
if (not marc_output)
Error("can't open \"" + marc_output_filename + "\" for appending!");
XmlWriter xml_writer(&marc_output);
record.write(&xml_writer);
return succeeded;
}
const std::string BASH_HELPER("pdf_images_to_text.sh");
std::string GetPathToPdfImagesScript(const char * const argv0) {
#pragma GCC diagnostic ignored "-Wvla"
char path[std::strlen(argv0) + 1];
#pragma GCC diagnostic warning "-Wvla"
std::strcpy(path, argv0);
const std::string pdf_images_script_path(ExecUtil::Which(BASH_HELPER));
if (::access(pdf_images_script_path.c_str(), X_OK) != 0)
Error("can't execute \"" + pdf_images_script_path + "\"!");
return pdf_images_script_path;
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 5)
Usage();
long offset;
if (not StringUtil::ToNumber(argv[1], &offset))
Error("file offset must be a number!");
const std::string marc_input_filename(argv[2]);
File marc_input(marc_input_filename, "rm");
if (not marc_input)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(argv[3]);
if (not marc_input.seek(offset, SEEK_SET))
Error("failed to position " + marc_input_filename + " at offset " + std::to_string(offset)
+ "! (" + std::to_string(errno) + ")");
try {
return ProcessRecord(&marc_input, marc_output_filename, GetPathToPdfImagesScript(argv[0]), argv[4])
? EXIT_SUCCESS : EXIT_FAILURE;
} catch (const std::exception &e) {
Error("While reading \"" + marc_input_filename + "\" starting at offset \"" + std::string(argv[1])
+ "\", caught exception: " + std::string(e.what()));
}
}
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/core/particle.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2017, Yan Zhou
// 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 MCKL_CORE_PARTICLE_HPP
#define MCKL_CORE_PARTICLE_HPP
#include <mckl/internal/common.hpp>
#include <mckl/core/iterator.hpp>
#include <mckl/core/weight.hpp>
#include <mckl/random/rng_set.hpp>
#include <mckl/random/seed.hpp>
namespace mckl
{
template <typename>
class Particle;
/// \brief A thin wrapper over a complete Particle
/// \ingroup Core
template <typename T>
class ParticleIndexBase
{
public:
ParticleIndexBase() : pptr_(nullptr), i_(0) {}
ParticleIndexBase(typename Particle<T>::size_type i, Particle<T> *pptr)
: pptr_(pptr), i_(i)
{
}
Particle<T> &particle() const { return *pptr_; }
Particle<T> *particle_ptr() const { return pptr_; }
T &state() const { return pptr_->state(); }
typename Particle<T>::size_type i() const { return i_; }
typename Particle<T>::rng_type &rng() const { return pptr_->rng(i_); }
private:
Particle<T> *pptr_;
typename Particle<T>::size_type i_;
}; // class ParticleIndexBase
/// \brief ParticleIndex base class trait
/// \ingroup Traits
MCKL_DEFINE_TYPE_TEMPLATE_DISPATCH_TRAIT(
ParticleIndexBaseType, particle_index_type, ParticleIndexBase)
/// \brief A thin wrapper over a complete Particle
/// \ingroup Core
///
/// \details
/// This class also serves as an random access iterator
template <typename T>
class ParticleIndex final : public ParticleIndexBaseType<T>
{
public:
using difference_type =
std::make_signed_t<typename Particle<T>::size_type>;
using value_type = ParticleIndex;
using pointer = const ParticleIndex *;
using reference = const ParticleIndex &;
using iterator_category = std::random_access_iterator_tag;
ParticleIndex() = default;
ParticleIndex(typename Particle<T>::size_type i, Particle<T> *pptr)
: ParticleIndexBaseType<T>(i, pptr)
{
}
/// \brief Dereference operator returns a reference to the index itself
reference operator*() const noexcept { return *this; }
/// \brief Member selection operator returns a pointer the index itself
pointer operator->() const noexcept { return this; }
/// \brief Subscript operator return a new index
template <typename IntType>
ParticleIndex operator[](IntType n)
{
return ParticleIndex(static_cast<typename Particle<T>::size_type>(
static_cast<difference_type>(this->i()) +
static_cast<difference_type>(n)),
this->particle_ptr());
}
friend bool operator==(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() == idx2.i();
}
friend bool operator!=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() != idx2.i();
}
friend bool operator<(const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() < idx2.i();
}
friend bool operator>(const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() > idx2.i();
}
friend bool operator<=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() <= idx2.i();
}
friend bool operator>=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() >= idx2.i();
}
friend ParticleIndex &operator++(ParticleIndex &idx)
{
return idx = ParticleIndex(idx.i() + 1, idx.particle_ptr());
}
friend ParticleIndex operator++(ParticleIndex &idx, int)
{
ParticleIndex ret(idx);
++idx;
return ret;
}
friend ParticleIndex &operator--(ParticleIndex &idx)
{
return idx = ParticleIndex(idx.i() - 1, idx.particle_ptr());
}
friend ParticleIndex operator--(ParticleIndex &idx, int)
{
ParticleIndex ret(idx);
--idx;
return ret;
}
template <typename IntType>
friend ParticleIndex operator+(const ParticleIndex &idx, IntType n)
{
return ParticleIndex(static_cast<typename Particle<T>::size_type>(
static_cast<difference_type>(idx.i()) +
static_cast<difference_type>(n)),
idx.particle_ptr());
}
template <typename IntType>
friend ParticleIndex operator+(IntType n, const ParticleIndex &idx)
{
return idx + n;
}
template <typename IntType>
friend ParticleIndex operator-(const ParticleIndex &idx, IntType n)
{
return idx + (-static_cast<difference_type>(n));
}
template <typename IntType>
friend ParticleIndex &operator+=(ParticleIndex &idx, IntType n)
{
return idx = idx + n;
}
template <typename IntType>
friend ParticleIndex &operator-=(ParticleIndex &idx, IntType n)
{
return idx = idx - n;
}
friend difference_type operator-(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Substract two ParticleIndex objects from two different "
"particle systems");
return static_cast<difference_type>(idx1.i()) -
static_cast<difference_type>(idx2.i());
}
}; // class ParticleIndex
/// \brief Range of ParticleIndex
/// \ingroup Core
template <typename T>
class ParticleRange : public Range<ParticleIndex<T>>
{
public:
using Range<ParticleIndex<T>>::Range;
Particle<T> &particle() const { return this->begin()->particle(); }
Particle<T> *particle_ptr() const { return this->begin()->particle_ptr(); }
typename Particle<T>::size_type ibegin() const
{
return this->begin()->i();
}
typename Particle<T>::size_type iend() const { return this->end()->i(); }
}; // class ParticleRange
/// \brief Particle system
/// \ingroup Core
///
/// \tparam T The sample collection type
///
/// \details
/// A collection of particles is formed by,
/// * The collection of samples
/// * The weights of samples
/// * A collection of RNG engines for parallel use
template <typename T>
class Particle
{
public:
using size_type = SizeType<T>;
using state_type = T;
using weight_type = WeightType<T>;
using rng_set_type = RNGSetType<T>;
using rng_type = typename rng_set_type::rng_type;
/// \brief Default constructor
Particle()
: state_(0)
, weight_(0)
, rng_set_(0)
, rng_(Seed<rng_type>::instance().get())
{
}
/// \brief Construct a particle system
///
/// \details
/// All arguments are passed down to the constructor of `T`
template <typename... Args>
explicit Particle(size_type N, Args &&... args)
: state_(N, std::forward<Args>(args)...)
, weight_(static_cast<SizeType<weight_type>>(N))
, rng_set_(static_cast<SizeType<rng_set_type>>(N))
, rng_(Seed<rng_type>::instance().get())
{
}
/// \brief Clone the Particle except the RNG engines
Particle clone() const
{
Particle particle(*this);
particle.rng_set_.reset();
particle.rng_.seed(Seed<rng_type>::instance().get());
return particle;
}
/// \brief The number of particles
size_type size() const { return state_.size(); }
/// \brief Resize by selecting according to user supplied index vector
///
/// \param n The new sample size
/// \param index N-vector of parent indices
template <typename InputIter>
void select(size_type n, InputIter index)
{
state_.select(n, index);
weight_.resize(static_cast<SizeType<weight_type>>(n));
weight_.set_equal();
rng_set_.resize(static_cast<SizeType<rng_set_type>>(n));
}
/// \brief Read and write access to the state collection object
state_type &state() { return state_; }
/// \brief Read only access to the state collection object
const state_type &state() const { return state_; }
/// \brief Read and write access to the weight collection object
weight_type &weight() { return weight_; }
/// \brief Read only access to the weight collection object
const weight_type &weight() const { return weight_; }
/// \brief Read and write access to the RNG collection object
rng_set_type &rng_set() { return rng_set_; }
/// \brief Read only access to the RNG collection object
const rng_set_type &rng_set() const { return rng_set_; }
/// \brief Get an (parallel) RNG stream for a given particle
rng_type &rng(size_type i)
{
return rng_set_[static_cast<std::size_t>(i)];
}
/// \brief Get an (parallel) RNG stream for a given particle
const rng_type &rng(size_type i) const
{
return rng_set_[static_cast<std::size_t>(i)];
}
/// \brief Get the (sequential) RNG used stream for resampling
rng_type &rng() { return rng_; }
/// \brief Get the (sequential) RNG used stream for resampling
const rng_type &rng() const { return rng_; }
/// \brief Get a ParticleIndex<T> object for the i-th particle
ParticleIndex<T> at(size_type i)
{
runtime_assert<std::out_of_range>(
i <= size(), "**Particle::at** index out of range");
return operator[](i);
}
/// \brief Get a ParticleIndex<T> object for the i-th particle
ParticleIndex<T> operator[](size_type i)
{
return ParticleIndex<T>(i, this);
}
/// \brief Get a ParticleIndex<T> object for the first particle
ParticleIndex<T> begin() { return operator[](0); }
/// \brief Get a ParticleIndex<T> object for one pass the last particle
ParticleIndex<T> end() { return operator[](size()); }
/// \brief Get a Range<ParticleItrator<T>> object of all particles
ParticleRange<T> range(size_type grainsize = 1)
{
return ParticleRange<T>(begin(), end(), grainsize);
}
/// \brief Get a ParticleRange<T> object given a range denoted by integral
/// values
ParticleRange<T> range(
size_type ibegin, size_type iend, size_type grainsize = 1)
{
return ParticleRange<T>(operator[](ibegin), operator[](iend),
grainsize);
}
private:
state_type state_;
weight_type weight_;
rng_set_type rng_set_;
rng_type rng_;
}; // class Particle
} // namespace mckl
#endif // MCKL_CORE_PARTICLE_HPP
<commit_msg>defualt particle constructor use default constructor of T<commit_after>//============================================================================
// MCKL/include/mckl/core/particle.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2017, Yan Zhou
// 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 MCKL_CORE_PARTICLE_HPP
#define MCKL_CORE_PARTICLE_HPP
#include <mckl/internal/common.hpp>
#include <mckl/core/iterator.hpp>
#include <mckl/core/weight.hpp>
#include <mckl/random/rng_set.hpp>
#include <mckl/random/seed.hpp>
namespace mckl
{
template <typename>
class Particle;
/// \brief A thin wrapper over a complete Particle
/// \ingroup Core
template <typename T>
class ParticleIndexBase
{
public:
ParticleIndexBase() : pptr_(nullptr), i_(0) {}
ParticleIndexBase(typename Particle<T>::size_type i, Particle<T> *pptr)
: pptr_(pptr), i_(i)
{
}
Particle<T> &particle() const { return *pptr_; }
Particle<T> *particle_ptr() const { return pptr_; }
T &state() const { return pptr_->state(); }
typename Particle<T>::size_type i() const { return i_; }
typename Particle<T>::rng_type &rng() const { return pptr_->rng(i_); }
private:
Particle<T> *pptr_;
typename Particle<T>::size_type i_;
}; // class ParticleIndexBase
/// \brief ParticleIndex base class trait
/// \ingroup Traits
MCKL_DEFINE_TYPE_TEMPLATE_DISPATCH_TRAIT(
ParticleIndexBaseType, particle_index_type, ParticleIndexBase)
/// \brief A thin wrapper over a complete Particle
/// \ingroup Core
///
/// \details
/// This class also serves as an random access iterator
template <typename T>
class ParticleIndex final : public ParticleIndexBaseType<T>
{
public:
using difference_type =
std::make_signed_t<typename Particle<T>::size_type>;
using value_type = ParticleIndex;
using pointer = const ParticleIndex *;
using reference = const ParticleIndex &;
using iterator_category = std::random_access_iterator_tag;
ParticleIndex() = default;
ParticleIndex(typename Particle<T>::size_type i, Particle<T> *pptr)
: ParticleIndexBaseType<T>(i, pptr)
{
}
/// \brief Dereference operator returns a reference to the index itself
reference operator*() const noexcept { return *this; }
/// \brief Member selection operator returns a pointer the index itself
pointer operator->() const noexcept { return this; }
/// \brief Subscript operator return a new index
template <typename IntType>
ParticleIndex operator[](IntType n)
{
return ParticleIndex(static_cast<typename Particle<T>::size_type>(
static_cast<difference_type>(this->i()) +
static_cast<difference_type>(n)),
this->particle_ptr());
}
friend bool operator==(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() == idx2.i();
}
friend bool operator!=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() != idx2.i();
}
friend bool operator<(const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() < idx2.i();
}
friend bool operator>(const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() > idx2.i();
}
friend bool operator<=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() <= idx2.i();
}
friend bool operator>=(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Compare two ParticleIndex objects from two different particle "
"systems");
return idx1.i() >= idx2.i();
}
friend ParticleIndex &operator++(ParticleIndex &idx)
{
return idx = ParticleIndex(idx.i() + 1, idx.particle_ptr());
}
friend ParticleIndex operator++(ParticleIndex &idx, int)
{
ParticleIndex ret(idx);
++idx;
return ret;
}
friend ParticleIndex &operator--(ParticleIndex &idx)
{
return idx = ParticleIndex(idx.i() - 1, idx.particle_ptr());
}
friend ParticleIndex operator--(ParticleIndex &idx, int)
{
ParticleIndex ret(idx);
--idx;
return ret;
}
template <typename IntType>
friend ParticleIndex operator+(const ParticleIndex &idx, IntType n)
{
return ParticleIndex(static_cast<typename Particle<T>::size_type>(
static_cast<difference_type>(idx.i()) +
static_cast<difference_type>(n)),
idx.particle_ptr());
}
template <typename IntType>
friend ParticleIndex operator+(IntType n, const ParticleIndex &idx)
{
return idx + n;
}
template <typename IntType>
friend ParticleIndex operator-(const ParticleIndex &idx, IntType n)
{
return idx + (-static_cast<difference_type>(n));
}
template <typename IntType>
friend ParticleIndex &operator+=(ParticleIndex &idx, IntType n)
{
return idx = idx + n;
}
template <typename IntType>
friend ParticleIndex &operator-=(ParticleIndex &idx, IntType n)
{
return idx = idx - n;
}
friend difference_type operator-(
const ParticleIndex &idx1, const ParticleIndex &idx2)
{
runtime_assert(idx1.particle_ptr() == idx2.particle_ptr(),
"Substract two ParticleIndex objects from two different "
"particle systems");
return static_cast<difference_type>(idx1.i()) -
static_cast<difference_type>(idx2.i());
}
}; // class ParticleIndex
/// \brief Range of ParticleIndex
/// \ingroup Core
template <typename T>
class ParticleRange : public Range<ParticleIndex<T>>
{
public:
using Range<ParticleIndex<T>>::Range;
Particle<T> &particle() const { return this->begin()->particle(); }
Particle<T> *particle_ptr() const { return this->begin()->particle_ptr(); }
typename Particle<T>::size_type ibegin() const
{
return this->begin()->i();
}
typename Particle<T>::size_type iend() const { return this->end()->i(); }
}; // class ParticleRange
/// \brief Particle system
/// \ingroup Core
///
/// \tparam T The sample collection type
///
/// \details
/// A collection of particles is formed by,
/// * The collection of samples
/// * The weights of samples
/// * A collection of RNG engines for parallel use
template <typename T>
class Particle
{
public:
using size_type = SizeType<T>;
using state_type = T;
using weight_type = WeightType<T>;
using rng_set_type = RNGSetType<T>;
using rng_type = typename rng_set_type::rng_type;
/// \brief Default constructor
Particle()
: weight_(0), rng_set_(0), rng_(Seed<rng_type>::instance().get())
{
}
/// \brief Construct a particle system
///
/// \details
/// All arguments are passed down to the constructor of `T`
template <typename... Args>
explicit Particle(size_type N, Args &&... args)
: state_(N, std::forward<Args>(args)...)
, weight_(static_cast<SizeType<weight_type>>(N))
, rng_set_(static_cast<SizeType<rng_set_type>>(N))
, rng_(Seed<rng_type>::instance().get())
{
}
/// \brief Clone the Particle except the RNG engines
Particle clone() const
{
Particle particle(*this);
particle.rng_set_.reset();
particle.rng_.seed(Seed<rng_type>::instance().get());
return particle;
}
/// \brief The number of particles
size_type size() const { return state_.size(); }
/// \brief Resize by selecting according to user supplied index vector
///
/// \param n The new sample size
/// \param index N-vector of parent indices
template <typename InputIter>
void select(size_type n, InputIter index)
{
state_.select(n, index);
weight_.resize(static_cast<SizeType<weight_type>>(n));
weight_.set_equal();
rng_set_.resize(static_cast<SizeType<rng_set_type>>(n));
}
/// \brief Read and write access to the state collection object
state_type &state() { return state_; }
/// \brief Read only access to the state collection object
const state_type &state() const { return state_; }
/// \brief Read and write access to the weight collection object
weight_type &weight() { return weight_; }
/// \brief Read only access to the weight collection object
const weight_type &weight() const { return weight_; }
/// \brief Read and write access to the RNG collection object
rng_set_type &rng_set() { return rng_set_; }
/// \brief Read only access to the RNG collection object
const rng_set_type &rng_set() const { return rng_set_; }
/// \brief Get an (parallel) RNG stream for a given particle
rng_type &rng(size_type i)
{
return rng_set_[static_cast<std::size_t>(i)];
}
/// \brief Get an (parallel) RNG stream for a given particle
const rng_type &rng(size_type i) const
{
return rng_set_[static_cast<std::size_t>(i)];
}
/// \brief Get the (sequential) RNG used stream for resampling
rng_type &rng() { return rng_; }
/// \brief Get the (sequential) RNG used stream for resampling
const rng_type &rng() const { return rng_; }
/// \brief Get a ParticleIndex<T> object for the i-th particle
ParticleIndex<T> at(size_type i)
{
runtime_assert<std::out_of_range>(
i <= size(), "**Particle::at** index out of range");
return operator[](i);
}
/// \brief Get a ParticleIndex<T> object for the i-th particle
ParticleIndex<T> operator[](size_type i)
{
return ParticleIndex<T>(i, this);
}
/// \brief Get a ParticleIndex<T> object for the first particle
ParticleIndex<T> begin() { return operator[](0); }
/// \brief Get a ParticleIndex<T> object for one pass the last particle
ParticleIndex<T> end() { return operator[](size()); }
/// \brief Get a Range<ParticleItrator<T>> object of all particles
ParticleRange<T> range(size_type grainsize = 1)
{
return ParticleRange<T>(begin(), end(), grainsize);
}
/// \brief Get a ParticleRange<T> object given a range denoted by integral
/// values
ParticleRange<T> range(
size_type ibegin, size_type iend, size_type grainsize = 1)
{
return ParticleRange<T>(operator[](ibegin), operator[](iend),
grainsize);
}
private:
state_type state_;
weight_type weight_;
rng_set_type rng_set_;
rng_type rng_;
}; // class Particle
} // namespace mckl
#endif // MCKL_CORE_PARTICLE_HPP
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#include "device/gpu/gpudefs.hpp"
#include "device/gpu/gpuprogram.hpp"
#include "device/gpu/gpukernel.hpp"
#include "acl.h"
#include "SCShadersSi.h"
#include "si_ci_vi_merged_offset.h"
#include "si_ci_vi_merged_registers.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <ctime>
namespace gpu {
bool
NullKernel::siCreateHwInfo(const void* shader, AMUabiAddEncoding& encoding)
{
static const uint NumSiCsInfos = (70 + 5 + 1 + 32 + 6);
CALProgramInfoEntry* newInfos;
uint i = 0;
uint infoCount = NumSiCsInfos;
const SC_SI_HWSHADER_CS* cShader = reinterpret_cast<const SC_SI_HWSHADER_CS*>(shader);
newInfos = new CALProgramInfoEntry[infoCount];
encoding.progInfos = newInfos;
if (encoding.progInfos == 0) {
infoCount = 0;
return false;
}
newInfos[i].address = AMU_ABI_USER_ELEMENT_COUNT;
newInfos[i].value = cShader->common.userElementCount;
i++;
for (unsigned int j = 0; j < cShader->common.userElementCount; j++) {
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD0 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].dataClass;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD1 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].apiSlot;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD2 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].startUserReg;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD3 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].userRegCount;
i++;
}
newInfos[i].address = AMU_ABI_SI_NUM_VGPRS;
newInfos[i].value = cShader->common.numVgprs;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_SGPRS;
newInfos[i].value = cShader->common.numSgprs;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_SGPRS_AVAIL;
newInfos[i].value = SI_sgprs_avail; //512;//options.NumSGPRsAvailable;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_VGPRS_AVAIL;
newInfos[i].value = SI_vgprs_avail;//options.NumVGPRsAvailable;
i++;
newInfos[i].address = AMU_ABI_SI_FLOAT_MODE;
newInfos[i].value = cShader->common.floatMode;
i++;
newInfos[i].address = AMU_ABI_SI_IEEE_MODE;
newInfos[i].value = cShader->common.bIeeeMode;
i++;
newInfos[i].address = AMU_ABI_SI_SCRATCH_SIZE;
newInfos[i].value = cShader->common.scratchSize;;
i++;
newInfos[i].address = mmCOMPUTE_PGM_RSRC2;
newInfos[i].value = cShader->computePgmRsrc2.u32All;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_X;
newInfos[i].value = cShader->numThreadX;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Y;
newInfos[i].value = cShader->numThreadY;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Z;
newInfos[i].value = cShader->numThreadZ;
i++;
newInfos[i].address = AMU_ABI_ORDERED_APPEND_ENABLE;
newInfos[i].value = cShader->bOrderedAppendEnable;
i++;
newInfos[i].address = AMU_ABI_RAT_OP_IS_USED;
newInfos[i].value = cShader->common.uavResourceUsage[0];
i++;
for (unsigned int j = 0; j < ((SC_MAX_UAV + 31) / 32); j++) {
newInfos[i].address = AMU_ABI_UAV_RESOURCE_MASK_0 + j;
newInfos[i].value = cShader->common.uavResourceUsage[j];
i++;
}
newInfos[i].address = AMU_ABI_NUM_WAVEFRONT_PER_SIMD; // Setting the same as for scWrapR800Info
newInfos[i].value = 1;
i++;
newInfos[i].address = AMU_ABI_WAVEFRONT_SIZE;
newInfos[i].value = nullDev().hwInfo()->simdWidth_ * 4; //options.WavefrontSize;
i++;
newInfos[i].address = AMU_ABI_LDS_SIZE_AVAIL;
newInfos[i].value = SI_ldssize_avail; //options.LDSSize;
i++;
COMPUTE_PGM_RSRC2 computePgmRsrc2;
computePgmRsrc2.u32All = cShader->computePgmRsrc2.u32All;
newInfos[i].address = AMU_ABI_LDS_SIZE_USED;
newInfos[i].value = 64 * 4 * computePgmRsrc2.bits.LDS_SIZE;
i++;
infoCount = i;
assert((i + 4 * (16 - cShader->common.userElementCount)) == NumSiCsInfos);
encoding.progInfosCount = infoCount;
CALUavMask uavMask;
memcpy(uavMask.mask, cShader->common.uavResourceUsage, sizeof(CALUavMask));
encoding.uavMask = uavMask;
encoding.textData = HWSHADER_Get(cShader, common.hShaderMemHandle);
encoding.textSize = cShader->common.codeLenInByte;
instructionCnt_ = encoding.textSize / sizeof(uint32_t);
encoding.scratchRegisterCount = cShader->common.scratchSize;
encoding.UAVReturnBufferTotalSize = 0;
return true;
}
bool
HSAILKernel::aqlCreateHWInfo(const void* shader, size_t shaderSize)
{
// Copy the shader_isa into a buffer
hwMetaData_ = new char[shaderSize];
if (hwMetaData_ == NULL) {
return false;
}
memcpy(hwMetaData_, shader, shaderSize);
SC_SI_HWSHADER_CS* siMetaData = reinterpret_cast<SC_SI_HWSHADER_CS*>(hwMetaData_);
// Code to patch the pointers in the shader object.
// Must be preferably done in the compiler library
size_t offset = siMetaData->common.uSizeInBytes;
if (siMetaData->common.u32PvtDataSizeInBytes > 0) {
siMetaData->common.pPvtData =
reinterpret_cast<SC_BYTE *>(
reinterpret_cast<char *>(siMetaData) + offset);
offset += siMetaData->common.u32PvtDataSizeInBytes;
}
if (siMetaData->common.codeLenInByte > 0) {
siMetaData->common.hShaderMemHandle =
reinterpret_cast<char *>(siMetaData) + offset;
offset += siMetaData->common.codeLenInByte;
}
char* headerBaseAddress =
reinterpret_cast<char*>(siMetaData->common.hShaderMemHandle);
hsa_ext_code_descriptor_t* hcd =
reinterpret_cast<hsa_ext_code_descriptor_t*>(headerBaseAddress);
amd_kernel_code_t* akc = reinterpret_cast<amd_kernel_code_t*>(
headerBaseAddress + hcd->code.handle);
address codeStartAddress = reinterpret_cast<address>(akc);
address codeEndAddress = reinterpret_cast<address>(hcd) + siMetaData->common.codeLenInByte;
codeSize_ = codeEndAddress - codeStartAddress;
code_ = new gpu::Memory(dev(), amd::alignUp(codeSize_, gpu::ConstBuffer::VectorSize));
// Initialize kernel ISA code
if ((code_ != NULL) && code_->create(Resource::Shader)) {
address cpuCodePtr = static_cast<address>(code_->map(NULL, Resource::WriteOnly));
// Copy only amd_kernel_code_t
memcpy(cpuCodePtr, codeStartAddress, codeSize_);
code_->unmap(NULL);
}
else {
LogError("Failed to allocate ISA code!");
return false;
}
cpuAqlCode_ = akc;
assert((akc->workitem_private_segment_byte_size & 3) == 0 &&
"Scratch must be DWORD aligned");
workGroupInfo_.scratchRegs_ =
amd::alignUp(akc->workitem_private_segment_byte_size, 16) / sizeof(uint);
workGroupInfo_.availableSGPRs_ = dev().gslCtx()->getNumSGPRsAvailable();
workGroupInfo_.availableVGPRs_ = dev().gslCtx()->getNumVGPRsAvailable();
workGroupInfo_.preferredSizeMultiple_ = dev().getAttribs().wavefrontSize;
workGroupInfo_.privateMemSize_ = akc->workitem_private_segment_byte_size;
workGroupInfo_.localMemSize_ =
workGroupInfo_.usedLDSSize_ = akc->workgroup_group_segment_byte_size;
workGroupInfo_.usedSGPRs_ = akc->wavefront_sgpr_count;
workGroupInfo_.usedStackSize_ = 0;
workGroupInfo_.usedVGPRs_ = akc->workitem_vgpr_count;
workGroupInfo_.wavefrontPerSIMD_ = dev().getAttribs().wavefrontSize;
return true;
}
} // namespace gpu
<commit_msg>P4 to Git Change 1129400 by kzhuravl@win-kzhuravl-stg-oclhsa on 2015/03/11 00:40:42<commit_after>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#include "device/gpu/gpudefs.hpp"
#include "device/gpu/gpuprogram.hpp"
#include "device/gpu/gpukernel.hpp"
#include "acl.h"
#include "SCShadersSi.h"
#include "si_ci_vi_merged_offset.h"
#include "si_ci_vi_merged_registers.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <ctime>
namespace gpu {
bool
NullKernel::siCreateHwInfo(const void* shader, AMUabiAddEncoding& encoding)
{
static const uint NumSiCsInfos = (70 + 5 + 1 + 32 + 6);
CALProgramInfoEntry* newInfos;
uint i = 0;
uint infoCount = NumSiCsInfos;
const SC_SI_HWSHADER_CS* cShader = reinterpret_cast<const SC_SI_HWSHADER_CS*>(shader);
newInfos = new CALProgramInfoEntry[infoCount];
encoding.progInfos = newInfos;
if (encoding.progInfos == 0) {
infoCount = 0;
return false;
}
newInfos[i].address = AMU_ABI_USER_ELEMENT_COUNT;
newInfos[i].value = cShader->common.userElementCount;
i++;
for (unsigned int j = 0; j < cShader->common.userElementCount; j++) {
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD0 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].dataClass;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD1 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].apiSlot;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD2 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].startUserReg;
i++;
newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD3 + 4*j;
newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].userRegCount;
i++;
}
newInfos[i].address = AMU_ABI_SI_NUM_VGPRS;
newInfos[i].value = cShader->common.numVgprs;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_SGPRS;
newInfos[i].value = cShader->common.numSgprs;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_SGPRS_AVAIL;
newInfos[i].value = SI_sgprs_avail; //512;//options.NumSGPRsAvailable;
i++;
newInfos[i].address = AMU_ABI_SI_NUM_VGPRS_AVAIL;
newInfos[i].value = SI_vgprs_avail;//options.NumVGPRsAvailable;
i++;
newInfos[i].address = AMU_ABI_SI_FLOAT_MODE;
newInfos[i].value = cShader->common.floatMode;
i++;
newInfos[i].address = AMU_ABI_SI_IEEE_MODE;
newInfos[i].value = cShader->common.bIeeeMode;
i++;
newInfos[i].address = AMU_ABI_SI_SCRATCH_SIZE;
newInfos[i].value = cShader->common.scratchSize;;
i++;
newInfos[i].address = mmCOMPUTE_PGM_RSRC2;
newInfos[i].value = cShader->computePgmRsrc2.u32All;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_X;
newInfos[i].value = cShader->numThreadX;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Y;
newInfos[i].value = cShader->numThreadY;
i++;
newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Z;
newInfos[i].value = cShader->numThreadZ;
i++;
newInfos[i].address = AMU_ABI_ORDERED_APPEND_ENABLE;
newInfos[i].value = cShader->bOrderedAppendEnable;
i++;
newInfos[i].address = AMU_ABI_RAT_OP_IS_USED;
newInfos[i].value = cShader->common.uavResourceUsage[0];
i++;
for (unsigned int j = 0; j < ((SC_MAX_UAV + 31) / 32); j++) {
newInfos[i].address = AMU_ABI_UAV_RESOURCE_MASK_0 + j;
newInfos[i].value = cShader->common.uavResourceUsage[j];
i++;
}
newInfos[i].address = AMU_ABI_NUM_WAVEFRONT_PER_SIMD; // Setting the same as for scWrapR800Info
newInfos[i].value = 1;
i++;
newInfos[i].address = AMU_ABI_WAVEFRONT_SIZE;
newInfos[i].value = nullDev().hwInfo()->simdWidth_ * 4; //options.WavefrontSize;
i++;
newInfos[i].address = AMU_ABI_LDS_SIZE_AVAIL;
newInfos[i].value = SI_ldssize_avail; //options.LDSSize;
i++;
COMPUTE_PGM_RSRC2 computePgmRsrc2;
computePgmRsrc2.u32All = cShader->computePgmRsrc2.u32All;
newInfos[i].address = AMU_ABI_LDS_SIZE_USED;
newInfos[i].value = 64 * 4 * computePgmRsrc2.bits.LDS_SIZE;
i++;
infoCount = i;
assert((i + 4 * (16 - cShader->common.userElementCount)) == NumSiCsInfos);
encoding.progInfosCount = infoCount;
CALUavMask uavMask;
memcpy(uavMask.mask, cShader->common.uavResourceUsage, sizeof(CALUavMask));
encoding.uavMask = uavMask;
encoding.textData = HWSHADER_Get(cShader, common.hShaderMemHandle);
encoding.textSize = cShader->common.codeLenInByte;
instructionCnt_ = encoding.textSize / sizeof(uint32_t);
encoding.scratchRegisterCount = cShader->common.scratchSize;
encoding.UAVReturnBufferTotalSize = 0;
return true;
}
bool
HSAILKernel::aqlCreateHWInfo(const void* shader, size_t shaderSize)
{
// Copy the shader_isa into a buffer
hwMetaData_ = new char[shaderSize];
if (hwMetaData_ == NULL) {
return false;
}
memcpy(hwMetaData_, shader, shaderSize);
SC_SI_HWSHADER_CS* siMetaData = reinterpret_cast<SC_SI_HWSHADER_CS*>(hwMetaData_);
// Code to patch the pointers in the shader object.
// Must be preferably done in the compiler library
size_t offset = siMetaData->common.uSizeInBytes;
if (siMetaData->common.u32PvtDataSizeInBytes > 0) {
siMetaData->common.pPvtData =
reinterpret_cast<SC_BYTE *>(
reinterpret_cast<char *>(siMetaData) + offset);
offset += siMetaData->common.u32PvtDataSizeInBytes;
}
if (siMetaData->common.codeLenInByte > 0) {
siMetaData->common.hShaderMemHandle =
reinterpret_cast<char *>(siMetaData) + offset;
offset += siMetaData->common.codeLenInByte;
}
char* headerBaseAddress =
reinterpret_cast<char*>(siMetaData->common.hShaderMemHandle);
amd_kernel_code_t* akc = reinterpret_cast<amd_kernel_code_t*>(
headerBaseAddress);
address codeStartAddress = reinterpret_cast<address>(akc);
address codeEndAddress = reinterpret_cast<address>(akc) + siMetaData->common.codeLenInByte;
codeSize_ = codeEndAddress - codeStartAddress;
code_ = new gpu::Memory(dev(), amd::alignUp(codeSize_, gpu::ConstBuffer::VectorSize));
// Initialize kernel ISA code
if ((code_ != NULL) && code_->create(Resource::Shader)) {
address cpuCodePtr = static_cast<address>(code_->map(NULL, Resource::WriteOnly));
// Copy only amd_kernel_code_t
memcpy(cpuCodePtr, codeStartAddress, codeSize_);
code_->unmap(NULL);
}
else {
LogError("Failed to allocate ISA code!");
return false;
}
cpuAqlCode_ = akc;
assert((akc->workitem_private_segment_byte_size & 3) == 0 &&
"Scratch must be DWORD aligned");
workGroupInfo_.scratchRegs_ =
amd::alignUp(akc->workitem_private_segment_byte_size, 16) / sizeof(uint);
workGroupInfo_.availableSGPRs_ = dev().gslCtx()->getNumSGPRsAvailable();
workGroupInfo_.availableVGPRs_ = dev().gslCtx()->getNumVGPRsAvailable();
workGroupInfo_.preferredSizeMultiple_ = dev().getAttribs().wavefrontSize;
workGroupInfo_.privateMemSize_ = akc->workitem_private_segment_byte_size;
workGroupInfo_.localMemSize_ =
workGroupInfo_.usedLDSSize_ = akc->workgroup_group_segment_byte_size;
workGroupInfo_.usedSGPRs_ = akc->wavefront_sgpr_count;
workGroupInfo_.usedStackSize_ = 0;
workGroupInfo_.usedVGPRs_ = akc->workitem_vgpr_count;
workGroupInfo_.wavefrontPerSIMD_ = dev().getAttribs().wavefrontSize;
return true;
}
} // namespace gpu
<|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief array iterator
@author MITSUNARI Shigeo(@herumi)
*/
#include <assert.h>
namespace mcl { namespace fp {
/*
get w-bit size from x[0, bitSize)
@param x [in] data
@param bitSize [in] data size
@param w [in] split size < UnitBitSize
*/
template<class T>
class ArrayIterator {
const T *x_;
size_t bitSize_;
const size_t w_;
const T mask_;
size_t pos_;
public:
static const size_t TbitSize = sizeof(T) * 8;
ArrayIterator(const T *x, size_t bitSize, size_t w)
: x_(x)
, bitSize_(bitSize)
, w_(w)
, mask_(makeMask(w))
, pos_(0)
{
assert(w_ <= TbitSize);
}
static T makeMask(size_t w)
{
return (w == TbitSize) ? ~T(0) : (T(1) << w) - 1;
}
bool hasNext() const { return bitSize_ > 0; }
T getNext(size_t w = 0)
{
if (w == 0) w = w_;
assert(w <= TbitSize);
if (w > bitSize_) {
w = bitSize_;
}
if (!hasNext()) return 0;
const T mask = w == w_ ? mask_ : makeMask(w);
const size_t nextPos = pos_ + w;
if (nextPos <= TbitSize) {
T v = x_[0] >> pos_;
if (nextPos < TbitSize) {
pos_ = nextPos;
v &= mask;
} else {
pos_ = 0;
x_++;
}
bitSize_ -= w;
return v;
}
T v = (x_[0] >> pos_) | (x_[1] << (TbitSize - pos_));
v &= mask;
pos_ = nextPos - TbitSize;
bitSize_ -= w;
x_++;
return v;
}
// don't change iter
bool peek1bit()
{
assert(hasNext());
return (x_[0] >> pos_) & 1;
}
// ++iter
void consume1bit()
{
assert(hasNext());
const size_t nextPos = pos_ + 1;
if (nextPos < TbitSize) {
pos_ = nextPos;
} else {
pos_ = 0;
x_++;
}
bitSize_ -= 1;
}
};
} } // mcl::fp
<commit_msg>remove ArrayIterator<commit_after><|endoftext|>
|
<commit_before>/************************************ ABOUT ***********************************\
| This file is used to compile the db_schema.json file into any nessasary |
| formats including |
| SQL Initilizer Query (For both MySQL and SQLite3) |
| C++ object to store a row of the database for easy access |
| Java object to store a row of the databasae for easy access (android) |
| - Eventually there may be javascript support for the firefox / chrome |
| plugins |
\******************************************************************************/
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
// #include <boost/date.hpp>
#include <iostream>
#include <vector>
#include <sstream>
#include <map>
#include <stdlib.h>
using namespace std;
// Mapping of each SQL datatype to the corrisponding C++ datatype
map <string, string> SQLtoCPP {
{"varchar", "std::string"},
{"int", "int"},
{"timestamp", "std::string"}
};
// Mapping of each sql datatype to the C++ sqlite3 function to get that type from the database
map <string, string> SQLITEtoCPP{
{"varchar", "std::string(reinterpret_cast<const char*> (sqlite3_column_text (statement,i)))"},
{"int", "sqlite3_column_int (statement,i)"},
{"timestamp", "std::string(reinterpret_cast<const char*> (sqlite3_column_text (statement,i)))" } // Timestamp
};
// Mapping of each SQL datatype to the corrisponding Java datatype
map <string, string> SQLtoJava {
{"varchar", "String"},
{"int", "Integer"},
{"timestamp", "String"}
};
int main() {
cout << "Loading the JSON file" << endl;
using boost::property_tree::ptree;
ptree pt;
// Load the JSON into the property tree ometrherfke
string testfile = "db_schema.json";
read_json(testfile, pt);
cout << "JSON file loaded" << endl;
cout << "Parsing File" << endl;
stringstream CPPVariables; // Really these should all be files
stringstream CPPConstructor; // the construction for initilizing all of the variables from a sqlite3 statement
stringstream SQLRows; // to be joined and encapsulated
stringstream SQLITERows; // special formatting for sqlite (no extra data, no newlines)
vector<string> SQLIndexes; // to be joined as is
// Pre loop constructors
SQLRows << "CREATE TABLE rules (";
SQLITERows << "CREATE TABLE rules (";
// Allow tracking of the number of columns
int columnCount = 0;
// Loop Constructors
string concatinator = "";
for ( ptree::value_type const& v : pt.get_child("columns")) {
string columnName = v.first;
ptree subtree = v.second;
string type = subtree.get<std::string>("Type");
string size = subtree.get("Size", "");
string description = subtree.get("Description", "");
string indexName = subtree.get("Index", "");
string defaultValue = subtree.get("Default", "");
bool isNullable = subtree.get("Nullable", true);
string extraData = subtree.get("Extra", "");
bool isDepricated = subtree.get("Depricated", false);
// SQL colum Value
SQLRows << concatinator << endl << " `" << boost::to_lower_copy(columnName) << "`";
SQLRows << " " << boost::to_lower_copy(type); if (size.length() > 0) SQLRows << "(" << size << ")"; SQLRows << " ";
if (!isNullable) SQLRows << "NOT NULL";
if (defaultValue.length() > 0) SQLRows << " DEFAULT " << defaultValue;
if (extraData.length() > 0) SQLRows << " " << extraData;
concatinator = ",";
//SQLITE3 Constructor (no extra data, no newlines)
SQLITERows << concatinator << " `" << boost::to_lower_copy(columnName) << "`";
SQLITERows << " " << boost::to_lower_copy(type); if (size.length() > 0) SQLITERows << "\\(" << size << "\\)"; SQLITERows << " ";
if (!isNullable) SQLITERows << "NOT NULL";
if (defaultValue.length() > 0) SQLITERows << " DEFAULT " << defaultValue;
concatinator = ",";
// C++ Datatype variables
CPPVariables << "\t" << SQLtoCPP[type] << " " << columnName << ";" << endl;
// C++ SQLITE3 CONVERSIONS
CPPConstructor << "\t\t\tif (columnName == \"" << boost::to_lower_copy(columnName) << "\") {" << columnName << " = " << SQLITEtoCPP[type] << ";}" << endl;
// CREATE TABLE `virtual_aliases` (
// `id` int(11) NOT NULL auto_increment,
// `domain_id` int(11) NOT NULL,
// `source` varchar(100) NOT NULL,
// `destination` varchar(100) NOT NULL,
// PRIMARY KEY (`id`),
// FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
columnCount++;
}
// Post Loop Constst ructors
SQLRows << endl << ");" << endl; // the engine data might not be nessasary but IDK how SQL differes between implementations
SQLITERows << ");";
// cout << "CREATE INDEX " << indexName << "ON rules (" << columnName << ");" << endl;
ifstream CPPFileIn;
ofstream CPPFileOut;
char inputFilename[] = "templates/DomainSettings.h";
char outputFilename[] = "../CommandLineTool/DomainSettings.h";
CPPFileIn.open(inputFilename, ios::in);
if (!CPPFileIn) {
cerr << "Can't open input file " << inputFilename << endl;
exit(1);
}
CPPFileOut.open(outputFilename, ios::out);
if (!CPPFileOut) {
cerr << "Can't open output file " << outputFilename << endl;
exit(1);
}
string CPPFileLine;
while (getline(CPPFileIn, CPPFileLine)) {
CPPFileLine = boost::regex_replace(CPPFileLine, boost::regex("\\[\\[SQLCOLUMNCOUNT\\]\\]"), std::to_string(columnCount), boost::match_default | boost::format_all);
CPPFileLine = boost::regex_replace(CPPFileLine, boost::regex("\\[\\[SQLCREATETABLE\\]\\]"), "\""+SQLITERows.str()+"\"", boost::match_default | boost::format_all);
if (boost::regex_match(CPPFileLine, boost::regex ("\\s*\\[\\[CPPVARIABLES\\]\\]"))) {
CPPFileOut << CPPVariables.rdbuf();
}
else if (boost::regex_match(CPPFileLine, boost::regex("\\s*\\[\\[CPPCONSTRUCTOR\\]\\]"))) {
CPPFileOut << CPPConstructor.rdbuf();
}
else {
CPPFileOut << CPPFileLine << "\n"; // reappend the newline to the file
}
}
cout << SQLRows.rdbuf() << endl;
cout << CPPConstructor.rdbuf() << endl;
}<commit_msg>switched the autogenerated cpp file to use spaces instead of tabs<commit_after>/************************************ ABOUT ***********************************\
| This file is used to compile the db_schema.json file into any nessasary |
| formats including |
| SQL Initilizer Query (For both MySQL and SQLite3) |
| C++ object to store a row of the database for easy access |
| Java object to store a row of the databasae for easy access (android) |
| - Eventually there may be javascript support for the firefox / chrome |
| plugins |
\******************************************************************************/
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
// #include <boost/date.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <stdlib.h>
using namespace std;
// Mapping of each SQL datatype to the corrisponding C++ datatype
map <string, string> SQLtoCPP {
{"varchar", "std::string"},
{"int", "int"},
{"timestamp", "std::string"}
};
// Mapping of each sql datatype to the C++ sqlite3 function to get that type from the database
map <string, string> SQLITEtoCPP{
{"varchar", "std::string(reinterpret_cast<const char*> (sqlite3_column_text (statement,i)))"},
{"int", "sqlite3_column_int (statement,i)"},
{"timestamp", "std::string(reinterpret_cast<const char*> (sqlite3_column_text (statement,i)))" } // Timestamp
};
// Mapping of each SQL datatype to the corrisponding Java datatype
map <string, string> SQLtoJava {
{"varchar", "String"},
{"int", "Integer"},
{"timestamp", "String"}
};
int main() {
cout << "Loading the JSON file" << endl;
using boost::property_tree::ptree;
ptree pt;
// Load the JSON into the property tree ometrherfke
string testfile = "db_schema.json";
read_json(testfile, pt);
cout << "JSON file loaded" << endl;
cout << "Parsing File" << endl;
stringstream CPPVariables; // Really these should all be files
stringstream CPPConstructor; // the construction for initilizing all of the variables from a sqlite3 statement
stringstream SQLRows; // to be joined and encapsulated
stringstream SQLITERows; // special formatting for sqlite (no extra data, no newlines)
vector<string> SQLIndexes; // to be joined as is
// Pre loop constructors
SQLRows << "CREATE TABLE rules (";
SQLITERows << "CREATE TABLE rules (";
// Allow tracking of the number of columns
int columnCount = 0;
// Loop Constructors
string concatinator = "";
for ( ptree::value_type const& v : pt.get_child("columns")) {
string columnName = v.first;
ptree subtree = v.second;
string type = subtree.get<std::string>("Type");
string size = subtree.get("Size", "");
string description = subtree.get("Description", "");
string indexName = subtree.get("Index", "");
string defaultValue = subtree.get("Default", "");
bool isNullable = subtree.get("Nullable", true);
string extraData = subtree.get("Extra", "");
bool isDepricated = subtree.get("Depricated", false);
// SQL colum Value
SQLRows << concatinator << endl << " `" << boost::to_lower_copy(columnName) << "`";
SQLRows << " " << boost::to_lower_copy(type); if (size.length() > 0) SQLRows << "(" << size << ")"; SQLRows << " ";
if (!isNullable) SQLRows << "NOT NULL";
if (defaultValue.length() > 0) SQLRows << " DEFAULT " << defaultValue;
if (extraData.length() > 0) SQLRows << " " << extraData;
concatinator = ",";
//SQLITE3 Constructor (no extra data, no newlines)
SQLITERows << concatinator << " `" << boost::to_lower_copy(columnName) << "`";
SQLITERows << " " << boost::to_lower_copy(type); if (size.length() > 0) SQLITERows << "\\(" << size << "\\)"; SQLITERows << " ";
if (!isNullable) SQLITERows << "NOT NULL";
if (defaultValue.length() > 0) SQLITERows << " DEFAULT " << defaultValue;
concatinator = ",";
// C++ Datatype variables
CPPVariables << " " << SQLtoCPP[type] << " " << columnName << ";" << endl;
// C++ SQLITE3 CONVERSIONS
CPPConstructor << " if (columnName == \"" << boost::to_lower_copy(columnName) << "\") {" << columnName << " = " << SQLITEtoCPP[type] << ";}" << endl;
// CREATE TABLE `virtual_aliases` (
// `id` int(11) NOT NULL auto_increment,
// `domain_id` int(11) NOT NULL,
// `source` varchar(100) NOT NULL,
// `destination` varchar(100) NOT NULL,
// PRIMARY KEY (`id`),
// FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
columnCount++;
}
// Post Loop Constst ructors
SQLRows << endl << ");" << endl; // the engine data might not be nessasary but IDK how SQL differes between implementations
SQLITERows << ");";
// cout << "CREATE INDEX " << indexName << "ON rules (" << columnName << ");" << endl;
ifstream CPPFileIn;
ofstream CPPFileOut;
char inputFilename[] = "templates/DomainSettings.h";
char outputFilename[] = "../CommandLineTool/DomainSettings.h";
CPPFileIn.open(inputFilename, ios::in);
if (!CPPFileIn) {
cerr << "Can't open input file " << inputFilename << endl;
exit(1);
}
CPPFileOut.open(outputFilename, ios::out);
if (!CPPFileOut) {
cerr << "Can't open output file " << outputFilename << endl;
exit(1);
}
string CPPFileLine;
while (getline(CPPFileIn, CPPFileLine)) {
CPPFileLine = boost::regex_replace(CPPFileLine, boost::regex("\\[\\[SQLCOLUMNCOUNT\\]\\]"), std::to_string(columnCount), boost::match_default | boost::format_all);
CPPFileLine = boost::regex_replace(CPPFileLine, boost::regex("\\[\\[SQLCREATETABLE\\]\\]"), "\""+SQLITERows.str()+"\"", boost::match_default | boost::format_all);
if (boost::regex_match(CPPFileLine, boost::regex ("\\s*\\[\\[CPPVARIABLES\\]\\]"))) {
CPPFileOut << CPPVariables.rdbuf();
}
else if (boost::regex_match(CPPFileLine, boost::regex("\\s*\\[\\[CPPCONSTRUCTOR\\]\\]"))) {
CPPFileOut << CPPConstructor.rdbuf();
}
else {
CPPFileOut << CPPFileLine << "\n"; // reappend the newline to the file
}
}
cout << SQLRows.rdbuf() << endl;
cout << CPPConstructor.rdbuf() << endl;
}<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
/// \file basic_persist_array.hpp
//----------------------------------------------------------------------------
/// \brief Implementation of persistent array storage class.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-10-25
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the util open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
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
vsn 2.1 of the License, or (at your option) any later vsn.
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
***** END LICENSE BLOCK *****
*/
#ifndef _UTIL_PERSISTENT_ARRAY_HPP_
#define _UTIL_PERSISTENT_ARRAY_HPP_
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/static_assert.hpp>
#include <boost/scope_exit.hpp>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <util/compiler_hints.hpp>
#include <util/atomic.hpp>
#include <util/error.hpp>
#include <stdexcept>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
namespace util {
namespace {
namespace bip = boost::interprocess;
struct empty_data {};
}
template <
typename T,
size_t NLocks = 32,
typename Lock = boost::mutex,
typename ExtraHeaderData = empty_data>
struct persist_array {
struct header {
static const uint32_t s_version = 0xa0b1c2d3;
uint32_t version;
volatile long rec_count;
size_t max_recs;
size_t rec_size;
Lock locks[NLocks];
ExtraHeaderData extra_header_data;
T records[0];
};
protected:
typedef persist_array<T, NLocks, Lock, ExtraHeaderData> self_type;
BOOST_STATIC_ASSERT(!(NLocks & (NLocks - 1))); // must be power of 2
static const size_t s_lock_mask = NLocks-1;
// Shared memory file mapping
bip::file_mapping m_file;
// Shared memory mapped region
bip::mapped_region m_region;
// Locks that guard access to internal record structures.
header* m_header;
T* m_begin;
T* m_end;
void check_range(size_t a_id) const throw (badarg_error) {
size_t n = m_header->max_recs;
if (likely(a_id < n))
return;
throw badarg_error("Invalid record id specified ", a_id, " (max=", n-1, ')');
}
public:
typedef Lock lock_type;
typedef typename Lock::scoped_lock scoped_lock;
typedef typename Lock::scoped_try_lock scoped_try_lock;
BOOST_STATIC_ASSERT((NLocks & (NLocks-1)) == 0); // Must be power of 2.
persist_array()
: m_header(NULL), m_begin(NULL), m_end(NULL)
{}
/// Default permission mask used for opening a file
static int default_file_mode() { return S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; }
/// Initialize the storage
/// @return true if the storage file didn't exist and was created
bool init(const char* a_filename, size_t a_max_recs, bool a_read_only = false,
int a_mode = default_file_mode()) throw (io_error);
size_t count() const { return static_cast<size_t>(m_header->rec_count); }
size_t capacity() const { return m_header->max_recs; }
ExtraHeaderData& extra_header_data() { return m_header->extra_header_data; }
/// Allocate next record and return its ID.
/// @return
size_t allocate_rec() throw(std::runtime_error) {
size_t n = static_cast<size_t>(atomic::add(&m_header->rec_count,1));
if (n >= capacity()) {
atomic::dec(&m_header->rec_count);
throw std::runtime_error("Out of storage capacity!");
}
return n;
}
std::pair<T*, size_t> get_next() {
size_t n = allocate_rec();
return std::make_pair(get(n), n);
}
Lock& get_lock(size_t a_rec_id) {
return m_header->locks[a_rec_id & s_lock_mask];
}
/// Add a record with given ID to the store
void add(size_t a_id, const T& a_rec) {
BOOST_ASSERT(a_id < m_header->rec_count);
scoped_lock guard(get_lock(a_id));
*get(a_id) = a_rec;
}
/// Add a record to the storage and return it's id
size_t add(const T& a_rec) {
size_t n = allocate_rec();
scoped_lock guard(get_lock(n));
*(m_begin+n) = a_rec;
return n;
}
/// @return id of the given object in the storage
size_t id_of(const T* a_rec) const { return a_rec - m_begin; }
const T& operator[] (size_t a_id) const throw(badarg_error) {
check_range(a_id); return *get(a_id);
}
T& operator[] (size_t a_id) throw(badarg_error) {
check_range(a_id); return *get(a_id);
}
const T* get(size_t a_rec_id) const {
return likely(a_rec_id < m_header->max_recs) ? m_begin+a_rec_id : NULL;
}
T* get(size_t a_rec_id) {
return likely(a_rec_id < m_header->max_recs) ? m_begin+a_rec_id : NULL;
}
/// Flush header to disk
bool flush_header() { return m_region.flush(0, sizeof(header)); }
/// Flush region of cached records to disk
bool flush(size_t a_from_rec = 0, size_t a_num_recs = 0) {
return m_region.flush(a_from_rec, a_num_recs*sizeof(T));
}
/// Remove memory mapped file from disk
void remove() {
m_file.remove(m_file.get_name());
}
const T* begin() const { return m_begin; }
const T* end() const { return m_end; }
T* begin() { return m_begin; }
T* end() { return m_end; }
template <class Visitor>
void for_each(const Visitor& a_visitor) {
size_t n = 0;
for (const T* p = begin(), *e = p + count(); p != e; ++p, ++n)
a_visitor(n, p);
}
std::ostream& dump(std::ostream& out, const std::string& a_prefix="") {
for (const T* p = begin(), *e = p + count(); p != e; ++p)
out << a_prefix << *p << std::endl;
return out;
}
};
//-------------------------------------------------------------------------
// Implementation
//-------------------------------------------------------------------------
template <typename T, size_t NLocks, typename Lock, typename Ext>
bool persist_array<T,NLocks,Lock,Ext>::
init(const char* a_filename, size_t a_max_recs, bool a_read_only, int a_mode)
throw (io_error)
{
static const size_t s_pack_size = getpagesize();
size_t sz = sizeof(header) + (a_max_recs * sizeof(T));
sz += (s_pack_size - sz % s_pack_size);
bool l_exists;
try {
boost::filesystem::path l_name(a_filename);
try {
boost::filesystem::create_directories(l_name.parent_path());
} catch (boost::system::system_error& e) {
throw io_error("Cannot create directory: ",
l_name.parent_path(), ": ", e.what());
}
{
std::filebuf f;
f.open(a_filename, std::ios_base::in | std::ios_base::out
| std::ios_base::binary);
l_exists = f.is_open();
if (l_exists && !a_read_only) {
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
header h;
f.sgetn(reinterpret_cast<char*>(&h), sizeof(header));
if (h.version != header::s_version) {
throw io_error("Invalid file format ", a_filename);
}
if (h.rec_size != sizeof(T)) {
throw io_error("Invalid item size in file ", a_filename,
" (expected ", sizeof(T), " got ", h.rec_size, ')');
}
// Increase the file size if instructed to do so.
if (h.max_recs < a_max_recs) {
h.max_recs = a_max_recs;
f.pubseekoff(0, std::ios_base::beg);
f.sputn(reinterpret_cast<char*>(&h), sizeof(header));
f.pubseekoff(sz-1, std::ios_base::beg);
f.sputc(0);
}
}
}
if (!l_exists && !a_read_only) {
int l_fd = ::open(a_filename, O_RDWR | O_CREAT | O_TRUNC, a_mode);
if (l_fd < 0)
throw io_error(errno, "Error creating file ", a_filename);
BOOST_SCOPE_EXIT_TPL( (&l_fd) ) {
::close(l_fd);
} BOOST_SCOPE_EXIT_END;
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
header h;
h.version = header::s_version;
h.rec_count = 0;
h.max_recs = a_max_recs;
h.rec_size = sizeof(T);
if (::write(l_fd, &h, sizeof(h)) < 0)
throw io_error(errno, "Error writing to file ", a_filename);
if (::ftruncate(l_fd, sz) < 0)
throw io_error(errno, "Error setting file ",
a_filename, " to size ", sz);
::fsync(l_fd);
}
bip::file_mapping shmf(a_filename, a_read_only ? bip::read_only : bip::read_write);
bip::mapped_region region(shmf, a_read_only ? bip::read_only : bip::read_write);
//Get the address of the mapped region
void* addr = region.get_address();
size_t size = region.get_size();
m_file.swap(shmf);
m_region.swap(region);
//if (!exists && !a_read_only)
// memset(static_cast<char*>(addr) + sizeof(header), 0, size - sizeof(header));
m_header = static_cast<header*>(addr);
m_begin = m_header->records;
m_end = m_begin + a_max_recs;
BOOST_ASSERT(reinterpret_cast<char*>(m_end) <= static_cast<char*>(addr)+size);
//if (!l_exists && !a_read_only) {
if (!a_read_only) {
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
// If the file is open for writing, initialize the locks
// since previous program crash might have left locks in inconsistent state
for (Lock* l = m_header->locks, *e = l + NLocks; l != e; ++l)
new (l) Lock();
}
} catch (io_error& e) {
throw;
} catch (std::exception& e) {
throw io_error(e.what());
}
return !l_exists;
}
} // namespace util
#endif // _UTIL_PERSISTENT_ARRAY_HPP_
<commit_msg>Moved type from anonymous namespace<commit_after>//----------------------------------------------------------------------------
/// \file basic_persist_array.hpp
//----------------------------------------------------------------------------
/// \brief Implementation of persistent array storage class.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-10-25
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the util open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
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
vsn 2.1 of the License, or (at your option) any later vsn.
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
***** END LICENSE BLOCK *****
*/
#ifndef _UTIL_PERSISTENT_ARRAY_HPP_
#define _UTIL_PERSISTENT_ARRAY_HPP_
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/static_assert.hpp>
#include <boost/scope_exit.hpp>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <util/compiler_hints.hpp>
#include <util/atomic.hpp>
#include <util/error.hpp>
#include <stdexcept>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstddef>
#include <cstdlib>
#include <unistd.h>
namespace util {
namespace { namespace bip = boost::interprocess; }
namespace detail { struct empty_data {}; }
template <
typename T,
size_t NLocks = 32,
typename Lock = boost::mutex,
typename ExtraHeaderData = detail::empty_data>
struct persist_array {
struct header {
static const uint32_t s_version = 0xa0b1c2d3;
uint32_t version;
volatile long rec_count;
size_t max_recs;
size_t rec_size;
Lock locks[NLocks];
ExtraHeaderData extra_header_data;
T records[0];
};
protected:
typedef persist_array<T, NLocks, Lock, ExtraHeaderData> self_type;
BOOST_STATIC_ASSERT(!(NLocks & (NLocks - 1))); // must be power of 2
static const size_t s_lock_mask = NLocks-1;
// Shared memory file mapping
bip::file_mapping m_file;
// Shared memory mapped region
bip::mapped_region m_region;
// Locks that guard access to internal record structures.
header* m_header;
T* m_begin;
T* m_end;
void check_range(size_t a_id) const throw (badarg_error) {
size_t n = m_header->max_recs;
if (likely(a_id < n))
return;
throw badarg_error("Invalid record id specified ", a_id, " (max=", n-1, ')');
}
public:
typedef Lock lock_type;
typedef typename Lock::scoped_lock scoped_lock;
typedef typename Lock::scoped_try_lock scoped_try_lock;
BOOST_STATIC_ASSERT((NLocks & (NLocks-1)) == 0); // Must be power of 2.
persist_array()
: m_header(NULL), m_begin(NULL), m_end(NULL)
{}
/// Default permission mask used for opening a file
static int default_file_mode() { return S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; }
/// Initialize the storage
/// @return true if the storage file didn't exist and was created
bool init(const char* a_filename, size_t a_max_recs, bool a_read_only = false,
int a_mode = default_file_mode()) throw (io_error);
size_t count() const { return static_cast<size_t>(m_header->rec_count); }
size_t capacity() const { return m_header->max_recs; }
ExtraHeaderData& extra_header_data() { return m_header->extra_header_data; }
/// Allocate next record and return its ID.
/// @return
size_t allocate_rec() throw(std::runtime_error) {
size_t n = static_cast<size_t>(atomic::add(&m_header->rec_count,1));
if (n >= capacity()) {
atomic::dec(&m_header->rec_count);
throw std::runtime_error("Out of storage capacity!");
}
return n;
}
std::pair<T*, size_t> get_next() {
size_t n = allocate_rec();
return std::make_pair(get(n), n);
}
Lock& get_lock(size_t a_rec_id) {
return m_header->locks[a_rec_id & s_lock_mask];
}
/// Add a record with given ID to the store
void add(size_t a_id, const T& a_rec) {
BOOST_ASSERT(a_id < m_header->rec_count);
scoped_lock guard(get_lock(a_id));
*get(a_id) = a_rec;
}
/// Add a record to the storage and return it's id
size_t add(const T& a_rec) {
size_t n = allocate_rec();
scoped_lock guard(get_lock(n));
*(m_begin+n) = a_rec;
return n;
}
/// @return id of the given object in the storage
size_t id_of(const T* a_rec) const { return a_rec - m_begin; }
const T& operator[] (size_t a_id) const throw(badarg_error) {
check_range(a_id); return *get(a_id);
}
T& operator[] (size_t a_id) throw(badarg_error) {
check_range(a_id); return *get(a_id);
}
const T* get(size_t a_rec_id) const {
return likely(a_rec_id < m_header->max_recs) ? m_begin+a_rec_id : NULL;
}
T* get(size_t a_rec_id) {
return likely(a_rec_id < m_header->max_recs) ? m_begin+a_rec_id : NULL;
}
/// Flush header to disk
bool flush_header() { return m_region.flush(0, sizeof(header)); }
/// Flush region of cached records to disk
bool flush(size_t a_from_rec = 0, size_t a_num_recs = 0) {
return m_region.flush(a_from_rec, a_num_recs*sizeof(T));
}
/// Remove memory mapped file from disk
void remove() {
m_file.remove(m_file.get_name());
}
const T* begin() const { return m_begin; }
const T* end() const { return m_end; }
T* begin() { return m_begin; }
T* end() { return m_end; }
template <class Visitor>
void for_each(const Visitor& a_visitor) {
size_t n = 0;
for (const T* p = begin(), *e = p + count(); p != e; ++p, ++n)
a_visitor(n, p);
}
std::ostream& dump(std::ostream& out, const std::string& a_prefix="") {
for (const T* p = begin(), *e = p + count(); p != e; ++p)
out << a_prefix << *p << std::endl;
return out;
}
};
//-------------------------------------------------------------------------
// Implementation
//-------------------------------------------------------------------------
template <typename T, size_t NLocks, typename Lock, typename Ext>
bool persist_array<T,NLocks,Lock,Ext>::
init(const char* a_filename, size_t a_max_recs, bool a_read_only, int a_mode)
throw (io_error)
{
static const size_t s_pack_size = getpagesize();
size_t sz = sizeof(header) + (a_max_recs * sizeof(T));
sz += (s_pack_size - sz % s_pack_size);
bool l_exists;
try {
boost::filesystem::path l_name(a_filename);
try {
boost::filesystem::create_directories(l_name.parent_path());
} catch (boost::system::system_error& e) {
throw io_error("Cannot create directory: ",
l_name.parent_path(), ": ", e.what());
}
{
std::filebuf f;
f.open(a_filename, std::ios_base::in | std::ios_base::out
| std::ios_base::binary);
l_exists = f.is_open();
if (l_exists && !a_read_only) {
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
header h;
f.sgetn(reinterpret_cast<char*>(&h), sizeof(header));
if (h.version != header::s_version) {
throw io_error("Invalid file format ", a_filename);
}
if (h.rec_size != sizeof(T)) {
throw io_error("Invalid item size in file ", a_filename,
" (expected ", sizeof(T), " got ", h.rec_size, ')');
}
// Increase the file size if instructed to do so.
if (h.max_recs < a_max_recs) {
h.max_recs = a_max_recs;
f.pubseekoff(0, std::ios_base::beg);
f.sputn(reinterpret_cast<char*>(&h), sizeof(header));
f.pubseekoff(sz-1, std::ios_base::beg);
f.sputc(0);
}
}
}
if (!l_exists && !a_read_only) {
int l_fd = ::open(a_filename, O_RDWR | O_CREAT | O_TRUNC, a_mode);
if (l_fd < 0)
throw io_error(errno, "Error creating file ", a_filename);
BOOST_SCOPE_EXIT_TPL( (&l_fd) ) {
::close(l_fd);
} BOOST_SCOPE_EXIT_END;
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
header h;
h.version = header::s_version;
h.rec_count = 0;
h.max_recs = a_max_recs;
h.rec_size = sizeof(T);
if (::write(l_fd, &h, sizeof(h)) < 0)
throw io_error(errno, "Error writing to file ", a_filename);
if (::ftruncate(l_fd, sz) < 0)
throw io_error(errno, "Error setting file ",
a_filename, " to size ", sz);
::fsync(l_fd);
}
bip::file_mapping shmf(a_filename, a_read_only ? bip::read_only : bip::read_write);
bip::mapped_region region(shmf, a_read_only ? bip::read_only : bip::read_write);
//Get the address of the mapped region
void* addr = region.get_address();
size_t size = region.get_size();
m_file.swap(shmf);
m_region.swap(region);
//if (!exists && !a_read_only)
// memset(static_cast<char*>(addr) + sizeof(header), 0, size - sizeof(header));
m_header = static_cast<header*>(addr);
m_begin = m_header->records;
m_end = m_begin + a_max_recs;
BOOST_ASSERT(reinterpret_cast<char*>(m_end) <= static_cast<char*>(addr)+size);
//if (!l_exists && !a_read_only) {
if (!a_read_only) {
bip::file_lock flock(a_filename);
bip::scoped_lock<bip::file_lock> g_lock(flock);
// If the file is open for writing, initialize the locks
// since previous program crash might have left locks in inconsistent state
for (Lock* l = m_header->locks, *e = l + NLocks; l != e; ++l)
new (l) Lock();
}
} catch (io_error& e) {
throw;
} catch (std::exception& e) {
throw io_error(e.what());
}
return !l_exists;
}
} // namespace util
#endif // _UTIL_PERSISTENT_ARRAY_HPP_
<|endoftext|>
|
<commit_before>#include <BALL/VIEW/WIDGETS/SDWidget.h>
#include <BALL/VIEW/KERNEL/iconLoader.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/STRUCTURE/sdGenerator.h>
#include <QtGui/QPainter>
#include <QtGui/QStyle>
#include <QtGui/QStyleOptionFocusRect>
#include <QtGui/QAction>
#include <QtGui/QFileDialog>
#include <QtGui/QImageWriter>
#include <set>
namespace BALL
{
namespace VIEW
{
const char* SDWidget::Option::SHOW_HYDROGENS = "sd_widget_show_hydrogens";
const bool SDWidget::Default::SHOW_HYDROGENS = false;
SDWidget::SDWidget(QWidget *parent, bool show_hydrogens)
: QWidget(parent)
{
setup_();
options[SDWidget::Option::SHOW_HYDROGENS] = show_hydrogens;
}
SDWidget::SDWidget(const System& system, QWidget *parent)
: QWidget(parent)
{
setup_();
plot(system);
}
void SDWidget::setup_()
{
setDefaultOptions();
setBackgroundRole(QPalette::Base);
//Todo: Add a nice icon
QAction* export_image = new QAction(tr("Export image"), this);
export_image->setIcon(IconLoader::instance().getIcon("actions/document-save"));
addAction(export_image);
connect(export_image, SIGNAL(triggered()), this, SLOT(exportImage_()));
}
SDWidget::~SDWidget()
{}
void SDWidget::plot(const System& system, bool create_sd)
{
system_ = system;
if (create_sd)
{
SDGenerator sdg;
sdg.generateSD(system_);
}
update();
}
void SDWidget::paintEvent(QPaintEvent *)
{
drawFrame_();
renderSD_(this);
}
void SDWidget::drawFrame_()
{
QPainter p(this);
QStyleOptionFrame opt;
opt.initFrom(this);
opt.state |= QStyle::State_Sunken;
QRect erase_area = rect();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this) + 1;
erase_area.adjust(frameWidth, frameWidth, -frameWidth, -frameWidth);
p.eraseRect(erase_area);
style()->drawPrimitive(QStyle::PE_Frame, &opt, &p, this);
p.end();
}
void SDWidget::renderSD_(QPaintDevice* pd)
{
if(!pd)
{
return;
}
BoundingBoxProcessor bp;
system_.apply(bp);
Vector3 upper = bp.getUpper() + Vector3(5.,5.,5.);
Vector3 lower = bp.getLower() - Vector3(5.,5.,5.);
GeometricCenterProcessor gcp;
system_.apply(gcp);
Vector3 center = gcp.getCenter();
float xscale = pd->width() / (upper.x - lower.x);
float yscale = pd->height() / (upper.y - lower.y);
xscale = yscale = std::min(xscale, yscale);
QPainter painter(pd);
QPen pen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin);
painter.setPen(pen);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.translate(pd->width()/2, pd->height()/2);
QFont newFont = font();
newFont.setPixelSize(12);
painter.setFont(newFont);
QFontMetrics fontMetrics(newFont);
// check if hydrogen atoms should be shown!
bool show_H = options.getBool(Option::SHOW_HYDROGENS);
AtomIterator at_it = system_.beginAtom();
std::set<Atom*> already_seen;
for (; +at_it; ++at_it)
{
if ((at_it->getElement() == PTE[Element::H]) && !show_H) continue;
already_seen.insert(&(*at_it));
Atom::BondIterator b_it = at_it->beginBond();
Vector3 from3d = at_it->getPosition() - center;
QPointF from2d(from3d.x*xscale, from3d.y*yscale);
for (; +b_it; ++b_it)
{
Atom* partner = b_it->getPartner(*at_it);
if (
// treat each bond only once
(std::find(already_seen.begin(), already_seen.end(), partner) == already_seen.end())
// we don't draw hydrogens
&& !((partner->getElement() == PTE[Element::H]) && !show_H)
)
{
Vector3 to3d = partner->getPosition() - center;
QPointF to2d(to3d.x*xscale, to3d.y*yscale);
QPointF shifted_from = from2d;
// do we need to draw a character for the "to" atom?
if (partner->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(partner->getElement().getSymbol().c_str());
QPointF label_pos(to2d.x() - br.width()/2, to2d.y() + br.height()/2 - 4);
painter.drawText(label_pos, partner->getElement().getSymbol().c_str());
QRectF bounding_box(to2d.x() - br.width()/2 - 3,
to2d.y() - br.height()/2 - 4,
br.width() + 6, br.height() + 6);
to2d = getEndpoint_(bounding_box, to2d, from2d, false);
}
// and do we need to draw a character for the "from" atom?
if (at_it->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(at_it->getElement().getSymbol().c_str());
QRectF bounding_box(from2d.x() - br.width()/2 - 3,
from2d.y() - br.height()/2 - 4,
br.width() + 6, br.height() + 6);
shifted_from = getEndpoint_(bounding_box, to2d, from2d, true);
}
// do we need to draw a double bond?
if (b_it->getOrder() == Bond::ORDER__DOUBLE)
{
// compute two lines, slightly shifted wrt the normal of this line
QLineF bond_line = QLineF(shifted_from, to2d);
QLineF normal = bond_line.normalVector();
normal = normal.unitVector();
QPointF shift;
shift.setX(2*(normal.p2().x() - bond_line.p1().x()));
shift.setY(2*(normal.p2().y() - bond_line.p1().y()));
QLineF first_line = bond_line;
first_line.translate(shift);
shift.setX(-1.*shift.x());
shift.setY(-1.*shift.y());
QLineF second_line = bond_line;
second_line.translate(shift);
pen.setWidth(2);
painter.setPen(pen);
painter.drawLine(first_line);
painter.drawLine(second_line);
pen.setWidth(3);
painter.setPen(pen);
}
else if (b_it->getOrder() == Bond::ORDER__TRIPLE)
{
// compute two lines, slightly shifted wrt the normal of this line
QLineF bond_line = QLineF(shifted_from, to2d);
QLineF normal = bond_line.normalVector();
normal = normal.unitVector();
QPointF shift;
shift.setX(3*(normal.p2().x() - bond_line.p1().x()));
shift.setY(3*(normal.p2().y() - bond_line.p1().y()));
QLineF first_line = bond_line;
first_line.translate(shift);
shift.setX(-1.*shift.x());
shift.setY(-1.*shift.y());
QLineF second_line = bond_line;
second_line.translate(shift);
pen.setWidth(2);
painter.setPen(pen);
painter.drawLine(first_line);
painter.drawLine(bond_line);
painter.drawLine(second_line);
pen.setWidth(3);
painter.setPen(pen);
}
else // assume it's a single bond...
painter.drawLine(shifted_from, to2d);
}
}
// do we need to draw a character for the "from" atom?
if (at_it->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(at_it->getElement().getSymbol().c_str());
QPointF label_pos(from2d.x() - br.width()/2, from2d.y() + br.height()/2 - 4);
painter.drawText(label_pos, at_it->getElement().getSymbol().c_str());
}
}
}
QPointF SDWidget::getEndpoint_(QRectF& character_boundary, QPointF from, QPointF to, bool character_is_from)
{
// compute all relevant lines...
// the line from "from" to "to" :-)
QLineF line_from_to(from, to);
// the upper part of the box
QLineF upper(character_boundary.topLeft(), character_boundary.topRight());
// the right part of the box
QLineF right(character_boundary.topRight(), character_boundary.bottomRight());
// the lower part of the box
QLineF lower(character_boundary.bottomRight(), character_boundary.bottomLeft());
// and finally the left part
QLineF left(character_boundary.bottomLeft(), character_boundary.topLeft());
// intersect them
QPointF intersection_point;
if (line_from_to.intersect(upper, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(right, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(lower, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(left, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
//If to and from are too close, the computed intersection is incorrect.
//In this case just return the point not having the character
return character_is_from ? from : to;
}
void SDWidget::clear()
{
system_.clear();
update();
}
void SDWidget::setDefaultOptions()
{
options.setDefaultBool(SDWidget::Option::SHOW_HYDROGENS,
SDWidget::Default::SHOW_HYDROGENS);
}
void SDWidget::exportImage_()
{
QString file = QFileDialog::getSaveFileName(this, tr("Export image"), QString(), "Images (*.png *.xpm *.jpg *.bmp *.gif)");
if(file != QString::null)
{
QImage image(width(), height(), QImage::Format_ARGB32);
image.fill(0);
renderSD_(&image);
image.save(file);
}
}
}
}
<commit_msg>Safeguard SDWidget against lines of width 0<commit_after>#include <BALL/VIEW/WIDGETS/SDWidget.h>
#include <BALL/VIEW/KERNEL/iconLoader.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/STRUCTURE/sdGenerator.h>
#include <QtGui/QPainter>
#include <QtGui/QStyle>
#include <QtGui/QStyleOptionFocusRect>
#include <QtGui/QAction>
#include <QtGui/QFileDialog>
#include <QtGui/QImageWriter>
#include <set>
namespace BALL
{
namespace VIEW
{
const char* SDWidget::Option::SHOW_HYDROGENS = "sd_widget_show_hydrogens";
const bool SDWidget::Default::SHOW_HYDROGENS = false;
SDWidget::SDWidget(QWidget *parent, bool show_hydrogens)
: QWidget(parent)
{
setup_();
options[SDWidget::Option::SHOW_HYDROGENS] = show_hydrogens;
}
SDWidget::SDWidget(const System& system, QWidget *parent)
: QWidget(parent)
{
setup_();
plot(system);
}
void SDWidget::setup_()
{
setDefaultOptions();
setBackgroundRole(QPalette::Base);
//Todo: Add a nice icon
QAction* export_image = new QAction(tr("Export image"), this);
export_image->setIcon(IconLoader::instance().getIcon("actions/document-save"));
addAction(export_image);
connect(export_image, SIGNAL(triggered()), this, SLOT(exportImage_()));
}
SDWidget::~SDWidget()
{}
void SDWidget::plot(const System& system, bool create_sd)
{
system_ = system;
if (create_sd)
{
SDGenerator sdg;
sdg.generateSD(system_);
}
update();
}
void SDWidget::paintEvent(QPaintEvent *)
{
drawFrame_();
renderSD_(this);
}
void SDWidget::drawFrame_()
{
QPainter p(this);
QStyleOptionFrame opt;
opt.initFrom(this);
opt.state |= QStyle::State_Sunken;
QRect erase_area = rect();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this) + 1;
erase_area.adjust(frameWidth, frameWidth, -frameWidth, -frameWidth);
p.eraseRect(erase_area);
style()->drawPrimitive(QStyle::PE_Frame, &opt, &p, this);
p.end();
}
void SDWidget::renderSD_(QPaintDevice* pd)
{
if(!pd)
{
return;
}
BoundingBoxProcessor bp;
system_.apply(bp);
Vector3 upper = bp.getUpper() + Vector3(5.,5.,5.);
Vector3 lower = bp.getLower() - Vector3(5.,5.,5.);
GeometricCenterProcessor gcp;
system_.apply(gcp);
Vector3 center = gcp.getCenter();
float xscale = pd->width() / (upper.x - lower.x);
float yscale = pd->height() / (upper.y - lower.y);
xscale = yscale = std::min(xscale, yscale);
QPainter painter(pd);
QPen pen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin);
painter.setPen(pen);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.translate(pd->width()/2, pd->height()/2);
QFont newFont = font();
newFont.setPixelSize(12);
painter.setFont(newFont);
QFontMetrics fontMetrics(newFont);
// check if hydrogen atoms should be shown!
bool show_H = options.getBool(Option::SHOW_HYDROGENS);
AtomIterator at_it = system_.beginAtom();
std::set<Atom*> already_seen;
for (; +at_it; ++at_it)
{
if ((at_it->getElement() == PTE[Element::H]) && !show_H) continue;
already_seen.insert(&(*at_it));
Atom::BondIterator b_it = at_it->beginBond();
Vector3 from3d = at_it->getPosition() - center;
QPointF from2d(from3d.x*xscale, from3d.y*yscale);
for (; +b_it; ++b_it)
{
Atom* partner = b_it->getPartner(*at_it);
if (
// treat each bond only once
(std::find(already_seen.begin(), already_seen.end(), partner) == already_seen.end())
// we don't draw hydrogens
&& !((partner->getElement() == PTE[Element::H]) && !show_H)
)
{
Vector3 to3d = partner->getPosition() - center;
QPointF to2d(to3d.x*xscale, to3d.y*yscale);
QPointF shifted_from = from2d;
// do we need to draw a character for the "to" atom?
if (partner->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(partner->getElement().getSymbol().c_str());
QPointF label_pos(to2d.x() - br.width()/2, to2d.y() + br.height()/2 - 4);
painter.drawText(label_pos, partner->getElement().getSymbol().c_str());
QRectF bounding_box(to2d.x() - br.width()/2 - 3,
to2d.y() - br.height()/2 - 4,
br.width() + 6, br.height() + 6);
to2d = getEndpoint_(bounding_box, to2d, from2d, false);
}
// and do we need to draw a character for the "from" atom?
if (at_it->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(at_it->getElement().getSymbol().c_str());
QRectF bounding_box(from2d.x() - br.width()/2 - 3,
from2d.y() - br.height()/2 - 4,
br.width() + 6, br.height() + 6);
shifted_from = getEndpoint_(bounding_box, to2d, from2d, true);
}
// don't draw if the points are too close to each other (Qt tends to crash if this happens...)
if ((to2d - shifted_from).toPoint().manhattanLength() == 0)
continue;
// do we need to draw a double bond?
if (b_it->getOrder() == Bond::ORDER__DOUBLE)
{
// compute two lines, slightly shifted wrt the normal of this line
QLineF bond_line = QLineF(shifted_from, to2d);
QLineF normal = bond_line.normalVector();
normal = normal.unitVector();
QPointF shift;
shift.setX(2*(normal.p2().x() - bond_line.p1().x()));
shift.setY(2*(normal.p2().y() - bond_line.p1().y()));
QLineF first_line = bond_line;
first_line.translate(shift);
shift.setX(-1.*shift.x());
shift.setY(-1.*shift.y());
QLineF second_line = bond_line;
second_line.translate(shift);
pen.setWidth(2);
painter.setPen(pen);
painter.drawLine(first_line);
painter.drawLine(second_line);
pen.setWidth(3);
painter.setPen(pen);
}
else if (b_it->getOrder() == Bond::ORDER__TRIPLE)
{
// compute two lines, slightly shifted wrt the normal of this line
QLineF bond_line = QLineF(shifted_from, to2d);
QLineF normal = bond_line.normalVector();
normal = normal.unitVector();
QPointF shift;
shift.setX(3*(normal.p2().x() - bond_line.p1().x()));
shift.setY(3*(normal.p2().y() - bond_line.p1().y()));
QLineF first_line = bond_line;
first_line.translate(shift);
shift.setX(-1.*shift.x());
shift.setY(-1.*shift.y());
QLineF second_line = bond_line;
second_line.translate(shift);
pen.setWidth(2);
painter.setPen(pen);
painter.drawLine(first_line);
painter.drawLine(bond_line);
painter.drawLine(second_line);
pen.setWidth(3);
painter.setPen(pen);
}
else // assume it's a single bond...
painter.drawLine(shifted_from, to2d);
}
}
// do we need to draw a character for the "from" atom?
if (at_it->getElement() != PTE[Element::C])
{
QRect br = fontMetrics.boundingRect(at_it->getElement().getSymbol().c_str());
QPointF label_pos(from2d.x() - br.width()/2, from2d.y() + br.height()/2 - 4);
painter.drawText(label_pos, at_it->getElement().getSymbol().c_str());
}
}
}
QPointF SDWidget::getEndpoint_(QRectF& character_boundary, QPointF from, QPointF to, bool character_is_from)
{
// compute all relevant lines...
// the line from "from" to "to" :-)
QLineF line_from_to(from, to);
// the upper part of the box
QLineF upper(character_boundary.topLeft(), character_boundary.topRight());
// the right part of the box
QLineF right(character_boundary.topRight(), character_boundary.bottomRight());
// the lower part of the box
QLineF lower(character_boundary.bottomRight(), character_boundary.bottomLeft());
// and finally the left part
QLineF left(character_boundary.bottomLeft(), character_boundary.topLeft());
// intersect them
QPointF intersection_point;
if (line_from_to.intersect(upper, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(right, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(lower, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
if (line_from_to.intersect(left, &intersection_point) == QLineF::BoundedIntersection)
return intersection_point;
//If to and from are too close, the computed intersection is incorrect.
//In this case just return the point not having the character
return character_is_from ? from : to;
}
void SDWidget::clear()
{
system_.clear();
update();
}
void SDWidget::setDefaultOptions()
{
options.setDefaultBool(SDWidget::Option::SHOW_HYDROGENS,
SDWidget::Default::SHOW_HYDROGENS);
}
void SDWidget::exportImage_()
{
QString file = QFileDialog::getSaveFileName(this, tr("Export image"), QString(), "Images (*.png *.xpm *.jpg *.bmp *.gif)");
if(file != QString::null)
{
QImage image(width(), height(), QImage::Format_ARGB32);
image.fill(0);
renderSD_(&image);
image.save(file);
}
}
}
}
<|endoftext|>
|
<commit_before>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <Eigen/Dense>
#include <Random123/aes.h>
#include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/conventional/Engine.hpp>
#include <vSMC/internal/config.hpp>
#include <vSMC/internal/random.hpp>
/// The Parallel RNG (based on Rand123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED
/// The Parallel RNG (based on Rand123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE
namespace vSMC {
template <typename T> class Sampler;
/// Resample scheme
enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC,
RESIDUAL_STRATIFIED, RESIDUAL_SYSTEMATIC};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef r123::Engine< V_SMC_CRNG_TYPE > rng_type;
typedef rng_type::result_type seed_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
/// \param sampler The poiter to the Sampler which this particle set
/// belongs to
Particle (std::size_t N, rng_type::result_type seed = V_SMC_CRNG_SEED,
const Sampler<T> *sampler = NULL) :
size_(N), value_(N), sampler_(sampler),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
reset_prng(seed);
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Read only access to the sampler containing this particle set
///
/// \return A const reference to the sampler containing this particle set
const Sampler<T> &sampler () const
{
return *sampler_;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
void reset_prng (rng_type::result_type seed)
{
for (std::size_t i = 0; i != size_; ++i)
prng_[i] = rng_type(seed + i);
}
private :
std::size_t size_;
T value_;
const Sampler<T> *sampler_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
internal::binomial_distribution<>
binom(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(prng_[i]);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<commit_msg>workaround of possible 1offset situation in resampling due to numerical round<commit_after>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <Eigen/Dense>
#include <Random123/aes.h>
#include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/conventional/Engine.hpp>
#include <vSMC/internal/config.hpp>
#include <vSMC/internal/random.hpp>
/// The Parallel RNG (based on Rand123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED
/// The Parallel RNG (based on Rand123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE
namespace vSMC {
template <typename T> class Sampler;
/// Resample scheme
enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC,
RESIDUAL_STRATIFIED, RESIDUAL_SYSTEMATIC};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef r123::Engine< V_SMC_CRNG_TYPE > rng_type;
typedef rng_type::result_type seed_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
/// \param sampler The poiter to the Sampler which this particle set
/// belongs to
Particle (std::size_t N, rng_type::result_type seed = V_SMC_CRNG_SEED,
const Sampler<T> *sampler = NULL) :
size_(N), value_(N), sampler_(sampler),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
reset_prng(seed);
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Read only access to the sampler containing this particle set
///
/// \return A const reference to the sampler containing this particle set
const Sampler<T> &sampler () const
{
return *sampler_;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
void reset_prng (rng_type::result_type seed)
{
for (std::size_t i = 0; i != size_; ++i)
prng_[i] = rng_type(seed + i);
}
private :
std::size_t size_;
T value_;
const Sampler<T> *sampler_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
internal::binomial_distribution<>
binom(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(prng_[i]);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<|endoftext|>
|
<commit_before>#include "GUM_Sprite2.h"
#include "GUM_DTex.h"
#include "RenderTargetMgr.h"
#include "RenderTarget.h"
#include <sprite2/S2_RenderTargetMgr.h>
#include <sprite2/S2_RenderTarget.h>
#include <sprite2/S2_Sprite.h>
#include <sprite2/S2_Symbol.h>
#include <sprite2/RenderParams.h>
#include <sprite2/DrawNode.h>
#include <dtex2/DebugDraw.h>
#include <stdint.h>
namespace gum
{
SINGLETON_DEFINITION(Sprite2);
Sprite2::Sprite2()
{
}
void Sprite2::DebugDraw() const
{
s2::RenderTargetMgr* RT = s2::RenderTargetMgr::Instance();
for (int i = 0; i < 4; ++i) {
int texid = RT->GetTexID(i);
if (texid < 0) {
continue;
}
dtex::DebugDraw::Draw(texid, i + 1);
}
}
static void prepare_render_params(const s2::RenderParams& parent,
const s2::Sprite* spr,
s2::RenderParams& child)
{
if (parent.IsDisableDTexC2() || spr->IsDTexDisable()) {
child.SetDisableDTexC2(true);
}
}
static void
dtex_sym_insert(UID uid, const sm::rect& bounding, int tex_id, int tex_w, int tex_h)
{
DTex* dtex = DTex::Instance();
dtex->LoadSymStart();
sm::i16_rect r_dst;
r_dst.xmin = bounding.xmin + tex_w * 0.5f;
r_dst.ymin = bounding.ymin + tex_h * 0.5f;
r_dst.xmax = bounding.xmax + tex_w * 0.5f;
r_dst.ymax = bounding.ymax + tex_h * 0.5f;
dtex->LoadSymbol(uid, tex_id, tex_w, tex_h, r_dst, 1, 0, 0);
dtex->LoadSymFinish();
}
static const float*
dtex_sym_query(UID uid, int* tex_id)
{
return DTex::Instance()->QuerySymbol(uid, tex_id);
}
static uint64_t
get_sym_uid(const s2::Symbol* sym)
{
return ResourceUID::BinNode(sym->GetID());
}
static uint64_t
get_spr_uid(const s2::Sprite* spr)
{
return ResourceUID::Sprite(spr->GetID());
}
static uint64_t
get_actor_uid(const s2::Actor* actor)
{
return ResourceUID::Actor(actor);
}
static s2::RenderTarget*
fetch_screen()
{
return RenderTargetMgr::Instance()->Fetch();
}
static void
return_screen(s2::RenderTarget* rt)
{
RenderTargetMgr::Instance()->Return(dynamic_cast<gum::RenderTarget*>(rt));
}
void Sprite2::Init()
{
s2::DrawNode::InitDTexCB(prepare_render_params, dtex_sym_insert, dtex_sym_query);
s2::DrawNode::InitUIDCB(get_sym_uid, get_spr_uid, get_actor_uid);
s2::RenderTargetMgr::Instance()->InitScreenCB(fetch_screen, return_screen);
}
}<commit_msg>fix compile<commit_after>#include "GUM_Sprite2.h"
#include "GUM_DTex.h"
#include "RenderTargetMgr.h"
#include "RenderTarget.h"
#include <sprite2/S2_RenderTargetMgr.h>
#include <sprite2/S2_RenderTarget.h>
#include <sprite2/S2_Sprite.h>
#include <sprite2/S2_Symbol.h>
#include <sprite2/RenderParams.h>
#include <sprite2/DrawNode.h>
#include <dtex2/DebugDraw.h>
#include <stdint.h>
namespace gum
{
SINGLETON_DEFINITION(Sprite2);
Sprite2::Sprite2()
{
}
void Sprite2::DebugDraw() const
{
s2::RenderTargetMgr* RT = s2::RenderTargetMgr::Instance();
for (int i = 0; i < 4; ++i) {
int texid = RT->GetTexID(i);
if (texid < 0) {
continue;
}
dtex::DebugDraw::Draw(texid, i + 1);
}
}
static void prepare_render_params(const s2::RenderParams& parent,
const s2::Sprite* spr,
s2::RenderParams& child)
{
if (parent.IsDisableDTexC2() || spr->IsDTexDisable()) {
child.SetDisableDTexC2(true);
}
}
static void
dtex_sym_insert(UID uid, const sm::rect& bounding, int tex_id, int tex_w, int tex_h)
{
DTex* dtex = DTex::Instance();
dtex->LoadSymStart();
sm::i16_rect r_dst;
r_dst.xmin = bounding.xmin + tex_w * 0.5f;
r_dst.ymin = bounding.ymin + tex_h * 0.5f;
r_dst.xmax = bounding.xmax + tex_w * 0.5f;
r_dst.ymax = bounding.ymax + tex_h * 0.5f;
dtex->LoadSymbol(uid, tex_id, tex_w, tex_h, r_dst, 1, 0, 0);
dtex->LoadSymFinish();
}
static const float*
dtex_sym_query(UID uid, int* tex_id)
{
return DTex::Instance()->QuerySymbol(uid, tex_id);
}
static uint64_t
get_sym_uid(const s2::Symbol* sym)
{
return ResourceUID::BinNode(sym->GetID());
}
static uint64_t
get_spr_uid(const s2::Sprite* spr)
{
return ResourceUID::Sprite(spr->GetID());
}
static uint64_t
get_actor_uid(const s2::Actor* actor)
{
return ResourceUID::Actor(actor);
}
static s2::RenderTarget*
fetch_screen()
{
return RenderTargetMgr::Instance()->Fetch();
}
static void
return_screen(s2::RenderTarget* rt)
{
RenderTargetMgr::Instance()->Return(static_cast<gum::RenderTarget*>(rt));
}
void Sprite2::Init()
{
s2::DrawNode::InitDTexCB(prepare_render_params, dtex_sym_insert, dtex_sym_query);
s2::DrawNode::InitUIDCB(get_sym_uid, get_spr_uid, get_actor_uid);
s2::RenderTargetMgr::Instance()->InitScreenCB(fetch_screen, return_screen);
}
}<|endoftext|>
|
<commit_before>
#include <GUIDOEngine/GUIDOEngine.h>
#include <GUIDOEngine/GDeviceOSX.h>
#include <GUIDOEngine/GFontOSX.h>
#include <GUIDOEngine/GMemoryDeviceOSX.h>
#include <GUIDOEngine/GPrinterDeviceOSX.h>
#include <GUIDOEngine/GSystemOSX.h>
#include <GUIDOEngine/SVGSystem.h>
#include <guido-c.h>
// const char *byte_to_binary(int x);
const char* GuidoCGetVersion()
{
return "0.5.0";
}
// System
GuidoCGraphicSystem * GuidoCCreateSystem()
{
fprintf(stderr, "Creating system!\n");
// FIXME need to pass CGContextRef as first param here
/*
In a WX paint handler:
wxPaintDC MyDC(this);
CGContextRef context = ((wxMacCGContext*)MyDC.GetGraphicContext())->GetNativeContext();
*/
GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new GSystemOSX(0,0);
return system;
}
uint32_t* GuidoCNativePaint(GuidoCGraphicDevice * device)
{
CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext());
uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context);
return data;
}
void GuidoCPrintDeviceInfo(GuidoCGraphicDevice * device)
{
CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext());
uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context);
int m = CGBitmapContextGetBitsPerComponent(context);
int n = CGBitmapContextGetBitsPerPixel(context);
int w = CGBitmapContextGetWidth(context);
int h = CGBitmapContextGetHeight(context);
unsigned i = CGBitmapContextGetBitmapInfo(context);
unsigned a = CGBitmapContextGetAlphaInfo(context);
fprintf(stderr, "Data format: bitsPerComp=%d bitsPerPixel=%d width=%d height=%d\n", m, n, w, h);
// fprintf(stderr, "Info: %s\n", byte_to_binary(i));
// fprintf(stderr, "Alpha info: %s\n", byte_to_binary(a));
if (i & kCGBitmapFloatComponents) fprintf(stderr, "The components are floats\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrderDefault) fprintf(stderr, "The byte order is the default\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Little) fprintf(stderr, "The byte order is 16LE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Little) fprintf(stderr, "The byte order is 32LE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Big) fprintf(stderr, "The byte order is 16BE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Big) fprintf(stderr, "The byte order is 32BE\n");
if (a == kCGImageAlphaNone) fprintf(stderr, "Alpha: kCGImageAlphaNone\n");
if (a == kCGImageAlphaPremultipliedLast) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedLast\n");
if (a == kCGImageAlphaPremultipliedFirst) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedFirst\n");
if (a == kCGImageAlphaLast) fprintf(stderr, "Alpha: kCGImageAlphaLast\n");
if (a == kCGImageAlphaFirst) fprintf(stderr, "Alpha: kCGImageAlphaFirst\n");
if (a == kCGImageAlphaNoneSkipLast) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipLast\n");
if (a == kCGImageAlphaNoneSkipFirst) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipFirst\n");
}
GuidoCGraphicSystem * GuidoCCreateSVGSystem()
{
GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new SVGSystem();
return system;
}
void GuidoCFreeSystem(GuidoCGraphicSystem * system)
{
delete (GSystemOSX*) system;
}
void GuidoCFreeSVGSystem(GuidoCGraphicSystem * system)
{
delete (SVGSystem*) system;
}
GuidoCGraphicDevice * GuidoCCreateDisplayDevice(GuidoCGraphicSystem * system)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateDisplayDevice();
}
GuidoCGraphicDevice * GuidoCCreateMemoryDevice(GuidoCGraphicSystem * system, int width, int height)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(width, height);
}
GuidoCGraphicDevice * GuidoCCreateMemoryDevicePath(GuidoCGraphicSystem * system, const char* path)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(path);
}
GuidoCGraphicDevice * GuidoCCreatePrinterDevice(GuidoCGraphicSystem * system)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreatePrinterDevice();
}
// const char *byte_to_binary(int x)
// {
// static char b[9];
// b[0] = '\0';
// int z;
// for (z = 128; z > 0; z >>= 1)
// strcat(b, ((x & z) == z) ? "1" : "0");
// return b;
// }
<commit_msg>Cleaning<commit_after>
#include <GUIDOEngine/GUIDOEngine.h>
#include <GUIDOEngine/GDeviceOSX.h>
#include <GUIDOEngine/GFontOSX.h>
#include <GUIDOEngine/GMemoryDeviceOSX.h>
#include <GUIDOEngine/GPrinterDeviceOSX.h>
#include <GUIDOEngine/GSystemOSX.h>
#include <GUIDOEngine/SVGSystem.h>
#include <guido-c.h>
const char* GuidoCGetVersion()
{
return "0.5.0";
}
GuidoCGraphicSystem * GuidoCCreateSystem()
{
GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new GSystemOSX(0,0);
return system;
}
uint32_t* GuidoCNativePaint(GuidoCGraphicDevice * device)
{
CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext());
uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context);
return data;
}
void GuidoCPrintDeviceInfo(GuidoCGraphicDevice * device)
{
CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext());
uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context);
int m = CGBitmapContextGetBitsPerComponent(context);
int n = CGBitmapContextGetBitsPerPixel(context);
int w = CGBitmapContextGetWidth(context);
int h = CGBitmapContextGetHeight(context);
unsigned i = CGBitmapContextGetBitmapInfo(context);
unsigned a = CGBitmapContextGetAlphaInfo(context);
fprintf(stderr, "Data format: bitsPerComp=%d bitsPerPixel=%d width=%d height=%d\n", m, n, w, h);
// fprintf(stderr, "Info: %s\n", byte_to_binary(i));
// fprintf(stderr, "Alpha info: %s\n", byte_to_binary(a));
if (i & kCGBitmapFloatComponents) fprintf(stderr, "The components are floats\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrderDefault) fprintf(stderr, "The byte order is the default\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Little) fprintf(stderr, "The byte order is 16LE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Little) fprintf(stderr, "The byte order is 32LE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Big) fprintf(stderr, "The byte order is 16BE\n");
if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Big) fprintf(stderr, "The byte order is 32BE\n");
if (a == kCGImageAlphaNone) fprintf(stderr, "Alpha: kCGImageAlphaNone\n");
if (a == kCGImageAlphaPremultipliedLast) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedLast\n");
if (a == kCGImageAlphaPremultipliedFirst) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedFirst\n");
if (a == kCGImageAlphaLast) fprintf(stderr, "Alpha: kCGImageAlphaLast\n");
if (a == kCGImageAlphaFirst) fprintf(stderr, "Alpha: kCGImageAlphaFirst\n");
if (a == kCGImageAlphaNoneSkipLast) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipLast\n");
if (a == kCGImageAlphaNoneSkipFirst) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipFirst\n");
}
GuidoCGraphicSystem * GuidoCCreateSVGSystem()
{
GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new SVGSystem();
return system;
}
void GuidoCFreeSystem(GuidoCGraphicSystem * system)
{
delete (GSystemOSX*) system;
}
void GuidoCFreeSVGSystem(GuidoCGraphicSystem * system)
{
delete (SVGSystem*) system;
}
GuidoCGraphicDevice * GuidoCCreateDisplayDevice(GuidoCGraphicSystem * system)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateDisplayDevice();
}
GuidoCGraphicDevice * GuidoCCreateMemoryDevice(GuidoCGraphicSystem * system, int width, int height)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(width, height);
}
GuidoCGraphicDevice * GuidoCCreateMemoryDevicePath(GuidoCGraphicSystem * system, const char* path)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(path);
}
GuidoCGraphicDevice * GuidoCCreatePrinterDevice(GuidoCGraphicSystem * system)
{
return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreatePrinterDevice();
}
// const char *byte_to_binary(int x)
// {
// static char b[9];
// b[0] = '\0';
// int z;
// for (z = 128; z > 0; z >>= 1)
// strcat(b, ((x & z) == z) ? "1" : "0");
// return b;
// }
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkUnstructuredGrid.hh
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
// .NAME vtkUnstructuredGrid - dataset represents arbitrary combinations of all possible cell types
// .SECTION Description
// vtkUnstructuredGrid is a data object that is a concrete implementation
// of vtkDataSet. vtkUnstructuredGrid represents any combinations of any cell
// types. This includes 0D (e.g., points), 1D (e.g., lines, polylines), 2D
// (e.g., triangles, polygons), and 3D (e.g., hexahedron, tetrahedron).
#ifndef __vtkUnstructuredGrid_h
#define __vtkUnstructuredGrid_h
#include "vtkPointSet.hh"
#include "vtkIdList.hh"
#include "vtkCellArray.hh"
#include "vtkCellList.hh"
#include "vtkLinkList.hh"
class vtkUnstructuredGrid : public vtkPointSet {
public:
vtkUnstructuredGrid();
vtkUnstructuredGrid(const vtkUnstructuredGrid& up);
~vtkUnstructuredGrid();
char *GetClassName() {return "vtkUnstructuredGrid";};
char *GetDataType() {return "vtkUnstructuredGrid";};
void PrintSelf(ostream& os, vtkIndent indent);
// cell creation/manipulation methods
void Allocate(int numCells=1000, int extSize=1000);
int InsertNextCell(int type, int npts, int *pts);
int InsertNextCell(int type, vtkIdList& ptIds);
void Reset();
void SetCells(int *types, vtkCellArray *cells);
vtkCellArray *GetCells() {return this->Connectivity;};
// dataset interface
vtkDataSet *MakeObject() {return new vtkUnstructuredGrid(*this);};
void CopyStructure(vtkDataSet *ds);
int GetNumberOfCells();
vtkCell *GetCell(int cellId);
void GetCellPoints(int cellId, vtkIdList& ptIds);
void GetPointCells(int ptId, vtkIdList& cellIds);
int GetCellType(int cellId);
void Squeeze();
void Initialize();
int GetMaxCellSize();
protected:
// points inherited
// point data (i.e., scalars, vectors, normals, tcoords) inherited
vtkCellList *Cells;
vtkCellArray *Connectivity;
vtkLinkList *Links;
void BuildLinks();
};
#endif
<commit_msg>ENH: Added additional cell structure functionality.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkUnstructuredGrid.hh
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
// .NAME vtkUnstructuredGrid - dataset represents arbitrary combinations of all possible cell types
// .SECTION Description
// vtkUnstructuredGrid is a data object that is a concrete implementation
// of vtkDataSet. vtkUnstructuredGrid represents any combinations of any cell
// types. This includes 0D (e.g., points), 1D (e.g., lines, polylines), 2D
// (e.g., triangles, polygons), and 3D (e.g., hexahedron, tetrahedron).
#ifndef __vtkUnstructuredGrid_h
#define __vtkUnstructuredGrid_h
#include "vtkPointSet.hh"
#include "vtkIdList.hh"
#include "vtkCellArray.hh"
#include "vtkCellList.hh"
#include "vtkLinkList.hh"
class vtkUnstructuredGrid : public vtkPointSet {
public:
vtkUnstructuredGrid();
vtkUnstructuredGrid(const vtkUnstructuredGrid& up);
~vtkUnstructuredGrid();
char *GetClassName() {return "vtkUnstructuredGrid";};
char *GetDataType() {return "vtkUnstructuredGrid";};
void PrintSelf(ostream& os, vtkIndent indent);
// cell creation/manipulation methods
void Allocate(int numCells=1000, int extSize=1000);
int InsertNextCell(int type, int npts, int *pts);
int InsertNextCell(int type, vtkIdList& ptIds);
void Reset();
void SetCells(int *types, vtkCellArray *cells);
vtkCellArray *GetCells() {return this->Connectivity;};
// dataset interface
vtkDataSet *MakeObject() {return new vtkUnstructuredGrid(*this);};
void CopyStructure(vtkDataSet *ds);
int GetNumberOfCells();
vtkCell *GetCell(int cellId);
void GetCellPoints(int cellId, vtkIdList& ptIds);
void GetPointCells(int ptId, vtkIdList& cellIds);
int GetCellType(int cellId);
void Squeeze();
void Initialize();
int GetMaxCellSize();
// special cell structure methods
void BuildLinks();
void GetCellPoints(int cellId, int& npts, int* &pts);
void ReplaceCell(int cellId, int npts, int *pts);
int InsertNextLinkedCell(int type, int npts, int *pts);
void RemoveReferenceToCell(int ptId, int cellId);
void AddReferenceToCell(int ptId, int cellId);
void ResizeCellList(int ptId, int size);
protected:
// points inherited
// point data (i.e., scalars, vectors, normals, tcoords) inherited
vtkCellList *Cells;
vtkCellArray *Connectivity;
vtkLinkList *Links;
};
#endif
<|endoftext|>
|
<commit_before>#include <chrono>
#include <random>
#include <array>
#include <opencv2/core/core.hpp>
#include <opencv2/ocl/ocl.hpp>
#include "opencl.hpp"
#include "utility.hpp"
#include "hog.pencil.h"
#include "HogDescriptor.h"
#include "hog.clh"
void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat )
{
carp::Timing timing("HOG");
for (;repeat>0; --repeat) {
for ( auto & size : sizes ) {
for ( auto & item : pool ) {
std::mt19937 rng(0); //uses same seed, reseed for all iteration
cv::Mat cpu_gray;
cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY );
static_assert(sizeof(float[2]) == sizeof(std::array<float,2>), "This code needs std::array to behave exactly like C arrays.");
std::vector<std::array<float,2>> locations;
std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1);
std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1);
std::generate_n(std::back_inserter(locations), num_positions, [&](){ return std::array<float,2>{{ genx(rng), geny(rng) }}; });
std::vector<float> cpu_result(num_positions * HISTOGRAM_BINS), gpu_result(num_positions * HISTOGRAM_BINS), pen_result(num_positions * HISTOGRAM_BINS);
std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil;
{
//CPU implement
const auto cpu_start = std::chrono::high_resolution_clock::now();
auto result = nel::HOGDescriptor< NUMBER_OF_CELLS
, NUMBER_OF_BINS
, GAUSSIAN_WEIGHTS
, SPARTIAL_WEIGHTS
, SIGNED_HOG
>::compute(cpu_gray, locations, size);
const auto cpu_end = std::chrono::high_resolution_clock::now();
std::copy(result.begin(), result.end(), cpu_result.begin());
elapsed_time_cpu = cpu_end - cpu_start;
//Free up resources
}
{
carp::opencl::device device;
size_t max_work_group_size;
cl_int err;
err = clGetDeviceInfo( device.get_device_id()
, CL_DEVICE_MAX_WORK_GROUP_SIZE
, sizeof(size_t)
, &max_work_group_size
, nullptr
);
const int work_size_locations = 64;
const int work_size_x = pow(2, std::ceil(std::log2(max_work_group_size / work_size_locations)/2)); //The square root of the max size/locations, rounded up to power-of-two
const int work_size_y = max_work_group_size / work_size_locations / work_size_x;
if (err != CL_SUCCESS) throw std::runtime_error("Cannot query max work group size.");
const auto gpu_compile_start = std::chrono::high_resolution_clock::now();
device.source_compile( hog_opencl_cl, hog_opencl_cl_len, {"calc_histogram", "fill_zeros"} );
const auto gpu_copy_start = std::chrono::high_resolution_clock::now();
cl_mem gpu_gray = clCreateBuffer( device.get_context()
, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR
, cpu_gray.elemSize()*cpu_gray.rows*cpu_gray.step1()
, cpu_gray.data
, &err
);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy source image to GPU.");
cl_mem gpu_locations = clCreateBuffer( device.get_context()
, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR
, sizeof(float[2])*num_positions
, locations.data()
, &err
);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy locations array to GPU.");
cl_mem gpu_hist = clCreateBuffer(device.get_context(), CL_MEM_WRITE_ONLY, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, nullptr, &err);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot allocate histogram array.");
device["fill_zeros"](gpu_hist, HISTOGRAM_BINS*num_positions).groupsize({255}, {HISTOGRAM_BINS*num_positions});
const auto gpu_start = std::chrono::high_resolution_clock::now();
device["calc_histogram"]( cpu_gray.rows
, cpu_gray.cols
, (int)cpu_gray.step1()
, gpu_gray
, num_positions
, gpu_locations
, size
, gpu_hist
, carp::opencl::buffer(sizeof(cl_float)*HISTOGRAM_BINS*num_positions)
).groupsize({work_size_locations,work_size_x,work_size_y}, {num_positions, (int)ceil(size), (int)ceil(size)});
const auto gpu_end = std::chrono::high_resolution_clock::now();
err = clEnqueueReadBuffer(device.get_queue(), gpu_hist, CL_TRUE, 0, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, gpu_result.data(), 0, nullptr, nullptr);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy histogram array to host.");
err = clReleaseMemObject(gpu_hist);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free histogram array.");
err = clReleaseMemObject(gpu_locations);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_locations array.");
err = clReleaseMemObject(gpu_gray);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_image array.");
const auto gpu_copy_end = std::chrono::high_resolution_clock::now();
const auto gpu_compile_end = std::chrono::high_resolution_clock::now();
elapsed_time_gpu_p_copy = gpu_copy_end - gpu_copy_start;
elapsed_time_gpu_nocopy = gpu_end - gpu_start;
auto elapsed_time_gpu_compile = gpu_compile_end - gpu_compile_start;
//Free up resources
}
{
pen_result.resize(num_positions * HISTOGRAM_BINS, 0.0f);
const auto pencil_start = std::chrono::high_resolution_clock::now();
pencil_hog( cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>()
, num_positions, reinterpret_cast<const float (*)[2]>(locations.data())
, size
, pen_result.data()
);
const auto pencil_end = std::chrono::high_resolution_clock::now();
elapsed_time_pencil = pencil_end - pencil_start;
//Free up resources
}
// Verifying the results
if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5
|| cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5
)
{
std::vector<float> diff;
std::transform(cpu_result.begin(), cpu_result.end(), gpu_result.begin(), std::back_inserter(diff), std::minus<float>());
std::cerr << "ERROR: Results don't match." << std::endl;
std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl;
std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl;
std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl;
std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl;
std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl;
throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results.");
}
timing.print( elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil );
}
}
}
}
int main(int argc, char* argv[])
{
try {
std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl;
auto pool = carp::get_pool("pool");
#ifdef RUN_ONLY_ONE_EXPERIMENT
time_hog( pool, {64}, 50, 1 );
#else
time_hog( pool, {16, 32, 64, 128, 192}, 50, 10 );
#endif
return EXIT_SUCCESS;
}catch(const std::exception& e) {
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
} // main
<commit_msg>Better groupsize for calling fill_zeros OpenCL kernel<commit_after>#include <chrono>
#include <random>
#include <array>
#include <opencv2/core/core.hpp>
#include <opencv2/ocl/ocl.hpp>
#include "opencl.hpp"
#include "utility.hpp"
#include "hog.pencil.h"
#include "HogDescriptor.h"
#include "hog.clh"
void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat )
{
carp::Timing timing("HOG");
for (;repeat>0; --repeat) {
for ( auto & size : sizes ) {
for ( auto & item : pool ) {
std::mt19937 rng(0); //uses same seed, reseed for all iteration
cv::Mat cpu_gray;
cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY );
static_assert(sizeof(float[2]) == sizeof(std::array<float,2>), "This code needs std::array to behave exactly like C arrays.");
std::vector<std::array<float,2>> locations;
std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1);
std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1);
std::generate_n(std::back_inserter(locations), num_positions, [&](){ return std::array<float,2>{{ genx(rng), geny(rng) }}; });
std::vector<float> cpu_result(num_positions * HISTOGRAM_BINS), gpu_result(num_positions * HISTOGRAM_BINS), pen_result(num_positions * HISTOGRAM_BINS);
std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil;
{
//CPU implement
const auto cpu_start = std::chrono::high_resolution_clock::now();
auto result = nel::HOGDescriptor< NUMBER_OF_CELLS
, NUMBER_OF_BINS
, GAUSSIAN_WEIGHTS
, SPARTIAL_WEIGHTS
, SIGNED_HOG
>::compute(cpu_gray, locations, size);
const auto cpu_end = std::chrono::high_resolution_clock::now();
std::copy(result.begin(), result.end(), cpu_result.begin());
elapsed_time_cpu = cpu_end - cpu_start;
//Free up resources
}
{
carp::opencl::device device;
size_t max_work_group_size;
cl_int err;
err = clGetDeviceInfo( device.get_device_id()
, CL_DEVICE_MAX_WORK_GROUP_SIZE
, sizeof(size_t)
, &max_work_group_size
, nullptr
);
const int work_size_locations = 64;
const int work_size_x = pow(2, std::ceil(std::log2(max_work_group_size / work_size_locations)/2)); //The square root of the max size/locations, rounded up to power-of-two
const int work_size_y = max_work_group_size / work_size_locations / work_size_x;
if (err != CL_SUCCESS) throw std::runtime_error("Cannot query max work group size.");
const auto gpu_compile_start = std::chrono::high_resolution_clock::now();
device.source_compile( hog_opencl_cl, hog_opencl_cl_len, {"calc_histogram", "fill_zeros"} );
const auto gpu_copy_start = std::chrono::high_resolution_clock::now();
cl_mem gpu_gray = clCreateBuffer( device.get_context()
, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR
, cpu_gray.elemSize()*cpu_gray.rows*cpu_gray.step1()
, cpu_gray.data
, &err
);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy source image to GPU.");
cl_mem gpu_locations = clCreateBuffer( device.get_context()
, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR
, sizeof(float[2])*num_positions
, locations.data()
, &err
);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy locations array to GPU.");
cl_mem gpu_hist = clCreateBuffer(device.get_context(), CL_MEM_WRITE_ONLY, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, nullptr, &err);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot allocate histogram array.");
device["fill_zeros"](gpu_hist, HISTOGRAM_BINS*num_positions).groupsize({std::min<size_t>(max_work_group_size, HISTOGRAM_BINS*num_positions)}, {HISTOGRAM_BINS*num_positions});
const auto gpu_start = std::chrono::high_resolution_clock::now();
device["calc_histogram"]( cpu_gray.rows
, cpu_gray.cols
, (int)cpu_gray.step1()
, gpu_gray
, num_positions
, gpu_locations
, size
, gpu_hist
, carp::opencl::buffer(sizeof(cl_float)*HISTOGRAM_BINS*num_positions)
).groupsize({work_size_locations,work_size_x,work_size_y}, {num_positions, (int)ceil(size), (int)ceil(size)});
const auto gpu_end = std::chrono::high_resolution_clock::now();
err = clEnqueueReadBuffer(device.get_queue(), gpu_hist, CL_TRUE, 0, sizeof(cl_float)*HISTOGRAM_BINS*num_positions, gpu_result.data(), 0, nullptr, nullptr);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot copy histogram array to host.");
err = clReleaseMemObject(gpu_hist);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free histogram array.");
err = clReleaseMemObject(gpu_locations);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_locations array.");
err = clReleaseMemObject(gpu_gray);
if (err != CL_SUCCESS) throw std::runtime_error("Cannot free gpu_image array.");
const auto gpu_copy_end = std::chrono::high_resolution_clock::now();
const auto gpu_compile_end = std::chrono::high_resolution_clock::now();
elapsed_time_gpu_p_copy = gpu_copy_end - gpu_copy_start;
elapsed_time_gpu_nocopy = gpu_end - gpu_start;
auto elapsed_time_gpu_compile = gpu_compile_end - gpu_compile_start;
//Free up resources
}
{
pen_result.resize(num_positions * HISTOGRAM_BINS, 0.0f);
const auto pencil_start = std::chrono::high_resolution_clock::now();
pencil_hog( cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>()
, num_positions, reinterpret_cast<const float (*)[2]>(locations.data())
, size
, pen_result.data()
);
const auto pencil_end = std::chrono::high_resolution_clock::now();
elapsed_time_pencil = pencil_end - pencil_start;
//Free up resources
}
// Verifying the results
if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5
|| cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5
)
{
std::vector<float> diff;
std::transform(cpu_result.begin(), cpu_result.end(), gpu_result.begin(), std::back_inserter(diff), std::minus<float>());
std::cerr << "ERROR: Results don't match." << std::endl;
std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl;
std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl;
std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl;
std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl;
std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl;
throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results.");
}
timing.print( elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil );
}
}
}
}
int main(int argc, char* argv[])
{
try {
std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl;
auto pool = carp::get_pool("pool");
#ifdef RUN_ONLY_ONE_EXPERIMENT
time_hog( pool, {64}, 50, 1 );
#else
time_hog( pool, {16, 32, 64, 128, 192}, 50, 10 );
#endif
return EXIT_SUCCESS;
}catch(const std::exception& e) {
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
} // main
<|endoftext|>
|
<commit_before>#include "RenderTarget.h"
#include <unirender/UR_RenderContext.h>
#include <shaderlab/ShaderMgr.h>
#include <shaderlab/Sprite2Shader.h>
#include <shaderlab/FilterShader.h>
#include <shaderlab/ShaderMgr.h>
#include <sprite2/RenderScissor.h>
#include <sprite2/RenderCtxStack.h>
namespace gum
{
RenderTarget::RenderTarget(int width, int height)
: s2::RenderTarget(width, height)
{
}
void RenderTarget::Bind()
{
s2::RenderScissor::Instance()->Disable();
int w = Width(),
h = Height();
s2::RenderContext ctx(w, h, w, h);
// use last model view
const s2::RenderContext* last = s2::RenderCtxStack::Instance()->Top();
if (last) {
ctx.SetModelView(last->GetMVOffset(), last->GetMVScale());
}
s2::RenderCtxStack::Instance()->Push(ctx);
s2::RenderTarget::Bind();
}
void RenderTarget::Unbind()
{
s2::RenderCtxStack::Instance()->Pop();
s2::RenderScissor::Instance()->Enable();
s2::RenderTarget::Unbind();
}
void RenderTarget::Draw(const sm::rect& src, const sm::rect& dst, int dst_w, int dst_h) const
{
sl::ShaderMgr::Instance()->FlushShader();
float vertices[8], texcoords[8];
float w, h;
if (dst_w != 0 && dst_h != 0) {
w = dst_w;
h = dst_h;
} else {
w = Width();
h = Height();
}
s2::RenderScissor::Instance()->Disable();
s2::RenderCtxStack::Instance()->Push(s2::RenderContext(w, h, w, h));
float hw = w * 0.5f,
hh = h * 0.5f;
vertices[0] = w * dst.xmin - hw; vertices[1] = h * dst.ymin - hh;
vertices[2] = w * dst.xmax - hw; vertices[3] = h * dst.ymin - hh;
vertices[4] = w * dst.xmax - hw; vertices[5] = h * dst.ymax - hh;
vertices[6] = w * dst.xmin - hw; vertices[7] = h * dst.ymax - hh;
texcoords[0] = src.xmin; texcoords[1] = src.ymin;
texcoords[2] = src.xmax; texcoords[3] = src.ymin;
texcoords[4] = src.xmax; texcoords[5] = src.ymax;
texcoords[6] = src.xmin; texcoords[7] = src.ymax;
sl::ShaderMgr* sl_mgr = sl::ShaderMgr::Instance();
switch (sl_mgr->GetShaderType())
{
case sl::SPRITE2:
{
sl::Sprite2Shader* shader = static_cast<sl::Sprite2Shader*>(sl_mgr->GetShader());
shader->SetColor(0xffffffff, 0);
shader->SetColorMap(0x000000ff, 0x0000ff00, 0x00ff0000);
shader->DrawQuad(vertices, texcoords, GetTexID());
}
break;
case sl::FILTER:
{
sl::FilterShader* shader = static_cast<sl::FilterShader*>(sl_mgr->GetShader());
shader->SetColor(0xffffffff, 0);
shader->Draw(vertices, texcoords, GetTexID());
}
break;
default:
break;
}
s2::RenderCtxStack::Instance()->Pop();
s2::RenderScissor::Instance()->Enable();
}
void RenderTarget::Clear()
{
Bind();
sl::ShaderMgr* mgr = sl::ShaderMgr::Instance();
mgr->GetContext()->Clear(0);
Unbind();
}
}<commit_msg>[FIXED] rt draw, use last viewport<commit_after>#include "RenderTarget.h"
#include <unirender/UR_RenderContext.h>
#include <shaderlab/ShaderMgr.h>
#include <shaderlab/Sprite2Shader.h>
#include <shaderlab/FilterShader.h>
#include <shaderlab/ShaderMgr.h>
#include <sprite2/RenderScissor.h>
#include <sprite2/RenderCtxStack.h>
namespace gum
{
RenderTarget::RenderTarget(int width, int height)
: s2::RenderTarget(width, height)
{
}
void RenderTarget::Bind()
{
s2::RenderScissor::Instance()->Disable();
int w = Width(),
h = Height();
s2::RenderContext ctx(w, h, w, h);
// use last model view
const s2::RenderContext* last = s2::RenderCtxStack::Instance()->Top();
if (last) {
ctx.SetModelView(last->GetMVOffset(), last->GetMVScale());
}
s2::RenderCtxStack::Instance()->Push(ctx);
s2::RenderTarget::Bind();
}
void RenderTarget::Unbind()
{
s2::RenderCtxStack::Instance()->Pop();
s2::RenderScissor::Instance()->Enable();
s2::RenderTarget::Unbind();
}
void RenderTarget::Draw(const sm::rect& src, const sm::rect& dst, int dst_w, int dst_h) const
{
sl::ShaderMgr::Instance()->FlushShader();
float vertices[8], texcoords[8];
float w, h;
if (dst_w != 0 && dst_h != 0) {
w = dst_w;
h = dst_h;
} else {
w = Width();
h = Height();
}
const s2::RenderContext* last = s2::RenderCtxStack::Instance()->Top();
int vp_x, vp_y, vp_w, vp_h;
if (last) {
last->GetViewport(vp_x, vp_y, vp_w, vp_h);
}
s2::RenderScissor::Instance()->Disable();
s2::RenderCtxStack::Instance()->Push(s2::RenderContext(w, h, w, h));
if (last) {
const s2::RenderContext* curr = s2::RenderCtxStack::Instance()->Top();
const_cast<s2::RenderContext*>(curr)->SetViewport(vp_x, vp_y, vp_w, vp_h);
}
float hw = w * 0.5f,
hh = h * 0.5f;
vertices[0] = w * dst.xmin - hw; vertices[1] = h * dst.ymin - hh;
vertices[2] = w * dst.xmax - hw; vertices[3] = h * dst.ymin - hh;
vertices[4] = w * dst.xmax - hw; vertices[5] = h * dst.ymax - hh;
vertices[6] = w * dst.xmin - hw; vertices[7] = h * dst.ymax - hh;
texcoords[0] = src.xmin; texcoords[1] = src.ymin;
texcoords[2] = src.xmax; texcoords[3] = src.ymin;
texcoords[4] = src.xmax; texcoords[5] = src.ymax;
texcoords[6] = src.xmin; texcoords[7] = src.ymax;
sl::ShaderMgr* sl_mgr = sl::ShaderMgr::Instance();
switch (sl_mgr->GetShaderType())
{
case sl::SPRITE2:
{
sl::Sprite2Shader* shader = static_cast<sl::Sprite2Shader*>(sl_mgr->GetShader());
shader->SetColor(0xffffffff, 0);
shader->SetColorMap(0x000000ff, 0x0000ff00, 0x00ff0000);
shader->DrawQuad(vertices, texcoords, GetTexID());
}
break;
case sl::FILTER:
{
sl::FilterShader* shader = static_cast<sl::FilterShader*>(sl_mgr->GetShader());
shader->SetColor(0xffffffff, 0);
shader->Draw(vertices, texcoords, GetTexID());
}
break;
default:
break;
}
s2::RenderCtxStack::Instance()->Pop();
s2::RenderScissor::Instance()->Enable();
}
void RenderTarget::Clear()
{
Bind();
sl::ShaderMgr* mgr = sl::ShaderMgr::Instance();
mgr->GetContext()->Clear(0);
Unbind();
}
}<|endoftext|>
|
<commit_before>#include <memory>
#include <svgren/render.hpp>
// Some bad stuff defines OVERFLOW macro and there is an enum value with same name in svgdom/dom.h.
#ifdef OVERFLOW
# undef OVERFLOW
#endif
#include <svgdom/dom.hpp>
#include "image.hpp"
#include "../context.hpp"
#include "../util/util.hpp"
using namespace morda;
using namespace morda::res;
image::image(std::shared_ptr<morda::context> c) :
resource(std::move(c))
{}
atlas_image::atlas_image(std::shared_ptr<morda::context> c, std::shared_ptr<res::texture> tex, const rectangle& rect) :
image(std::move(c)),
image::texture(this->context->renderer, rect.d.abs()),
tex(std::move(tex))
{
// this->texCoords[3] = vector2(rect.left(), this->tex->tex().dim().y - rect.bottom()).compDivBy(this->tex->tex().dim());
// this->texCoords[2] = vector2(rect.right(), this->tex->tex().dim().y - rect.bottom()).compDivBy(this->tex->tex().dim());
// this->texCoords[1] = vector2(rect.right(), this->tex->tex().dim().y - rect.top()).compDivBy(this->tex->tex().dim());
// this->texCoords[0] = vector2(rect.left(), this->tex->tex().dim().y - rect.top()).compDivBy(this->tex->tex().dim());
//TODO:
ASSERT(false)
}
atlas_image::atlas_image(std::shared_ptr<morda::context> c, std::shared_ptr<res::texture> tex) :
image(std::move(c)),
image::texture(this->context->renderer, tex->tex().dims()),
tex(std::move(tex)),
vao(this->context->renderer->pos_tex_quad_01_vao)
{}
std::shared_ptr<atlas_image> atlas_image::load(morda::context& ctx, const puu::forest& desc, const papki::file& fi){
std::shared_ptr<res::texture> tex;
rectangle rect(-1, -1);
for(auto& p : desc){
if(p.value == "tex"){
tex = ctx.loader.load<res::texture>(get_property_value(p).to_string());
}else if(p.value == "rect"){
rect = parse_rect(p.children);
}
}
if(!tex){
throw std::runtime_error("atlas_image::load(): could not load texture");
}
if(rect.p.x() >= 0){
return std::make_shared<atlas_image>(utki::make_shared_from(ctx), tex, rect);
}else{
return std::make_shared<atlas_image>(utki::make_shared_from(ctx), tex);
}
}
void atlas_image::render(const matrix4& matrix, const vertex_array& vao)const{
this->context->renderer->shader->pos_tex->render(matrix, *this->vao, this->tex->tex());
}
std::shared_ptr<const image::texture> atlas_image::get(vector2 forDim)const{
return utki::make_shared_from(*this);
}
namespace{
class fixed_texture : public image::texture{
protected:
std::shared_ptr<texture_2d> tex_v;
fixed_texture(std::shared_ptr<morda::renderer> r, std::shared_ptr<texture_2d> tex) :
image::texture(std::move(r), tex->dims()),
tex_v(std::move(tex))
{}
public:
void render(const matrix4& matrix, const vertex_array& vao)const override{
this->renderer->shader->pos_tex->render(matrix, vao, *this->tex_v);
}
};
class res_raster_image :
public image,
public fixed_texture
{
public:
res_raster_image(std::shared_ptr<morda::context> c, std::shared_ptr<texture_2d> tex) :
image(std::move(c)),
fixed_texture(this->context->renderer, std::move(tex))
{}
std::shared_ptr<const image::texture> get(vector2 forDim)const override{
return utki::make_shared_from(*this);
}
vector2 dims(real dpi)const noexcept override{
return this->tex_v->dims();
}
static std::shared_ptr<res_raster_image> load(morda::context& ctx, const papki::file& fi){
return std::make_shared<res_raster_image>(utki::make_shared_from(ctx), load_texture(*ctx.renderer, fi));
}
};
class res_svg_image : public image{
std::unique_ptr<svgdom::svg_element> dom;
public:
res_svg_image(std::shared_ptr<morda::context> c, decltype(dom) dom) :
image(std::move(c)),
dom(std::move(dom))
{}
vector2 dims(real dpi)const noexcept override{
auto wh = this->dom->get_dimensions(dpi);
using std::ceil;
return vector2(ceil(wh[0]), ceil(wh[1]));
}
class svg_texture : public fixed_texture{
std::weak_ptr<const res_svg_image> parent;
public:
svg_texture(std::shared_ptr<morda::renderer> r, std::shared_ptr<const res_svg_image> parent, std::shared_ptr<texture_2d> tex) :
fixed_texture(std::move(r), std::move(tex)),
parent(parent)
{}
~svg_texture()noexcept{
if(auto p = this->parent.lock()){
r4::vector2<unsigned> d = this->tex_v->dims().to<unsigned>();
p->cache.erase(std::make_tuple(d.x(), d.y()));
}
}
};
std::shared_ptr<const texture> get(vector2 forDim)const override{
// TRACE(<< "forDim = " << forDim << std::endl)
unsigned width = unsigned(forDim.x());
// TRACE(<< "imWidth = " << imWidth << std::endl)
unsigned height = unsigned(forDim.y());
// TRACE(<< "imHeight = " << imHeight << std::endl)
{ // check if in cache
auto i = this->cache.find(std::make_tuple(width, height));
if(i != this->cache.end()){
if(auto p = i->second.lock()){
return p;
}
}
}
// TRACE(<< "not in cache" << std::endl)
ASSERT(this->dom)
// TRACE(<< "width = " << this->dom->width << std::endl)
// TRACE(<< "height = " << this->dom->height << std::endl)
// TRACE(<< "dpi = " << morda::gui::inst().units.dpi() << std::endl)
// TRACE(<< "id = " << this->dom->id << std::endl)
svgren::parameters svgParams;
svgParams.dpi = this->context->units.dots_per_inch;
svgParams.width_request = width;
svgParams.height_request = height;
auto svg = svgren::render(*this->dom, svgParams);
ASSERT(svg.width != 0)
ASSERT(svg.height != 0)
ASSERT_INFO(svg.width * svg.height == svg.pixels.size(), "imWidth = " << svg.width << " imHeight = " << svg.height << " pixels.size() = " << svg.pixels.size())
auto img = std::make_shared<svg_texture>(
this->context->renderer,
utki::make_shared_from(*this),
this->context->renderer->factory->create_texture_2d(r4::vector2<unsigned>(svg.width, svg.height), utki::make_span(svg.pixels))
);
this->cache[std::make_tuple(svg.width, svg.height)] = img;
return img;
}
mutable std::map<std::tuple<unsigned, unsigned>, std::weak_ptr<texture>> cache;
static std::shared_ptr<res_svg_image> load(morda::context& ctx, const papki::file& fi){
return std::make_shared<res_svg_image>(utki::make_shared_from(ctx), svgdom::load(fi));
}
};
}
std::shared_ptr<image> image::load(morda::context& ctx, const puu::forest& desc, const papki::file& fi) {
for(auto& p : desc){
if(p.value == "file"){
fi.set_path(get_property_value(p).to_string());
return image::load(ctx, fi);
}
}
return atlas_image::load(ctx, desc, fi);
}
std::shared_ptr<image> image::load(morda::context& ctx, const papki::file& fi) {
if(fi.suffix().compare("svg") == 0){
return res_svg_image::load(ctx, fi);
}else{
return res_raster_image::load(ctx, fi);
}
}
<commit_msg>stuff<commit_after>#include <memory>
#include <svgren/render.hpp>
// Some bad stuff defines OVERFLOW macro and there is an enum value with same name in svgdom/dom.h.
#ifdef OVERFLOW
# undef OVERFLOW
#endif
#include <svgdom/dom.hpp>
#include "image.hpp"
#include "../context.hpp"
#include "../util/util.hpp"
using namespace morda;
using namespace morda::res;
image::image(std::shared_ptr<morda::context> c) :
resource(std::move(c))
{}
atlas_image::atlas_image(std::shared_ptr<morda::context> c, std::shared_ptr<res::texture> tex, const rectangle& rect) :
image(std::move(c)),
image::texture(this->context->renderer, rect.d.abs()),
tex(std::move(tex))
{
// this->texCoords[3] = vector2(rect.left(), this->tex->tex().dim().y - rect.bottom()).compDivBy(this->tex->tex().dim());
// this->texCoords[2] = vector2(rect.right(), this->tex->tex().dim().y - rect.bottom()).compDivBy(this->tex->tex().dim());
// this->texCoords[1] = vector2(rect.right(), this->tex->tex().dim().y - rect.top()).compDivBy(this->tex->tex().dim());
// this->texCoords[0] = vector2(rect.left(), this->tex->tex().dim().y - rect.top()).compDivBy(this->tex->tex().dim());
//TODO:
ASSERT(false)
}
atlas_image::atlas_image(std::shared_ptr<morda::context> c, std::shared_ptr<res::texture> tex) :
image(std::move(c)),
image::texture(this->context->renderer, tex->tex().dims()),
tex(std::move(tex)),
vao(this->context->renderer->pos_tex_quad_01_vao)
{}
std::shared_ptr<atlas_image> atlas_image::load(morda::context& ctx, const puu::forest& desc, const papki::file& fi){
std::shared_ptr<res::texture> tex;
rectangle rect(-1, -1);
for(auto& p : desc){
if(p.value == "tex"){
tex = ctx.loader.load<res::texture>(get_property_value(p).to_string());
}else if(p.value == "rect"){
rect = parse_rect(p.children);
}
}
if(!tex){
throw std::runtime_error("atlas_image::load(): could not load texture");
}
if(rect.p.x() >= 0){
return std::make_shared<atlas_image>(utki::make_shared_from(ctx), tex, rect);
}else{
return std::make_shared<atlas_image>(utki::make_shared_from(ctx), tex);
}
}
void atlas_image::render(const matrix4& matrix, const vertex_array& vao)const{
this->context->renderer->shader->pos_tex->render(matrix, *this->vao, this->tex->tex());
}
std::shared_ptr<const image::texture> atlas_image::get(vector2 forDim)const{
return utki::make_shared_from(*this);
}
namespace{
class fixed_texture : public image::texture{
protected:
std::shared_ptr<texture_2d> tex_v;
fixed_texture(std::shared_ptr<morda::renderer> r, std::shared_ptr<texture_2d> tex) :
image::texture(std::move(r), tex->dims()),
tex_v(std::move(tex))
{}
public:
void render(const matrix4& matrix, const vertex_array& vao)const override{
this->renderer->shader->pos_tex->render(matrix, vao, *this->tex_v);
}
};
class res_raster_image :
public image,
public fixed_texture
{
public:
res_raster_image(std::shared_ptr<morda::context> c, std::shared_ptr<texture_2d> tex) :
image(std::move(c)),
fixed_texture(this->context->renderer, std::move(tex))
{}
std::shared_ptr<const image::texture> get(vector2 forDim)const override{
return utki::make_shared_from(*this);
}
vector2 dims(real dpi)const noexcept override{
return this->tex_v->dims();
}
static std::shared_ptr<res_raster_image> load(morda::context& ctx, const papki::file& fi){
return std::make_shared<res_raster_image>(utki::make_shared_from(ctx), load_texture(*ctx.renderer, fi));
}
};
class res_svg_image : public image{
std::unique_ptr<svgdom::svg_element> dom;
public:
res_svg_image(std::shared_ptr<morda::context> c, decltype(dom) dom) :
image(std::move(c)),
dom(std::move(dom))
{}
vector2 dims(real dpi)const noexcept override{
auto wh = this->dom->get_dimensions(dpi);
using std::ceil;
return vector2(ceil(wh[0]), ceil(wh[1]));
}
class svg_texture : public fixed_texture{
std::weak_ptr<const res_svg_image> parent;
public:
svg_texture(std::shared_ptr<morda::renderer> r, std::shared_ptr<const res_svg_image> parent, std::shared_ptr<texture_2d> tex) :
fixed_texture(std::move(r), std::move(tex)),
parent(parent)
{}
~svg_texture()noexcept{
if(auto p = this->parent.lock()){
r4::vector2<unsigned> d = this->tex_v->dims().to<unsigned>();
p->cache.erase(std::make_tuple(d.x(), d.y()));
}
}
};
std::shared_ptr<const texture> get(vector2 forDim)const override{
// TRACE(<< "forDim = " << forDim << std::endl)
unsigned width = unsigned(forDim.x());
// TRACE(<< "imWidth = " << imWidth << std::endl)
unsigned height = unsigned(forDim.y());
// TRACE(<< "imHeight = " << imHeight << std::endl)
{ // check if in cache
auto i = this->cache.find(std::make_tuple(width, height));
if(i != this->cache.end()){
if(auto p = i->second.lock()){
return p;
}
}
}
// TRACE(<< "not in cache" << std::endl)
ASSERT(this->dom)
// TRACE(<< "width = " << this->dom->width << std::endl)
// TRACE(<< "height = " << this->dom->height << std::endl)
// TRACE(<< "dpi = " << morda::gui::inst().units.dpi() << std::endl)
// TRACE(<< "id = " << this->dom->id << std::endl)
svgren::parameters svg_params;
svg_params.dpi = unsigned(this->context->units.dots_per_inch);
svg_params.width_request = width;
svg_params.height_request = height;
auto svg = svgren::render(*this->dom, svg_params);
ASSERT(svg.width != 0)
ASSERT(svg.height != 0)
ASSERT_INFO(svg.width * svg.height == svg.pixels.size(), "imWidth = " << svg.width << " imHeight = " << svg.height << " pixels.size() = " << svg.pixels.size())
auto img = std::make_shared<svg_texture>(
this->context->renderer,
utki::make_shared_from(*this),
this->context->renderer->factory->create_texture_2d(r4::vector2<unsigned>(svg.width, svg.height), utki::make_span(svg.pixels))
);
this->cache[std::make_tuple(svg.width, svg.height)] = img;
return img;
}
mutable std::map<std::tuple<unsigned, unsigned>, std::weak_ptr<texture>> cache;
static std::shared_ptr<res_svg_image> load(morda::context& ctx, const papki::file& fi){
return std::make_shared<res_svg_image>(utki::make_shared_from(ctx), svgdom::load(fi));
}
};
}
std::shared_ptr<image> image::load(morda::context& ctx, const puu::forest& desc, const papki::file& fi) {
for(auto& p : desc){
if(p.value == "file"){
fi.set_path(get_property_value(p).to_string());
return image::load(ctx, fi);
}
}
return atlas_image::load(ctx, desc, fi);
}
std::shared_ptr<image> image::load(morda::context& ctx, const papki::file& fi) {
if(fi.suffix().compare("svg") == 0){
return res_svg_image::load(ctx, fi);
}else{
return res_raster_image::load(ctx, fi);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwsh9.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:58:55 $
*
* 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_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <svx/svdmark.hxx>
#include <svx/svdview.hxx>
#include <svx/galbrws.hxx>
#include <svx/gallery.hxx>
#include <svx/hlnkitem.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/dispatch.hxx>
#include <svtools/whiter.hxx>
#include <avmedia/mediaplayer.hxx>
#include "tabvwsh.hxx"
#include "viewdata.hxx"
#include "tabview.hxx"
#include "drwlayer.hxx"
#include "userdat.hxx"
#include "docsh.hxx"
// forwards -> galwrap.cxx (wg. CLOOKs)
USHORT GallerySGA_FORMAT_GRAPHIC();
Graphic GalleryGetGraphic ();
BOOL GalleryIsLinkage ();
String GalleryGetFullPath ();
String GalleryGetFilterName ();
// forwards -> imapwrap.cxx (wg. CLOOKs)
class SvxIMapDlg;
USHORT ScIMapChildWindowId();
SvxIMapDlg* ScGetIMapDlg();
const void* ScIMapDlgGetObj( SvxIMapDlg* pDlg );
const ImageMap& ScIMapDlgGetMap( SvxIMapDlg* pDlg );
//------------------------------------------------------------------
void ScTabViewShell::ExecChildWin(SfxRequest& rReq)
{
USHORT nSlot = rReq.GetSlot();
switch(nSlot)
{
case SID_GALLERY:
{
SfxViewFrame* pThisFrame = GetViewFrame();
pThisFrame->ToggleChildWindow( GalleryChildWindow::GetChildWindowId() );
pThisFrame->GetBindings().Invalidate( SID_GALLERY );
rReq.Ignore();
}
break;
case SID_AVMEDIA_PLAYER:
{
SfxViewFrame* pThisFrame = GetViewFrame();
pThisFrame->ToggleChildWindow( ::avmedia::MediaPlayer::GetChildWindowId() );
pThisFrame->GetBindings().Invalidate( SID_AVMEDIA_PLAYER );
rReq.Ignore();
}
break;
}
}
void ScTabViewShell::GetChildWinState( SfxItemSet& rSet )
{
if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_GALLERY ) )
{
USHORT nId = GalleryChildWindow::GetChildWindowId();
rSet.Put( SfxBoolItem( SID_GALLERY, GetViewFrame()->HasChildWindow( nId ) ) );
}
else if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_AVMEDIA_PLAYER ) )
{
USHORT nId = ::avmedia::MediaPlayer::GetChildWindowId();
rSet.Put( SfxBoolItem( SID_AVMEDIA_PLAYER, GetViewFrame()->HasChildWindow( nId ) ) );
}
}
//------------------------------------------------------------------
void ScTabViewShell::ExecGallery( SfxRequest& rReq )
{
const SfxItemSet* pArgs = rReq.GetArgs();
if ( pArgs )
{
const SfxPoolItem* pItem = NULL;
SfxItemState eState = pArgs->GetItemState(SID_GALLERY_FORMATS, TRUE, &pItem);
if ( eState == SFX_ITEM_SET )
{
UINT32 nFormats = ((const SfxUInt32Item*)pItem)->GetValue();
/******************************************************************
* Graphik einfuegen
******************************************************************/
if ( nFormats & GallerySGA_FORMAT_GRAPHIC() )
{
MakeDrawLayer();
Graphic aGraphic = GalleryGetGraphic();
Point aPos = GetInsertPos();
String aPath, aFilter;
if ( GalleryIsLinkage() ) // als Link einfuegen?
{
aPath = GalleryGetFullPath();
aFilter = GalleryGetFilterName();
}
PasteGraphic( aPos, aGraphic, aPath, aFilter );
}
else if ( nFormats & SGA_FORMAT_SOUND )
{
// #98115# for sounds (linked or not), insert a hyperlink button,
// like in Impress and Writer
GalleryExplorer* pGal = SVX_GALLERY();
if ( pGal )
{
const SfxStringItem aMediaURLItem( SID_INSERT_AVMEDIA, pGal->GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
GetViewFrame()->GetDispatcher()->Execute( SID_INSERT_AVMEDIA, SFX_CALLMODE_SYNCHRON, &aMediaURLItem, 0L );
}
}
}
}
}
void ScTabViewShell::GetGalleryState( SfxItemSet& /* rSet */ )
{
}
//------------------------------------------------------------------
ScInputHandler* ScTabViewShell::GetInputHandler() const
{
return pInputHandler;
}
//------------------------------------------------------------------
String __EXPORT ScTabViewShell::GetDescription() const
{
return String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(" ** Test ** "));
}
void ScTabViewShell::ExecImageMap( SfxRequest& rReq )
{
USHORT nSlot = rReq.GetSlot();
switch(nSlot)
{
case SID_IMAP:
{
SfxViewFrame* pThisFrame = GetViewFrame();
USHORT nId = ScIMapChildWindowId();
pThisFrame->ToggleChildWindow( nId );
GetViewFrame()->GetBindings().Invalidate( SID_IMAP );
if ( pThisFrame->HasChildWindow( nId ) )
{
SvxIMapDlg* pDlg = ScGetIMapDlg();
if ( pDlg )
{
SdrView* pDrView = GetSdrView();
if ( pDrView )
{
const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
if ( rMarkList.GetMarkCount() == 1 )
UpdateIMap( rMarkList.GetMark( 0 )->GetMarkedSdrObj() );
}
}
}
rReq.Ignore();
}
break;
case SID_IMAP_EXEC:
{
SdrView* pDrView = GetSdrView();
SdrMark* pMark = pDrView ? pDrView->GetMarkedObjectList().GetMark(0) : 0;
if ( pMark )
{
SdrObject* pSdrObj = pMark->GetMarkedSdrObj();
SvxIMapDlg* pDlg = ScGetIMapDlg();
if ( ScIMapDlgGetObj(pDlg) == (void*) pSdrObj )
{
const ImageMap& rImageMap = ScIMapDlgGetMap(pDlg);
ScIMapInfo* pIMapInfo = ScDrawLayer::GetIMapInfo( pSdrObj );
if ( !pIMapInfo )
pSdrObj->InsertUserData( new ScIMapInfo( rImageMap ) );
else
pIMapInfo->SetImageMap( rImageMap );
GetViewData()->GetDocShell()->SetDrawModified();
}
}
}
break;
}
}
void ScTabViewShell::GetImageMapState( SfxItemSet& rSet )
{
SfxWhichIter aIter(rSet);
USHORT nWhich = aIter.FirstWhich();
while ( nWhich )
{
switch ( nWhich )
{
case SID_IMAP:
{
// Disabled wird nicht mehr...
BOOL bThere = FALSE;
SfxViewFrame* pThisFrame = GetViewFrame();
USHORT nId = ScIMapChildWindowId();
if ( pThisFrame->KnowsChildWindow(nId) )
if ( pThisFrame->HasChildWindow(nId) )
bThere = TRUE;
ObjectSelectionType eType=GetCurObjectSelectionType();
BOOL bEnable=(eType==OST_OleObject) ||(eType==OST_Graphic);
if(!bThere && !bEnable)
{
rSet.DisableItem( nWhich );
}
else
{
rSet.Put( SfxBoolItem( nWhich, bThere ) );
}
}
break;
case SID_IMAP_EXEC:
{
BOOL bDisable = TRUE;
SdrView* pDrView = GetSdrView();
if ( pDrView )
{
const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
if ( rMarkList.GetMarkCount() == 1 )
if ( ScIMapDlgGetObj(ScGetIMapDlg()) ==
(void*) rMarkList.GetMark(0)->GetMarkedSdrObj() )
bDisable = FALSE;
}
rSet.Put( SfxBoolItem( SID_IMAP_EXEC, bDisable ) );
}
break;
}
nWhich = aIter.NextWhich();
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.11.330); FILE MERGED 2008/03/31 17:20:02 rt 1.11.330.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwsh9.cxx,v $
* $Revision: 1.12 $
*
* 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_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <svx/svdmark.hxx>
#include <svx/svdview.hxx>
#include <svx/galbrws.hxx>
#include <svx/gallery.hxx>
#include <svx/hlnkitem.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/dispatch.hxx>
#include <svtools/whiter.hxx>
#include <avmedia/mediaplayer.hxx>
#include "tabvwsh.hxx"
#include "viewdata.hxx"
#include "tabview.hxx"
#include "drwlayer.hxx"
#include "userdat.hxx"
#include "docsh.hxx"
// forwards -> galwrap.cxx (wg. CLOOKs)
USHORT GallerySGA_FORMAT_GRAPHIC();
Graphic GalleryGetGraphic ();
BOOL GalleryIsLinkage ();
String GalleryGetFullPath ();
String GalleryGetFilterName ();
// forwards -> imapwrap.cxx (wg. CLOOKs)
class SvxIMapDlg;
USHORT ScIMapChildWindowId();
SvxIMapDlg* ScGetIMapDlg();
const void* ScIMapDlgGetObj( SvxIMapDlg* pDlg );
const ImageMap& ScIMapDlgGetMap( SvxIMapDlg* pDlg );
//------------------------------------------------------------------
void ScTabViewShell::ExecChildWin(SfxRequest& rReq)
{
USHORT nSlot = rReq.GetSlot();
switch(nSlot)
{
case SID_GALLERY:
{
SfxViewFrame* pThisFrame = GetViewFrame();
pThisFrame->ToggleChildWindow( GalleryChildWindow::GetChildWindowId() );
pThisFrame->GetBindings().Invalidate( SID_GALLERY );
rReq.Ignore();
}
break;
case SID_AVMEDIA_PLAYER:
{
SfxViewFrame* pThisFrame = GetViewFrame();
pThisFrame->ToggleChildWindow( ::avmedia::MediaPlayer::GetChildWindowId() );
pThisFrame->GetBindings().Invalidate( SID_AVMEDIA_PLAYER );
rReq.Ignore();
}
break;
}
}
void ScTabViewShell::GetChildWinState( SfxItemSet& rSet )
{
if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_GALLERY ) )
{
USHORT nId = GalleryChildWindow::GetChildWindowId();
rSet.Put( SfxBoolItem( SID_GALLERY, GetViewFrame()->HasChildWindow( nId ) ) );
}
else if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_AVMEDIA_PLAYER ) )
{
USHORT nId = ::avmedia::MediaPlayer::GetChildWindowId();
rSet.Put( SfxBoolItem( SID_AVMEDIA_PLAYER, GetViewFrame()->HasChildWindow( nId ) ) );
}
}
//------------------------------------------------------------------
void ScTabViewShell::ExecGallery( SfxRequest& rReq )
{
const SfxItemSet* pArgs = rReq.GetArgs();
if ( pArgs )
{
const SfxPoolItem* pItem = NULL;
SfxItemState eState = pArgs->GetItemState(SID_GALLERY_FORMATS, TRUE, &pItem);
if ( eState == SFX_ITEM_SET )
{
UINT32 nFormats = ((const SfxUInt32Item*)pItem)->GetValue();
/******************************************************************
* Graphik einfuegen
******************************************************************/
if ( nFormats & GallerySGA_FORMAT_GRAPHIC() )
{
MakeDrawLayer();
Graphic aGraphic = GalleryGetGraphic();
Point aPos = GetInsertPos();
String aPath, aFilter;
if ( GalleryIsLinkage() ) // als Link einfuegen?
{
aPath = GalleryGetFullPath();
aFilter = GalleryGetFilterName();
}
PasteGraphic( aPos, aGraphic, aPath, aFilter );
}
else if ( nFormats & SGA_FORMAT_SOUND )
{
// #98115# for sounds (linked or not), insert a hyperlink button,
// like in Impress and Writer
GalleryExplorer* pGal = SVX_GALLERY();
if ( pGal )
{
const SfxStringItem aMediaURLItem( SID_INSERT_AVMEDIA, pGal->GetURL().GetMainURL( INetURLObject::NO_DECODE ) );
GetViewFrame()->GetDispatcher()->Execute( SID_INSERT_AVMEDIA, SFX_CALLMODE_SYNCHRON, &aMediaURLItem, 0L );
}
}
}
}
}
void ScTabViewShell::GetGalleryState( SfxItemSet& /* rSet */ )
{
}
//------------------------------------------------------------------
ScInputHandler* ScTabViewShell::GetInputHandler() const
{
return pInputHandler;
}
//------------------------------------------------------------------
String __EXPORT ScTabViewShell::GetDescription() const
{
return String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(" ** Test ** "));
}
void ScTabViewShell::ExecImageMap( SfxRequest& rReq )
{
USHORT nSlot = rReq.GetSlot();
switch(nSlot)
{
case SID_IMAP:
{
SfxViewFrame* pThisFrame = GetViewFrame();
USHORT nId = ScIMapChildWindowId();
pThisFrame->ToggleChildWindow( nId );
GetViewFrame()->GetBindings().Invalidate( SID_IMAP );
if ( pThisFrame->HasChildWindow( nId ) )
{
SvxIMapDlg* pDlg = ScGetIMapDlg();
if ( pDlg )
{
SdrView* pDrView = GetSdrView();
if ( pDrView )
{
const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
if ( rMarkList.GetMarkCount() == 1 )
UpdateIMap( rMarkList.GetMark( 0 )->GetMarkedSdrObj() );
}
}
}
rReq.Ignore();
}
break;
case SID_IMAP_EXEC:
{
SdrView* pDrView = GetSdrView();
SdrMark* pMark = pDrView ? pDrView->GetMarkedObjectList().GetMark(0) : 0;
if ( pMark )
{
SdrObject* pSdrObj = pMark->GetMarkedSdrObj();
SvxIMapDlg* pDlg = ScGetIMapDlg();
if ( ScIMapDlgGetObj(pDlg) == (void*) pSdrObj )
{
const ImageMap& rImageMap = ScIMapDlgGetMap(pDlg);
ScIMapInfo* pIMapInfo = ScDrawLayer::GetIMapInfo( pSdrObj );
if ( !pIMapInfo )
pSdrObj->InsertUserData( new ScIMapInfo( rImageMap ) );
else
pIMapInfo->SetImageMap( rImageMap );
GetViewData()->GetDocShell()->SetDrawModified();
}
}
}
break;
}
}
void ScTabViewShell::GetImageMapState( SfxItemSet& rSet )
{
SfxWhichIter aIter(rSet);
USHORT nWhich = aIter.FirstWhich();
while ( nWhich )
{
switch ( nWhich )
{
case SID_IMAP:
{
// Disabled wird nicht mehr...
BOOL bThere = FALSE;
SfxViewFrame* pThisFrame = GetViewFrame();
USHORT nId = ScIMapChildWindowId();
if ( pThisFrame->KnowsChildWindow(nId) )
if ( pThisFrame->HasChildWindow(nId) )
bThere = TRUE;
ObjectSelectionType eType=GetCurObjectSelectionType();
BOOL bEnable=(eType==OST_OleObject) ||(eType==OST_Graphic);
if(!bThere && !bEnable)
{
rSet.DisableItem( nWhich );
}
else
{
rSet.Put( SfxBoolItem( nWhich, bThere ) );
}
}
break;
case SID_IMAP_EXEC:
{
BOOL bDisable = TRUE;
SdrView* pDrView = GetSdrView();
if ( pDrView )
{
const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
if ( rMarkList.GetMarkCount() == 1 )
if ( ScIMapDlgGetObj(ScGetIMapDlg()) ==
(void*) rMarkList.GetMark(0)->GetMarkedSdrObj() )
bDisable = FALSE;
}
rSet.Put( SfxBoolItem( SID_IMAP_EXEC, bDisable ) );
}
break;
}
nWhich = aIter.NextWhich();
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sc.hxx"
#include <svx/svdundo.hxx>
#include <svx/svdocapt.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/sound.hxx>
#include "svl/zforlist.hxx"
#include "viewfunc.hxx"
#include "detfunc.hxx"
#include "detdata.hxx"
#include "viewdata.hxx"
#include "drwlayer.hxx"
#include "docsh.hxx"
#include "undocell.hxx"
#include "futext.hxx"
#include "docfunc.hxx"
#include "globstr.hrc"
#include "sc.hrc"
#include "fusel.hxx"
#include "reftokenhelper.hxx"
#include "externalrefmgr.hxx"
#include "cell.hxx"
#include <vector>
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::std::vector;
#define D_TIMEFACTOR 86400.0
//==================================================================
void ScViewFunc::DetectiveAddPred()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddPred( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT(); //! use broadcast in DocFunc instead?
}
void ScViewFunc::DetectiveDelPred()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelPred( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveAddSucc()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddSucc( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveDelSucc()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelSucc( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveAddError()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddError( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveDelAll()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelAll( GetViewData()->GetTabNo() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveMarkInvalid()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveMarkInvalid( GetViewData()->GetTabNo() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveRefresh()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().DetectiveRefresh();
if (!bDone)
Sound::Beep();
RecalcPPT();
}
static void lcl_jumpToRange(const ScRange& rRange, ScViewData* pView, ScDocument* pDoc)
{
String aAddrText;
rRange.Format(aAddrText, SCR_ABS_3D, pDoc);
SfxStringItem aPosItem(SID_CURRENTCELL, aAddrText);
SfxBoolItem aUnmarkItem(FN_PARAM_1, TRUE); // remove existing selection
pView->GetDispatcher().Execute(
SID_CURRENTCELL, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD,
&aPosItem, &aUnmarkItem, 0L);
}
void ScViewFunc::MarkAndJumpToRanges(const ScRangeList& rRanges)
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScRangeList aRanges(rRanges);
ScRange* p = aRanges.front();
ScRangeList aRangesToMark;
ScAddress aCurPos = pView->GetCurPos();
size_t ListSize = aRanges.size();
for ( size_t i = 0; i < ListSize; ++i )
{
p = aRanges[i];
// Collect only those ranges that are on the same sheet as the current
// cursor.
if (p->aStart.Tab() == aCurPos.Tab())
aRangesToMark.Append(*p);
}
if (aRangesToMark.empty())
return;
// Jump to the first range of all precedent ranges.
p = aRangesToMark.front();
lcl_jumpToRange(*p, pView, pDocSh->GetDocument());
ListSize = aRangesToMark.size();
for ( size_t i = 0; i < ListSize; ++i )
{
p = aRangesToMark[i];
MarkRange(*p, false, true);
}
}
void ScViewFunc::DetectiveMarkPred()
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
ScMarkData& rMarkData = pView->GetMarkData();
ScAddress aCurPos = pView->GetCurPos();
ScRangeList aRanges;
if (rMarkData.IsMarked() || rMarkData.IsMultiMarked())
rMarkData.FillRangeListWithMarks(&aRanges, false);
else
aRanges.Append(aCurPos);
vector<ScSharedTokenRef> aRefTokens;
pDocSh->GetDocFunc().DetectiveCollectAllPreds(aRanges, aRefTokens);
if (aRefTokens.empty())
// No precedents found. Nothing to do.
return;
ScSharedTokenRef p = aRefTokens.front();
if (ScRefTokenHelper::isExternalRef(p))
{
// This is external. Open the external document if available, and
// jump to the destination.
sal_uInt16 nFileId = p->GetIndex();
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
const String* pPath = pRefMgr->getExternalFileName(nFileId);
ScRange aRange;
if (pPath && ScRefTokenHelper::getRangeFromToken(aRange, p, true))
{
const String& rTabName = p->GetString();
OUStringBuffer aBuf;
aBuf.append(*pPath);
aBuf.append(sal_Unicode('#'));
aBuf.append(rTabName);
aBuf.append(sal_Unicode('.'));
String aRangeStr;
aRange.Format(aRangeStr, SCA_VALID);
aBuf.append(aRangeStr);
ScGlobal::OpenURL(aBuf.makeStringAndClear(), String());
}
return;
}
else
{
ScRange aRange;
ScRefTokenHelper::getRangeFromToken(aRange, p, false);
if (aRange.aStart.Tab() != aCurPos.Tab())
{
// The first precedent range is on a different sheet. Jump to it
// immediately and forget the rest.
lcl_jumpToRange(aRange, pView, pDoc);
return;
}
}
ScRangeList aDestRanges;
ScRefTokenHelper::getRangeListFromTokens(aDestRanges, aRefTokens);
MarkAndJumpToRanges(aDestRanges);
}
void ScViewFunc::DetectiveMarkSucc()
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScMarkData& rMarkData = pView->GetMarkData();
ScAddress aCurPos = pView->GetCurPos();
ScRangeList aRanges;
if (rMarkData.IsMarked() || rMarkData.IsMultiMarked())
rMarkData.FillRangeListWithMarks(&aRanges, false);
else
aRanges.Append(aCurPos);
vector<ScSharedTokenRef> aRefTokens;
pDocSh->GetDocFunc().DetectiveCollectAllSuccs(aRanges, aRefTokens);
if (aRefTokens.empty())
// No dependants found. Nothing to do.
return;
ScRangeList aDestRanges;
ScRefTokenHelper::getRangeListFromTokens(aDestRanges, aRefTokens);
MarkAndJumpToRanges(aDestRanges);
}
void ScViewFunc::InsertCurrentTime(short nCellFmt, const OUString& rUndoStr)
{
ScViewData* pViewData = GetViewData();
ScAddress aCurPos = pViewData->GetCurPos();
ScDocShell* pDocSh = pViewData->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
SfxUndoManager* pUndoMgr = pDocSh->GetUndoManager();
SvNumberFormatter* pFormatter = pDoc->GetFormatTable();
Date aActDate;
double fDate = aActDate - *pFormatter->GetNullDate();
Time aActTime;
double fTime =
aActTime.Get100Sec() / 100.0 + aActTime.GetSec() +
(aActTime.GetMin() * 60.0) + (aActTime.GetHour() * 3600.0);
fTime /= D_TIMEFACTOR;
pUndoMgr->EnterListAction(rUndoStr, rUndoStr);
pDocSh->GetDocFunc().PutCell(aCurPos, new ScValueCell(fDate+fTime), false);
SetNumberFormat(nCellFmt);
pUndoMgr->LeaveListAction();
}
//---------------------------------------------------------------------------
void ScViewFunc::ShowNote( bool bShow )
{
if( bShow )
HideNoteMarker();
const ScViewData& rViewData = *GetViewData();
ScAddress aPos( rViewData.GetCurX(), rViewData.GetCurY(), rViewData.GetTabNo() );
// show note moved to ScDocFunc, to be able to use it in notesuno.cxx
rViewData.GetDocShell()->GetDocFunc().ShowNote( aPos, bShow );
}
void ScViewFunc::EditNote()
{
// zum Editieren einblenden und aktivieren
ScDocShell* pDocSh = GetViewData()->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
SCCOL nCol = GetViewData()->GetCurX();
SCROW nRow = GetViewData()->GetCurY();
SCTAB nTab = GetViewData()->GetTabNo();
ScAddress aPos( nCol, nRow, nTab );
// start drawing undo to catch undo action for insertion of the caption object
pDocSh->MakeDrawLayer();
ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();
pDrawLayer->BeginCalcUndo();
// generated undo action is processed in FuText::StopEditMode
// get existing note or create a new note (including caption drawing object)
if( ScPostIt* pNote = pDoc->GetOrCreateNote( aPos ) )
{
// hide temporary note caption
HideNoteMarker();
// show caption object without changing internal visibility state
pNote->ShowCaptionTemp( aPos );
/* Drawing object has been created in ScDocument::GetOrCreateNote() or
in ScPostIt::ShowCaptionTemp(), so ScPostIt::GetCaption() should
return a caption object. */
if( SdrCaptionObj* pCaption = pNote->GetCaption() )
{
// #i33764# enable the resize handles before starting edit mode
if( FuPoor* pDraw = GetDrawFuncPtr() )
static_cast< FuSelection* >( pDraw )->ActivateNoteHandles( pCaption );
// activate object (as in FuSelection::TestComment)
GetViewData()->GetDispatcher().Execute( SID_DRAW_NOTEEDIT, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
// jetzt den erzeugten FuText holen und in den EditModus setzen
FuPoor* pPoor = GetDrawFuncPtr();
if ( pPoor && (pPoor->GetSlotID() == SID_DRAW_NOTEEDIT) ) // hat keine RTTI
{
ScrollToObject( pCaption ); // Objekt komplett sichtbar machen
static_cast< FuText* >( pPoor )->SetInEditMode( pCaption );
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>When inserting current date/time, set cell format only when necessary.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sc.hxx"
#include <svx/svdundo.hxx>
#include <svx/svdocapt.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/sound.hxx>
#include "svl/zforlist.hxx"
#include "svl/zformat.hxx"
#include "viewfunc.hxx"
#include "detfunc.hxx"
#include "detdata.hxx"
#include "viewdata.hxx"
#include "drwlayer.hxx"
#include "docsh.hxx"
#include "undocell.hxx"
#include "futext.hxx"
#include "docfunc.hxx"
#include "globstr.hrc"
#include "sc.hrc"
#include "fusel.hxx"
#include "reftokenhelper.hxx"
#include "externalrefmgr.hxx"
#include "cell.hxx"
#include <vector>
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::std::vector;
#define D_TIMEFACTOR 86400.0
//==================================================================
void ScViewFunc::DetectiveAddPred()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddPred( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT(); //! use broadcast in DocFunc instead?
}
void ScViewFunc::DetectiveDelPred()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelPred( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveAddSucc()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddSucc( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveDelSucc()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelSucc( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveAddError()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveAddError( GetViewData()->GetCurPos() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveDelAll()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveDelAll( GetViewData()->GetTabNo() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveMarkInvalid()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().
DetectiveMarkInvalid( GetViewData()->GetTabNo() );
if (!bDone)
Sound::Beep();
RecalcPPT();
}
void ScViewFunc::DetectiveRefresh()
{
ScDocShell* pDocSh = GetViewData()->GetDocShell();
BOOL bDone = pDocSh->GetDocFunc().DetectiveRefresh();
if (!bDone)
Sound::Beep();
RecalcPPT();
}
static void lcl_jumpToRange(const ScRange& rRange, ScViewData* pView, ScDocument* pDoc)
{
String aAddrText;
rRange.Format(aAddrText, SCR_ABS_3D, pDoc);
SfxStringItem aPosItem(SID_CURRENTCELL, aAddrText);
SfxBoolItem aUnmarkItem(FN_PARAM_1, TRUE); // remove existing selection
pView->GetDispatcher().Execute(
SID_CURRENTCELL, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD,
&aPosItem, &aUnmarkItem, 0L);
}
void ScViewFunc::MarkAndJumpToRanges(const ScRangeList& rRanges)
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScRangeList aRanges(rRanges);
ScRange* p = aRanges.front();
ScRangeList aRangesToMark;
ScAddress aCurPos = pView->GetCurPos();
size_t ListSize = aRanges.size();
for ( size_t i = 0; i < ListSize; ++i )
{
p = aRanges[i];
// Collect only those ranges that are on the same sheet as the current
// cursor.
if (p->aStart.Tab() == aCurPos.Tab())
aRangesToMark.Append(*p);
}
if (aRangesToMark.empty())
return;
// Jump to the first range of all precedent ranges.
p = aRangesToMark.front();
lcl_jumpToRange(*p, pView, pDocSh->GetDocument());
ListSize = aRangesToMark.size();
for ( size_t i = 0; i < ListSize; ++i )
{
p = aRangesToMark[i];
MarkRange(*p, false, true);
}
}
void ScViewFunc::DetectiveMarkPred()
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
ScMarkData& rMarkData = pView->GetMarkData();
ScAddress aCurPos = pView->GetCurPos();
ScRangeList aRanges;
if (rMarkData.IsMarked() || rMarkData.IsMultiMarked())
rMarkData.FillRangeListWithMarks(&aRanges, false);
else
aRanges.Append(aCurPos);
vector<ScSharedTokenRef> aRefTokens;
pDocSh->GetDocFunc().DetectiveCollectAllPreds(aRanges, aRefTokens);
if (aRefTokens.empty())
// No precedents found. Nothing to do.
return;
ScSharedTokenRef p = aRefTokens.front();
if (ScRefTokenHelper::isExternalRef(p))
{
// This is external. Open the external document if available, and
// jump to the destination.
sal_uInt16 nFileId = p->GetIndex();
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
const String* pPath = pRefMgr->getExternalFileName(nFileId);
ScRange aRange;
if (pPath && ScRefTokenHelper::getRangeFromToken(aRange, p, true))
{
const String& rTabName = p->GetString();
OUStringBuffer aBuf;
aBuf.append(*pPath);
aBuf.append(sal_Unicode('#'));
aBuf.append(rTabName);
aBuf.append(sal_Unicode('.'));
String aRangeStr;
aRange.Format(aRangeStr, SCA_VALID);
aBuf.append(aRangeStr);
ScGlobal::OpenURL(aBuf.makeStringAndClear(), String());
}
return;
}
else
{
ScRange aRange;
ScRefTokenHelper::getRangeFromToken(aRange, p, false);
if (aRange.aStart.Tab() != aCurPos.Tab())
{
// The first precedent range is on a different sheet. Jump to it
// immediately and forget the rest.
lcl_jumpToRange(aRange, pView, pDoc);
return;
}
}
ScRangeList aDestRanges;
ScRefTokenHelper::getRangeListFromTokens(aDestRanges, aRefTokens);
MarkAndJumpToRanges(aDestRanges);
}
void ScViewFunc::DetectiveMarkSucc()
{
ScViewData* pView = GetViewData();
ScDocShell* pDocSh = pView->GetDocShell();
ScMarkData& rMarkData = pView->GetMarkData();
ScAddress aCurPos = pView->GetCurPos();
ScRangeList aRanges;
if (rMarkData.IsMarked() || rMarkData.IsMultiMarked())
rMarkData.FillRangeListWithMarks(&aRanges, false);
else
aRanges.Append(aCurPos);
vector<ScSharedTokenRef> aRefTokens;
pDocSh->GetDocFunc().DetectiveCollectAllSuccs(aRanges, aRefTokens);
if (aRefTokens.empty())
// No dependants found. Nothing to do.
return;
ScRangeList aDestRanges;
ScRefTokenHelper::getRangeListFromTokens(aDestRanges, aRefTokens);
MarkAndJumpToRanges(aDestRanges);
}
void ScViewFunc::InsertCurrentTime(short nCellFmt, const OUString& rUndoStr)
{
ScViewData* pViewData = GetViewData();
ScAddress aCurPos = pViewData->GetCurPos();
ScDocShell* pDocSh = pViewData->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
SfxUndoManager* pUndoMgr = pDocSh->GetUndoManager();
SvNumberFormatter* pFormatter = pDoc->GetFormatTable();
Date aActDate;
double fDate = aActDate - *pFormatter->GetNullDate();
Time aActTime;
double fTime =
aActTime.Get100Sec() / 100.0 + aActTime.GetSec() +
(aActTime.GetMin() * 60.0) + (aActTime.GetHour() * 3600.0);
fTime /= D_TIMEFACTOR;
pUndoMgr->EnterListAction(rUndoStr, rUndoStr);
pDocSh->GetDocFunc().PutCell(aCurPos, new ScValueCell(fDate+fTime), false);
// Set the new cell format only when it differs from the current cell
// format type.
sal_uInt32 nCurNumFormat = pDoc->GetNumberFormat(aCurPos);
const SvNumberformat* pEntry = pFormatter->GetEntry(nCurNumFormat);
if (!pEntry || !(pEntry->GetType() & nCellFmt))
SetNumberFormat(nCellFmt);
pUndoMgr->LeaveListAction();
}
//---------------------------------------------------------------------------
void ScViewFunc::ShowNote( bool bShow )
{
if( bShow )
HideNoteMarker();
const ScViewData& rViewData = *GetViewData();
ScAddress aPos( rViewData.GetCurX(), rViewData.GetCurY(), rViewData.GetTabNo() );
// show note moved to ScDocFunc, to be able to use it in notesuno.cxx
rViewData.GetDocShell()->GetDocFunc().ShowNote( aPos, bShow );
}
void ScViewFunc::EditNote()
{
// zum Editieren einblenden und aktivieren
ScDocShell* pDocSh = GetViewData()->GetDocShell();
ScDocument* pDoc = pDocSh->GetDocument();
SCCOL nCol = GetViewData()->GetCurX();
SCROW nRow = GetViewData()->GetCurY();
SCTAB nTab = GetViewData()->GetTabNo();
ScAddress aPos( nCol, nRow, nTab );
// start drawing undo to catch undo action for insertion of the caption object
pDocSh->MakeDrawLayer();
ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();
pDrawLayer->BeginCalcUndo();
// generated undo action is processed in FuText::StopEditMode
// get existing note or create a new note (including caption drawing object)
if( ScPostIt* pNote = pDoc->GetOrCreateNote( aPos ) )
{
// hide temporary note caption
HideNoteMarker();
// show caption object without changing internal visibility state
pNote->ShowCaptionTemp( aPos );
/* Drawing object has been created in ScDocument::GetOrCreateNote() or
in ScPostIt::ShowCaptionTemp(), so ScPostIt::GetCaption() should
return a caption object. */
if( SdrCaptionObj* pCaption = pNote->GetCaption() )
{
// #i33764# enable the resize handles before starting edit mode
if( FuPoor* pDraw = GetDrawFuncPtr() )
static_cast< FuSelection* >( pDraw )->ActivateNoteHandles( pCaption );
// activate object (as in FuSelection::TestComment)
GetViewData()->GetDispatcher().Execute( SID_DRAW_NOTEEDIT, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
// jetzt den erzeugten FuText holen und in den EditModus setzen
FuPoor* pPoor = GetDrawFuncPtr();
if ( pPoor && (pPoor->GetSlotID() == SID_DRAW_NOTEEDIT) ) // hat keine RTTI
{
ScrollToObject( pCaption ); // Objekt komplett sichtbar machen
static_cast< FuText* >( pPoor )->SetInEditMode( pCaption );
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*
* TcpConnection.cpp
*
* Created on: 13.05.2017
* Author: felix
*/
#include <unistd.h>
#include <asn-one-objects/GenericAsnOneObject.h>
#include <common/Log.h>
#include <network/TcpConnection.h>
namespace Flix {
TcpConnection::TcpConnection(int connectionSocket, const std::string& peer, int port):
connectionSocket(connectionSocket),
peer(peer),
port(port)
{
opened = connectionSocket >= 0 ? true : false;
LOG_INFO("Accepted connection from " << peer << ":" << port);
}
TcpConnection::~TcpConnection()
{
}
int TcpConnection::getConnectionSocket(void) const
{
return connectionSocket;
}
const std::string& TcpConnection::getPeer(void) const
{
return peer;
}
int TcpConnection::getPort(void) const
{
return port;
}
bool TcpConnection::close(void)
{
if (!isOpened()) {
return false;
}
::close(connectionSocket);
opened = false;
return true;
}
bool TcpConnection::isOpened(void) const
{
return opened;
}
void TcpConnection::handleIncomingData(const StreamBuffer& stream)
{
if (!isOpened()) {
return;
}
inputStream.insert(inputStream.end(), stream.cbegin(), stream.cend());
AsnOneDecodeStatus decodeStatus = AsnOneDecodeStatus::UNKNOWN;
bool quitImmediately = false;
while (inputStream.size() > 0 && decodeStatus != AsnOneDecodeStatus::INCOMPLETE && !quitImmediately) {
ssize_t consumedBytes = 0;
GenericAsnOneObject* asnOneObject = GenericAsnOneObject::decode(inputStream, consumedBytes, decodeStatus);
if (!asnOneObject) {
switch (decodeStatus) {
case AsnOneDecodeStatus::INVALID_TAG:
case AsnOneDecodeStatus::NOT_SUPPORTED:
case AsnOneDecodeStatus::UNKNOWN:
LOG_NOTICE("Protocol error detected (" << decodeStatus << ")! Closing connection.");
close();
quitImmediately = true;
break;
default:
break;
}
} else {
LOG_INFO("Cleaning up ASN.1 object...");
delete asnOneObject;
}
inputStream.erase(inputStream.begin(), inputStream.begin() + consumedBytes);
}
}
} /* namespace Flix */
<commit_msg>Fixed detection of invalid ASN.1 objects.<commit_after>/*
* TcpConnection.cpp
*
* Created on: 13.05.2017
* Author: felix
*/
#include <unistd.h>
#include <asn-one-objects/GenericAsnOneObject.h>
#include <common/Log.h>
#include <network/TcpConnection.h>
namespace Flix {
TcpConnection::TcpConnection(int connectionSocket, const std::string& peer, int port):
connectionSocket(connectionSocket),
peer(peer),
port(port)
{
opened = connectionSocket >= 0 ? true : false;
LOG_INFO("Accepted connection from " << peer << ":" << port);
}
TcpConnection::~TcpConnection()
{
}
int TcpConnection::getConnectionSocket(void) const
{
return connectionSocket;
}
const std::string& TcpConnection::getPeer(void) const
{
return peer;
}
int TcpConnection::getPort(void) const
{
return port;
}
bool TcpConnection::close(void)
{
if (!isOpened()) {
return false;
}
::close(connectionSocket);
opened = false;
return true;
}
bool TcpConnection::isOpened(void) const
{
return opened;
}
void TcpConnection::handleIncomingData(const StreamBuffer& stream)
{
if (!isOpened()) {
return;
}
inputStream.insert(inputStream.end(), stream.cbegin(), stream.cend());
AsnOneDecodeStatus decodeStatus = AsnOneDecodeStatus::UNKNOWN;
bool quitImmediately = false;
while (inputStream.size() > 0 && decodeStatus != AsnOneDecodeStatus::INCOMPLETE && !quitImmediately) {
ssize_t consumedBytes = 0;
GenericAsnOneObject* asnOneObject = GenericAsnOneObject::decode(inputStream, consumedBytes, decodeStatus);
if (!asnOneObject) {
switch (decodeStatus) {
case AsnOneDecodeStatus::OK:
case AsnOneDecodeStatus::INCOMPLETE:
break;
default:
LOG_NOTICE("Protocol error detected (" << decodeStatus << ")! Closing connection.");
close();
quitImmediately = true;
break;
}
} else {
LOG_INFO("Cleaning up ASN.1 object...");
delete asnOneObject;
}
inputStream.erase(inputStream.begin(), inputStream.begin() + consumedBytes);
}
}
} /* namespace Flix */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017, Matias Fontanini
* 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
* 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 <string.h>
#include <tins/offline_packet_filter.h>
#include <tins/pdu.h>
#include <tins/exceptions.h>
using std::string;
namespace Tins {
OfflinePacketFilter::OfflinePacketFilter(const OfflinePacketFilter& other) {
*this = other;
}
OfflinePacketFilter& OfflinePacketFilter::operator=(const OfflinePacketFilter& other) {
string_filter_ = other.string_filter_;
init(string_filter_, pcap_datalink(other.handle_), pcap_snapshot(other.handle_));
return* this;
}
OfflinePacketFilter::~OfflinePacketFilter() {
pcap_freecode(&filter_);
pcap_close(handle_);
}
void OfflinePacketFilter::init(const string& pcap_filter,
int link_type,
unsigned int snap_len) {
handle_ = pcap_open_dead(
link_type,
snap_len
);
if (!handle_) {
throw pcap_open_failed();
}
if (pcap_compile(handle_, &filter_, pcap_filter.c_str(), 1, 0xffffffff) == -1) {
string error(pcap_geterr(handle_));
pcap_freecode(&filter_);
pcap_close(handle_);
throw invalid_pcap_filter(error.c_str());
}
}
bool OfflinePacketFilter::matches_filter(const uint8_t* buffer, uint32_t total_sz) const {
pcap_pkthdr header;
memset(&header, 0, sizeof(header));
header.len = total_sz;
header.caplen = total_sz;
return pcap_offline_filter(&filter_, &header, buffer) != 0;
}
bool OfflinePacketFilter::matches_filter(PDU& pdu) const {
PDU::serialization_type buffer = pdu.serialize();
return matches_filter(&buffer[0], static_cast<uint32_t>(buffer.size()));
}
} // Tins
<commit_msg>OfflinePacketFilter: avoid leak during copy-construction or assignment<commit_after>/*
* Copyright (c) 2017, Matias Fontanini
* 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
* 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 <string.h>
#include <tins/offline_packet_filter.h>
#include <tins/pdu.h>
#include <tins/exceptions.h>
using std::string;
namespace Tins {
OfflinePacketFilter::OfflinePacketFilter(const OfflinePacketFilter& other) {
string_filter_ = other.string_filter_;
init(string_filter_, pcap_datalink(other.handle_), pcap_snapshot(other.handle_));
}
OfflinePacketFilter& OfflinePacketFilter::operator=(const OfflinePacketFilter& other) {
string_filter_ = other.string_filter_;
pcap_freecode(&filter_);
pcap_close(handle_);
init(string_filter_, pcap_datalink(other.handle_), pcap_snapshot(other.handle_));
return* this;
}
OfflinePacketFilter::~OfflinePacketFilter() {
pcap_freecode(&filter_);
pcap_close(handle_);
}
void OfflinePacketFilter::init(const string& pcap_filter,
int link_type,
unsigned int snap_len) {
handle_ = pcap_open_dead(
link_type,
snap_len
);
if (!handle_) {
throw pcap_open_failed();
}
if (pcap_compile(handle_, &filter_, pcap_filter.c_str(), 1, 0xffffffff) == -1) {
string error(pcap_geterr(handle_));
pcap_freecode(&filter_);
pcap_close(handle_);
throw invalid_pcap_filter(error.c_str());
}
}
bool OfflinePacketFilter::matches_filter(const uint8_t* buffer, uint32_t total_sz) const {
pcap_pkthdr header;
memset(&header, 0, sizeof(header));
header.len = total_sz;
header.caplen = total_sz;
return pcap_offline_filter(&filter_, &header, buffer) != 0;
}
bool OfflinePacketFilter::matches_filter(PDU& pdu) const {
PDU::serialization_type buffer = pdu.serialize();
return matches_filter(&buffer[0], static_cast<uint32_t>(buffer.size()));
}
} // Tins
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/LightPointNode>
#include <osgSim/LightPointSystem>
#include "LightPointDrawable.h"
#include <osg/Timer>
#include <osg/BoundingBox>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osgUtil/CullVisitor>
#include <typeinfo>
namespace osgSim
{
osg::StateSet* getSingletonLightPointSystemSet()
{
static osg::ref_ptr<osg::StateSet> s_stateset = 0;
if (!s_stateset)
{
s_stateset = new osg::StateSet;
// force light point nodes to be drawn after everything else by picking a renderin bin number after
// the transparent bin.
s_stateset->setRenderBinDetails(20,"DepthSortedBin");
}
return s_stateset.get();
}
LightPointNode::LightPointNode():
_minPixelSize(0.0f),
_maxPixelSize(30.0f),
_maxVisibleDistance2(FLT_MAX),
_lightSystem(0)
{
setStateSet(getSingletonLightPointSystemSet());
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
LightPointNode::LightPointNode(const LightPointNode& lpn,const osg::CopyOp& copyop):
osg::Node(lpn,copyop),
_lightPointList(lpn._lightPointList),
_minPixelSize(lpn._minPixelSize),
_maxPixelSize(lpn._maxPixelSize),
_maxVisibleDistance2(lpn._maxVisibleDistance2),
_lightSystem(lpn._lightSystem)
{
}
unsigned int LightPointNode::addLightPoint(const LightPoint& lp)
{
unsigned int num = _lightPointList.size();
_lightPointList.push_back(lp);
dirtyBound();
return num;
}
void LightPointNode::removeLightPoint(unsigned int pos)
{
if (pos<_lightPointList.size())
{
_lightPointList.erase(_lightPointList.begin()+pos);
dirtyBound();
}
dirtyBound();
}
osg::BoundingSphere LightPointNode::computeBound() const
{
osg::BoundingSphere bsphere;
bsphere.init();
_bbox.init();
if (_lightPointList.empty())
{
return bsphere;
}
LightPointList::const_iterator itr;
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
_bbox.expandBy(itr->_position);
}
bsphere.set(_bbox.center(),0.0f);
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
osg::Vec3 dv(itr->_position-bsphere.center());
float radius = dv.length()+itr->_radius;
if (bsphere.radius()<radius) bsphere.radius()=radius;
}
bsphere.radius()+=1.0f;
return bsphere;
}
void LightPointNode::traverse(osg::NodeVisitor& nv)
{
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER
#ifdef USE_TIMER
osg::Timer timer;
osg::Timer_t t1=0,t2=0,t3=0,t4=0,t5=0,t6=0,t7=0,t8=0;
#endif
#ifdef USE_TIMER
t1 = timer.tick();
#endif
osgUtil::CullVisitor* cv = NULL;
if (typeid(nv)==typeid(osgUtil::CullVisitor))
{
cv = static_cast<osgUtil::CullVisitor*>(&nv);
}
#ifdef USE_TIMER
t2 = timer.tick();
#endif
// should we disabled small feature culling here?
if (cv /*&& !cv->isCulled(_bbox)*/)
{
osg::Matrix matrix = cv->getModelViewMatrix();
osg::RefMatrix& projection = cv->getProjectionMatrix();
osgUtil::StateGraph* rg = cv->getCurrentStateGraph();
if (rg->leaves_empty())
{
// this is first leaf to be added to StateGraph
// and therefore should not already know to current render bin,
// so need to add it.
cv->getCurrentRenderBin()->addStateGraph(rg);
}
#ifdef USE_TIMER
t3 = timer.tick();
#endif
LightPointDrawable* drawable = NULL;
osg::Referenced* object = rg->getUserData();
if (object)
{
if (typeid(*object)==typeid(LightPointDrawable))
{
// resuse the user data attached to the render graph.
drawable = static_cast<LightPointDrawable*>(object);
}
else
{
// will need to replace UserData.
osg::notify(osg::WARN) << "Warning: Replacing osgUtil::StateGraph::_userData to support osgSim::LightPointNode, may have undefined results."<<std::endl;
}
}
if (!drawable)
{
// set it for the frst time.
drawable = new LightPointDrawable;
rg->setUserData(drawable);
if (cv->getFrameStamp())
{
drawable->setReferenceTime(cv->getFrameStamp()->getReferenceTime());
}
}
// search for a drawable in the RenderLead list equal to the attached the one attached to StateGraph user data
// as this will be our special light point drawable.
osgUtil::StateGraph::LeafList::iterator litr;
for(litr = rg->_leaves.begin();
litr != rg->_leaves.end() && (*litr)->_drawable!=drawable;
++litr)
{}
if (litr == rg->_leaves.end())
{
// havn't found the drawable added in the RenderLeaf list, there this my be the
// first time through LightPointNode in this frame, so need to add drawable into the StateGraph RenderLeaf list
// and update its time signatures.
drawable->reset();
rg->addLeaf(new osgUtil::RenderLeaf(drawable,&projection,NULL,FLT_MAX));
// need to update the drawable's frame count.
if (cv->getFrameStamp())
{
drawable->updateReferenceTime(cv->getFrameStamp()->getReferenceTime());
}
}
#ifdef USE_TIMER
t4 = timer.tick();
#endif
#ifdef USE_TIMER
t7 = timer.tick();
#endif
if (cv->getComputeNearFarMode() != osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR)
cv->updateCalculatedNearFar(matrix,_bbox);
const float minimumIntensity = 1.0f/256.0f;
const osg::Vec3 eyePoint = cv->getEyeLocal();
double time=drawable->getReferenceTime();
double timeInterval=drawable->getReferenceTimeInterval();
const osg::Polytope clipvol(cv->getCurrentCullingSet().getFrustum());
const bool computeClipping = false;//(clipvol.getCurrentMask()!=0);
//LightPointDrawable::ColorPosition cp;
for(LightPointList::iterator itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
const LightPoint& lp = *itr;
if (!lp._on) continue;
const osg::Vec3& position = lp._position;
// skip light point if it is not contianed in the view frustum.
if (computeClipping && !clipvol.contains(position)) continue;
// delta vector between eyepoint and light point.
osg::Vec3 dv(eyePoint-position);
float intensity = (_lightSystem.valid()) ? _lightSystem->getIntensity() : lp._intensity;
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
if (_maxVisibleDistance2!=FLT_MAX)
{
if (dv.length2()>_maxVisibleDistance2) continue;
}
osg::Vec4 color = lp._color;
// check the sector.
if (lp._sector.valid())
{
intensity *= (*lp._sector)(dv);
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
}
// temporary accounting of intensity.
//color *= intensity;
// check the blink sequence.
bool doBlink = lp._blinkSequence.valid();
if (doBlink && _lightSystem.valid())
doBlink = (_lightSystem->getAnimationState() == LightPointSystem::ANIMATION_ON);
if (doBlink)
{
osg::Vec4 bs = lp._blinkSequence->color(time,timeInterval);
color[0] *= bs[0];
color[1] *= bs[1];
color[2] *= bs[2];
color[3] *= bs[3];
}
// if alpha value is less than the min intentsive then skip
if (color[3]<=minimumIntensity) continue;
float pixelSize = cv->pixelSize(position,lp._radius);
// cout << "pixelsize = "<<pixelSize<<endl;
// adjust pixel size to account for intensity.
if (intensity!=1.0) pixelSize *= sqrt(intensity);
// round up to the minimum pixel size if required.
if (pixelSize<_minPixelSize) pixelSize = _minPixelSize;
osg::Vec3 xpos(position*matrix);
if (lp._blendingMode==LightPoint::BLENDED)
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
//color[3] = pixelSize;
color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addBlendedLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
//float remainder = pixelSize-(float)lowerBoundPixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
float alpha = color[3];
drawable->addBlendedLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] = alpha*remainder;
drawable->addBlendedLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addBlendedLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
else // ADDITIVE blending.
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
//color[3] = pixelSize;
color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addAdditiveLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
//float remainder = pixelSize-(float)lowerBoundPixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
float alpha = color[3];
color[3] = alpha*(1.0f-remainder);
drawable->addAdditiveLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] = alpha*remainder;
drawable->addAdditiveLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addAdditiveLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
}
#ifdef USE_TIMER
t8 = timer.tick();
#endif
}
#ifdef USE_TIMER
cout << "compute"<<endl;
cout << " t2-t1="<<t2-t1<<endl;
cout << " t4-t3="<<t4-t3<<endl;
cout << " t6-t5="<<t6-t5<<endl;
cout << " t8-t7="<<t8-t7<<endl;
cout << "_lightPointList.size()="<<_lightPointList.size()<<endl;
cout << " t8-t7/size = "<<(float)(t8-t7)/(float)_lightPointList.size()<<endl;
#endif
}
} // end of namespace
<commit_msg>From Brede Johansen, "some tweaks to the osgSim lightpoints.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/LightPointNode>
#include <osgSim/LightPointSystem>
#include "LightPointDrawable.h"
#include <osg/Timer>
#include <osg/BoundingBox>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osgUtil/CullVisitor>
#include <typeinfo>
namespace osgSim
{
osg::StateSet* getSingletonLightPointSystemSet()
{
static osg::ref_ptr<osg::StateSet> s_stateset = 0;
if (!s_stateset)
{
s_stateset = new osg::StateSet;
// force light point nodes to be drawn after everything else by picking a renderin bin number after
// the transparent bin.
s_stateset->setRenderBinDetails(20,"DepthSortedBin");
}
return s_stateset.get();
}
LightPointNode::LightPointNode():
_minPixelSize(0.0f),
_maxPixelSize(30.0f),
_maxVisibleDistance2(FLT_MAX),
_lightSystem(0)
{
setStateSet(getSingletonLightPointSystemSet());
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
LightPointNode::LightPointNode(const LightPointNode& lpn,const osg::CopyOp& copyop):
osg::Node(lpn,copyop),
_lightPointList(lpn._lightPointList),
_minPixelSize(lpn._minPixelSize),
_maxPixelSize(lpn._maxPixelSize),
_maxVisibleDistance2(lpn._maxVisibleDistance2),
_lightSystem(lpn._lightSystem)
{
}
unsigned int LightPointNode::addLightPoint(const LightPoint& lp)
{
unsigned int num = _lightPointList.size();
_lightPointList.push_back(lp);
dirtyBound();
return num;
}
void LightPointNode::removeLightPoint(unsigned int pos)
{
if (pos<_lightPointList.size())
{
_lightPointList.erase(_lightPointList.begin()+pos);
dirtyBound();
}
dirtyBound();
}
osg::BoundingSphere LightPointNode::computeBound() const
{
osg::BoundingSphere bsphere;
bsphere.init();
_bbox.init();
if (_lightPointList.empty())
{
return bsphere;
}
LightPointList::const_iterator itr;
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
_bbox.expandBy(itr->_position);
}
bsphere.set(_bbox.center(),0.0f);
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
osg::Vec3 dv(itr->_position-bsphere.center());
float radius = dv.length()+itr->_radius;
if (bsphere.radius()<radius) bsphere.radius()=radius;
}
bsphere.radius()+=1.0f;
return bsphere;
}
void LightPointNode::traverse(osg::NodeVisitor& nv)
{
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER
#ifdef USE_TIMER
osg::Timer timer;
osg::Timer_t t1=0,t2=0,t3=0,t4=0,t5=0,t6=0,t7=0,t8=0;
#endif
#ifdef USE_TIMER
t1 = timer.tick();
#endif
osgUtil::CullVisitor* cv = NULL;
if (typeid(nv)==typeid(osgUtil::CullVisitor))
{
cv = static_cast<osgUtil::CullVisitor*>(&nv);
}
#ifdef USE_TIMER
t2 = timer.tick();
#endif
// should we disabled small feature culling here?
if (cv /*&& !cv->isCulled(_bbox)*/)
{
osg::Matrix matrix = cv->getModelViewMatrix();
osg::RefMatrix& projection = cv->getProjectionMatrix();
osgUtil::StateGraph* rg = cv->getCurrentStateGraph();
if (rg->leaves_empty())
{
// this is first leaf to be added to StateGraph
// and therefore should not already know to current render bin,
// so need to add it.
cv->getCurrentRenderBin()->addStateGraph(rg);
}
#ifdef USE_TIMER
t3 = timer.tick();
#endif
LightPointDrawable* drawable = NULL;
osg::Referenced* object = rg->getUserData();
if (object)
{
if (typeid(*object)==typeid(LightPointDrawable))
{
// resuse the user data attached to the render graph.
drawable = static_cast<LightPointDrawable*>(object);
}
else
{
// will need to replace UserData.
osg::notify(osg::WARN) << "Warning: Replacing osgUtil::StateGraph::_userData to support osgSim::LightPointNode, may have undefined results."<<std::endl;
}
}
if (!drawable)
{
// set it for the frst time.
drawable = new LightPointDrawable;
rg->setUserData(drawable);
if (cv->getFrameStamp())
{
drawable->setReferenceTime(cv->getFrameStamp()->getReferenceTime());
}
}
// search for a drawable in the RenderLead list equal to the attached the one attached to StateGraph user data
// as this will be our special light point drawable.
osgUtil::StateGraph::LeafList::iterator litr;
for(litr = rg->_leaves.begin();
litr != rg->_leaves.end() && (*litr)->_drawable!=drawable;
++litr)
{}
if (litr == rg->_leaves.end())
{
// havn't found the drawable added in the RenderLeaf list, there this my be the
// first time through LightPointNode in this frame, so need to add drawable into the StateGraph RenderLeaf list
// and update its time signatures.
drawable->reset();
rg->addLeaf(new osgUtil::RenderLeaf(drawable,&projection,NULL,FLT_MAX));
// need to update the drawable's frame count.
if (cv->getFrameStamp())
{
drawable->updateReferenceTime(cv->getFrameStamp()->getReferenceTime());
}
}
#ifdef USE_TIMER
t4 = timer.tick();
#endif
#ifdef USE_TIMER
t7 = timer.tick();
#endif
if (cv->getComputeNearFarMode() != osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR)
cv->updateCalculatedNearFar(matrix,_bbox);
const float minimumIntensity = 1.0f/256.0f;
const osg::Vec3 eyePoint = cv->getEyeLocal();
double time=drawable->getReferenceTime();
double timeInterval=drawable->getReferenceTimeInterval();
const osg::Polytope clipvol(cv->getCurrentCullingSet().getFrustum());
const bool computeClipping = false;//(clipvol.getCurrentMask()!=0);
//LightPointDrawable::ColorPosition cp;
for(LightPointList::iterator itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
const LightPoint& lp = *itr;
if (!lp._on) continue;
const osg::Vec3& position = lp._position;
// skip light point if it is not contianed in the view frustum.
if (computeClipping && !clipvol.contains(position)) continue;
// delta vector between eyepoint and light point.
osg::Vec3 dv(eyePoint-position);
float intensity = (_lightSystem.valid()) ? _lightSystem->getIntensity() : lp._intensity;
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
// (SIB) Clip on distance, if close to limit, add transparancy
float distanceFactor = 1.0f;
if (_maxVisibleDistance2!=FLT_MAX)
{
if (dv.length2()>_maxVisibleDistance2) continue;
else if (_maxVisibleDistance2 > 0)
distanceFactor = 1.0f - osg::square(dv.length2() / _maxVisibleDistance2);
}
osg::Vec4 color = lp._color;
// check the sector.
if (lp._sector.valid())
{
intensity *= (*lp._sector)(dv);
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
}
// temporary accounting of intensity.
//color *= intensity;
// check the blink sequence.
bool doBlink = lp._blinkSequence.valid();
if (doBlink && _lightSystem.valid())
doBlink = (_lightSystem->getAnimationState() == LightPointSystem::ANIMATION_ON);
if (doBlink)
{
osg::Vec4 bs = lp._blinkSequence->color(time,timeInterval);
color[0] *= bs[0];
color[1] *= bs[1];
color[2] *= bs[2];
color[3] *= bs[3];
}
// if alpha value is less than the min intentsive then skip
if (color[3]<=minimumIntensity) continue;
float pixelSize = cv->pixelSize(position,lp._radius);
// cout << "pixelsize = "<<pixelSize<<endl;
// adjust pixel size to account for intensity.
if (intensity!=1.0) pixelSize *= sqrt(intensity);
// adjust alfa to account for max range (Fade on distance)
color[3] *= distanceFactor;
// round up to the minimum pixel size if required.
float orgPixelSize = pixelSize;
if (pixelSize<_minPixelSize) pixelSize = _minPixelSize;
osg::Vec3 xpos(position*matrix);
if (lp._blendingMode==LightPoint::BLENDED)
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addBlendedLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
drawable->addBlendedLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] *= remainder;
drawable->addBlendedLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addBlendedLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
else // ADDITIVE blending.
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addAdditiveLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
float alpha = color[3];
color[3] = alpha*(1.0f-remainder);
drawable->addAdditiveLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] = alpha*remainder;
drawable->addAdditiveLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addAdditiveLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
}
#ifdef USE_TIMER
t8 = timer.tick();
#endif
}
#ifdef USE_TIMER
cout << "compute"<<endl;
cout << " t2-t1="<<t2-t1<<endl;
cout << " t4-t3="<<t4-t3<<endl;
cout << " t6-t5="<<t6-t5<<endl;
cout << " t8-t7="<<t8-t7<<endl;
cout << "_lightPointList.size()="<<_lightPointList.size()<<endl;
cout << " t8-t7/size = "<<(float)(t8-t7)/(float)_lightPointList.size()<<endl;
#endif
}
} // end of namespace
<|endoftext|>
|
<commit_before>#include "output_ts_base.h"
namespace Mist {
TSOutput::TSOutput(Socket::Connection & conn) : TS_BASECLASS(conn){
packCounter=0;
ts_from = 0;
setBlocking(true);
sendRepeatingHeaders = 0;
appleCompat=false;
lastHeaderTime = 0;
}
void TSOutput::fillPacket(char const * data, size_t dataLen, bool & firstPack, bool video, bool keyframe, uint32_t pkgPid, int & contPkg){
do {
if (!packData.getBytesFree()){
if ( (sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){
lastHeaderTime = thisPacket.getTime();
TS::Packet tmpPack;
tmpPack.FromPointer(TS::PAT);
tmpPack.setContinuityCounter(++contPAT);
sendTS(tmpPack.checkAndGetBuffer());
sendTS(TS::createPMT(selectedTracks, myMeta, ++contPMT));
sendTS(TS::createSDT(streamName, ++contSDT));
packCounter += 3;
}
sendTS(packData.checkAndGetBuffer());
packCounter ++;
packData.clear();
}
if (!dataLen){return;}
if (packData.getBytesFree() == 184){
packData.clear();
packData.setPID(pkgPid);
packData.setContinuityCounter(++contPkg);
if (firstPack){
packData.setUnitStart(1);
if (video){
if (keyframe){
packData.setRandomAccess(true);
packData.setESPriority(true);
}
packData.setPCR(thisPacket.getTime() * 27000);
}
firstPack = false;
}
}
int tmp = packData.fillFree(data, dataLen);
data += tmp;
dataLen -= tmp;
} while(dataLen);
}
void TSOutput::sendNext(){
//Get ready some data to speed up accesses
uint32_t trackId = thisPacket.getTrackId();
DTSC::Track & Trk = myMeta.tracks[trackId];
bool & firstPack = first[trackId];
uint32_t pkgPid = 255 + trackId;
int & contPkg = contCounters[pkgPid];
uint64_t packTime = thisPacket.getTime();
bool video = (Trk.type == "video");
bool keyframe = thisPacket.getInt("keyframe");
firstPack = true;
char * dataPointer = 0;
unsigned int dataLen = 0;
thisPacket.getString("data", dataPointer, dataLen); //data
//apple compatibility timestamp correction
if (appleCompat){
packTime -= ts_from;
if (Trk.type == "audio"){
packTime = 0;
}
}
packTime *= 90;
std::string bs;
//prepare bufferstring
if (video){
if (Trk.codec == "H264" || Trk.codec == "HEVC"){
unsigned int extraSize = 0;
//dataPointer[4] & 0x1f is used to check if this should be done later: fillPacket("\000\000\000\001\011\360", 6);
if (Trk.codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){
extraSize += 6;
}
if (keyframe){
if (Trk.codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(Trk.init);
bs = avccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-START*/
if (Trk.codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(Trk.init);
bs = hvccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-END*/
}
unsigned int watKunnenWeIn1Ding = 65490-13;
unsigned int splitCount = (dataLen+extraSize) / watKunnenWeIn1Ding;
unsigned int currPack = 0;
unsigned int ThisNaluSize = 0;
unsigned int i = 0;
unsigned int nalLead = 0;
uint64_t offset = thisPacket.getInt("offset") * 90;
while (currPack <= splitCount){
unsigned int alreadySent = 0;
bs = TS::Packet::getPESVideoLeadIn((currPack != splitCount ? watKunnenWeIn1Ding : dataLen+extraSize - currPack*watKunnenWeIn1Ding), packTime, offset, !currPack, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (!currPack){
if (Trk.codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){
//End of previous nal unit, if not already present
fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += 6;
}
if (keyframe){
if (Trk.codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(Trk.init);
bs = avccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += bs.size();
}
/*LTS-START*/
if (Trk.codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(Trk.init);
bs = hvccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += bs.size();
}
/*LTS-END*/
}
}
while (i + 4 < (unsigned int)dataLen){
if (nalLead){
fillPacket("\000\000\000\001"+4-nalLead,nalLead, firstPack, video, keyframe, pkgPid, contPkg);
i += nalLead;
alreadySent += nalLead;
nalLead = 0;
}
if (!ThisNaluSize){
ThisNaluSize = (dataPointer[i] << 24) + (dataPointer[i+1] << 16) + (dataPointer[i+2] << 8) + dataPointer[i+3];
if (ThisNaluSize + i + 4 > (unsigned int)dataLen){
DEBUG_MSG(DLVL_WARN, "Too big NALU detected (%u > %d) - skipping!", ThisNaluSize + i + 4, dataLen);
break;
}
if (alreadySent + 4 > watKunnenWeIn1Ding){
nalLead = 4 - (watKunnenWeIn1Ding-alreadySent);
fillPacket("\000\000\000\001",watKunnenWeIn1Ding-alreadySent, firstPack, video, keyframe, pkgPid, contPkg);
i += watKunnenWeIn1Ding-alreadySent;
alreadySent += watKunnenWeIn1Ding-alreadySent;
}else{
fillPacket("\000\000\000\001",4, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += 4;
i += 4;
}
}
if (alreadySent + ThisNaluSize > watKunnenWeIn1Ding){
fillPacket(dataPointer+i,watKunnenWeIn1Ding-alreadySent, firstPack, video, keyframe, pkgPid, contPkg);
i += watKunnenWeIn1Ding-alreadySent;
ThisNaluSize -= watKunnenWeIn1Ding-alreadySent;
alreadySent += watKunnenWeIn1Ding-alreadySent;
}else{
fillPacket(dataPointer+i,ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += ThisNaluSize;
i += ThisNaluSize;
ThisNaluSize = 0;
}
if (alreadySent == watKunnenWeIn1Ding){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
firstPack = true;
break;
}
}
currPack++;
}
}else{
uint64_t offset = thisPacket.getInt("offset") * 90;
bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
}else if (Trk.type == "audio"){
long unsigned int tempLen = dataLen;
if (Trk.codec == "AAC"){
tempLen += 7;
}
bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (Trk.codec == "AAC"){
bs = TS::getAudioHeader(dataLen, Trk.init);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
fillPacket(dataPointer,dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
if (packData.getBytesFree() < 184){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
}
}
}
<commit_msg>Fixed TS-output (=HLS) related SIGABRT problem<commit_after>#include "output_ts_base.h"
#include <mist/bitfields.h>
namespace Mist {
TSOutput::TSOutput(Socket::Connection & conn) : TS_BASECLASS(conn){
packCounter=0;
ts_from = 0;
setBlocking(true);
sendRepeatingHeaders = 0;
appleCompat=false;
lastHeaderTime = 0;
}
void TSOutput::fillPacket(char const * data, size_t dataLen, bool & firstPack, bool video, bool keyframe, uint32_t pkgPid, int & contPkg){
do {
if (!packData.getBytesFree()){
if ( (sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){
lastHeaderTime = thisPacket.getTime();
TS::Packet tmpPack;
tmpPack.FromPointer(TS::PAT);
tmpPack.setContinuityCounter(++contPAT);
sendTS(tmpPack.checkAndGetBuffer());
sendTS(TS::createPMT(selectedTracks, myMeta, ++contPMT));
sendTS(TS::createSDT(streamName, ++contSDT));
packCounter += 3;
}
sendTS(packData.checkAndGetBuffer());
packCounter ++;
packData.clear();
}
if (!dataLen){return;}
if (packData.getBytesFree() == 184){
packData.clear();
packData.setPID(pkgPid);
packData.setContinuityCounter(++contPkg);
if (firstPack){
packData.setUnitStart(1);
if (video){
if (keyframe){
packData.setRandomAccess(true);
packData.setESPriority(true);
}
packData.setPCR(thisPacket.getTime() * 27000);
}
firstPack = false;
}
}
size_t tmp = packData.fillFree(data, dataLen);
data += tmp;
dataLen -= tmp;
} while(dataLen);
}
void TSOutput::sendNext(){
//Get ready some data to speed up accesses
uint32_t trackId = thisPacket.getTrackId();
DTSC::Track & Trk = myMeta.tracks[trackId];
bool & firstPack = first[trackId];
uint32_t pkgPid = 255 + trackId;
int & contPkg = contCounters[pkgPid];
uint64_t packTime = thisPacket.getTime();
bool video = (Trk.type == "video");
bool keyframe = thisPacket.getInt("keyframe");
firstPack = true;
char * dataPointer = 0;
unsigned int tmpDataLen = 0;
thisPacket.getString("data", dataPointer, tmpDataLen); //data
uint64_t dataLen = tmpDataLen;
//apple compatibility timestamp correction
if (appleCompat){
packTime -= ts_from;
if (Trk.type == "audio"){
packTime = 0;
}
}
packTime *= 90;
std::string bs;
//prepare bufferstring
if (video){
if (Trk.codec == "H264" || Trk.codec == "HEVC"){
unsigned int extraSize = 0;
//dataPointer[4] & 0x1f is used to check if this should be done later: fillPacket("\000\000\000\001\011\360", 6);
if (Trk.codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){
extraSize += 6;
}
if (keyframe){
if (Trk.codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(Trk.init);
bs = avccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-START*/
if (Trk.codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(Trk.init);
bs = hvccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-END*/
}
unsigned int watKunnenWeIn1Ding = 65490-13;
unsigned int splitCount = (dataLen+extraSize) / watKunnenWeIn1Ding;
unsigned int currPack = 0;
uint64_t ThisNaluSize = 0;
unsigned int i = 0;
unsigned int nalLead = 0;
uint64_t offset = thisPacket.getInt("offset") * 90;
while (currPack <= splitCount){
unsigned int alreadySent = 0;
bs = TS::Packet::getPESVideoLeadIn((currPack != splitCount ? watKunnenWeIn1Ding : dataLen+extraSize - currPack*watKunnenWeIn1Ding), packTime, offset, !currPack, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (!currPack){
if (Trk.codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){
//End of previous nal unit, if not already present
fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += 6;
}
if (keyframe){
if (Trk.codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(Trk.init);
bs = avccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += bs.size();
}
/*LTS-START*/
if (Trk.codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(Trk.init);
bs = hvccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += bs.size();
}
/*LTS-END*/
}
}
while (i + 4 < (unsigned int)dataLen){
if (nalLead){
fillPacket("\000\000\000\001"+4-nalLead,nalLead, firstPack, video, keyframe, pkgPid, contPkg);
i += nalLead;
alreadySent += nalLead;
nalLead = 0;
}
if (!ThisNaluSize){
ThisNaluSize = Bit::btohl(dataPointer + i);
if (ThisNaluSize + i + 4 > dataLen){
WARN_MSG("Too big NALU detected (%" PRIu64 " > %" PRIu64 ") - skipping!", ThisNaluSize + i + 4, dataLen);
break;
}
if (alreadySent + 4 > watKunnenWeIn1Ding){
nalLead = 4 - (watKunnenWeIn1Ding-alreadySent);
fillPacket("\000\000\000\001",watKunnenWeIn1Ding-alreadySent, firstPack, video, keyframe, pkgPid, contPkg);
i += watKunnenWeIn1Ding-alreadySent;
alreadySent += watKunnenWeIn1Ding-alreadySent;
}else{
fillPacket("\000\000\000\001",4, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += 4;
i += 4;
}
}
if (alreadySent + ThisNaluSize > watKunnenWeIn1Ding){
fillPacket(dataPointer+i,watKunnenWeIn1Ding-alreadySent, firstPack, video, keyframe, pkgPid, contPkg);
i += watKunnenWeIn1Ding-alreadySent;
ThisNaluSize -= watKunnenWeIn1Ding-alreadySent;
alreadySent += watKunnenWeIn1Ding-alreadySent;
}else{
fillPacket(dataPointer+i,ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);
alreadySent += ThisNaluSize;
i += ThisNaluSize;
ThisNaluSize = 0;
}
if (alreadySent == watKunnenWeIn1Ding){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
firstPack = true;
break;
}
}
currPack++;
}
}else{
uint64_t offset = thisPacket.getInt("offset") * 90;
bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
}else if (Trk.type == "audio"){
long unsigned int tempLen = dataLen;
if (Trk.codec == "AAC"){
tempLen += 7;
}
bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, Trk.bps);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (Trk.codec == "AAC"){
bs = TS::getAudioHeader(dataLen, Trk.init);
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
fillPacket(dataPointer,dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
if (packData.getBytesFree() < 184){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
}
}
}
<|endoftext|>
|
<commit_before>#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include <QDateTime>
#include <cstdlib>
// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);
TransactionFilterProxy::TransactionFilterProxy(QObject *parent) :
QSortFilterProxyModel(parent),
dateFrom(MIN_DATE),
dateTo(MAX_DATE),
addrPrefix(),
typeFilter(ALL_TYPES),
minAmount(0),
limitRows(-1)
{
}
bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
int type = index.data(TransactionTableModel::TypeRole).toInt();
QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(TransactionTableModel::AddressRole).toString();
QString label = index.data(TransactionTableModel::LabelRole).toString();
qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
if(!(TYPE(type) & typeFilter))
return false;
if(datetime < dateFrom || datetime > dateTo)
return false;
if(!address.startsWith(addrPrefix) && !label.startsWith(addrPrefix))
return false;
if(amount < minAmount)
return false;
return true;
}
void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to)
{
this->dateFrom = from;
this->dateTo = to;
invalidateFilter();
}
void TransactionFilterProxy::setAddressPrefix(const QString &addrPrefix)
{
this->addrPrefix = addrPrefix;
invalidateFilter();
}
void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
this->typeFilter = modes;
invalidateFilter();
}
void TransactionFilterProxy::setMinAmount(qint64 minimum)
{
this->minAmount = minimum;
invalidateFilter();
}
void TransactionFilterProxy::setLimit(int limit)
{
this->limitRows = limit;
}
int TransactionFilterProxy::rowCount(const QModelIndex &parent) const
{
if(limitRows != -1)
{
return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
}
else
{
return QSortFilterProxyModel::rowCount(parent);
}
}
<commit_msg>allow for filtering addresses and labels by searching for the typed string anywhere, not just at the beginning (#641)<commit_after>#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include <QDateTime>
#include <cstdlib>
// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);
TransactionFilterProxy::TransactionFilterProxy(QObject *parent) :
QSortFilterProxyModel(parent),
dateFrom(MIN_DATE),
dateTo(MAX_DATE),
addrPrefix(),
typeFilter(ALL_TYPES),
minAmount(0),
limitRows(-1)
{
}
bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
int type = index.data(TransactionTableModel::TypeRole).toInt();
QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(TransactionTableModel::AddressRole).toString();
QString label = index.data(TransactionTableModel::LabelRole).toString();
qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
if(!(TYPE(type) & typeFilter))
return false;
if(datetime < dateFrom || datetime > dateTo)
return false;
if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive))
return false;
if(amount < minAmount)
return false;
return true;
}
void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to)
{
this->dateFrom = from;
this->dateTo = to;
invalidateFilter();
}
void TransactionFilterProxy::setAddressPrefix(const QString &addrPrefix)
{
this->addrPrefix = addrPrefix;
invalidateFilter();
}
void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
this->typeFilter = modes;
invalidateFilter();
}
void TransactionFilterProxy::setMinAmount(qint64 minimum)
{
this->minAmount = minimum;
invalidateFilter();
}
void TransactionFilterProxy::setLimit(int limit)
{
this->limitRows = limit;
}
int TransactionFilterProxy::rowCount(const QModelIndex &parent) const
{
if(limitRows != -1)
{
return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
}
else
{
return QSortFilterProxyModel::rowCount(parent);
}
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFontHost.h"
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkDEBUGFAIL("SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream*) {
SkDEBUGFAIL("SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromFile(char const*) {
SkDEBUGFAIL("SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
uint32_t fontID,
SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) {
SkDEBUGFAIL("SkFontHost::GetAdvancedTypefaceMetrics unimplemented");
return NULL;
}
void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
}
///////////////////////////////////////////////////////////////////////////////
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkDEBUGFAIL("SkFontHost::OpenStream unimplemented");
return NULL;
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkDebugf("SkFontHost::GetFileName unimplemented\n");
return 0;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkDEBUGFAIL("SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkDEBUGFAIL("SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkDEBUGFAIL("SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkFontID SkFontHost::NextLogicalFont(SkFontID currFontID, SkFontID origFontID) {
return 0;
}
<commit_msg>Fix compile error in SkFontHost_none.cpp Review URL: https://codereview.appspot.com/6501083<commit_after>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFontHost.h"
#include "SkScalerContext.h"
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkDEBUGFAIL("SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream*) {
SkDEBUGFAIL("SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromFile(char const*) {
SkDEBUGFAIL("SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
uint32_t fontID,
SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) {
SkDEBUGFAIL("SkFontHost::GetAdvancedTypefaceMetrics unimplemented");
return NULL;
}
void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
}
///////////////////////////////////////////////////////////////////////////////
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkDEBUGFAIL("SkFontHost::OpenStream unimplemented");
return NULL;
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkDebugf("SkFontHost::GetFileName unimplemented\n");
return 0;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkDEBUGFAIL("SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkDEBUGFAIL("SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkDEBUGFAIL("SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkFontID SkFontHost::NextLogicalFont(SkFontID currFontID, SkFontID origFontID) {
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef RENHOOK_HOOKS_INLINE_HOOK_H
#define RENHOOK_HOOKS_INLINE_HOOK_H
#include <string>
#include <Windows.h>
#include <renhook/exception.hpp>
#include <renhook/executable.hpp>
#include <renhook/hook_writer.hpp>
#include <renhook/pattern.hpp>
#include <renhook/suspend_threads.hpp>
#include <renhook/zydis.hpp>
#include <renhook/memory/memory_allocator.hpp>
#include <renhook/memory/virtual_protect.hpp>
namespace renhook
{
/**
* @brief An inline hook.
*
* @tparam T The hooked function type.
*/
template<typename T>
class inline_hook
{
public:
/**
* @brief Construct an empty hook.
*/
inline_hook()
: m_target_address(0)
, m_detour_address(0)
, m_wildcard(0)
, m_offset(0)
, m_attached(false)
, m_decoded_length(0)
, m_block(nullptr)
{
}
/**
* @brief Construct a new hook.
*
* @param target_address[in] The address of the function that will be hooked.
* @param detour_address[in] The address of the callback.
*/
inline_hook(uintptr_t target_address, uintptr_t detour_address)
: inline_hook()
{
m_target_address = target_address;
m_detour_address = detour_address;
}
/**
* @brief Construct a new hook.
*
* @param target_address[in] The address of the function that will be hooked.
* @param detour_address[in] The address of the callback.
*/
inline_hook(uintptr_t target_address, T detour_address)
: inline_hook(target_address, reinterpret_cast<uintptr_t>(detour_address))
{
}
/**
* @brief Construct a new hook using a pattern.
*
* @param pattern[in] The pattern of the function that will be hooked.
* @param detour_address[in] The address of the callback.
* @param wildcard[in] The wildcard for #pattern.
* @param offset[in] The offset of the #pattern.
*/
inline_hook(pattern pattern, uintptr_t detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)
: inline_hook()
{
m_detour_address = detour_address;
m_pattern = std::move(pattern);
m_wildcard = wildcard;
m_offset = offset;
}
/**
* @brief Construct a new hook using a pattern.
*
* @param pattern[in] The pattern of the function that will be hooked.
* @param detour_address[in] The address of the callback.
* @param wildcard[in] The wildcard for #pattern.
* @param offset[in] The offset of the #pattern.
*/
inline_hook(pattern pattern, T detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)
: inline_hook(pattern, reinterpret_cast<uintptr_t>(detour_address), wildcard, offset)
{
}
/**
* @brief Construct a new hook.
*
* @param module[in] The module which contain the #function.
* @param function[in] The function that will be hooked.
* @param detour_address[in] The address of the callback.
*
* @note If the module is not loaded, the library will load it when the hook is attached.
*/
inline_hook(const std::string& module, const std::string& function, uintptr_t detour_address)
: inline_hook()
{
m_module = module;
m_function = function;
}
/**
* @brief Construct a new hook.
*
* @param module[in] The module which contain the #function.
* @param function[in] The function that will be hooked.
* @param detour_address[in] The address of the callback.
*
* @note If the module is not loaded, the library will load it when the hook is attached.
*/
inline_hook(const std::string& module, const std::string& function, T detour_address)
: inline_hook(module, function, reinterpret_cast<uintptr_t>(detour_address))
{
}
inline_hook(inline_hook&& rhs) noexcept
: m_target_address(rhs.m_target_address)
, m_detour_address(rhs.m_detour_address)
, m_pattern(std::move(rhs.m_pattern))
, m_wildcard(rhs.m_wildcard)
, m_offset(rhs.m_offset)
, m_attached(rhs.m_attached)
, m_decoded_length(rhs.m_decoded_length)
, m_block(rhs.m_block)
{
rhs.m_attached = false;
rhs.m_block = nullptr;
}
~inline_hook()
{
detach();
}
inline_hook& operator=(inline_hook&& rhs) noexcept
{
m_target_address = rhs.m_target_address;
m_detour_address = rhs.m_detour_address;
m_pattern = std::move(rhs.m_pattern);
m_wildcard = rhs.m_wildcard;
m_offset = rhs.m_offset;
m_attached = rhs.m_attached;
m_decoded_length = rhs.m_decoded_length;
m_block = rhs.m_block;
rhs.m_attached = false;
rhs.m_block = nullptr;
return *this;
}
inline_hook(inline_hook&) = delete;
inline_hook& operator=(const inline_hook&) = delete;
/**
* @brief Call the original function.
*
* @return The value returned by the original function.
*/
operator T() const
{
return reinterpret_cast<T>(m_block);
}
/**
* @brief Enable the hook.
*/
void attach()
{
using namespace renhook::memory;
if (m_attached)
{
return;
}
if (!m_module.empty())
{
auto module_handle = GetModuleHandleA(m_module.c_str());
if (!module_handle)
{
LoadLibraryA(m_module.c_str());
module_handle = GetModuleHandleA(m_module.c_str());
if (!module_handle)
{
throw renhook::exception("module not found");
}
}
m_target_address = reinterpret_cast<uintptr_t>(GetProcAddress(module_handle, m_function.c_str()));
if (m_target_address == 0)
{
throw renhook::exception("cannot find function in module");
}
}
if (m_target_address == 0)
{
if (m_pattern.empty())
{
throw renhook::exception("cannot attach an empty hook");
}
auto addresses = m_pattern.find(m_wildcard);
m_target_address = addresses.at(m_offset);
}
m_target_address = skip_jumps(m_target_address);
m_detour_address = skip_jumps(m_detour_address);
renhook::zydis zydis;
auto instructions = zydis.decode(m_target_address, executable::get_code_size(), hook_size, m_decoded_length);
suspend_threads threads(m_target_address, m_decoded_length);
extern memory_allocator global_allocator;
m_block = static_cast<uint8_t*>(global_allocator.alloc());
// Write the bytes to our memory.
virtual_protect block_protection(m_block, memory_allocator::block_size, protection::read | protection::write | protection::execute);
hook_writer block_writer(m_block);
block_writer.copy_from(m_target_address, m_decoded_length);
block_writer.write_jump(m_target_address + m_decoded_length);
relocate_instructions(instructions, &block_writer);
// Write the jump in the original function.
virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);
hook_writer func_writer(m_target_address);
func_writer.write_jump(m_detour_address);
func_writer.write_nops(m_decoded_length - hook_size);
flush_cache();
m_attached = true;
}
/**
* @brief Disable the hook.
*/
void detach()
{
using namespace renhook::memory;
if (!m_attached)
{
return;
}
suspend_threads threads(m_target_address, m_decoded_length);
virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);
hook_writer func_writer(m_target_address);
func_writer.copy_from(m_block, m_decoded_length);
renhook::zydis zydis;
auto instructions = zydis.decode(reinterpret_cast<uintptr_t>(m_block), executable::get_code_size(), m_decoded_length, m_decoded_length);
relocate_instructions(instructions, nullptr);
extern memory_allocator global_allocator;
global_allocator.free(m_block);
m_block = nullptr;
flush_cache();
m_attached = false;
}
protected:
/**
* @brief Get the block address.
*
* @return The block address.
*
* @note This is only used in tests.
*/
const uint8_t* get_block_address() const
{
return m_block;
}
private:
/**
* @brief The size of the hook.
*/
#ifdef _WIN64
static constexpr size_t hook_size = 14;
#else
static constexpr size_t hook_size = 5;
#endif
/**
* @brief Check if the first instruction is a jump, if it is follow it until the real address of the function is found.
*
* @param address[in] The address to check.
*
* @return The real function's address.
*/
uintptr_t skip_jumps(uintptr_t address) const
{
if (address == 0)
{
return 0;
}
auto memory = reinterpret_cast<uint8_t*>(address);
if (memory[0] == 0xEB)
{
// We have a 8-bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 2 + *reinterpret_cast<int8_t*>(&memory[1]));
return skip_jumps(address);
}
else if (memory[0] == 0xE9)
{
// We have a 32-bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 5 + *reinterpret_cast<int32_t*>(&memory[1]));
return skip_jumps(address);
}
else if (memory[0] == 0xFF && memory[1] == 0x25)
{
#ifdef _WIN64
// We have a 32bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 6 + *reinterpret_cast<int32_t*>(&memory[2]));
#else
// We have an absolute pointer.
address = *reinterpret_cast<uintptr_t*>(&memory[2]);
#endif
return skip_jumps(address);
}
#ifdef _WIN64
else if (memory[0] == 0x48 && memory[1] == 0xFF && memory[2] == 0x25)
{
// We have a 32bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 7 + *reinterpret_cast<int32_t*>(&memory[3]));
return skip_jumps(address);
}
#endif
return address;
}
/**
* @brief Relocate all EIP / RIP instructions.
*
* @param instructions[in] An array of decoded instructions.
* @param block_writer[in] The writer of the block (only necessary if the hook is attached).
*/
void relocate_instructions(std::vector<zydis::instruction>& instructions, hook_writer* block_writer)
{
auto instr_address = m_attached ? m_target_address : reinterpret_cast<uintptr_t>(m_block);
size_t index = 0;
for (auto& instr : instructions)
{
// Check if it is a conditional jump.
if (instr.is_relative &&
((instr.decoded.opcode & 0xF0) == 0x70 ||
(instr.decoded.opcode_map == ZYDIS_OPCODE_MAP_0F && (instr.decoded.opcode & 0xF0) == 0x80) ||
instr.decoded.mnemonic == ZYDIS_MNEMONIC_CALL))
{
// Calculate where the displacement is in instruction.
auto disp_address = instr_address + instr.disp.offset;
#ifdef _WIN64
constexpr size_t jmp_size = 14;
constexpr size_t jmp_instr_size = 6;
#else
constexpr size_t jmp_size = 5;
constexpr size_t jmp_instr_size = 1;
#endif
auto table_address = m_block + m_decoded_length + hook_size;
// The address of the jump instruction in jump table for the current instruction.
auto jmp_instr_address = table_address + (jmp_size * index);
// Create a jump table if it is not attached, else get the real address from jump table.
if (!m_attached)
{
block_writer->write_jump(instr.disp.absolute_address);
instr.disp.absolute_address = reinterpret_cast<uintptr_t>(jmp_instr_address);
}
else
{
instr.disp.absolute_address = *reinterpret_cast<uintptr_t*>(jmp_instr_address + jmp_instr_size);
#ifndef _WIN64
// On x86 we have a displacement instead of absolute address.
instr.disp.absolute_address += reinterpret_cast<uintptr_t>(jmp_instr_address) + jmp_size;
#endif
}
switch (instr.disp.size)
{
case 8:
{
*reinterpret_cast<int8_t*>(disp_address) = static_cast<int8_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
case 16:
{
*reinterpret_cast<int16_t*>(disp_address) = static_cast<int16_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
case 32:
{
*reinterpret_cast<int32_t*>(disp_address) = static_cast<int32_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
}
index++;
}
instr_address += instr.decoded.length;
}
}
/**
* @brief Flush instruction cache for the original function and for the codecave.
*/
void flush_cache() const
{
auto current_process = GetCurrentProcess();
FlushInstructionCache(current_process, m_block, memory::memory_allocator::block_size);
FlushInstructionCache(current_process, reinterpret_cast<void*>(m_target_address), m_decoded_length);
}
uintptr_t m_target_address;
uintptr_t m_detour_address;
pattern m_pattern;
uint8_t m_wildcard;
size_t m_offset;
std::string m_module;
std::string m_function;
bool m_attached;
size_t m_decoded_length;
uint8_t* m_block;
};
}
#endif
<commit_msg>Fix build error and set detour address when calling a constructor with a module<commit_after>#ifndef RENHOOK_HOOKS_INLINE_HOOK_H
#define RENHOOK_HOOKS_INLINE_HOOK_H
#include <string>
#include <Windows.h>
#include <renhook/exception.hpp>
#include <renhook/executable.hpp>
#include <renhook/hook_writer.hpp>
#include <renhook/pattern.hpp>
#include <renhook/suspend_threads.hpp>
#include <renhook/utils.hpp>
#include <renhook/zydis.hpp>
#include <renhook/memory/memory_allocator.hpp>
#include <renhook/memory/virtual_protect.hpp>
namespace renhook
{
/**
* @brief An inline hook.
*
* @tparam T The hooked function type.
*/
template<typename T>
class inline_hook
{
public:
/**
* @brief Construct an empty hook.
*/
inline_hook()
: m_target_address(0)
, m_detour_address(0)
, m_wildcard(0)
, m_offset(0)
, m_attached(false)
, m_decoded_length(0)
, m_block(nullptr)
{
}
/**
* @brief Construct a new hook.
*
* @param target_address[in] The address of the function that will be hooked.
* @param detour_address[in] The address of the callback.
*/
inline_hook(uintptr_t target_address, uintptr_t detour_address)
: inline_hook()
{
m_target_address = target_address;
m_detour_address = detour_address;
}
/**
* @brief Construct a new hook.
*
* @param target_address[in] The address of the function that will be hooked.
* @param detour_address[in] The address of the callback.
*/
inline_hook(uintptr_t target_address, T detour_address)
: inline_hook(target_address, reinterpret_cast<uintptr_t>(detour_address))
{
}
/**
* @brief Construct a new hook using a pattern.
*
* @param pattern[in] The pattern of the function that will be hooked.
* @param detour_address[in] The address of the callback.
* @param wildcard[in] The wildcard for #pattern.
* @param offset[in] The offset of the #pattern.
*/
inline_hook(pattern pattern, uintptr_t detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)
: inline_hook()
{
m_detour_address = detour_address;
m_pattern = std::move(pattern);
m_wildcard = wildcard;
m_offset = offset;
}
/**
* @brief Construct a new hook using a pattern.
*
* @param pattern[in] The pattern of the function that will be hooked.
* @param detour_address[in] The address of the callback.
* @param wildcard[in] The wildcard for #pattern.
* @param offset[in] The offset of the #pattern.
*/
inline_hook(pattern pattern, T detour_address, uint8_t wildcard = 0xCC, size_t offset = 0)
: inline_hook(pattern, reinterpret_cast<uintptr_t>(detour_address), wildcard, offset)
{
}
/**
* @brief Construct a new hook.
*
* @param module[in] The module which contain the #function.
* @param function[in] The function that will be hooked.
* @param detour_address[in] The address of the callback.
*
* @note If the module is not loaded, the library will load it when the hook is attached.
*/
inline_hook(const std::string& module, const std::string& function, uintptr_t detour_address)
: inline_hook()
{
m_module = module;
m_function = function;
m_detour_address = detour_address;
}
/**
* @brief Construct a new hook.
*
* @param module[in] The module which contain the #function.
* @param function[in] The function that will be hooked.
* @param detour_address[in] The address of the callback.
*
* @note If the module is not loaded, the library will load it when the hook is attached.
*/
inline_hook(const std::string& module, const std::string& function, T detour_address)
: inline_hook(module, function, reinterpret_cast<uintptr_t>(detour_address))
{
}
inline_hook(inline_hook&& rhs) noexcept
: m_target_address(rhs.m_target_address)
, m_detour_address(rhs.m_detour_address)
, m_pattern(std::move(rhs.m_pattern))
, m_wildcard(rhs.m_wildcard)
, m_offset(rhs.m_offset)
, m_attached(rhs.m_attached)
, m_decoded_length(rhs.m_decoded_length)
, m_block(rhs.m_block)
{
rhs.m_attached = false;
rhs.m_block = nullptr;
}
~inline_hook()
{
detach();
}
inline_hook& operator=(inline_hook&& rhs) noexcept
{
m_target_address = rhs.m_target_address;
m_detour_address = rhs.m_detour_address;
m_pattern = std::move(rhs.m_pattern);
m_wildcard = rhs.m_wildcard;
m_offset = rhs.m_offset;
m_attached = rhs.m_attached;
m_decoded_length = rhs.m_decoded_length;
m_block = rhs.m_block;
rhs.m_attached = false;
rhs.m_block = nullptr;
return *this;
}
inline_hook(inline_hook&) = delete;
inline_hook& operator=(const inline_hook&) = delete;
/**
* @brief Call the original function.
*
* @return The value returned by the original function.
*/
operator T() const
{
return reinterpret_cast<T>(m_block);
}
/**
* @brief Enable the hook.
*/
void attach()
{
using namespace renhook::memory;
if (m_attached)
{
return;
}
if (!m_module.empty())
{
auto module_handle = GetModuleHandleA(m_module.c_str());
if (!module_handle)
{
LoadLibraryA(m_module.c_str());
module_handle = GetModuleHandleA(m_module.c_str());
if (!module_handle)
{
throw renhook::exception("module not found");
}
}
m_target_address = reinterpret_cast<uintptr_t>(GetProcAddress(module_handle, m_function.c_str()));
if (m_target_address == 0)
{
throw renhook::exception("cannot find function in module");
}
}
if (m_target_address == 0)
{
if (m_pattern.empty())
{
throw renhook::exception("cannot attach an empty hook");
}
auto addresses = m_pattern.find(m_wildcard);
m_target_address = addresses.at(m_offset);
}
m_target_address = skip_jumps(m_target_address);
m_detour_address = skip_jumps(m_detour_address);
renhook::zydis zydis;
auto instructions = zydis.decode(m_target_address, executable::get_code_size(), hook_size, m_decoded_length);
suspend_threads threads(m_target_address, m_decoded_length);
extern memory_allocator global_allocator;
m_block = static_cast<uint8_t*>(global_allocator.alloc());
// Write the bytes to our memory.
virtual_protect block_protection(m_block, memory_allocator::block_size, protection::read | protection::write | protection::execute);
hook_writer block_writer(m_block);
block_writer.copy_from(m_target_address, m_decoded_length);
block_writer.write_jump(m_target_address + m_decoded_length);
relocate_instructions(instructions, &block_writer);
// Write the jump in the original function.
virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);
hook_writer func_writer(m_target_address);
func_writer.write_jump(m_detour_address);
func_writer.write_nops(m_decoded_length - hook_size);
flush_cache();
m_attached = true;
}
/**
* @brief Disable the hook.
*/
void detach()
{
using namespace renhook::memory;
if (!m_attached)
{
return;
}
suspend_threads threads(m_target_address, m_decoded_length);
virtual_protect func_protection(m_target_address, m_decoded_length, protection::read | protection::write | protection::execute);
hook_writer func_writer(m_target_address);
func_writer.copy_from(m_block, m_decoded_length);
renhook::zydis zydis;
auto instructions = zydis.decode(reinterpret_cast<uintptr_t>(m_block), executable::get_code_size(), m_decoded_length, m_decoded_length);
relocate_instructions(instructions, nullptr);
extern memory_allocator global_allocator;
global_allocator.free(m_block);
m_block = nullptr;
flush_cache();
m_attached = false;
}
protected:
/**
* @brief Get the block address.
*
* @return The block address.
*
* @note This is only used in tests.
*/
const uint8_t* get_block_address() const
{
return m_block;
}
private:
/**
* @brief The size of the hook.
*/
#ifdef _WIN64
static constexpr size_t hook_size = 14;
#else
static constexpr size_t hook_size = 5;
#endif
/**
* @brief Check if the first instruction is a jump, if it is follow it until the real address of the function is found.
*
* @param address[in] The address to check.
*
* @return The real function's address.
*/
uintptr_t skip_jumps(uintptr_t address) const
{
if (address == 0)
{
return 0;
}
auto memory = reinterpret_cast<uint8_t*>(address);
if (memory[0] == 0xEB)
{
// We have a 8-bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 2 + *reinterpret_cast<int8_t*>(&memory[1]));
return skip_jumps(address);
}
else if (memory[0] == 0xE9)
{
// We have a 32-bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 5 + *reinterpret_cast<int32_t*>(&memory[1]));
return skip_jumps(address);
}
else if (memory[0] == 0xFF && memory[1] == 0x25)
{
#ifdef _WIN64
// We have a 32bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 6 + *reinterpret_cast<int32_t*>(&memory[2]));
#else
// We have an absolute pointer.
address = *reinterpret_cast<uintptr_t*>(&memory[2]);
#endif
return skip_jumps(address);
}
#ifdef _WIN64
else if (memory[0] == 0x48 && memory[1] == 0xFF && memory[2] == 0x25)
{
// We have a 32bit offset to the target.
address = reinterpret_cast<uintptr_t>(memory + 7 + *reinterpret_cast<int32_t*>(&memory[3]));
return skip_jumps(address);
}
#endif
return address;
}
/**
* @brief Relocate all EIP / RIP instructions.
*
* @param instructions[in] An array of decoded instructions.
* @param block_writer[in] The writer of the block (only necessary if the hook is attached).
*/
void relocate_instructions(std::vector<zydis::instruction>& instructions, hook_writer* block_writer)
{
auto instr_address = m_attached ? m_target_address : reinterpret_cast<uintptr_t>(m_block);
size_t index = 0;
for (auto& instr : instructions)
{
// Check if it is a conditional jump.
if (instr.is_relative &&
((instr.decoded.opcode & 0xF0) == 0x70 ||
(instr.decoded.opcode_map == ZYDIS_OPCODE_MAP_0F && (instr.decoded.opcode & 0xF0) == 0x80) ||
instr.decoded.mnemonic == ZYDIS_MNEMONIC_CALL))
{
// Calculate where the displacement is in instruction.
auto disp_address = instr_address + instr.disp.offset;
#ifdef _WIN64
constexpr size_t jmp_size = 14;
constexpr size_t jmp_instr_size = 6;
#else
constexpr size_t jmp_size = 5;
constexpr size_t jmp_instr_size = 1;
#endif
auto table_address = m_block + m_decoded_length + hook_size;
// The address of the jump instruction in jump table for the current instruction.
auto jmp_instr_address = table_address + (jmp_size * index);
// Create a jump table if it is not attached, else get the real address from jump table.
if (!m_attached)
{
block_writer->write_jump(instr.disp.absolute_address);
instr.disp.absolute_address = reinterpret_cast<uintptr_t>(jmp_instr_address);
}
else
{
instr.disp.absolute_address = *reinterpret_cast<uintptr_t*>(jmp_instr_address + jmp_instr_size);
#ifndef _WIN64
// On x86 we have a displacement instead of absolute address.
instr.disp.absolute_address += reinterpret_cast<uintptr_t>(jmp_instr_address) + jmp_size;
#endif
}
switch (instr.disp.size)
{
case 8:
{
*reinterpret_cast<int8_t*>(disp_address) = static_cast<int8_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
case 16:
{
*reinterpret_cast<int16_t*>(disp_address) = static_cast<int16_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
case 32:
{
*reinterpret_cast<int32_t*>(disp_address) = static_cast<int32_t>(utils::calculate_displacement(instr_address, instr.disp.absolute_address, instr.decoded.length));
break;
}
}
index++;
}
instr_address += instr.decoded.length;
}
}
/**
* @brief Flush instruction cache for the original function and for the codecave.
*/
void flush_cache() const
{
auto current_process = GetCurrentProcess();
FlushInstructionCache(current_process, m_block, memory::memory_allocator::block_size);
FlushInstructionCache(current_process, reinterpret_cast<void*>(m_target_address), m_decoded_length);
}
uintptr_t m_target_address;
uintptr_t m_detour_address;
pattern m_pattern;
uint8_t m_wildcard;
size_t m_offset;
std::string m_module;
std::string m_function;
bool m_attached;
size_t m_decoded_length;
uint8_t* m_block;
};
}
#endif
<|endoftext|>
|
<commit_before>#include "ros2_simple_logger/Logger.h"
simpleLogger* simpleLogger::instance = NULL;
std::mutex simpleLogger::globalLogger_mutex;
void simpleLogger::initLogger(rclcpp::node::Node::SharedPtr _node)
{
std::lock_guard<std::mutex> lock(globalLogger_mutex);
this->publisher = _node->create_publisher<ros2_simple_logger::msg::LoggingMessage>("ros2_log", rmw_qos_profile_sensor_data);
}
simpleLogger *simpleLogger::getInstance()
{
//TODO check if a static local instance would be better
if(instance == NULL)
instance = new simpleLogger();
return instance;
}
simpleLogger::~simpleLogger()
{
//Close the file writer
logFileWriter.close();
}
void simpleLogger::setLogLevel(LogLevel level)
{
messageLogLevel = level;
printLogLevel = level;
}
void simpleLogger::setLogFilePath(std::__cxx11::string path)
{
if(path != "" && logFileWriter.is_open())
logFileWriter.close();
//Check if the filename already exists
if(check_if_file_exists(path))
{
int result = 0;
//Backup logfile already exists
if(check_if_file_exists(path+".1"))
{
//Remove it
result = remove((path+".1").c_str());
if(result != 0)
throw std::runtime_error("Can't remove old logfile "+ path + ".1");
}
//Yes move the file to path.1
result = rename (path.c_str(), (path+".1").c_str());
if(result != 0)
throw std::runtime_error("Can't move old logfile to "+ path + ".1");
}
//Open the logfile
logFileWriter.open(path);
//Check if we could open it
if(!logFileWriter.is_open())
throw std::runtime_error("Can't open logfile: " + path);
logFilePath = path;
}
simpleLogger &simpleLogger::getStream(LogLevel level)
{
if(level != currentLogLevel)
log_stream<<'\n';
currentLogLevel = level;
//Return this as stream
return *this;
}
void simpleLogger::set_now(builtin_interfaces::msg::Time &time)
{
//See ros2 demos for more information
std::chrono::nanoseconds now = std::chrono::high_resolution_clock::now().time_since_epoch();
if (now <= std::chrono::nanoseconds(0)) {
time.sec = time.nanosec = 0;
} else {
time.sec = static_cast<builtin_interfaces::msg::Time::_sec_type>(now.count() / 1000000000);
time.nanosec = now.count() % 1000000000;
}
}
simpleLogger::simpleLogger():std::ostream(this)
{
}
int simpleLogger::overflow(int c)
{
if(c == EOF)
return c;
if(c == '\n')
{
//Some thread safety - not perfect
std::lock_guard<std::mutex> lock(globalLogger_mutex);
if(log_stream.str() == "")
return c;
//Prepare ros message
//builtin_interfaces::msg::Time time;
set_now(time);
//msg->level = level;
//msg->stamp = time;
//Get time
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
//Generate loglevel output
std::string levelStr = "";
switch(currentLogLevel)
{
case Debug:
levelStr = printInColor("Debug : ", ConsoleColor::FG_BLUE);
break;
case Info:
levelStr = printInColor("Info : ", ConsoleColor::FG_GREEN);
break;
case Important:
levelStr = printInColor("Important: ", ConsoleColor::FG_WHITE, ConsoleColor::BG_GREEN);
break;
case Warning:
levelStr = printInColor("Warning: ", ConsoleColor::FG_RED);
break;
case Error:
levelStr = printInColor("Error : ", ConsoleColor::FG_RED, ConsoleColor::BG_YELLOW);
break;
case Fatal:
levelStr = printInColor("Fatal : ", ConsoleColor::FG_RED, ConsoleColor::BG_WHITE);
break;
}
std::ostringstream timeStrStream;
//Write preset into log_stream
#if __GNUC__ >= 5
timeStrStream << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X") << " : ";
#else
timeStrStream << ctime (&in_time_t) << " : " ;
#endif
if(printLogLevel <= currentLogLevel)
std::cout << timeStrStream.str() << levelStr << log_stream.str() << std::endl;
if(fileLogLevel <= currentLogLevel && logFileWriter.is_open())
logFileWriter << timeStrStream.str() << levelStr << log_stream.str() << '\n';
if(messageLogLevel <= currentLogLevel && publisher != NULL){
auto msg = std::make_shared<ros2_simple_logger::msg::LoggingMessage>();
msg->stamp = time;
msg->level = messageLogLevel;
msg->message = log_stream.str();
publisher->publish(msg);
}
log_stream.str("");
}
else
{
log_stream << (char)c;
}
return c;
}
bool simpleLogger::check_if_file_exists(const std::__cxx11::string filename)
{
std::ifstream file(filename);
return file.good();
}
<commit_msg>No new line when switching loglevel<commit_after>#include "ros2_simple_logger/Logger.h"
simpleLogger* simpleLogger::instance = NULL;
std::mutex simpleLogger::globalLogger_mutex;
void simpleLogger::initLogger(rclcpp::node::Node::SharedPtr _node)
{
std::lock_guard<std::mutex> lock(globalLogger_mutex);
this->publisher = _node->create_publisher<ros2_simple_logger::msg::LoggingMessage>("ros2_log", rmw_qos_profile_sensor_data);
}
simpleLogger *simpleLogger::getInstance()
{
//TODO check if a static local instance would be better
if(instance == NULL)
instance = new simpleLogger();
return instance;
}
simpleLogger::~simpleLogger()
{
//Close the file writer
logFileWriter.close();
}
void simpleLogger::setLogLevel(LogLevel level)
{
messageLogLevel = level;
printLogLevel = level;
}
void simpleLogger::setLogFilePath(std::__cxx11::string path)
{
if(path != "" && logFileWriter.is_open())
logFileWriter.close();
//Check if the filename already exists
if(check_if_file_exists(path))
{
int result = 0;
//Backup logfile already exists
if(check_if_file_exists(path+".1"))
{
//Remove it
result = remove((path+".1").c_str());
if(result != 0)
throw std::runtime_error("Can't remove old logfile "+ path + ".1");
}
//Yes move the file to path.1
result = rename (path.c_str(), (path+".1").c_str());
if(result != 0)
throw std::runtime_error("Can't move old logfile to "+ path + ".1");
}
//Open the logfile
logFileWriter.open(path);
//Check if we could open it
if(!logFileWriter.is_open())
throw std::runtime_error("Can't open logfile: " + path);
logFilePath = path;
}
simpleLogger &simpleLogger::getStream(LogLevel level)
{
if(level != currentLogLevel)
*this<<'\n';
currentLogLevel = level;
//Return this as stream
return *this;
}
void simpleLogger::set_now(builtin_interfaces::msg::Time &time)
{
//See ros2 demos for more information
std::chrono::nanoseconds now = std::chrono::high_resolution_clock::now().time_since_epoch();
if (now <= std::chrono::nanoseconds(0)) {
time.sec = time.nanosec = 0;
} else {
time.sec = static_cast<builtin_interfaces::msg::Time::_sec_type>(now.count() / 1000000000);
time.nanosec = now.count() % 1000000000;
}
}
simpleLogger::simpleLogger():std::ostream(this)
{
}
int simpleLogger::overflow(int c)
{
if(c == EOF)
return c;
if(c == '\n')
{
//Some thread safety - not perfect
std::lock_guard<std::mutex> lock(globalLogger_mutex);
if(log_stream.str() == "")
return c;
//Prepare ros message
//builtin_interfaces::msg::Time time;
set_now(time);
//msg->level = level;
//msg->stamp = time;
//Get time
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
//Generate loglevel output
std::string levelStr = "";
switch(currentLogLevel)
{
case Debug:
levelStr = printInColor("Debug : ", ConsoleColor::FG_BLUE);
break;
case Info:
levelStr = printInColor("Info : ", ConsoleColor::FG_GREEN);
break;
case Important:
levelStr = printInColor("Important: ", ConsoleColor::FG_WHITE, ConsoleColor::BG_GREEN);
break;
case Warning:
levelStr = printInColor("Warning: ", ConsoleColor::FG_RED);
break;
case Error:
levelStr = printInColor("Error : ", ConsoleColor::FG_RED, ConsoleColor::BG_YELLOW);
break;
case Fatal:
levelStr = printInColor("Fatal : ", ConsoleColor::FG_RED, ConsoleColor::BG_WHITE);
break;
}
std::ostringstream timeStrStream;
//Write preset into log_stream
#if __GNUC__ >= 5
timeStrStream << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X") << " : ";
#else
timeStrStream << ctime (&in_time_t) << " : " ;
#endif
if(printLogLevel <= currentLogLevel)
std::cout << timeStrStream.str() << levelStr << log_stream.str() << std::endl;
if(fileLogLevel <= currentLogLevel && logFileWriter.is_open())
logFileWriter << timeStrStream.str() << levelStr << log_stream.str() << '\n';
if(messageLogLevel <= currentLogLevel && publisher != NULL){
auto msg = std::make_shared<ros2_simple_logger::msg::LoggingMessage>();
msg->stamp = time;
msg->level = messageLogLevel;
msg->message = log_stream.str();
publisher->publish(msg);
}
log_stream.str("");
}
else
{
log_stream << (char)c;
}
return c;
}
bool simpleLogger::check_if_file_exists(const std::__cxx11::string filename)
{
std::ifstream file(filename);
return file.good();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.