text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "OpenableControlViewModelBase.h"
#include "IReactionControllerModel.h"
namespace ExampleApp
{
namespace OpenableControl
{
namespace View
{
OpenableControlViewModelBase::OpenableControlViewModelBase(Reaction::View::IReactionControllerModel& reactionControllerModel)
: m_openState(0.f)
, m_reactionControllerModel(reactionControllerModel)
{
}
OpenableControlViewModelBase::~OpenableControlViewModelBase()
{
}
bool OpenableControlViewModelBase::HasReactorControl() const
{
return m_reactionControllerModel.HasModalControl(GetIdentity());
}
bool OpenableControlViewModelBase::TryAcquireReactorControl()
{
if(m_reactionControllerModel.IsModalControlAcquired())
{
return m_reactionControllerModel.HasModalControl(GetIdentity());
}
else
{
m_reactionControllerModel.AcquireModalControl(GetIdentity());
return true;
}
}
bool OpenableControlViewModelBase::TryAcquireOpenableControl()
{
if(m_reactionControllerModel.IsAnyOpenableOpen())
{
return m_reactionControllerModel.IsOpenableOpen(GetIdentity());
}
else
{
m_reactionControllerModel.AcquireOpenableOpen(GetIdentity());
return true;
}
}
void OpenableControlViewModelBase::ReleaseOpenableControl()
{
if(m_reactionControllerModel.IsOpenableOpen(GetIdentity()))
{
m_reactionControllerModel.ReleaseOpenableOpen(GetIdentity());
}
}
void OpenableControlViewModelBase::ReleaseReactorControl()
{
return m_reactionControllerModel.ReleaseModalControl(GetIdentity());
}
bool OpenableControlViewModelBase::Open(bool acquireReactor)
{
if (!acquireReactor)
{
m_openState = 1.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
return true;
}
else if(TryAcquireReactorControl())
{
m_openState = 1.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
ReleaseReactorControl();
{
const bool acquiredOpenableControl = TryAcquireOpenableControl();
Eegeo_ASSERT(acquiredOpenableControl, "failed to acquire openable control");
}
return true;
}
return false;
}
bool OpenableControlViewModelBase::Close(bool releaseReactor)
{
if (!releaseReactor)
{
m_openState = 0.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
return true;
}
else if(TryAcquireReactorControl())
{
m_openState = 0.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
ReleaseReactorControl();
ReleaseOpenableControl();
return true;
}
return false;
}
void OpenableControlViewModelBase::UpdateOpenState(float openState)
{
Eegeo_ASSERT(openState >= 0.f && openState <= 1.f, "Invalid value %f for open state, valid range for UI open-state is 0.0 to 1.0 inclusive.\n", openState)
{
const bool acquiredReactorControl = TryAcquireReactorControl();
Eegeo_ASSERT(acquiredReactorControl, "failed to acquire reactor control");
}
if(openState < 1.f)
{
ReleaseOpenableControl();
}
m_openState = openState;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
}
void OpenableControlViewModelBase::InsertOpenStateChangedCallback(Eegeo::Helpers::ICallback2<IOpenableControlViewModel&, float>& callback)
{
m_openStateChangedCallbacks.AddCallback(callback);
}
void OpenableControlViewModelBase::RemoveOpenStateChangedCallback(Eegeo::Helpers::ICallback2<IOpenableControlViewModel&, float>& callback)
{
m_openStateChangedCallbacks.RemoveCallback(callback);
}
bool OpenableControlViewModelBase::IsFullyOpen() const
{
return OpenState() == 1.f;
}
bool OpenableControlViewModelBase::IsFullyClosed() const
{
return OpenState() == 0.f;
}
float OpenableControlViewModelBase::OpenState() const
{
return m_openState;
}
}
}
}
<commit_msg>Fix for MPLY-8398. Forgot to commit a line. See commit 4bd88cb540df. Buddy: Calum<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "OpenableControlViewModelBase.h"
#include "IReactionControllerModel.h"
namespace ExampleApp
{
namespace OpenableControl
{
namespace View
{
OpenableControlViewModelBase::OpenableControlViewModelBase(Reaction::View::IReactionControllerModel& reactionControllerModel)
: m_openState(0.f)
, m_reactionControllerModel(reactionControllerModel)
{
}
OpenableControlViewModelBase::~OpenableControlViewModelBase()
{
}
bool OpenableControlViewModelBase::HasReactorControl() const
{
return m_reactionControllerModel.HasModalControl(GetIdentity());
}
bool OpenableControlViewModelBase::TryAcquireReactorControl()
{
if(m_reactionControllerModel.IsModalControlAcquired())
{
return m_reactionControllerModel.HasModalControl(GetIdentity());
}
else
{
m_reactionControllerModel.AcquireModalControl(GetIdentity());
return true;
}
}
bool OpenableControlViewModelBase::TryAcquireOpenableControl()
{
if(m_reactionControllerModel.IsAnyOpenableOpen())
{
return m_reactionControllerModel.IsOpenableOpen(GetIdentity());
}
else
{
m_reactionControllerModel.AcquireOpenableOpen(GetIdentity());
return true;
}
}
void OpenableControlViewModelBase::ReleaseOpenableControl()
{
if(m_reactionControllerModel.IsOpenableOpen(GetIdentity()))
{
m_reactionControllerModel.ReleaseOpenableOpen(GetIdentity());
}
}
void OpenableControlViewModelBase::ReleaseReactorControl()
{
return m_reactionControllerModel.ReleaseModalControl(GetIdentity());
}
bool OpenableControlViewModelBase::Open(bool acquireReactor)
{
if (!acquireReactor)
{
m_openState = 1.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
return true;
}
else if(TryAcquireReactorControl())
{
m_openState = 1.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
{
const bool acquiredOpenableControl = TryAcquireOpenableControl();
Eegeo_ASSERT(acquiredOpenableControl, "failed to acquire openable control");
}
return true;
}
return false;
}
bool OpenableControlViewModelBase::Close(bool releaseReactor)
{
if (!releaseReactor)
{
m_openState = 0.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
return true;
}
else if(TryAcquireReactorControl())
{
m_openState = 0.f;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
ReleaseReactorControl();
ReleaseOpenableControl();
return true;
}
return false;
}
void OpenableControlViewModelBase::UpdateOpenState(float openState)
{
Eegeo_ASSERT(openState >= 0.f && openState <= 1.f, "Invalid value %f for open state, valid range for UI open-state is 0.0 to 1.0 inclusive.\n", openState)
{
const bool acquiredReactorControl = TryAcquireReactorControl();
Eegeo_ASSERT(acquiredReactorControl, "failed to acquire reactor control");
}
if(openState < 1.f)
{
ReleaseOpenableControl();
}
m_openState = openState;
m_openStateChangedCallbacks.ExecuteCallbacks(*this, m_openState);
}
void OpenableControlViewModelBase::InsertOpenStateChangedCallback(Eegeo::Helpers::ICallback2<IOpenableControlViewModel&, float>& callback)
{
m_openStateChangedCallbacks.AddCallback(callback);
}
void OpenableControlViewModelBase::RemoveOpenStateChangedCallback(Eegeo::Helpers::ICallback2<IOpenableControlViewModel&, float>& callback)
{
m_openStateChangedCallbacks.RemoveCallback(callback);
}
bool OpenableControlViewModelBase::IsFullyOpen() const
{
return OpenState() == 1.f;
}
bool OpenableControlViewModelBase::IsFullyClosed() const
{
return OpenState() == 0.f;
}
float OpenableControlViewModelBase::OpenState() const
{
return m_openState;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "DCCSock.h"
#include "User.h"
#include "Utils.h"
CDCCSock::~CDCCSock() {
if ((m_pFile) && (!m_bNoDelFile)) {
m_pFile->Close();
delete m_pFile;
}
if (m_pUser) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CDCCSock::ReadData(const char* data, int len) {
if (!m_pFile) {
DEBUG("File not open! closing get.");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!");
Close();
}
if (m_bSend) {
m_sSendBuf.append(data, len);
while (m_sSendBuf.size() >= 4) {
unsigned int iRemoteSoFar;
memcpy(&iRemoteSoFar, m_sSendBuf.data(), 4);
iRemoteSoFar = ntohl(iRemoteSoFar);
if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) {
SendPacket();
}
m_sSendBuf.erase(0, 4);
}
} else {
m_pFile->Write(data, len);
m_uBytesSoFar += len;
unsigned long uSoFar = htonl(m_uBytesSoFar);
Write((char*) &uSoFar, sizeof(unsigned long));
if (m_uBytesSoFar >= m_uFileSize) {
Close();
}
}
}
void CDCCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused.");
}
void CDCCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out.");
}
void CDCCSock::SockError(int iErrno) {
DEBUG(GetSockName() << " == SockError(" << iErrno << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + CString(iErrno) + "]");
}
void CDCCSock::Connected() {
DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started.");
if (m_bSend) {
SendPacket();
}
SetTimeout(120);
}
void CDCCSock::Disconnected() {
const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - ";
DEBUG(GetSockName() << " == Disconnected()");
if (m_uBytesSoFar > m_uFileSize) {
m_pUser->PutModule(m_sModuleName, sStart + "TooMuchData!");
} else if (m_uBytesSoFar == m_uFileSize) {
if (m_bSend) {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Sent [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]");
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Saved to [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]");
}
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Incomplete!");
}
}
void CDCCSock::SendPacket() {
if (!m_pFile) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely.");
Close();
return;
}
char szBuf[4096];
int iLen = m_pFile->Read(szBuf, 4096);
if (iLen < 0) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file.");
Close();
return;
}
if (iLen > 0) {
Write(szBuf, iLen);
m_uBytesSoFar += iLen;
}
}
Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) {
Close();
CDCCSock* pSock = new CDCCSock(m_pUser, m_sRemoteNick, m_sLocalFile, m_sModuleName, m_uFileSize, m_pFile);
pSock->SetSockName("DCC::SEND::" + m_sRemoteNick);
pSock->SetTimeout(120);
pSock->SetFileName(m_sFileName);
pSock->SetFileOffset(m_uBytesSoFar);
m_bNoDelFile = true;
return pSock;
}
CFile* CDCCSock::OpenFile(bool bWrite) {
if ((m_pFile) || (m_sLocalFile.empty())) {
m_pUser->PutModule(m_sModuleName, ((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file.");
return false;
}
m_pFile = new CFile(m_sLocalFile);
if (bWrite) {
if (m_pFile->Exists()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
} else {
if (!m_pFile->IsReg()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
m_uFileSize = m_pFile->GetSize();
}
m_sFileName = m_pFile->GetShortName();
return m_pFile;
}
<commit_msg>Fix an implicit (CFile *) false (this should have been NULL for sure)<commit_after>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "DCCSock.h"
#include "User.h"
#include "Utils.h"
CDCCSock::~CDCCSock() {
if ((m_pFile) && (!m_bNoDelFile)) {
m_pFile->Close();
delete m_pFile;
}
if (m_pUser) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CDCCSock::ReadData(const char* data, int len) {
if (!m_pFile) {
DEBUG("File not open! closing get.");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!");
Close();
}
if (m_bSend) {
m_sSendBuf.append(data, len);
while (m_sSendBuf.size() >= 4) {
unsigned int iRemoteSoFar;
memcpy(&iRemoteSoFar, m_sSendBuf.data(), 4);
iRemoteSoFar = ntohl(iRemoteSoFar);
if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) {
SendPacket();
}
m_sSendBuf.erase(0, 4);
}
} else {
m_pFile->Write(data, len);
m_uBytesSoFar += len;
unsigned long uSoFar = htonl(m_uBytesSoFar);
Write((char*) &uSoFar, sizeof(unsigned long));
if (m_uBytesSoFar >= m_uFileSize) {
Close();
}
}
}
void CDCCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused.");
}
void CDCCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out.");
}
void CDCCSock::SockError(int iErrno) {
DEBUG(GetSockName() << " == SockError(" << iErrno << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + CString(iErrno) + "]");
}
void CDCCSock::Connected() {
DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started.");
if (m_bSend) {
SendPacket();
}
SetTimeout(120);
}
void CDCCSock::Disconnected() {
const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - ";
DEBUG(GetSockName() << " == Disconnected()");
if (m_uBytesSoFar > m_uFileSize) {
m_pUser->PutModule(m_sModuleName, sStart + "TooMuchData!");
} else if (m_uBytesSoFar == m_uFileSize) {
if (m_bSend) {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Sent [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]");
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Saved to [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]");
}
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Incomplete!");
}
}
void CDCCSock::SendPacket() {
if (!m_pFile) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely.");
Close();
return;
}
char szBuf[4096];
int iLen = m_pFile->Read(szBuf, 4096);
if (iLen < 0) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file.");
Close();
return;
}
if (iLen > 0) {
Write(szBuf, iLen);
m_uBytesSoFar += iLen;
}
}
Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) {
Close();
CDCCSock* pSock = new CDCCSock(m_pUser, m_sRemoteNick, m_sLocalFile, m_sModuleName, m_uFileSize, m_pFile);
pSock->SetSockName("DCC::SEND::" + m_sRemoteNick);
pSock->SetTimeout(120);
pSock->SetFileName(m_sFileName);
pSock->SetFileOffset(m_uBytesSoFar);
m_bNoDelFile = true;
return pSock;
}
CFile* CDCCSock::OpenFile(bool bWrite) {
if ((m_pFile) || (m_sLocalFile.empty())) {
m_pUser->PutModule(m_sModuleName, ((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file.");
return NULL;
}
m_pFile = new CFile(m_sLocalFile);
if (bWrite) {
if (m_pFile->Exists()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
} else {
if (!m_pFile->IsReg()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
m_uFileSize = m_pFile->GetSize();
}
m_sFileName = m_pFile->GetShortName();
return m_pFile;
}
<|endoftext|>
|
<commit_before>//===--- Stack.h - Utilities for dealing with stack space -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Defines utilities for dealing with stack allocation and stack space.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Stack.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/CrashRecoveryContext.h"
static LLVM_THREAD_LOCAL void *BottomOfStack = nullptr;
static void *getStackPointer() {
#if __GNUC__ || __has_builtin(__builtin_frame_address)
return __builtin_frame_address(0);
#elif defined(_MSC_VER)
return _AddressOfReturnAddress();
#else
char CharOnStack = 0;
// The volatile store here is intended to escape the local variable, to
// prevent the compiler from optimizing CharOnStack into anything other
// than a char on the stack.
//
// Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.
char *volatile Ptr = &CharOnStack;
return Ptr;
#endif
}
void clang::noteBottomOfStack() {
if (!BottomOfStack)
BottomOfStack = getStackPointer();
}
bool clang::isStackNearlyExhausted() {
// We consider 256 KiB to be sufficient for any code that runs between checks
// for stack size.
constexpr size_t SufficientStack = 256 << 10;
// If we don't know where the bottom of the stack is, hope for the best.
if (!BottomOfStack)
return false;
intptr_t StackDiff = (intptr_t)getStackPointer() - (intptr_t)BottomOfStack;
size_t StackUsage = (size_t)std::abs(StackDiff);
// If the stack pointer has a surprising value, we do not understand this
// stack usage scheme. (Perhaps the target allocates new stack regions on
// demand for us.) Don't try to guess what's going on.
if (StackUsage > DesiredStackSize)
return false;
return StackUsage >= DesiredStackSize - SufficientStack;
}
void clang::runWithSufficientStackSpaceSlow(llvm::function_ref<void()> Diag,
llvm::function_ref<void()> Fn) {
llvm::CrashRecoveryContext CRC;
CRC.RunSafelyOnThread([&] {
noteBottomOfStack();
Diag();
Fn();
}, DesiredStackSize);
}
<commit_msg>Fix file header.<commit_after>//===--- Stack.cpp - Utilities for dealing with stack space ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Defines utilities for dealing with stack allocation and stack space.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Stack.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/CrashRecoveryContext.h"
static LLVM_THREAD_LOCAL void *BottomOfStack = nullptr;
static void *getStackPointer() {
#if __GNUC__ || __has_builtin(__builtin_frame_address)
return __builtin_frame_address(0);
#elif defined(_MSC_VER)
return _AddressOfReturnAddress();
#else
char CharOnStack = 0;
// The volatile store here is intended to escape the local variable, to
// prevent the compiler from optimizing CharOnStack into anything other
// than a char on the stack.
//
// Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.
char *volatile Ptr = &CharOnStack;
return Ptr;
#endif
}
void clang::noteBottomOfStack() {
if (!BottomOfStack)
BottomOfStack = getStackPointer();
}
bool clang::isStackNearlyExhausted() {
// We consider 256 KiB to be sufficient for any code that runs between checks
// for stack size.
constexpr size_t SufficientStack = 256 << 10;
// If we don't know where the bottom of the stack is, hope for the best.
if (!BottomOfStack)
return false;
intptr_t StackDiff = (intptr_t)getStackPointer() - (intptr_t)BottomOfStack;
size_t StackUsage = (size_t)std::abs(StackDiff);
// If the stack pointer has a surprising value, we do not understand this
// stack usage scheme. (Perhaps the target allocates new stack regions on
// demand for us.) Don't try to guess what's going on.
if (StackUsage > DesiredStackSize)
return false;
return StackUsage >= DesiredStackSize - SufficientStack;
}
void clang::runWithSufficientStackSpaceSlow(llvm::function_ref<void()> Diag,
llvm::function_ref<void()> Fn) {
llvm::CrashRecoveryContext CRC;
CRC.RunSafelyOnThread([&] {
noteBottomOfStack();
Diag();
Fn();
}, DesiredStackSize);
}
<|endoftext|>
|
<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/robust_estimation/rand_sampling.hpp"
#include "testing/testing.h"
#include <set>
using namespace openMVG;
using namespace openMVG::robust;
// Assert that each time exactly N random number are picked (no repetition)
TEST(UniformSampleTest, NoRepetions) {
std::vector<std::size_t> samples;
for (std::size_t total = 1; total < 500; total *= 2)
{
//Size of the data set
for (std::size_t num_samples = 1; num_samples <= total; num_samples *= 2)
{ //Size of the consensus set
UniformSample(num_samples, total, &samples);
std::set<std::size_t> myset;
for (std::size_t i = 0; i < num_samples; ++i)
{
myset.insert(samples[i]);
CHECK(samples[i] >= 0);
CHECK(samples[i] < total);
}
CHECK_EQUAL(num_samples, myset.size());
}
}
}
TEST(UniformSampleTest, NoRepetionsBeginEnd) {
std::vector<std::size_t> samples;
for (std::size_t end = 1; end < 500; end *= 2)
{
//Size of the data set
for (std::size_t num_samples = 1; num_samples <= end; num_samples *= 2)
{
//Size of the consensus set
assert((end-num_samples) >= 0);
const std::size_t begin = end-num_samples;
UniformSample(begin, end, num_samples, &samples);
std::set<std::size_t> myset;
for (std::size_t i = 0; i < num_samples; ++i)
{
myset.insert(samples[i]);
CHECK(samples[i] >= begin);
CHECK(samples[i] < end);
}
CHECK_EQUAL(num_samples, myset.size());
}
}
}
TEST(UniformSampleTest, randSample) {
for (std::size_t upperBound = 1; upperBound < 501; upperBound *= 2)
{
for (std::size_t numSamples = 1; numSamples <= upperBound; numSamples *= 2)
{
assert((upperBound-numSamples) >= 0);
const std::size_t lowerBound = upperBound-numSamples;
const auto samples = randSample<std::size_t>(lowerBound, upperBound, numSamples);
std::set<std::size_t> myset;
// std::cout << "Upper " << upperBound << " Lower " << lowerBound << " numSamples " << numSamples << "\n";
for (std::size_t i = 0; i < numSamples; ++i)
{
// std::cout << samples[i] << " ";
myset.insert(samples[i]);
CHECK(samples[i] >= lowerBound);
CHECK(samples[i] < upperBound);
}
// std::cout << "\n";
// this verifies no repetitions
CHECK_EQUAL(numSamples, myset.size());
}
}
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<commit_msg>[robust_estimation] better test coverage<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/robust_estimation/rand_sampling.hpp"
#include "testing/testing.h"
#include <set>
#include <vector>
using namespace openMVG;
using namespace openMVG::robust;
// Assert that each time exactly N random number are picked (no repetition)
TEST(UniformSampleTest, NoRepetions) {
for(std::size_t upperBound = 1; upperBound < 513; upperBound *= 2)
{
//Size of the data set
for(std::size_t numSamples = 1; numSamples <= upperBound; numSamples *= 2)
{
//Size of the consensus set
std::vector<std::size_t> samples;
std::cout << "Upper " << upperBound << " Lower " << 0 << " numSamples " << numSamples << "\n";
UniformSample(numSamples, upperBound, &samples);
std::set<std::size_t> myset;
for(const auto& s : samples)
{
myset.insert(s);
CHECK(s >= 0);
CHECK(s < upperBound);
}
CHECK_EQUAL(num_samples, myset.size());
}
}
}
TEST(UniformSampleTest, NoRepetionsBeginEnd) {
for(std::size_t upperBound = 1; upperBound < 513; upperBound *= 2)
{
//Size of the data set
for(std::size_t numSamples = 1; numSamples <= upperBound; numSamples *= 2)
{
//Size of the consensus set
assert((upperBound-numSamples) >= 0);
const std::size_t begin = upperBound-numSamples;
std::cout << "Upper " << upperBound << " Lower " << begin << " numSamples " << numSamples << "\n";
std::vector<std::size_t> samples;
UniformSample(begin, upperBound, numSamples, &samples);
std::set<std::size_t> myset;
for(const auto& s : samples)
{
myset.insert(s);
CHECK(s >= begin);
CHECK(s < upperBound);
}
CHECK_EQUAL(numSamples, myset.size());
}
}
}
TEST(UniformSampleTest, randSample) {
for(std::size_t upperBound = 1; upperBound < 513; upperBound *= 2)
{
for(std::size_t numSamples = 1; numSamples <= upperBound; numSamples *= 2)
{
assert((upperBound-numSamples) >= 0);
const std::size_t lowerBound = upperBound-numSamples;
const auto samples = randSample<std::size_t>(lowerBound, upperBound, numSamples);
std::set<std::size_t> myset;
std::cout << "Upper " << upperBound << " Lower " << lowerBound << " numSamples " << numSamples << "\n";
for(const auto& s : samples)
{
// std::cout << samples[i] << " ";
myset.insert(s);
CHECK(s >= lowerBound);
CHECK(s < upperBound);
}
// std::cout << "\n";
// this verifies no repetitions
CHECK_EQUAL(numSamples, myset.size());
}
}
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "disktexture2d.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/input/texturesource.h"
#include "renderer/modeling/texture/texture.h"
#include "renderer/utility/messagecontext.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/colorspace.h"
#include "foundation/image/genericprogressiveimagefilereader.h"
#include "foundation/image/tile.h"
#include "foundation/platform/thread.h"
#include "foundation/utility/api/apistring.h"
#include "foundation/utility/api/specializedapiarrays.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/makevector.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/string.h"
#include "foundation/utility/uid.h"
// Standard headers.
#include <cstddef>
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// 2D on-disk texture.
//
const char* Model = "disk_texture_2d";
class DiskTexture2d
: public Texture
{
public:
DiskTexture2d(
const char* name,
const ParamArray& params,
const SearchPaths& search_paths)
: Texture(name, params)
, m_reader(&global_logger())
{
const EntityDefMessageContext context("texture", this);
// Establish and store the qualified path to the texture file.
m_filepath = to_string(search_paths.qualify(m_params.get_required<string>("filename", "")));
// Retrieve the color space.
const string color_space =
m_params.get_required<string>(
"color_space",
"linear_rgb",
make_vector("linear_rgb", "srgb", "ciexyz"),
context);
if (color_space == "linear_rgb")
m_color_space = ColorSpaceLinearRGB;
else if (color_space == "srgb")
m_color_space = ColorSpaceSRGB;
else m_color_space = ColorSpaceCIEXYZ;
}
void release() override
{
delete this;
}
const char* get_model() const override
{
return Model;
}
void on_render_end(
const Project& project,
const BaseGroup* parent) override
{
if (m_reader.is_open())
m_reader.close();
Texture::on_render_end(project, parent);
}
ColorSpace get_color_space() const override
{
return m_color_space;
}
void collect_asset_paths(StringArray& paths) const override
{
if (m_params.strings().exist("filename"))
{
const char* filename = m_params.get("filename");
if (!is_empty_string(filename))
paths.push_back(filename);
}
}
void update_asset_paths(const StringDictionary& mappings) override
{
m_params.set("filename", mappings.get(m_params.get("filename")));
}
const CanvasProperties& properties() override
{
boost::mutex::scoped_lock lock(m_mutex);
open_image_file();
return m_props;
}
Source* create_source(
const UniqueID assembly_uid,
const TextureInstance& texture_instance) override
{
return new TextureSource(assembly_uid, texture_instance);
}
Tile* load_tile(
const size_t tile_x,
const size_t tile_y) override
{
boost::mutex::scoped_lock lock(m_mutex);
open_image_file();
return m_reader.read_tile(tile_x, tile_y);
}
void unload_tile(
const size_t tile_x,
const size_t tile_y,
const Tile* tile) override
{
delete tile;
}
private:
string m_filepath;
ColorSpace m_color_space;
mutable boost::mutex m_mutex;
GenericProgressiveImageFileReader m_reader;
CanvasProperties m_props;
void open_image_file()
{
if (!m_reader.is_open())
{
RENDERER_LOG_INFO(
"opening texture file %s and reading metadata...",
m_filepath.c_str());
m_reader.open(m_filepath.c_str());
m_reader.read_canvas_properties(m_props);
}
}
};
}
//
// DiskTexture2dFactory class implementation.
//
void DiskTexture2dFactory::release()
{
delete this;
}
const char* DiskTexture2dFactory::get_model() const
{
return Model;
}
Dictionary DiskTexture2dFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "2D Texture File")
.insert("default_model", "true");
}
DictionaryArray DiskTexture2dFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "filename")
.insert("label", "File Path")
.insert("type", "file")
.insert("file_picker_mode", "open")
.insert("file_picker_type", "image")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "color_space")
.insert("label", "Color Space")
.insert("type", "enumeration")
.insert("items",
Dictionary()
.insert("Linear RGB", "linear_rgb")
.insert("sRGB", "srgb")
.insert("CIE XYZ", "ciexyz"))
.insert("use", "required")
.insert("default", "srgb"));
return metadata;
}
auto_release_ptr<Texture> DiskTexture2dFactory::create(
const char* name,
const ParamArray& params,
const SearchPaths& search_paths) const
{
return auto_release_ptr<Texture>(new DiskTexture2d(name, params, search_paths));
}
} // namespace renderer
<commit_msg>Emit log message when closing texture file<commit_after>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "disktexture2d.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/input/texturesource.h"
#include "renderer/modeling/texture/texture.h"
#include "renderer/utility/messagecontext.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/colorspace.h"
#include "foundation/image/genericprogressiveimagefilereader.h"
#include "foundation/image/tile.h"
#include "foundation/platform/thread.h"
#include "foundation/utility/api/apistring.h"
#include "foundation/utility/api/specializedapiarrays.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/makevector.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/string.h"
#include "foundation/utility/uid.h"
// Standard headers.
#include <cstddef>
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// 2D on-disk texture.
//
const char* Model = "disk_texture_2d";
class DiskTexture2d
: public Texture
{
public:
DiskTexture2d(
const char* name,
const ParamArray& params,
const SearchPaths& search_paths)
: Texture(name, params)
, m_reader(&global_logger())
{
const EntityDefMessageContext context("texture", this);
// Establish and store the qualified path to the texture file.
m_filepath = to_string(search_paths.qualify(m_params.get_required<string>("filename", "")));
// Retrieve the color space.
const string color_space =
m_params.get_required<string>(
"color_space",
"linear_rgb",
make_vector("linear_rgb", "srgb", "ciexyz"),
context);
if (color_space == "linear_rgb")
m_color_space = ColorSpaceLinearRGB;
else if (color_space == "srgb")
m_color_space = ColorSpaceSRGB;
else m_color_space = ColorSpaceCIEXYZ;
}
void release() override
{
delete this;
}
const char* get_model() const override
{
return Model;
}
void on_render_end(
const Project& project,
const BaseGroup* parent) override
{
if (m_reader.is_open())
{
RENDERER_LOG_INFO("closing texture file %s...", m_filepath.c_str());
m_reader.close();
}
Texture::on_render_end(project, parent);
}
ColorSpace get_color_space() const override
{
return m_color_space;
}
void collect_asset_paths(StringArray& paths) const override
{
if (m_params.strings().exist("filename"))
{
const char* filename = m_params.get("filename");
if (!is_empty_string(filename))
paths.push_back(filename);
}
}
void update_asset_paths(const StringDictionary& mappings) override
{
m_params.set("filename", mappings.get(m_params.get("filename")));
}
const CanvasProperties& properties() override
{
boost::mutex::scoped_lock lock(m_mutex);
open_image_file();
return m_props;
}
Source* create_source(
const UniqueID assembly_uid,
const TextureInstance& texture_instance) override
{
return new TextureSource(assembly_uid, texture_instance);
}
Tile* load_tile(
const size_t tile_x,
const size_t tile_y) override
{
boost::mutex::scoped_lock lock(m_mutex);
open_image_file();
return m_reader.read_tile(tile_x, tile_y);
}
void unload_tile(
const size_t tile_x,
const size_t tile_y,
const Tile* tile) override
{
delete tile;
}
private:
string m_filepath;
ColorSpace m_color_space;
mutable boost::mutex m_mutex;
GenericProgressiveImageFileReader m_reader;
CanvasProperties m_props;
void open_image_file()
{
if (!m_reader.is_open())
{
RENDERER_LOG_INFO(
"opening texture file %s and reading metadata...",
m_filepath.c_str());
m_reader.open(m_filepath.c_str());
m_reader.read_canvas_properties(m_props);
}
}
};
}
//
// DiskTexture2dFactory class implementation.
//
void DiskTexture2dFactory::release()
{
delete this;
}
const char* DiskTexture2dFactory::get_model() const
{
return Model;
}
Dictionary DiskTexture2dFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "2D Texture File")
.insert("default_model", "true");
}
DictionaryArray DiskTexture2dFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "filename")
.insert("label", "File Path")
.insert("type", "file")
.insert("file_picker_mode", "open")
.insert("file_picker_type", "image")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "color_space")
.insert("label", "Color Space")
.insert("type", "enumeration")
.insert("items",
Dictionary()
.insert("Linear RGB", "linear_rgb")
.insert("sRGB", "srgb")
.insert("CIE XYZ", "ciexyz"))
.insert("use", "required")
.insert("default", "srgb"));
return metadata;
}
auto_release_ptr<Texture> DiskTexture2dFactory::create(
const char* name,
const ParamArray& params,
const SearchPaths& search_paths) const
{
return auto_release_ptr<Texture>(new DiskTexture2d(name, params, search_paths));
}
} // namespace renderer
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include <mesos/docker/spec.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <process/io.hpp>
#include <process/process.hpp>
#include <process/subprocess.hpp>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/os/constants.hpp>
#include "common/status_utils.hpp"
#include "slave/containerizer/mesos/provisioner/backends/copy.hpp"
using namespace process;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
class CopyBackendProcess : public Process<CopyBackendProcess>
{
public:
CopyBackendProcess()
: ProcessBase(process::ID::generate("copy-provisioner-backend")) {}
Future<Nothing> provision(const vector<string>& layers, const string& rootfs);
Future<bool> destroy(const string& rootfs);
private:
Future<Nothing> _provision(string layer, const string& rootfs);
};
Try<Owned<Backend>> CopyBackend::create(const Flags&)
{
return Owned<Backend>(new CopyBackend(
Owned<CopyBackendProcess>(new CopyBackendProcess())));
}
CopyBackend::~CopyBackend()
{
terminate(process.get());
wait(process.get());
}
CopyBackend::CopyBackend(Owned<CopyBackendProcess> _process)
: process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Future<Nothing> CopyBackend::provision(
const vector<string>& layers,
const string& rootfs,
const string& backendDir)
{
return dispatch(
process.get(), &CopyBackendProcess::provision, layers, rootfs);
}
Future<bool> CopyBackend::destroy(
const string& rootfs,
const string& backendDir)
{
return dispatch(process.get(), &CopyBackendProcess::destroy, rootfs);
}
Future<Nothing> CopyBackendProcess::provision(
const vector<string>& layers,
const string& rootfs)
{
if (layers.size() == 0) {
return Failure("No filesystem layers provided");
}
if (os::exists(rootfs)) {
return Failure("Rootfs is already provisioned");
}
Try<Nothing> mkdir = os::mkdir(rootfs);
if (mkdir.isError()) {
return Failure("Failed to create rootfs directory: " + mkdir.error());
}
vector<Future<Nothing>> futures{Nothing()};
foreach (const string layer, layers) {
futures.push_back(
futures.back().then(
defer(self(), &Self::_provision, layer, rootfs)));
}
return collect(futures)
.then([]() -> Future<Nothing> { return Nothing(); });
}
Future<Nothing> CopyBackendProcess::_provision(
string layer,
const string& rootfs)
{
#ifndef __WINDOWS__
// Traverse the layer to check if there is any whiteout files, if
// yes, remove the corresponding files/directories from the rootfs.
// Note: We assume all image types use AUFS whiteout format.
char* source[] = {const_cast<char*>(layer.c_str()), nullptr};
FTS* tree = ::fts_open(source, FTS_NOCHDIR | FTS_PHYSICAL, nullptr);
if (tree == nullptr) {
return Failure("Failed to open '" + layer + "': " + os::strerror(errno));
}
vector<string> whiteouts;
for (FTSENT *node = ::fts_read(tree);
node != nullptr; node = ::fts_read(tree)) {
string ftsPath = string(node->fts_path);
if (node->fts_info == FTS_DNR ||
node->fts_info == FTS_ERR ||
node->fts_info == FTS_NS) {
return Failure(
"Failed to read '" + ftsPath + "': " + os::strerror(node->fts_errno));
}
// Skip the postorder visit of a directory.
// See the manpage of fts_read in the following link:
// http://man7.org/linux/man-pages/man3/fts_read.3.html
if (node->fts_info == FTS_DP) {
continue;
}
if (ftsPath == layer) {
continue;
}
string layerPath = ftsPath.substr(layer.length() + 1);
string rootfsPath = path::join(rootfs, layerPath);
Option<string> removePath;
// Handle whiteout files.
if (node->fts_info == FTS_F &&
strings::startsWith(node->fts_name, docker::spec::WHITEOUT_PREFIX)) {
Path whiteout = Path(layerPath);
// Keep the absolute paths of the whiteout files, we will
// remove them from rootfs after layer is copied to rootfs.
whiteouts.push_back(rootfsPath);
if (node->fts_name == string(docker::spec::WHITEOUT_OPAQUE_PREFIX)) {
removePath = path::join(rootfs, whiteout.dirname());
} else {
removePath = path::join(
rootfs,
whiteout.dirname(),
whiteout.basename().substr(strlen(docker::spec::WHITEOUT_PREFIX)));
}
}
if (os::exists(rootfsPath)) {
bool ftsIsDir = node->fts_info == FTS_D || node->fts_info == FTS_DC;
if (os::stat::isdir(rootfsPath) != ftsIsDir) {
// Handle overwriting between a directory and a non-directory.
// Note: If a symlink is overwritten by a directory, the symlink
// must be removed before the directory is traversed so the
// following case won't cause a security issue:
// ROOTFS: /bad@ -> /usr
// LAYER: /bad/bin/.wh.wh.opq
removePath = rootfsPath;
} else if (os::stat::islink(rootfsPath)) {
// Handle overwriting a symlink with a regular file.
// Note: The symlink must be removed, or 'cp' would follow the
// link and overwrite the target instead of the link itself,
// which would cause a security issue in the following case:
// ROOTFS: /bad@ -> /usr/bin/python
// LAYER: /bad is a malicious executable
removePath = rootfsPath;
}
}
// The file/directory referred to by removePath may be empty or have
// already been removed because its parent directory is labeled as
// opaque whiteout or overwritten by a file, so here we need to
// check if it exists before trying to remove it.
if (removePath.isSome() && os::exists(removePath.get())) {
if (os::stat::isdir(removePath.get())) {
// It is OK to remove the entire directory labeled as opaque
// whiteout, since the same directory exists in this layer and
// will be copied back to rootfs.
Try<Nothing> rmdir = os::rmdir(removePath.get());
if (rmdir.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove directory '" +
removePath.get() + "': " + rmdir.error());
}
} else {
Try<Nothing> rm = os::rm(removePath.get());
if (rm.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove file '" +
removePath.get() + "': " + rm.error());
}
}
}
}
if (errno != 0) {
Error error = ErrnoError();
::fts_close(tree);
return Failure(error);
}
if (::fts_close(tree) != 0) {
return Failure(
"Failed to stop traversing file system: " + os::strerror(errno));
}
VLOG(1) << "Copying layer path '" << layer << "' to rootfs '" << rootfs
<< "'";
#if defined(__APPLE__) || defined(__FreeBSD__)
if (!strings::endsWith(layer, "/")) {
layer += "/";
}
// BSD cp doesn't support -T flag, but supports source trailing
// slash so we only copy the content but not the folder.
vector<string> args{"cp", "-a", layer, rootfs};
#else
vector<string> args{"cp", "-aT", layer, rootfs};
#endif // __APPLE__ || __FreeBSD__
Try<Subprocess> s = subprocess(
"cp",
args,
Subprocess::PATH(os::DEV_NULL),
Subprocess::PATH(os::DEV_NULL),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create 'cp' subprocess: " + s.error());
}
Subprocess cp = s.get();
return cp.status()
.then([=](const Option<int>& status) -> Future<Nothing> {
if (status.isNone()) {
return Failure("Failed to reap subprocess to copy image");
} else if (status.get() != 0) {
return io::read(cp.err().get())
.then([](const string& err) -> Future<Nothing> {
return Failure("Failed to copy layer: " + err);
});
}
// Remove the whiteout files from rootfs.
foreach (const string whiteout, whiteouts) {
Try<Nothing> rm = os::rm(whiteout);
if (rm.isError()) {
return Failure(
"Failed to remove whiteout file '" +
whiteout + "': " + rm.error());
}
}
return Nothing();
});
#else
return Failure(
"Provisioning a rootfs from an image is not supported on Windows");
#endif // __WINDOWS__
}
Future<bool> CopyBackendProcess::destroy(const string& rootfs)
{
vector<string> argv{"rm", "-rf", rootfs};
Try<Subprocess> s = subprocess(
"rm",
argv,
Subprocess::PATH(os::DEV_NULL),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO));
if (s.isError()) {
return Failure("Failed to create 'rm' subprocess: " + s.error());
}
return s->status()
.then([](const Option<int>& status) -> Future<bool> {
if (status.isNone()) {
return Failure("Failed to reap subprocess to destroy rootfs");
} else if (status.get() != 0) {
return Failure("Failed to destroy rootfs, exit status: " +
WSTRINGIFY(status.get()));
}
return true;
});
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Made copy backend destroy more robust.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include <mesos/docker/spec.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <process/io.hpp>
#include <process/process.hpp>
#include <process/subprocess.hpp>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/os/constants.hpp>
#include "common/status_utils.hpp"
#include "slave/containerizer/mesos/provisioner/backends/copy.hpp"
using namespace process;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
class CopyBackendProcess : public Process<CopyBackendProcess>
{
public:
CopyBackendProcess()
: ProcessBase(process::ID::generate("copy-provisioner-backend")) {}
Future<Nothing> provision(const vector<string>& layers, const string& rootfs);
Future<bool> destroy(const string& rootfs);
private:
Future<Nothing> _provision(string layer, const string& rootfs);
};
Try<Owned<Backend>> CopyBackend::create(const Flags&)
{
return Owned<Backend>(new CopyBackend(
Owned<CopyBackendProcess>(new CopyBackendProcess())));
}
CopyBackend::~CopyBackend()
{
terminate(process.get());
wait(process.get());
}
CopyBackend::CopyBackend(Owned<CopyBackendProcess> _process)
: process(_process)
{
spawn(CHECK_NOTNULL(process.get()));
}
Future<Nothing> CopyBackend::provision(
const vector<string>& layers,
const string& rootfs,
const string& backendDir)
{
return dispatch(
process.get(), &CopyBackendProcess::provision, layers, rootfs);
}
Future<bool> CopyBackend::destroy(
const string& rootfs,
const string& backendDir)
{
return dispatch(process.get(), &CopyBackendProcess::destroy, rootfs);
}
Future<Nothing> CopyBackendProcess::provision(
const vector<string>& layers,
const string& rootfs)
{
if (layers.size() == 0) {
return Failure("No filesystem layers provided");
}
if (os::exists(rootfs)) {
return Failure("Rootfs is already provisioned");
}
Try<Nothing> mkdir = os::mkdir(rootfs);
if (mkdir.isError()) {
return Failure("Failed to create rootfs directory: " + mkdir.error());
}
vector<Future<Nothing>> futures{Nothing()};
foreach (const string layer, layers) {
futures.push_back(
futures.back().then(
defer(self(), &Self::_provision, layer, rootfs)));
}
return collect(futures)
.then([]() -> Future<Nothing> { return Nothing(); });
}
Future<Nothing> CopyBackendProcess::_provision(
string layer,
const string& rootfs)
{
#ifndef __WINDOWS__
// Traverse the layer to check if there is any whiteout files, if
// yes, remove the corresponding files/directories from the rootfs.
// Note: We assume all image types use AUFS whiteout format.
char* source[] = {const_cast<char*>(layer.c_str()), nullptr};
FTS* tree = ::fts_open(source, FTS_NOCHDIR | FTS_PHYSICAL, nullptr);
if (tree == nullptr) {
return Failure("Failed to open '" + layer + "': " + os::strerror(errno));
}
vector<string> whiteouts;
for (FTSENT *node = ::fts_read(tree);
node != nullptr; node = ::fts_read(tree)) {
string ftsPath = string(node->fts_path);
if (node->fts_info == FTS_DNR ||
node->fts_info == FTS_ERR ||
node->fts_info == FTS_NS) {
return Failure(
"Failed to read '" + ftsPath + "': " + os::strerror(node->fts_errno));
}
// Skip the postorder visit of a directory.
// See the manpage of fts_read in the following link:
// http://man7.org/linux/man-pages/man3/fts_read.3.html
if (node->fts_info == FTS_DP) {
continue;
}
if (ftsPath == layer) {
continue;
}
string layerPath = ftsPath.substr(layer.length() + 1);
string rootfsPath = path::join(rootfs, layerPath);
Option<string> removePath;
// Handle whiteout files.
if (node->fts_info == FTS_F &&
strings::startsWith(node->fts_name, docker::spec::WHITEOUT_PREFIX)) {
Path whiteout = Path(layerPath);
// Keep the absolute paths of the whiteout files, we will
// remove them from rootfs after layer is copied to rootfs.
whiteouts.push_back(rootfsPath);
if (node->fts_name == string(docker::spec::WHITEOUT_OPAQUE_PREFIX)) {
removePath = path::join(rootfs, whiteout.dirname());
} else {
removePath = path::join(
rootfs,
whiteout.dirname(),
whiteout.basename().substr(strlen(docker::spec::WHITEOUT_PREFIX)));
}
}
if (os::exists(rootfsPath)) {
bool ftsIsDir = node->fts_info == FTS_D || node->fts_info == FTS_DC;
if (os::stat::isdir(rootfsPath) != ftsIsDir) {
// Handle overwriting between a directory and a non-directory.
// Note: If a symlink is overwritten by a directory, the symlink
// must be removed before the directory is traversed so the
// following case won't cause a security issue:
// ROOTFS: /bad@ -> /usr
// LAYER: /bad/bin/.wh.wh.opq
removePath = rootfsPath;
} else if (os::stat::islink(rootfsPath)) {
// Handle overwriting a symlink with a regular file.
// Note: The symlink must be removed, or 'cp' would follow the
// link and overwrite the target instead of the link itself,
// which would cause a security issue in the following case:
// ROOTFS: /bad@ -> /usr/bin/python
// LAYER: /bad is a malicious executable
removePath = rootfsPath;
}
}
// The file/directory referred to by removePath may be empty or have
// already been removed because its parent directory is labeled as
// opaque whiteout or overwritten by a file, so here we need to
// check if it exists before trying to remove it.
if (removePath.isSome() && os::exists(removePath.get())) {
if (os::stat::isdir(removePath.get())) {
// It is OK to remove the entire directory labeled as opaque
// whiteout, since the same directory exists in this layer and
// will be copied back to rootfs.
Try<Nothing> rmdir = os::rmdir(removePath.get());
if (rmdir.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove directory '" +
removePath.get() + "': " + rmdir.error());
}
} else {
Try<Nothing> rm = os::rm(removePath.get());
if (rm.isError()) {
::fts_close(tree);
return Failure(
"Failed to remove file '" +
removePath.get() + "': " + rm.error());
}
}
}
}
if (errno != 0) {
Error error = ErrnoError();
::fts_close(tree);
return Failure(error);
}
if (::fts_close(tree) != 0) {
return Failure(
"Failed to stop traversing file system: " + os::strerror(errno));
}
VLOG(1) << "Copying layer path '" << layer << "' to rootfs '" << rootfs
<< "'";
#if defined(__APPLE__) || defined(__FreeBSD__)
if (!strings::endsWith(layer, "/")) {
layer += "/";
}
// BSD cp doesn't support -T flag, but supports source trailing
// slash so we only copy the content but not the folder.
vector<string> args{"cp", "-a", layer, rootfs};
#else
vector<string> args{"cp", "-aT", layer, rootfs};
#endif // __APPLE__ || __FreeBSD__
Try<Subprocess> s = subprocess(
"cp",
args,
Subprocess::PATH(os::DEV_NULL),
Subprocess::PATH(os::DEV_NULL),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create 'cp' subprocess: " + s.error());
}
Subprocess cp = s.get();
return cp.status()
.then([=](const Option<int>& status) -> Future<Nothing> {
if (status.isNone()) {
return Failure("Failed to reap subprocess to copy image");
} else if (status.get() != 0) {
return io::read(cp.err().get())
.then([](const string& err) -> Future<Nothing> {
return Failure("Failed to copy layer: " + err);
});
}
// Remove the whiteout files from rootfs.
foreach (const string whiteout, whiteouts) {
Try<Nothing> rm = os::rm(whiteout);
if (rm.isError()) {
return Failure(
"Failed to remove whiteout file '" +
whiteout + "': " + rm.error());
}
}
return Nothing();
});
#else
return Failure(
"Provisioning a rootfs from an image is not supported on Windows");
#endif // __WINDOWS__
}
Future<bool> CopyBackendProcess::destroy(const string& rootfs)
{
vector<string> argv{"rm", "-rf", rootfs};
Try<Subprocess> s = subprocess(
"rm",
argv,
Subprocess::PATH(os::DEV_NULL),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO));
if (s.isError()) {
return Failure("Failed to create 'rm' subprocess: " + s.error());
}
return s->status()
.then([](const Option<int>& status) -> Future<bool> {
if (status.isNone()) {
return Failure("Failed to reap subprocess to destroy rootfs");
}
if (status.get() != 0) {
// It's possible that `rm -rf` will fail if some other
// programs are accessing the files. No need to return a hard
// failure here because the directory will be removed later
// and re-attempted on agent recovery.
LOG(ERROR) << "Failed to destroy rootfs, exit status: "
<< WSTRINGIFY(status.get());
}
return true;
});
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>#ifndef STAN_ANALYZE_MCMC_COMPUTE_POTENTIAL_SCALE_REDUCTION_HPP
#define STAN_ANALYZE_MCMC_COMPUTE_POTENTIAL_SCALE_REDUCTION_HPP
#include <stan/math/prim/mat.hpp>
#include <stan/analyze/mcmc/autocovariance.hpp>
#include <stan/analyze/mcmc/split_chains.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <algorithm>
#include <cmath>
#include <vector>
#include <limits>
namespace stan {
namespace analyze {
/**
* Computes the potential scale reduction (Rhat) for the specified
* parameter across all kept samples.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_potential_scale_reduction(
std::vector<const double*> draws, std::vector<size_t> sizes) {
int num_chains = sizes.size();
size_t num_draws = sizes[0];
for (int chain = 1; chain < num_chains; ++chain) {
num_draws = std::min(num_draws, sizes[chain]);
}
// check if chains are constant; all equal to first draw's value
Eigen::VectorXd draw_val(num_chains);
for (int chain = 0; chain < num_chains; chain++)
draw_val(chain) = static_cast<double>(chain);
for (int chain = 0; chain < num_chains; chain++) {
Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(
draws[chain], sizes[chain]);
for (int n = 0; n < num_draws; n++) {
if (!boost::math::isfinite(draw(n))) {
return std::numeric_limits<double>::quiet_NaN();
}
}
if (draw.isApproxToConstant(draw(0))) {
draw_val(chain) = draw(0);
}
}
if (draw_val.isApproxToConstant(draw_val(0))) {
return std::numeric_limits<double>::quiet_NaN();
}
using boost::accumulators::accumulator_set;
using boost::accumulators::stats;
using boost::accumulators::tag::mean;
using boost::accumulators::tag::variance;
Eigen::VectorXd chain_mean(num_chains);
accumulator_set<double, stats<variance>> acc_chain_mean;
Eigen::VectorXd chain_var(num_chains);
double unbiased_var_scale = num_draws / (num_draws - 1.0);
for (int chain = 0; chain < num_chains; ++chain) {
accumulator_set<double, stats<mean, variance>> acc_draw;
for (int n = 0; n < num_draws; ++n) {
acc_draw(draws[chain][n]);
}
chain_mean(chain) = boost::accumulators::mean(acc_draw);
acc_chain_mean(chain_mean(chain));
chain_var(chain) = boost::accumulators::variance(acc_draw)
* unbiased_var_scale;
}
double var_between = num_draws * boost::accumulators::variance(acc_chain_mean)
* num_chains / (num_chains - 1);
double var_within = chain_var.mean();
// rewrote [(n-1)*W/n + B/n]/W as (n-1+ B/W)/n
return sqrt((var_between / var_within + num_draws - 1) / num_draws);
}
/**
* Computes the potential scale reduction (Rhat) for the specified
* parameter across all kept samples.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain. Argument size will be broadcast to
* same length as draws.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_potential_scale_reduction(
std::vector<const double*> draws, size_t size) {
int num_chains = draws.size();
std::vector<size_t> sizes(num_chains, size);
return compute_potential_scale_reduction(draws, sizes);
}
/**
* Computes the split potential scale reduction (Rhat) for the
* specified parameter across all kept samples. When the number of
* total draws N is odd, the (N+1)/2th draw is ignored.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_split_potential_scale_reduction(
std::vector<const double*> draws, std::vector<size_t> sizes) {
int num_chains = sizes.size();
size_t num_draws = sizes[0];
for (int chain = 1; chain < num_chains; ++chain) {
num_draws = std::min(num_draws, sizes[chain]);
}
std::vector<const double*> split_draws = split_chains(draws, sizes);
double half = num_draws / 2.0;
std::vector<size_t> half_sizes(2 * num_chains, std::floor(half));
return compute_potential_scale_reduction(split_draws, half_sizes);
}
/**
* Computes the split potential scale reduction (Rhat) for the
* specified parameter across all kept samples. When the number of
* total draws N is odd, the (N+1)/2th draw is ignored.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain. Argument size will be broadcast to
* same length as draws.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_split_potential_scale_reduction(
std::vector<const double*> draws, size_t size) {
int num_chains = draws.size();
std::vector<size_t> sizes(num_chains, size);
return compute_split_potential_scale_reduction(draws, sizes);
}
} // namespace analyze
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_ANALYZE_MCMC_COMPUTE_POTENTIAL_SCALE_REDUCTION_HPP
#define STAN_ANALYZE_MCMC_COMPUTE_POTENTIAL_SCALE_REDUCTION_HPP
#include <stan/math/prim/mat.hpp>
#include <stan/analyze/mcmc/autocovariance.hpp>
#include <stan/analyze/mcmc/split_chains.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <algorithm>
#include <cmath>
#include <vector>
#include <limits>
namespace stan {
namespace analyze {
/**
* Computes the potential scale reduction (Rhat) for the specified
* parameter across all kept samples.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_potential_scale_reduction(
std::vector<const double*> draws, std::vector<size_t> sizes) {
int num_chains = sizes.size();
size_t num_draws = sizes[0];
for (int chain = 1; chain < num_chains; ++chain) {
num_draws = std::min(num_draws, sizes[chain]);
}
// check if chains are constant; all equal to first draw's value
Eigen::VectorXd draw_val(num_chains);
for (int chain = 0; chain < num_chains; chain++)
draw_val(chain) = static_cast<double>(chain);
for (int chain = 0; chain < num_chains; chain++) {
Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(
draws[chain], sizes[chain]);
for (int n = 0; n < num_draws; n++) {
if (!boost::math::isfinite(draw(n))) {
return std::numeric_limits<double>::quiet_NaN();
}
}
if (draw.isApproxToConstant(draw(0))) {
draw_val(chain) = draw(0);
}
}
if (draw_val.isApproxToConstant(draw_val(0))) {
return std::numeric_limits<double>::quiet_NaN();
}
using boost::accumulators::accumulator_set;
using boost::accumulators::stats;
using boost::accumulators::tag::mean;
using boost::accumulators::tag::variance;
Eigen::VectorXd chain_mean(num_chains);
accumulator_set<double, stats<variance>> acc_chain_mean;
Eigen::VectorXd chain_var(num_chains);
double unbiased_var_scale = num_draws / (num_draws - 1.0);
for (int chain = 0; chain < num_chains; ++chain) {
accumulator_set<double, stats<mean, variance>> acc_draw;
for (int n = 0; n < num_draws; ++n) {
acc_draw(draws[chain][n]);
}
chain_mean(chain) = boost::accumulators::mean(acc_draw);
acc_chain_mean(chain_mean(chain));
chain_var(chain)
= boost::accumulators::variance(acc_draw) * unbiased_var_scale;
}
double var_between = num_draws * boost::accumulators::variance(acc_chain_mean)
* num_chains / (num_chains - 1);
double var_within = chain_var.mean();
// rewrote [(n-1)*W/n + B/n]/W as (n-1+ B/W)/n
return sqrt((var_between / var_within + num_draws - 1) / num_draws);
}
/**
* Computes the potential scale reduction (Rhat) for the specified
* parameter across all kept samples.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain. Argument size will be broadcast to
* same length as draws.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_potential_scale_reduction(
std::vector<const double*> draws, size_t size) {
int num_chains = draws.size();
std::vector<size_t> sizes(num_chains, size);
return compute_potential_scale_reduction(draws, sizes);
}
/**
* Computes the split potential scale reduction (Rhat) for the
* specified parameter across all kept samples. When the number of
* total draws N is odd, the (N+1)/2th draw is ignored.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_split_potential_scale_reduction(
std::vector<const double*> draws, std::vector<size_t> sizes) {
int num_chains = sizes.size();
size_t num_draws = sizes[0];
for (int chain = 1; chain < num_chains; ++chain) {
num_draws = std::min(num_draws, sizes[chain]);
}
std::vector<const double*> split_draws = split_chains(draws, sizes);
double half = num_draws / 2.0;
std::vector<size_t> half_sizes(2 * num_chains, std::floor(half));
return compute_potential_scale_reduction(split_draws, half_sizes);
}
/**
* Computes the split potential scale reduction (Rhat) for the
* specified parameter across all kept samples. When the number of
* total draws N is odd, the (N+1)/2th draw is ignored.
*
* See more details in Stan reference manual section "Potential
* Scale Reduction". http://mc-stan.org/users/documentation
*
* Current implementation assumes draws are stored in contiguous
* blocks of memory. Chains are trimmed from the back to match the
* length of the shortest chain. Argument size will be broadcast to
* same length as draws.
*
* @param draws stores pointers to arrays of chains
* @param sizes stores sizes of chains
* @return potential scale reduction for the specified parameter
*/
inline double compute_split_potential_scale_reduction(
std::vector<const double*> draws, size_t size) {
int num_chains = draws.size();
std::vector<size_t> sizes(num_chains, size);
return compute_split_potential_scale_reduction(draws, sizes);
}
} // namespace analyze
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Eckhart Wörner <ewoerner@kde.org>
//
#include "GpsdConnection.h"
#include "MarbleDebug.h"
#include <errno.h>
using namespace Marble;
GpsdConnection::GpsdConnection( QObject* parent )
: QObject( parent ),
m_timer( 0 )
{
connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
}
void GpsdConnection::initialize()
{
m_timer.stop();
gps_data_t* data = m_gpsd.open();
if ( data ) {
m_status = PositionProviderStatusAcquiring;
emit statusChanged( m_status );
#if defined( GPSD_API_MAJOR_VERSION ) && ( GPSD_API_MAJOR_VERSION >= 3 ) && defined( WATCH_ENABLE )
m_gpsd.stream( WATCH_ENABLE );
#endif
m_timer.start( 1000 );
}
else {
// There is also gps_errstr() for libgps version >= 2.90,
// but it doesn't return a sensible error description
switch ( errno ) {
case NL_NOSERVICE:
m_error = tr("Internal gpsd error (cannot get service entry)");
break;
case NL_NOHOST:
m_error = tr("Internal gpsd error (cannot get host entry)");
break;
case NL_NOPROTO:
m_error = tr("Internal gpsd error (cannot get protocol entry)");
break;
case NL_NOSOCK:
m_error = tr("Internal gpsd error (unable to create socket)");
break;
case NL_NOSOCKOPT:
m_error = tr("Internal gpsd error (unable to set socket option)");
break;
case NL_NOCONNECT:
m_error = tr("No GPS device found by gpsd.");
break;
default:
m_error = tr("Unknown error when opening gpsd connection");
break;
}
m_status = PositionProviderStatusError;
emit statusChanged( m_status );
mDebug() << "Connection to gpsd failed, no position info available: " << m_error;
}
}
void GpsdConnection::update()
{
gps_data_t* data = 0;
#if defined( GPSD_API_MAJOR_VERSION ) && ( GPSD_API_MAJOR_VERSION >= 3 ) && defined( POLICY_SET )
while ((data = m_gpsd.poll()) && !(data->set & POLICY_SET)) {
data = m_gpsd.poll();
}
#else
data = m_gpsd.query( "o" );
#endif
if ( data ) {
emit gpsdInfo( *data );
}
else if ( m_status != PositionProviderStatusAcquiring ) {
mDebug() << "Lost connection to gpsd, trying to re-open.";
initialize();
}
}
QString GpsdConnection::error() const
{
return m_error;
}
#include "GpsdConnection.moc"
<commit_msg>Fix gpsd data interpretation for libgps >= 2.90 (wrong flag used to determine if data is available) CCBUG: 233603<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Eckhart Wörner <ewoerner@kde.org>
//
#include "GpsdConnection.h"
#include "MarbleDebug.h"
#include <errno.h>
using namespace Marble;
GpsdConnection::GpsdConnection( QObject* parent )
: QObject( parent ),
m_timer( 0 )
{
connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
}
void GpsdConnection::initialize()
{
m_timer.stop();
gps_data_t* data = m_gpsd.open();
if ( data ) {
m_status = PositionProviderStatusAcquiring;
emit statusChanged( m_status );
#if defined( GPSD_API_MAJOR_VERSION ) && ( GPSD_API_MAJOR_VERSION >= 3 ) && defined( WATCH_ENABLE )
m_gpsd.stream( WATCH_ENABLE );
#endif
m_timer.start( 1000 );
}
else {
// There is also gps_errstr() for libgps version >= 2.90,
// but it doesn't return a sensible error description
switch ( errno ) {
case NL_NOSERVICE:
m_error = tr("Internal gpsd error (cannot get service entry)");
break;
case NL_NOHOST:
m_error = tr("Internal gpsd error (cannot get host entry)");
break;
case NL_NOPROTO:
m_error = tr("Internal gpsd error (cannot get protocol entry)");
break;
case NL_NOSOCK:
m_error = tr("Internal gpsd error (unable to create socket)");
break;
case NL_NOSOCKOPT:
m_error = tr("Internal gpsd error (unable to set socket option)");
break;
case NL_NOCONNECT:
m_error = tr("No GPS device found by gpsd.");
break;
default:
m_error = tr("Unknown error when opening gpsd connection");
break;
}
m_status = PositionProviderStatusError;
emit statusChanged( m_status );
mDebug() << "Connection to gpsd failed, no position info available: " << m_error;
}
}
void GpsdConnection::update()
{
gps_data_t* data = 0;
#if defined( GPSD_API_MAJOR_VERSION ) && ( GPSD_API_MAJOR_VERSION >= 3 ) && defined( PACKET_SET )
while ((data = m_gpsd.poll()) && !(data->set & PACKET_SET)) {
data = m_gpsd.poll();
}
#else
data = m_gpsd.query( "o" );
#endif
if ( data ) {
emit gpsdInfo( *data );
}
else if ( m_status != PositionProviderStatusAcquiring ) {
mDebug() << "Lost connection to gpsd, trying to re-open.";
initialize();
}
}
QString GpsdConnection::error() const
{
return m_error;
}
#include "GpsdConnection.moc"
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "targetsettingswidget.h"
#include "ui_targetsettingswidget.h"
#include <QPushButton>
using namespace ProjectExplorer::Internal;
TargetSettingsWidget::TargetSettingsWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::TargetSettingsWidget),
m_targetSelector(new TargetSelector(this))
{
ui->setupUi(this);
ui->header->setStyleSheet(QLatin1String("QWidget#header {"
"border-image: url(:/projectexplorer/images/targetseparatorbackground.png) 43 0 0 0 repeat;"
"}"));
QHBoxLayout *headerLayout = new QHBoxLayout;
headerLayout->setContentsMargins(5, 3, 0, 0);
ui->header->setLayout(headerLayout);
QWidget *buttonWidget = new QWidget(ui->header);
QVBoxLayout *buttonLayout = new QVBoxLayout;
buttonLayout->setContentsMargins(0, 0, 0, 0);
buttonLayout->setSpacing(4);
buttonWidget->setLayout(buttonLayout);
m_addButton = new QPushButton(tr("Add Kit"), buttonWidget);
buttonLayout->addWidget(m_addButton);
m_manageButton = new QPushButton(tr("Manage Kits..."), buttonWidget);
connect(m_manageButton, SIGNAL(clicked()), this, SIGNAL(manageButtonClicked()));
buttonLayout->addWidget(m_manageButton);
headerLayout->addWidget(buttonWidget, 0, Qt::AlignVCenter);
headerLayout->addWidget(m_targetSelector, 0, Qt::AlignBottom);
headerLayout->addStretch(10);
connect(m_targetSelector, SIGNAL(currentChanged(int,int)),
this, SIGNAL(currentChanged(int,int)));
connect(m_targetSelector, SIGNAL(toolTipRequested(QPoint,int)),
this, SIGNAL(toolTipRequested(QPoint,int)));
connect(m_targetSelector, SIGNAL(menuShown(int)),
this, SIGNAL(menuShown(int)));
QPalette shadowPal;
QLinearGradient grad(0, 0, 0, 2);
grad.setColorAt(0, QColor(0, 0, 0, 60));
grad.setColorAt(1, Qt::transparent);
shadowPal.setBrush(QPalette::All, QPalette::Window, grad);
ui->shadow->setPalette(shadowPal);
ui->shadow->setAutoFillBackground(true);
}
TargetSettingsWidget::~TargetSettingsWidget()
{
delete ui;
}
void TargetSettingsWidget::insertTarget(int index, int subIndex, const QString &name)
{
m_targetSelector->insertTarget(index, subIndex, name);
}
void TargetSettingsWidget::renameTarget(int index, const QString &name)
{
m_targetSelector->renameTarget(index, name);
}
void TargetSettingsWidget::removeTarget(int index)
{
m_targetSelector->removeTarget(index);
}
void TargetSettingsWidget::setCurrentIndex(int index)
{
m_targetSelector->setCurrentIndex(index);
}
void TargetSettingsWidget::setCurrentSubIndex(int index)
{
m_targetSelector->setCurrentSubIndex(index);
}
void TargetSettingsWidget::setAddButtonEnabled(bool enabled)
{
m_addButton->setEnabled(enabled);
}
void TargetSettingsWidget::setAddButtonMenu(QMenu *menu)
{
m_addButton->setMenu(menu);
}
void TargetSettingsWidget::setTargetMenu(QMenu *menu)
{
m_targetSelector->setTargetMenu(menu);
}
QString TargetSettingsWidget::targetNameAt(int index) const
{
return m_targetSelector->targetAt(index).name;
}
void TargetSettingsWidget::setCentralWidget(QWidget *widget)
{
ui->scrollArea->setWidget(widget);
}
int TargetSettingsWidget::targetCount() const
{
return m_targetSelector->targetCount();
}
int TargetSettingsWidget::currentIndex() const
{
return m_targetSelector->currentIndex();
}
int TargetSettingsWidget::currentSubIndex() const
{
return m_targetSelector->currentSubIndex();
}
<commit_msg>Theming: Fix styling of TargetSettingsWidget<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "targetsettingswidget.h"
#include "ui_targetsettingswidget.h"
#include <utils/theme/theme.h>
#include <QPushButton>
using namespace ProjectExplorer::Internal;
TargetSettingsWidget::TargetSettingsWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::TargetSettingsWidget),
m_targetSelector(new TargetSelector(this))
{
ui->setupUi(this);
if (Utils::creatorTheme()->widgetStyle() == Utils::Theme::StyleFlat) {
ui->separator->setVisible(false);
ui->shadow->setVisible(false);
} else {
ui->header->setStyleSheet(QLatin1String("QWidget#header {"
"border-image: url(:/projectexplorer/images/targetseparatorbackground.png) 43 0 0 0 repeat;"
"}"));
}
QHBoxLayout *headerLayout = new QHBoxLayout;
headerLayout->setContentsMargins(5, 3, 0, 0);
ui->header->setLayout(headerLayout);
QWidget *buttonWidget = new QWidget(ui->header);
QVBoxLayout *buttonLayout = new QVBoxLayout;
buttonLayout->setContentsMargins(0, 0, 0, 0);
buttonLayout->setSpacing(4);
buttonWidget->setLayout(buttonLayout);
m_addButton = new QPushButton(tr("Add Kit"), buttonWidget);
buttonLayout->addWidget(m_addButton);
m_manageButton = new QPushButton(tr("Manage Kits..."), buttonWidget);
connect(m_manageButton, SIGNAL(clicked()), this, SIGNAL(manageButtonClicked()));
buttonLayout->addWidget(m_manageButton);
headerLayout->addWidget(buttonWidget, 0, Qt::AlignVCenter);
headerLayout->addWidget(m_targetSelector, 0, Qt::AlignBottom);
headerLayout->addStretch(10);
connect(m_targetSelector, SIGNAL(currentChanged(int,int)),
this, SIGNAL(currentChanged(int,int)));
connect(m_targetSelector, SIGNAL(toolTipRequested(QPoint,int)),
this, SIGNAL(toolTipRequested(QPoint,int)));
connect(m_targetSelector, SIGNAL(menuShown(int)),
this, SIGNAL(menuShown(int)));
QPalette shadowPal;
QLinearGradient grad(0, 0, 0, 2);
grad.setColorAt(0, QColor(0, 0, 0, 60));
grad.setColorAt(1, Qt::transparent);
shadowPal.setBrush(QPalette::All, QPalette::Window, grad);
ui->shadow->setPalette(shadowPal);
ui->shadow->setAutoFillBackground(true);
}
TargetSettingsWidget::~TargetSettingsWidget()
{
delete ui;
}
void TargetSettingsWidget::insertTarget(int index, int subIndex, const QString &name)
{
m_targetSelector->insertTarget(index, subIndex, name);
}
void TargetSettingsWidget::renameTarget(int index, const QString &name)
{
m_targetSelector->renameTarget(index, name);
}
void TargetSettingsWidget::removeTarget(int index)
{
m_targetSelector->removeTarget(index);
}
void TargetSettingsWidget::setCurrentIndex(int index)
{
m_targetSelector->setCurrentIndex(index);
}
void TargetSettingsWidget::setCurrentSubIndex(int index)
{
m_targetSelector->setCurrentSubIndex(index);
}
void TargetSettingsWidget::setAddButtonEnabled(bool enabled)
{
m_addButton->setEnabled(enabled);
}
void TargetSettingsWidget::setAddButtonMenu(QMenu *menu)
{
m_addButton->setMenu(menu);
}
void TargetSettingsWidget::setTargetMenu(QMenu *menu)
{
m_targetSelector->setTargetMenu(menu);
}
QString TargetSettingsWidget::targetNameAt(int index) const
{
return m_targetSelector->targetAt(index).name;
}
void TargetSettingsWidget::setCentralWidget(QWidget *widget)
{
ui->scrollArea->setWidget(widget);
}
int TargetSettingsWidget::targetCount() const
{
return m_targetSelector->targetCount();
}
int TargetSettingsWidget::currentIndex() const
{
return m_targetSelector->currentIndex();
}
int TargetSettingsWidget::currentSubIndex() const
{
return m_targetSelector->currentSubIndex();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgvertexcolormaterial.h"
#include <qopenglshaderprogram.h>
QT_BEGIN_NAMESPACE
class QSGVertexColorMaterialShader : public QSGMaterialShader
{
public:
virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
virtual char const *const *attributeNames() const;
static QSGMaterialType type;
private:
virtual void initialize();
virtual const char *vertexShader() const;
virtual const char *fragmentShader() const;
int m_matrix_id;
int m_opacity_id;
};
QSGMaterialType QSGVertexColorMaterialShader::type;
void QSGVertexColorMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
{
if (!(newEffect->flags() & QSGMaterial::Blending) || state.isOpacityDirty())
program()->setUniformValue(m_opacity_id, state.opacity());
if (state.isMatrixDirty())
program()->setUniformValue(m_matrix_id, state.combinedMatrix());
}
char const *const *QSGVertexColorMaterialShader::attributeNames() const
{
static const char *const attr[] = { "vertexCoord", "vertexColor", 0 };
return attr;
}
void QSGVertexColorMaterialShader::initialize()
{
m_matrix_id = program()->uniformLocation("matrix");
m_opacity_id = program()->uniformLocation("opacity");
}
const char *QSGVertexColorMaterialShader::vertexShader() const {
return
"attribute highp vec4 vertexCoord; \n"
"attribute highp vec4 vertexColor; \n"
"uniform highp mat4 matrix; \n"
"uniform highp float opacity; \n"
"varying lowp vec4 color; \n"
"void main() { \n"
" gl_Position = matrix * vertexCoord; \n"
" color = vertexColor * opacity; \n"
"}";
}
const char *QSGVertexColorMaterialShader::fragmentShader() const {
return
"varying lowp vec4 color; \n"
"void main() { \n"
" gl_FragColor = color; \n"
"}";
}
/*!
\class QSGVertexColorMaterial
\brief The QSGVertexColorMaterial class provides a convenient way of rendering per-vertex
colored geometry in the scene graph.
\inmodule QtQuick
\ingroup qtquick-scenegraph-materials
The vertex color material will give each vertex in a geometry a color. Pixels between
vertices will be linearly interpolated. The colors can contain transparency.
The geometry to be rendered with vertex color must have the following layout. Attribute
position 0 must contain vertices. Attribute position 1 must contain colors, a tuple of
4 values with RGBA layout. Both floats in the range of 0 to 1 and unsigned bytes in
the range 0 to 255 are valid for the color values. The
QSGGeometry::defaultAttributes_ColoredPoint2D() constructs an attribute set
compatible with this material.
The vertex color material respects both current opacity and current matrix when
updating it's rendering state.
*/
/*!
Creates a new vertex color material.
*/
QSGVertexColorMaterial::QSGVertexColorMaterial()
{
setFlag(Blending, true);
}
/*!
int QSGVertexColorMaterial::compare() const
As the vertex color material has all its state in the vertex attributes,
all materials will be equal.
\internal
*/
int QSGVertexColorMaterial::compare(const QSGMaterial * /* other */) const
{
return 0;
}
/*!
\internal
*/
QSGMaterialType *QSGVertexColorMaterial::type() const
{
return &QSGVertexColorMaterialShader::type;
}
/*!
\internal
*/
QSGMaterialShader *QSGVertexColorMaterial::createShader() const
{
return new QSGVertexColorMaterialShader;
}
QT_END_NAMESPACE
<commit_msg>Don't set opacity when we are not told<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgvertexcolormaterial.h"
#include <qopenglshaderprogram.h>
QT_BEGIN_NAMESPACE
class QSGVertexColorMaterialShader : public QSGMaterialShader
{
public:
virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
virtual char const *const *attributeNames() const;
static QSGMaterialType type;
private:
virtual void initialize();
virtual const char *vertexShader() const;
virtual const char *fragmentShader() const;
int m_matrix_id;
int m_opacity_id;
};
QSGMaterialType QSGVertexColorMaterialShader::type;
void QSGVertexColorMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
{
if (state.isOpacityDirty())
program()->setUniformValue(m_opacity_id, state.opacity());
if (state.isMatrixDirty())
program()->setUniformValue(m_matrix_id, state.combinedMatrix());
}
char const *const *QSGVertexColorMaterialShader::attributeNames() const
{
static const char *const attr[] = { "vertexCoord", "vertexColor", 0 };
return attr;
}
void QSGVertexColorMaterialShader::initialize()
{
m_matrix_id = program()->uniformLocation("matrix");
m_opacity_id = program()->uniformLocation("opacity");
}
const char *QSGVertexColorMaterialShader::vertexShader() const {
return
"attribute highp vec4 vertexCoord; \n"
"attribute highp vec4 vertexColor; \n"
"uniform highp mat4 matrix; \n"
"uniform highp float opacity; \n"
"varying lowp vec4 color; \n"
"void main() { \n"
" gl_Position = matrix * vertexCoord; \n"
" color = vertexColor * opacity; \n"
"}";
}
const char *QSGVertexColorMaterialShader::fragmentShader() const {
return
"varying lowp vec4 color; \n"
"void main() { \n"
" gl_FragColor = color; \n"
"}";
}
/*!
\class QSGVertexColorMaterial
\brief The QSGVertexColorMaterial class provides a convenient way of rendering per-vertex
colored geometry in the scene graph.
\inmodule QtQuick
\ingroup qtquick-scenegraph-materials
The vertex color material will give each vertex in a geometry a color. Pixels between
vertices will be linearly interpolated. The colors can contain transparency.
The geometry to be rendered with vertex color must have the following layout. Attribute
position 0 must contain vertices. Attribute position 1 must contain colors, a tuple of
4 values with RGBA layout. Both floats in the range of 0 to 1 and unsigned bytes in
the range 0 to 255 are valid for the color values. The
QSGGeometry::defaultAttributes_ColoredPoint2D() constructs an attribute set
compatible with this material.
The vertex color material respects both current opacity and current matrix when
updating it's rendering state.
*/
/*!
Creates a new vertex color material.
*/
QSGVertexColorMaterial::QSGVertexColorMaterial()
{
setFlag(Blending, true);
}
/*!
int QSGVertexColorMaterial::compare() const
As the vertex color material has all its state in the vertex attributes,
all materials will be equal.
\internal
*/
int QSGVertexColorMaterial::compare(const QSGMaterial * /* other */) const
{
return 0;
}
/*!
\internal
*/
QSGMaterialType *QSGVertexColorMaterial::type() const
{
return &QSGVertexColorMaterialShader::type;
}
/*!
\internal
*/
QSGMaterialShader *QSGVertexColorMaterial::createShader() const
{
return new QSGVertexColorMaterialShader;
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/** Copyright (c) 2012, 2013
* Ares Programming Language Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Ares Programming Language
* Project and its contributors.
* 4. Neither the name of the Ares Programming Language Project 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 ARES PROGRAMMING LANGUAGE PROJECT 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 REGENTS 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.
*
*****************************************************************************
* driver.cpp - Virtual Platform Driver
*
* Implements objects used to manipulate the compiler, interpreter and
* execution enviroment of Ares Project
*
*/
#include <string>
#include <fstream>
#include <sstream>
#include "driver.h"
using namespace std;
#define LANG_DEBUG
namespace LANG_NAMESPACE
{
namespace VirtualEngine
{
Driver::Driver(std::ostream & out)
: origin(LANG_SHELL_NAME), checkOnly(false),
verboseMode(VerboseMode::Normal), lines(0), totalLines(0),
errors(0), warnings(0), hints(0), output(out)
{
enviro = new SyntaxTree::Environment(0);
}
Driver::~Driver() { }
bool
Driver::parseStream(istream & in, const string & sname)
{
enviro->clear();
origin = sname;
bool result = false;
try { // Captura erros léxicos e sintáticos
Scanner scanner(&in);
this->lexer = &scanner;
Parser parser(*this);
#ifdef LANG_DEBUG
if(verboseMode == VerboseMode::Debug) {
scanner.set_debug(true);
parser.set_debug_level(true);
}
#endif
result = parser.parse() == 0;
resetLines();
} catch(string & m) {
error(m);
}
return result;
}
bool
Driver::parseString(const string & input, const string & sname)
{
istringstream iss(input.c_str());
return parseStream(iss, sname);
}
bool
Driver::parseFile(const string & filename)
{
fileSystem::path file = fileSystem::absolute(filename);
if(fileSystem::exists(file) && file.extension() == string("." LANG_EXTENSION)) {
if(verboseMode >= VerboseMode::High) output << "=> Start parsing: " << filename << endl;
ifstream in(filename.c_str());
if(!in.good()) {
error("Could not open file: " + filename);
return false;
}
return parseStream(in, fileSystem::absolute(filename).filename().string());
} else
warning(war_tail "This isn't seems a valid " LANG_NAME " file: " + filename);
return false;
}
int
Driver::error(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::Low) {
output << "[" << l << "]: " << err_tail << m << endl;
++errors;
}
return 1;
}
int
Driver::error(const string & m)
{
if(verboseMode >= VerboseMode::Low) {
output << "[" << origin << "] ";
output << err_tail << m << endl;
++errors;
}
return 1;
}
void
Driver::warning(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::Normal) {
output << "[" << l << "]: " << war_tail << m << endl;
++warnings;
}
}
void
Driver::warning(const string & m)
{
if(verboseMode >= VerboseMode::Normal) {
output << "[" << origin << "] ";
output << war_tail << m << endl;
++warnings;
}
}
void
Driver::hint(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::High) {
output << "[" << l << "]: " << hin_tail << m << endl;
++hints;
}
}
void
Driver::hint(const string & m)
{
if(verboseMode >= VerboseMode::High) {
output << "[" << origin << "] ";
output << hin_tail << m << endl;
++hints;
}
}
void
Driver::resetMessages()
{
errors = 0;
warnings = 0;
hints = 0;
}
string
Driver::resumeMessages()
{
stringstream result;
if(errors > 0 || warnings > 0 || hints > 0) {
result << "Messages: ";
if(verboseMode >= VerboseMode::Low && errors > 0) result << COLOR_BRED << errors << COLOR_RESET <<(errors > 1 ? " errors " : " error ");
if(verboseMode >= VerboseMode::Normal && warnings > 0) result << COLOR_BPURPLE << warnings << COLOR_RESET <<(warnings > 1 ? " warnings " : " warning ");
if(verboseMode >= VerboseMode::High && hints > 0) result << COLOR_BBLUE << hints << COLOR_RESET <<(hints > 1 ? " hints " : " hint ");
result << endl;
}
return result.str();
}
void
Driver::syntaxOkFor(const string what)
{
output << "=> Syntax OK for " << COLOR_BGREEN << what << COLOR_RESET << endl;
}
void
Driver::resetLines()
{
totalLines += lines;
lines = 0;
}
void
Driver::incLines(int qtde)
{
lines += qtde;
}
void
Driver::decLines()
{
--lines;
}
void
Driver::produce(FinallyAction::Action action, ostream & out)
{
switch(action) {
case FinallyAction::None:
break;
case FinallyAction::PrintOnConsole:
if(errors == 0 && verboseMode >= VerboseMode::High) {
enviro->toString(out, 0);
syntaxOkFor(origin);
} else {
resetMessages();
}
break;
case FinallyAction::ExecuteOnTheFly:
// TODO Implementar ambiente de execução
break;
case FinallyAction::GenerateBinaries:
// TODO Implementar geração de código
break;
default:
break;
}
}
std::ostream &
operator<< (const Driver & driver, const string val)
{
driver.output << val;
return driver.output;
}
} // Compiler
} // LANG_NAMESPACE
<commit_msg>Atualização no Driver para redirecionamento de saída do scanner<commit_after>/** Copyright (c) 2012, 2013
* Ares Programming Language Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Ares Programming Language
* Project and its contributors.
* 4. Neither the name of the Ares Programming Language Project 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 ARES PROGRAMMING LANGUAGE PROJECT 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 REGENTS 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.
*
*****************************************************************************
* driver.cpp - Virtual Platform Driver
*
* Implements objects used to manipulate the compiler, interpreter and
* execution enviroment of Ares Project
*
*/
#include <string>
#include <fstream>
#include <sstream>
#include "driver.h"
using namespace std;
#define LANG_DEBUG
namespace LANG_NAMESPACE
{
namespace VirtualEngine
{
Driver::Driver(std::ostream & out)
: origin(LANG_SHELL_NAME), checkOnly(false),
verboseMode(VerboseMode::Normal), lines(0), totalLines(0),
errors(0), warnings(0), hints(0), output(out)
{
enviro = new SyntaxTree::Environment(0);
}
Driver::~Driver() { }
bool
Driver::parseStream(istream & in, const string & sname)
{
enviro->clear();
origin = sname;
bool result = false;
try { // Captura erros léxicos e sintáticos
Scanner scanner(&in, &this->output);
this->lexer = &scanner;
Parser parser(*this);
#ifdef LANG_DEBUG
if(verboseMode == VerboseMode::Debug) {
scanner.set_debug(true);
parser.set_debug_level(true);
}
#endif
result = parser.parse() == 0;
resetLines();
} catch(string & m) {
error(m);
}
return result;
}
bool
Driver::parseString(const string & input, const string & sname)
{
istringstream iss(input.c_str());
return parseStream(iss, sname);
}
bool
Driver::parseFile(const string & filename)
{
fileSystem::path file = fileSystem::absolute(filename);
if(fileSystem::exists(file) && file.extension() == string("." LANG_EXTENSION)) {
if(verboseMode >= VerboseMode::High) output << "=> Start parsing: " << filename << endl;
ifstream in(filename.c_str());
if(!in.good()) {
error("Could not open file: " + filename);
return false;
}
return parseStream(in, fileSystem::absolute(filename).filename().string());
} else
warning(war_tail "This isn't seems a valid " LANG_NAME " file: " + filename);
return false;
}
int
Driver::error(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::Low) {
output << "[" << l << "]: " << err_tail << m << endl;
++errors;
}
return 1;
}
int
Driver::error(const string & m)
{
if(verboseMode >= VerboseMode::Low) {
output << "[" << origin << "] ";
output << err_tail << m << endl;
++errors;
}
return 1;
}
void
Driver::warning(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::Normal) {
output << "[" << l << "]: " << war_tail << m << endl;
++warnings;
}
}
void
Driver::warning(const string & m)
{
if(verboseMode >= VerboseMode::Normal) {
output << "[" << origin << "] ";
output << war_tail << m << endl;
++warnings;
}
}
void
Driver::hint(const class location & l, const string & m)
{
if(verboseMode >= VerboseMode::High) {
output << "[" << l << "]: " << hin_tail << m << endl;
++hints;
}
}
void
Driver::hint(const string & m)
{
if(verboseMode >= VerboseMode::High) {
output << "[" << origin << "] ";
output << hin_tail << m << endl;
++hints;
}
}
void
Driver::resetMessages()
{
errors = 0;
warnings = 0;
hints = 0;
}
string
Driver::resumeMessages()
{
stringstream result;
if(errors > 0 || warnings > 0 || hints > 0) {
result << "Messages: ";
if(verboseMode >= VerboseMode::Low && errors > 0) result << COLOR_BRED << errors << COLOR_RESET <<(errors > 1 ? " errors " : " error ");
if(verboseMode >= VerboseMode::Normal && warnings > 0) result << COLOR_BPURPLE << warnings << COLOR_RESET <<(warnings > 1 ? " warnings " : " warning ");
if(verboseMode >= VerboseMode::High && hints > 0) result << COLOR_BBLUE << hints << COLOR_RESET <<(hints > 1 ? " hints " : " hint ");
result << endl;
}
return result.str();
}
void
Driver::syntaxOkFor(const string what)
{
output << "=> Syntax OK for " << COLOR_BGREEN << what << COLOR_RESET << endl;
}
void
Driver::resetLines()
{
totalLines += lines;
lines = 0;
}
void
Driver::incLines(int qtde)
{
lines += qtde;
}
void
Driver::decLines()
{
--lines;
}
void
Driver::produce(FinallyAction::Action action, ostream & out)
{
switch(action) {
case FinallyAction::None:
break;
case FinallyAction::PrintOnConsole:
if(errors == 0 && verboseMode >= VerboseMode::High) {
enviro->toString(out, 0);
syntaxOkFor(origin);
} else {
resetMessages();
}
break;
case FinallyAction::ExecuteOnTheFly:
// TODO Implementar ambiente de execução
break;
case FinallyAction::GenerateBinaries:
// TODO Implementar geração de código
break;
default:
break;
}
}
std::ostream &
operator<< (const Driver & driver, const string val)
{
driver.output << val;
return driver.output;
}
} // Compiler
} // LANG_NAMESPACE
<|endoftext|>
|
<commit_before>/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Log$
* Revision 1.6 2004/09/08 13:56:51 peiyongz
* Apache License Version 2.0
*
* Revision 1.5 2003/05/16 21:43:20 knoaman
* Memory manager implementation: Modify constructors to pass in the memory manager.
*
* Revision 1.4 2003/05/15 18:48:27 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/03/07 18:16:57 tng
* Return a reference instead of void for operator=
*
* Revision 1.2 2002/11/04 14:54:58 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:38 peiyongz
* sane_include
*
* Revision 1.4 2001/08/07 15:21:20 knoaman
* The value of 'fLeafCount' was not set.
*
* Revision 1.3 2001/05/11 13:27:17 tng
* Copyright update.
*
* Revision 1.2 2001/04/19 18:17:28 tng
* Schema: SchemaValidator update, and use QName in Content Model
*
* Revision 1.1 2001/02/27 14:48:49 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
#if !defined(CONTENTLEAFNAMETYPEVECTOR_HPP)
#define CONTENTLEAFNAMETYPEVECTOR_HPP
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/framework/MemoryManager.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class ContentLeafNameTypeVector : public XMemory
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
ContentLeafNameTypeVector
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
ContentLeafNameTypeVector
(
QName** const qName
, ContentSpecNode::NodeTypes* const types
, const unsigned int count
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
~ContentLeafNameTypeVector();
ContentLeafNameTypeVector(const ContentLeafNameTypeVector&);
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
QName* getLeafNameAt(const unsigned int pos) const;
const ContentSpecNode::NodeTypes getLeafTypeAt(const unsigned int pos) const;
const unsigned int getLeafCount() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setValues
(
QName** const qName
, ContentSpecNode::NodeTypes* const types
, const unsigned int count
);
// -----------------------------------------------------------------------
// Miscellaneous
// -----------------------------------------------------------------------
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
ContentLeafNameTypeVector& operator=(const ContentLeafNameTypeVector&);
// -----------------------------------------------------------------------
// helper methods
// -----------------------------------------------------------------------
void cleanUp();
void init(const unsigned int);
// -----------------------------------------------------------------------
// Private Data Members
//
// -----------------------------------------------------------------------
MemoryManager* fMemoryManager;
QName** fLeafNames;
ContentSpecNode::NodeTypes *fLeafTypes;
unsigned int fLeafCount;
};
inline void ContentLeafNameTypeVector::cleanUp()
{
fMemoryManager->deallocate(fLeafNames); //delete [] fLeafNames;
fMemoryManager->deallocate(fLeafTypes); //delete [] fLeafTypes;
}
inline void ContentLeafNameTypeVector::init(const unsigned int size)
{
fLeafNames = (QName**) fMemoryManager->allocate(size * sizeof(QName*));//new QName*[size];
fLeafTypes = (ContentSpecNode::NodeTypes *) fMemoryManager->allocate
(
size * sizeof(ContentSpecNode::NodeTypes)
); //new ContentSpecNode::NodeTypes [size];
fLeafCount = size;
}
XERCES_CPP_NAMESPACE_END
#endif
<commit_msg>On Windows, export the class from the DLL<commit_after>/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Log$
* Revision 1.7 2005/03/25 10:54:22 amassari
* On Windows, export the class from the DLL
*
* Revision 1.6 2004/09/08 13:56:51 peiyongz
* Apache License Version 2.0
*
* Revision 1.5 2003/05/16 21:43:20 knoaman
* Memory manager implementation: Modify constructors to pass in the memory manager.
*
* Revision 1.4 2003/05/15 18:48:27 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2003/03/07 18:16:57 tng
* Return a reference instead of void for operator=
*
* Revision 1.2 2002/11/04 14:54:58 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:38 peiyongz
* sane_include
*
* Revision 1.4 2001/08/07 15:21:20 knoaman
* The value of 'fLeafCount' was not set.
*
* Revision 1.3 2001/05/11 13:27:17 tng
* Copyright update.
*
* Revision 1.2 2001/04/19 18:17:28 tng
* Schema: SchemaValidator update, and use QName in Content Model
*
* Revision 1.1 2001/02/27 14:48:49 tng
* Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang
*
*/
#if !defined(CONTENTLEAFNAMETYPEVECTOR_HPP)
#define CONTENTLEAFNAMETYPEVECTOR_HPP
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/framework/MemoryManager.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLPARSER_EXPORT ContentLeafNameTypeVector : public XMemory
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
ContentLeafNameTypeVector
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
ContentLeafNameTypeVector
(
QName** const qName
, ContentSpecNode::NodeTypes* const types
, const unsigned int count
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
~ContentLeafNameTypeVector();
ContentLeafNameTypeVector(const ContentLeafNameTypeVector&);
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
QName* getLeafNameAt(const unsigned int pos) const;
const ContentSpecNode::NodeTypes getLeafTypeAt(const unsigned int pos) const;
const unsigned int getLeafCount() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setValues
(
QName** const qName
, ContentSpecNode::NodeTypes* const types
, const unsigned int count
);
// -----------------------------------------------------------------------
// Miscellaneous
// -----------------------------------------------------------------------
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
ContentLeafNameTypeVector& operator=(const ContentLeafNameTypeVector&);
// -----------------------------------------------------------------------
// helper methods
// -----------------------------------------------------------------------
void cleanUp();
void init(const unsigned int);
// -----------------------------------------------------------------------
// Private Data Members
//
// -----------------------------------------------------------------------
MemoryManager* fMemoryManager;
QName** fLeafNames;
ContentSpecNode::NodeTypes *fLeafTypes;
unsigned int fLeafCount;
};
inline void ContentLeafNameTypeVector::cleanUp()
{
fMemoryManager->deallocate(fLeafNames); //delete [] fLeafNames;
fMemoryManager->deallocate(fLeafTypes); //delete [] fLeafTypes;
}
inline void ContentLeafNameTypeVector::init(const unsigned int size)
{
fLeafNames = (QName**) fMemoryManager->allocate(size * sizeof(QName*));//new QName*[size];
fLeafTypes = (ContentSpecNode::NodeTypes *) fMemoryManager->allocate
(
size * sizeof(ContentSpecNode::NodeTypes)
); //new ContentSpecNode::NodeTypes [size];
fLeafCount = size;
}
XERCES_CPP_NAMESPACE_END
#endif
<|endoftext|>
|
<commit_before>#include "dsa_common.h"
#include "simple_storage.h"
#include <boost/asio/strand.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
namespace dsa {
namespace fs = boost::filesystem;
using boost::filesystem::path;
#if (defined (_WIN32) || defined (_WIN64))
static std::string storage_root = "C:\\temp\\";
#else
static std::string storage_root = "";
#endif
inline void SimpleSafeStorageBucket::write_file(const std::string& key,
BytesRef content) {
path p(storage_root);
path p_temp = std::tmpnam(nullptr);
p /= (key);
try {
std::ofstream ofs(p_temp.string().c_str(), std::ios::out | std::ios::trunc);
if (ofs) {
ofs.write(reinterpret_cast<const char *>(content->data()),
content->size());
boost::filesystem::rename(p_temp, p);
} else {
// TODO - error handling
}
} catch (const fs::filesystem_error &ex) {
// TODO - error handling
}
return;
}
void SimpleSafeStorageBucket::write(const std::string &key, BytesRef &&content) {
if (_io_service != nullptr) {
if (!strand_map.count(key)) {
boost::asio::io_service::strand* strand =
new boost::asio::io_service::strand(*_io_service);
strand_map.insert(StrandPair(key, strand));
}
strand_map.at(key)->post([=]() {
write_file(key, content);
return;
});
return;
} else {
write_file(key, std::move(content));
}
}
}<commit_msg>storage bucket module windows fix.<commit_after>#include "dsa_common.h"
#include "simple_storage.h"
#include <boost/asio/strand.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
namespace dsa {
namespace fs = boost::filesystem;
using boost::filesystem::path;
#if (defined (_WIN32) || defined (_WIN64))
static std::string storage_root = "C:\\temp\\";
#else
static std::string storage_root = "";
static char templ[] = "/tmp/fileXXXXXX";
#endif
inline void SimpleSafeStorageBucket::write_file(const std::string& key,
BytesRef content) {
#if (defined (_WIN32) || defined (_WIN64))
std::string templ = tmpnam(nullptr)
#else
mkstemp(templ);
#endif
path p(storage_root);
p /= (key);
try {
std::ofstream ofs(templ, std::ios::out | std::ios::trunc);
if (ofs) {
ofs.write(reinterpret_cast<const char *>(content->data()),
content->size());
boost::filesystem::rename(templ, p);
} else {
// TODO - error handling
}
} catch (const fs::filesystem_error &ex) {
// TODO - error handling
}
}
void SimpleSafeStorageBucket::write(const std::string &key, BytesRef &&content) {
if (_io_service != nullptr) {
if (!strand_map.count(key)) {
boost::asio::io_service::strand* strand =
new boost::asio::io_service::strand(*_io_service);
strand_map.insert(StrandPair(key, strand));
}
strand_map.at(key)->post([=]() {
write_file(key, content);
return;
});
return;
} else {
write_file(key, std::move(content));
}
}
}<|endoftext|>
|
<commit_before>// STL
#include <iostream>
#include <string>
// CPPUNIT
#include <test/com/CppUnitCore.hpp>
// RMOL
#include <rmol/RMOL_Service.hpp>
// RMOL Test Suite
#include <test/OptimiseTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void testOptimiseHelper() {
try {
// Output log File
std::string lLogFilename ("OptimiseTestSuite.log");
// Number of random draws to be generated (best if greater than 100)
const int K = 100000;
// Methods of optimisation (0 = Monte-Carlo, 1 = Dynamic Programming,
// 2 = EMSR, 3 = EMSR-a, 4 = EMSR-b)
const short METHOD_FLAG = 0;
// Cabin Capacity (it must be greater then 100 here)
const double cabinCapacity = 100.0;
// Input file name
const std::string inputFileName ("samples/sample2.csv");
const bool hasInputFile = true;
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the list of classes/buckets
RMOL::RMOL_Service rmolService (logOutputFile, cabinCapacity);
if (hasInputFile) {
// Read the input file
rmolService.readFromInputFile (inputFileName);
} else {
// No input file has been provided. So, process a sample.
// STEP 0.
// List of demand distribution parameters (mean and standard deviation)
// Class/bucket 1: N (20, 9), p1 = 100
rmolService.addBucket (100.0, 20, 9);
// Class/bucket 2: N (45, 12), p2 = 70
rmolService.addBucket (70.0, 45, 12);
// Class/bucket 3: no need to define a demand distribution, p3 = 42
rmolService.addBucket (42.0, 0, 0);
}
switch (METHOD_FLAG) {
case 0 : // Calculate the optimal protections by the Monte Carlo
// Integration approach
rmolService.optimalOptimisationByMCIntegration (K);
break;
case 1 : // Calculate the optimal protections by DP.
rmolService.optimalOptimisationByDP ();
break;
case 2 : // Calculate the Bid-Price Vector by EMSR
rmolService.heuristicOptimisationByEmsr ();
break;
case 3 : // Calculate the protections by EMSR-a
rmolService.heuristicOptimisationByEmsrA ();
break;
case 4 : // Calculate the protections by EMSR-b
rmolService.heuristicOptimisationByEmsrB ();
break;
default : rmolService.optimalOptimisationByMCIntegration (K);
}
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void OptimiseTestSuite::testOptimise() {
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(););
}
// //////////////////////////////////////////////////////////////////////
// void OptimiseTestSuite::errorCase () {
// CPPUNIT_ASSERT (false);
// }
// //////////////////////////////////////////////////////////////////////
OptimiseTestSuite::OptimiseTestSuite () {
_describeKey << "Running test on RMOL Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<commit_msg>1. Prepared a unit test for EMSR-a with sell up probability algorithm, the flow of the algorithm still to be tested against a number 2. TestSuite is updated so that all implemented optimization algorithms are sequentially tested<commit_after>// STL
#include <iostream>
#include <string>
// CPPUNIT
#include <test/com/CppUnitCore.hpp>
// RMOL
#include <rmol/RMOL_Service.hpp>
#include <rmol/RMOL_Types.hpp>
// RMOL Test Suite
#include <test/OptimiseTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void testOptimiseHelper(const unsigned short optimisationMethodFlag) {
try {
// Output log File
std::string lLogFilename ("OptimiseTestSuite.log");
// Number of random draws to be generated (best if greater than 100)
const int K = 100000;
// Methods of optimisation (0 = Monte-Carlo, 1 = Dynamic Programming,
// 2 = EMSR, 3 = EMSR-a, 4 = EMSR-b, 5 = EMSR-a with sellup prob.)
const unsigned short METHOD_FLAG = optimisationMethodFlag;
// Cabin Capacity (it must be greater then 100 here)
const double cabinCapacity = 100.0;
// Input file name
const std::string inputFileName ("../samples/sample2.csv");
const bool hasInputFile = true;
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the list of classes/buckets
RMOL::RMOL_Service rmolService (logOutputFile, cabinCapacity);
if (hasInputFile) {
// Read the input file
rmolService.readFromInputFile (inputFileName);
} else {
// No input file has been provided. So, process a sample.
// STEP 0.
// List of demand distribution parameters (mean and standard deviation)
// Class/bucket 1: N (20, 9), p1 = 100
rmolService.addBucket (100.0, 20, 9);
// Class/bucket 2: N (45, 12), p2 = 70
rmolService.addBucket (70.0, 45, 12);
// Class/bucket 3: no need to define a demand distribution, p3 = 42
rmolService.addBucket (42.0, 0, 0);
}
switch (METHOD_FLAG) {
case 0 : // Calculate the optimal protections by the Monte Carlo
// Integration approach
rmolService.optimalOptimisationByMCIntegration (K);
break;
case 1 : // Calculate the optimal protections by DP.
rmolService.optimalOptimisationByDP ();
break;
case 2 : // Calculate the Bid-Price Vector by EMSR
rmolService.heuristicOptimisationByEmsr ();
break;
case 3 : // Calculate the protections by EMSR-a
rmolService.heuristicOptimisationByEmsrA ();
break;
case 4 : // Calculate the protections by EMSR-b
rmolService.heuristicOptimisationByEmsrB ();
break;
case 5 : // Calculate the protection by EMSR-a with sellup
{
std::vector<double> sampleVector;
double sampleProbability = 0.2;
// NOTE: size of sellup vector should be equal to no of buckets
short nbOfSampleBucket = 4;
for (short i = 1; i <= nbOfSampleBucket - 1; i++)
sampleVector.push_back(sampleProbability);
RMOL::SellupProbabilityVector_T& sellupProbabilityVector
= sampleVector;
rmolService.heuristicOptimisationByEmsrAwithSellup (sellupProbabilityVector);
break;
}
default : rmolService.optimalOptimisationByMCIntegration (K);
}
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void OptimiseTestSuite::testOptimise() {
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(0););
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(1););
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(2););
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(3););
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(4););
CPPUNIT_ASSERT_NO_THROW (testOptimiseHelper(5););
}
// //////////////////////////////////////////////////////////////////////
// void OptimiseTestSuite::errorCase () {
// CPPUNIT_ASSERT (false);
// }
// //////////////////////////////////////////////////////////////////////
OptimiseTestSuite::OptimiseTestSuite () {
_describeKey << "Running test on RMOL Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<|endoftext|>
|
<commit_before><commit_msg>remove reseed division<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#ifdef WCHAR_T_IS_UTF32
static const std::wstring kSysWideOldItalicLetterA = L"\x10300";
#else
static const std::wstring kSysWideOldItalicLetterA = L"\xd800\xdf00";
#endif
TEST(SysStrings, SysWideToUTF8) {
using base::SysWideToUTF8;
EXPECT_EQ("Hello, world", SysWideToUTF8(L"Hello, world"));
EXPECT_EQ("\xe4\xbd\xa0\xe5\xa5\xbd", SysWideToUTF8(L"\x4f60\x597d"));
// >16 bits
EXPECT_EQ("\xF0\x90\x8C\x80", SysWideToUTF8(kSysWideOldItalicLetterA));
// Error case. When Windows finds a UTF-16 character going off the end of
// a string, it just converts that literal value to UTF-8, even though this
// is invalid.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ("\xE4\xBD\xA0\xED\xA0\x80zyxw",
// SysWideToUTF8(L"\x4f60\xd800zyxw"));
// Test embedded NULLs.
std::wstring wide_null(L"a");
wide_null.push_back(0);
wide_null.push_back('b');
std::string expected_null("a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysWideToUTF8(wide_null));
}
TEST(SysStrings, SysUTF8ToWide) {
using base::SysUTF8ToWide;
EXPECT_EQ(L"Hello, world", SysUTF8ToWide("Hello, world"));
EXPECT_EQ(L"\x4f60\x597d", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5\xbd"));
// >16 bits
EXPECT_EQ(kSysWideOldItalicLetterA, SysUTF8ToWide("\xF0\x90\x8C\x80"));
// Error case. When Windows finds an invalid UTF-8 character, it just skips
// it. This seems weird because it's inconsistent with the reverse conversion.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ(L"\x4f60zyxw", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5zyxw"));
// Test embedded NULLs.
std::string utf8_null("a");
utf8_null.push_back(0);
utf8_null.push_back('b');
std::wstring expected_null(L"a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysUTF8ToWide(utf8_null));
}
// We assume the test is running in a UTF8 locale.
TEST(SysStrings, SysWideToNativeMB) {
using base::SysWideToNativeMB;
EXPECT_EQ("Hello, world", SysWideToNativeMB(L"Hello, world"));
EXPECT_EQ("\xe4\xbd\xa0\xe5\xa5\xbd", SysWideToNativeMB(L"\x4f60\x597d"));
// >16 bits
EXPECT_EQ("\xF0\x90\x8C\x80", SysWideToNativeMB(kSysWideOldItalicLetterA));
// Error case. When Windows finds a UTF-16 character going off the end of
// a string, it just converts that literal value to UTF-8, even though this
// is invalid.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ("\xE4\xBD\xA0\xED\xA0\x80zyxw",
// SysWideToNativeMB(L"\x4f60\xd800zyxw"));
// Test embedded NULLs.
std::wstring wide_null(L"a");
wide_null.push_back(0);
wide_null.push_back('b');
std::string expected_null("a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysWideToNativeMB(wide_null));
}
// We assume the test is running in a UTF8 locale.
TEST(SysStrings, SysNativeMBToWide) {
using base::SysNativeMBToWide;
EXPECT_EQ(L"Hello, world", SysNativeMBToWide("Hello, world"));
EXPECT_EQ(L"\x4f60\x597d", SysNativeMBToWide("\xe4\xbd\xa0\xe5\xa5\xbd"));
// >16 bits
EXPECT_EQ(kSysWideOldItalicLetterA, SysNativeMBToWide("\xF0\x90\x8C\x80"));
// Error case. When Windows finds an invalid UTF-8 character, it just skips
// it. This seems weird because it's inconsistent with the reverse conversion.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ(L"\x4f60zyxw", SysNativeMBToWide("\xe4\xbd\xa0\xe5\xa5zyxw"));
// Test embedded NULLs.
std::string utf8_null("a");
utf8_null.push_back(0);
utf8_null.push_back('b');
std::wstring expected_null(L"a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysNativeMBToWide(utf8_null));
}
static const wchar_t* const kConvertRoundtripCases[] = {
L"Google Video",
// "网页 图片 资讯更多 »"
L"\x7f51\x9875\x0020\x56fe\x7247\x0020\x8d44\x8baf\x66f4\x591a\x0020\x00bb",
// "Παγκόσμιος Ιστός"
L"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9"
L"\x03bf\x03c2\x0020\x0399\x03c3\x03c4\x03cc\x03c2",
// "Поиск страниц на русском"
L"\x041f\x043e\x0438\x0441\x043a\x0020\x0441\x0442"
L"\x0440\x0430\x043d\x0438\x0446\x0020\x043d\x0430"
L"\x0020\x0440\x0443\x0441\x0441\x043a\x043e\x043c",
// "전체서비스"
L"\xc804\xccb4\xc11c\xbe44\xc2a4",
// Test characters that take more than 16 bits. This will depend on whether
// wchar_t is 16 or 32 bits.
#if defined(WCHAR_T_IS_UTF16)
L"\xd800\xdf00",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\xd807\xdd40\xd807\xdd41\xd807\xdd42\xd807\xdd43\xd807\xdd44",
#elif defined(WCHAR_T_IS_UTF32)
L"\x10300",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\x11d40\x11d41\x11d42\x11d43\x11d44",
#endif
};
TEST(SysStrings, SysNativeMBAndWide) {
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = base::SysNativeMBToWide(base::SysWideToNativeMB(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
// We assume our test is running in UTF-8, so double check through ICU.
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = base::SysNativeMBToWide(WideToUTF8(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = UTF8ToWide(base::SysWideToNativeMB(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
}
<commit_msg>Only run the UTF-8 assuming sys conversion tests on Linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#ifdef WCHAR_T_IS_UTF32
static const std::wstring kSysWideOldItalicLetterA = L"\x10300";
#else
static const std::wstring kSysWideOldItalicLetterA = L"\xd800\xdf00";
#endif
TEST(SysStrings, SysWideToUTF8) {
using base::SysWideToUTF8;
EXPECT_EQ("Hello, world", SysWideToUTF8(L"Hello, world"));
EXPECT_EQ("\xe4\xbd\xa0\xe5\xa5\xbd", SysWideToUTF8(L"\x4f60\x597d"));
// >16 bits
EXPECT_EQ("\xF0\x90\x8C\x80", SysWideToUTF8(kSysWideOldItalicLetterA));
// Error case. When Windows finds a UTF-16 character going off the end of
// a string, it just converts that literal value to UTF-8, even though this
// is invalid.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ("\xE4\xBD\xA0\xED\xA0\x80zyxw",
// SysWideToUTF8(L"\x4f60\xd800zyxw"));
// Test embedded NULLs.
std::wstring wide_null(L"a");
wide_null.push_back(0);
wide_null.push_back('b');
std::string expected_null("a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysWideToUTF8(wide_null));
}
TEST(SysStrings, SysUTF8ToWide) {
using base::SysUTF8ToWide;
EXPECT_EQ(L"Hello, world", SysUTF8ToWide("Hello, world"));
EXPECT_EQ(L"\x4f60\x597d", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5\xbd"));
// >16 bits
EXPECT_EQ(kSysWideOldItalicLetterA, SysUTF8ToWide("\xF0\x90\x8C\x80"));
// Error case. When Windows finds an invalid UTF-8 character, it just skips
// it. This seems weird because it's inconsistent with the reverse conversion.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ(L"\x4f60zyxw", SysUTF8ToWide("\xe4\xbd\xa0\xe5\xa5zyxw"));
// Test embedded NULLs.
std::string utf8_null("a");
utf8_null.push_back(0);
utf8_null.push_back('b');
std::wstring expected_null(L"a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysUTF8ToWide(utf8_null));
}
// We assume the test is running in a UTF8 locale.
#if defined(OS_LINUX)
TEST(SysStrings, SysWideToNativeMB) {
using base::SysWideToNativeMB;
EXPECT_EQ("Hello, world", SysWideToNativeMB(L"Hello, world"));
EXPECT_EQ("\xe4\xbd\xa0\xe5\xa5\xbd", SysWideToNativeMB(L"\x4f60\x597d"));
// >16 bits
EXPECT_EQ("\xF0\x90\x8C\x80", SysWideToNativeMB(kSysWideOldItalicLetterA));
// Error case. When Windows finds a UTF-16 character going off the end of
// a string, it just converts that literal value to UTF-8, even though this
// is invalid.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ("\xE4\xBD\xA0\xED\xA0\x80zyxw",
// SysWideToNativeMB(L"\x4f60\xd800zyxw"));
// Test embedded NULLs.
std::wstring wide_null(L"a");
wide_null.push_back(0);
wide_null.push_back('b');
std::string expected_null("a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysWideToNativeMB(wide_null));
}
// We assume the test is running in a UTF8 locale.
TEST(SysStrings, SysNativeMBToWide) {
using base::SysNativeMBToWide;
EXPECT_EQ(L"Hello, world", SysNativeMBToWide("Hello, world"));
EXPECT_EQ(L"\x4f60\x597d", SysNativeMBToWide("\xe4\xbd\xa0\xe5\xa5\xbd"));
// >16 bits
EXPECT_EQ(kSysWideOldItalicLetterA, SysNativeMBToWide("\xF0\x90\x8C\x80"));
// Error case. When Windows finds an invalid UTF-8 character, it just skips
// it. This seems weird because it's inconsistent with the reverse conversion.
//
// This is what XP does, but Vista has different behavior, so we don't bother
// verifying it:
//EXPECT_EQ(L"\x4f60zyxw", SysNativeMBToWide("\xe4\xbd\xa0\xe5\xa5zyxw"));
// Test embedded NULLs.
std::string utf8_null("a");
utf8_null.push_back(0);
utf8_null.push_back('b');
std::wstring expected_null(L"a");
expected_null.push_back(0);
expected_null.push_back('b');
EXPECT_EQ(expected_null, SysNativeMBToWide(utf8_null));
}
static const wchar_t* const kConvertRoundtripCases[] = {
L"Google Video",
// "网页 图片 资讯更多 »"
L"\x7f51\x9875\x0020\x56fe\x7247\x0020\x8d44\x8baf\x66f4\x591a\x0020\x00bb",
// "Παγκόσμιος Ιστός"
L"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9"
L"\x03bf\x03c2\x0020\x0399\x03c3\x03c4\x03cc\x03c2",
// "Поиск страниц на русском"
L"\x041f\x043e\x0438\x0441\x043a\x0020\x0441\x0442"
L"\x0440\x0430\x043d\x0438\x0446\x0020\x043d\x0430"
L"\x0020\x0440\x0443\x0441\x0441\x043a\x043e\x043c",
// "전체서비스"
L"\xc804\xccb4\xc11c\xbe44\xc2a4",
// Test characters that take more than 16 bits. This will depend on whether
// wchar_t is 16 or 32 bits.
#if defined(WCHAR_T_IS_UTF16)
L"\xd800\xdf00",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\xd807\xdd40\xd807\xdd41\xd807\xdd42\xd807\xdd43\xd807\xdd44",
#elif defined(WCHAR_T_IS_UTF32)
L"\x10300",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\x11d40\x11d41\x11d42\x11d43\x11d44",
#endif
};
TEST(SysStrings, SysNativeMBAndWide) {
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = base::SysNativeMBToWide(base::SysWideToNativeMB(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
// We assume our test is running in UTF-8, so double check through ICU.
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = base::SysNativeMBToWide(WideToUTF8(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
std::wstring wide = kConvertRoundtripCases[i];
std::wstring trip = UTF8ToWide(base::SysWideToNativeMB(wide));
EXPECT_EQ(wide.size(), trip.size());
EXPECT_EQ(wide, trip);
}
}
#endif // OS_LINUX
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/platform_thread.h"
#include "base/waitable_event.h"
#include "base/waitable_event_watcher.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::WaitableEvent;
using base::WaitableEventWatcher;
namespace {
class QuitDelegate : public WaitableEventWatcher::Delegate {
public:
virtual void OnWaitableEventSignaled(WaitableEvent* event) {
MessageLoop::current()->Quit();
}
};
class DecrementCountDelegate : public WaitableEventWatcher::Delegate {
public:
DecrementCountDelegate(int* counter) : counter_(counter) {
}
virtual void OnWaitableEventSignaled(WaitableEvent* object) {
--(*counter_);
}
private:
int* counter_;
};
} // namespace
void RunTest_BasicSignal(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
EXPECT_EQ(NULL, watcher.GetWatchedEvent());
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
EXPECT_EQ(&event, watcher.GetWatchedEvent());
event.Signal();
MessageLoop::current()->Run();
EXPECT_EQ(NULL, watcher.GetWatchedEvent());
}
void RunTest_BasicCancel(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
watcher.StopWatching();
}
void RunTest_CancelAfterSet(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
int counter = 1;
DecrementCountDelegate delegate(&counter);
watcher.StartWatching(&event, &delegate);
event.Signal();
// Let the background thread do its business
PlatformThread::Sleep(30);
watcher.StopWatching();
MessageLoop::current()->RunAllPending();
// Our delegate should not have fired.
EXPECT_EQ(1, counter);
}
void RunTest_OutlivesMessageLoop(MessageLoop::Type message_loop_type) {
// Simulate a MessageLoop that dies before an WaitableEventWatcher. This
// ordinarily doesn't happen when people use the Thread class, but it can
// happen when people use the Singleton pattern or atexit.
WaitableEvent event(true, false);
{
WaitableEventWatcher watcher;
{
MessageLoop message_loop(message_loop_type);
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
}
}
}
//-----------------------------------------------------------------------------
TEST(ObjectWatcherTest, BasicSignal) {
RunTest_BasicSignal(MessageLoop::TYPE_DEFAULT);
RunTest_BasicSignal(MessageLoop::TYPE_IO);
RunTest_BasicSignal(MessageLoop::TYPE_UI);
}
TEST(ObjectWatcherTest, BasicCancel) {
RunTest_BasicCancel(MessageLoop::TYPE_DEFAULT);
RunTest_BasicCancel(MessageLoop::TYPE_IO);
RunTest_BasicCancel(MessageLoop::TYPE_UI);
}
TEST(ObjectWatcherTest, CancelAfterSet) {
RunTest_CancelAfterSet(MessageLoop::TYPE_DEFAULT);
RunTest_CancelAfterSet(MessageLoop::TYPE_IO);
RunTest_CancelAfterSet(MessageLoop::TYPE_UI);
}
TEST(ObjectWatcherTest, OutlivesMessageLoop) {
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_DEFAULT);
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_IO);
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_UI);
}
<commit_msg>Windows scons fix: forgot to rename some tests<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/platform_thread.h"
#include "base/waitable_event.h"
#include "base/waitable_event_watcher.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::WaitableEvent;
using base::WaitableEventWatcher;
namespace {
class QuitDelegate : public WaitableEventWatcher::Delegate {
public:
virtual void OnWaitableEventSignaled(WaitableEvent* event) {
MessageLoop::current()->Quit();
}
};
class DecrementCountDelegate : public WaitableEventWatcher::Delegate {
public:
DecrementCountDelegate(int* counter) : counter_(counter) {
}
virtual void OnWaitableEventSignaled(WaitableEvent* object) {
--(*counter_);
}
private:
int* counter_;
};
} // namespace
void RunTest_BasicSignal(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
EXPECT_EQ(NULL, watcher.GetWatchedEvent());
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
EXPECT_EQ(&event, watcher.GetWatchedEvent());
event.Signal();
MessageLoop::current()->Run();
EXPECT_EQ(NULL, watcher.GetWatchedEvent());
}
void RunTest_BasicCancel(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
watcher.StopWatching();
}
void RunTest_CancelAfterSet(MessageLoop::Type message_loop_type) {
MessageLoop message_loop(message_loop_type);
// A manual-reset event that is not yet signaled.
WaitableEvent event(true, false);
WaitableEventWatcher watcher;
int counter = 1;
DecrementCountDelegate delegate(&counter);
watcher.StartWatching(&event, &delegate);
event.Signal();
// Let the background thread do its business
PlatformThread::Sleep(30);
watcher.StopWatching();
MessageLoop::current()->RunAllPending();
// Our delegate should not have fired.
EXPECT_EQ(1, counter);
}
void RunTest_OutlivesMessageLoop(MessageLoop::Type message_loop_type) {
// Simulate a MessageLoop that dies before an WaitableEventWatcher. This
// ordinarily doesn't happen when people use the Thread class, but it can
// happen when people use the Singleton pattern or atexit.
WaitableEvent event(true, false);
{
WaitableEventWatcher watcher;
{
MessageLoop message_loop(message_loop_type);
QuitDelegate delegate;
watcher.StartWatching(&event, &delegate);
}
}
}
//-----------------------------------------------------------------------------
TEST(WaitableEventWatcherTest, BasicSignal) {
RunTest_BasicSignal(MessageLoop::TYPE_DEFAULT);
RunTest_BasicSignal(MessageLoop::TYPE_IO);
RunTest_BasicSignal(MessageLoop::TYPE_UI);
}
TEST(WaitableEventWatcherTest, BasicCancel) {
RunTest_BasicCancel(MessageLoop::TYPE_DEFAULT);
RunTest_BasicCancel(MessageLoop::TYPE_IO);
RunTest_BasicCancel(MessageLoop::TYPE_UI);
}
TEST(WaitableEventWatcherTest, CancelAfterSet) {
RunTest_CancelAfterSet(MessageLoop::TYPE_DEFAULT);
RunTest_CancelAfterSet(MessageLoop::TYPE_IO);
RunTest_CancelAfterSet(MessageLoop::TYPE_UI);
}
TEST(WaitableEventWatcherTest, OutlivesMessageLoop) {
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_DEFAULT);
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_IO);
RunTest_OutlivesMessageLoop(MessageLoop::TYPE_UI);
}
<|endoftext|>
|
<commit_before>/**
* @file ModelParametersIRFRLS.hpp
* @brief ModelParametersIRFRLS class header file.
* @author Freek Stulp, Thibaut Munzer
*
* This file is part of DmpBbo, a set of libraries and programs for the
* black-box optimization of dynamical movement primitives.
* Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
*
* DmpBbo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODELPARAMETERSIRFRLS_H
#define MODELPARAMETERSIRFRLS_H
#include <iosfwd>
#include "functionapproximators/ModelParameters.hpp"
namespace DmpBbo {
/** \brief Model parameters for the iRFRLS function approximator
* \ingroup FunctionApproximators
* \ingroup IRFRLS
*/
class ModelParametersIRFRLS : public ModelParameters
{
friend class FunctionApproximatorIRFRLS;
public:
/** Constructor for the model parameters of the IRFRLS function approximator.
* \param[in] linear_models Coefficient of the linear models (nb_cos x nb_out_dim).
* \param[in] cosines_periodes Matrix of periode for each cosine for each input dimension (nb_cos x nb_in_dim).
* \param[in] cosines_phase Vector of periode (nb_cos).
*/
ModelParametersIRFRLS(Eigen::VectorXd linear_models, Eigen::MatrixXd cosines_periodes, Eigen::VectorXd cosines_phase);
int getExpectedInputDim(void) const;
std::string toString(void) const;
ModelParameters* clone(void) const;
void getSelectableParameters(std::set<std::string>& selected_values_labels) const;
void getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const;
void getParameterVectorAll(Eigen::VectorXd& all_values) const;
inline int getParameterVectorAllSize(void) const
{
return all_values_vector_size_;
}
UnifiedModel* toUnifiedModel(void) const;
protected:
void setParameterVectorAll(const Eigen::VectorXd& values);
private:
Eigen::VectorXd weights_;
Eigen::MatrixXd cosines_periodes_;
Eigen::VectorXd cosines_phase_;
int nb_in_dim_;
int all_values_vector_size_;
/**
* Default constructor.
* \remarks This default constuctor is required for boost::serialization to work. Since this
* constructor should not be called by other classes, it is private (boost::serialization is a
* friend)
*/
ModelParametersIRFRLS(void) {};
/** Give boost serialization access to private members. */
friend class boost::serialization::access;
/** Serialize class data members to boost archive.
* \param[in] ar Boost archive
* \param[in] version Version of the class
* See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase
*/
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
};
}
#include <boost/serialization/export.hpp>
/** Register this derived class. */
BOOST_CLASS_EXPORT_KEY2(DmpBbo::ModelParametersIRFRLS, "ModelParametersIRFRLS")
/** Don't add version information to archives. */
BOOST_CLASS_IMPLEMENTATION(DmpBbo::ModelParametersIRFRLS,boost::serialization::object_serializable);
#endif // #ifndef MODELPARAMETERSIRFRLS_H
<commit_msg>Added accessor function for weights<commit_after>/**
* @file ModelParametersIRFRLS.hpp
* @brief ModelParametersIRFRLS class header file.
* @author Freek Stulp, Thibaut Munzer
*
* This file is part of DmpBbo, a set of libraries and programs for the
* black-box optimization of dynamical movement primitives.
* Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
*
* DmpBbo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODELPARAMETERSIRFRLS_H
#define MODELPARAMETERSIRFRLS_H
#include <iosfwd>
#include "functionapproximators/ModelParameters.hpp"
namespace DmpBbo {
/** \brief Model parameters for the iRFRLS function approximator
* \ingroup FunctionApproximators
* \ingroup IRFRLS
*/
class ModelParametersIRFRLS : public ModelParameters
{
friend class FunctionApproximatorIRFRLS;
public:
/** Constructor for the model parameters of the IRFRLS function approximator.
* \param[in] linear_models Coefficient of the linear models (nb_cos x nb_out_dim).
* \param[in] cosines_periodes Matrix of periode for each cosine for each input dimension (nb_cos x nb_in_dim).
* \param[in] cosines_phase Vector of periode (nb_cos).
*/
ModelParametersIRFRLS(Eigen::VectorXd linear_models, Eigen::MatrixXd cosines_periodes, Eigen::VectorXd cosines_phase);
int getExpectedInputDim(void) const;
std::string toString(void) const;
ModelParameters* clone(void) const;
void getSelectableParameters(std::set<std::string>& selected_values_labels) const;
void getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const;
void getParameterVectorAll(Eigen::VectorXd& all_values) const;
inline int getParameterVectorAllSize(void) const
{
return all_values_vector_size_;
}
UnifiedModel* toUnifiedModel(void) const;
/** Return the weights of the basis functions.
* \return weights of the basis functions.
*/
const Eigen::VectorXd& weights(void) const { return weights_; }
protected:
void setParameterVectorAll(const Eigen::VectorXd& values);
private:
Eigen::VectorXd weights_;
Eigen::MatrixXd cosines_periodes_;
Eigen::VectorXd cosines_phase_;
int nb_in_dim_;
int all_values_vector_size_;
/**
* Default constructor.
* \remarks This default constuctor is required for boost::serialization to work. Since this
* constructor should not be called by other classes, it is private (boost::serialization is a
* friend)
*/
ModelParametersIRFRLS(void) {};
/** Give boost serialization access to private members. */
friend class boost::serialization::access;
/** Serialize class data members to boost archive.
* \param[in] ar Boost archive
* \param[in] version Version of the class
* See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase
*/
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
};
}
#include <boost/serialization/export.hpp>
/** Register this derived class. */
BOOST_CLASS_EXPORT_KEY2(DmpBbo::ModelParametersIRFRLS, "ModelParametersIRFRLS")
/** Don't add version information to archives. */
BOOST_CLASS_IMPLEMENTATION(DmpBbo::ModelParametersIRFRLS,boost::serialization::object_serializable);
#endif // #ifndef MODELPARAMETERSIRFRLS_H
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/shader_translator.h"
#include <string.h>
#include "base/at_exit.h"
#include "base/logging.h"
namespace {
void FinalizeShaderTranslator(void* /* dummy */) {
ShFinalize();
}
bool InitializeShaderTranslator() {
static bool initialized = false;
if (!initialized && ShInitialize()) {
base::AtExitManager::RegisterCallback(&FinalizeShaderTranslator, NULL);
initialized = true;
}
return initialized;
}
using gpu::gles2::ShaderTranslator;
void GetVariableInfo(ShHandle compiler, ShShaderInfo var_type,
ShaderTranslator::VariableMap* var_map) {
int name_len = 0, mapped_name_len = 0;
switch (var_type) {
case SH_ACTIVE_ATTRIBUTES:
ShGetInfo(compiler, SH_ACTIVE_ATTRIBUTE_MAX_LENGTH, &name_len);
break;
case SH_ACTIVE_UNIFORMS:
ShGetInfo(compiler, SH_ACTIVE_UNIFORM_MAX_LENGTH, &name_len);
break;
default: NOTREACHED();
}
ShGetInfo(compiler, SH_MAPPED_NAME_MAX_LENGTH, &mapped_name_len);
if (name_len <= 1 || mapped_name_len <= 1) return;
scoped_array<char> name(new char[name_len]);
scoped_array<char> mapped_name(new char[mapped_name_len]);
int num_vars = 0;
ShGetInfo(compiler, var_type, &num_vars);
for (int i = 0; i < num_vars; ++i) {
int size = 0;
ShDataType type = SH_NONE;
switch (var_type) {
case SH_ACTIVE_ATTRIBUTES:
ShGetActiveAttrib(
compiler, i, NULL, &size, &type, name.get(), mapped_name.get());
break;
case SH_ACTIVE_UNIFORMS:
ShGetActiveUniform(
compiler, i, NULL, &size, &type, name.get(), mapped_name.get());
break;
default: NOTREACHED();
}
ShaderTranslator::VariableInfo info(type, size, name.get());
(*var_map)[mapped_name.get()] = info;
}
}
} // namespace
namespace gpu {
namespace gles2 {
ShaderTranslator::ShaderTranslator()
: compiler_(NULL),
implementation_is_glsl_es_(false),
needs_built_in_function_emulation_(false) {
}
ShaderTranslator::~ShaderTranslator() {
if (compiler_ != NULL)
ShDestruct(compiler_);
}
bool ShaderTranslator::Init(
ShShaderType shader_type,
ShShaderSpec shader_spec,
const ShBuiltInResources* resources,
ShaderTranslatorInterface::GlslImplementationType glsl_implementation_type,
ShaderTranslatorInterface::GlslBuiltInFunctionBehavior
glsl_built_in_function_behavior) {
// Make sure Init is called only once.
DCHECK(compiler_ == NULL);
DCHECK(shader_type == SH_FRAGMENT_SHADER || shader_type == SH_VERTEX_SHADER);
DCHECK(shader_spec == SH_GLES2_SPEC || shader_spec == SH_WEBGL_SPEC);
DCHECK(resources != NULL);
if (!InitializeShaderTranslator())
return false;
ShShaderOutput shader_output =
(glsl_implementation_type == kGlslES ? SH_ESSL_OUTPUT : SH_GLSL_OUTPUT);
compiler_ = ShConstructCompiler(
shader_type, shader_spec, shader_output, resources);
implementation_is_glsl_es_ = (glsl_implementation_type == kGlslES);
needs_built_in_function_emulation_ =
(glsl_built_in_function_behavior == kGlslBuiltInFunctionEmulated);
return compiler_ != NULL;
}
bool ShaderTranslator::Translate(const char* shader) {
// Make sure this instance is initialized.
DCHECK(compiler_ != NULL);
DCHECK(shader != NULL);
ClearResults();
bool success = false;
int compile_options =
SH_OBJECT_CODE | SH_ATTRIBUTES_UNIFORMS | SH_MAP_LONG_VARIABLE_NAMES;
if (needs_built_in_function_emulation_)
compile_options |= SH_EMULATE_BUILT_IN_FUNCTIONS;
if (ShCompile(compiler_, &shader, 1, compile_options)) {
success = true;
// Get translated shader.
int obj_code_len = 0;
ShGetInfo(compiler_, SH_OBJECT_CODE_LENGTH, &obj_code_len);
if (obj_code_len > 1) {
translated_shader_.reset(new char[obj_code_len]);
ShGetObjectCode(compiler_, translated_shader_.get());
}
// Get info for attribs and uniforms.
GetVariableInfo(compiler_, SH_ACTIVE_ATTRIBUTES, &attrib_map_);
GetVariableInfo(compiler_, SH_ACTIVE_UNIFORMS, &uniform_map_);
}
// Get info log.
int info_log_len = 0;
ShGetInfo(compiler_, SH_INFO_LOG_LENGTH, &info_log_len);
if (info_log_len > 1) {
info_log_.reset(new char[info_log_len]);
ShGetInfoLog(compiler_, info_log_.get());
} else {
info_log_.reset();
}
return success;
}
const char* ShaderTranslator::translated_shader() const {
return translated_shader_.get();
}
const char* ShaderTranslator::info_log() const {
return info_log_.get();
}
const ShaderTranslatorInterface::VariableMap&
ShaderTranslator::attrib_map() const {
return attrib_map_;
}
const ShaderTranslatorInterface::VariableMap&
ShaderTranslator::uniform_map() const {
return uniform_map_;
}
void ShaderTranslator::ClearResults() {
translated_shader_.reset();
info_log_.reset();
attrib_map_.clear();
uniform_map_.clear();
}
} // namespace gles2
} // namespace gpu
<commit_msg>Quick fix to resolve a heap corruption in shader translator.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/shader_translator.h"
#include <string.h>
#include "base/at_exit.h"
#include "base/logging.h"
namespace {
void FinalizeShaderTranslator(void* /* dummy */) {
ShFinalize();
}
bool InitializeShaderTranslator() {
static bool initialized = false;
if (!initialized && ShInitialize()) {
base::AtExitManager::RegisterCallback(&FinalizeShaderTranslator, NULL);
initialized = true;
}
return initialized;
}
using gpu::gles2::ShaderTranslator;
void GetVariableInfo(ShHandle compiler, ShShaderInfo var_type,
ShaderTranslator::VariableMap* var_map) {
int name_len = 0, mapped_name_len = 0;
switch (var_type) {
case SH_ACTIVE_ATTRIBUTES:
ShGetInfo(compiler, SH_ACTIVE_ATTRIBUTE_MAX_LENGTH, &name_len);
break;
case SH_ACTIVE_UNIFORMS:
ShGetInfo(compiler, SH_ACTIVE_UNIFORM_MAX_LENGTH, &name_len);
break;
default: NOTREACHED();
}
ShGetInfo(compiler, SH_MAPPED_NAME_MAX_LENGTH, &mapped_name_len);
if (name_len <= 1 || mapped_name_len <= 1) return;
scoped_array<char> name(new char[name_len]);
scoped_array<char> mapped_name(new char[mapped_name_len]);
int num_vars = 0;
ShGetInfo(compiler, var_type, &num_vars);
for (int i = 0; i < num_vars; ++i) {
int len = 0;
int size = 0;
ShDataType type = SH_NONE;
switch (var_type) {
case SH_ACTIVE_ATTRIBUTES:
ShGetActiveAttrib(
compiler, i, &len, &size, &type, name.get(), mapped_name.get());
break;
case SH_ACTIVE_UNIFORMS:
ShGetActiveUniform(
compiler, i, &len, &size, &type, name.get(), mapped_name.get());
break;
default: NOTREACHED();
}
// In theory we should CHECK(len <= name_len - 1) here, but ANGLE needs
// to handle long struct field name mapping before we can do this.
// Also, we should modify the ANGLE interface to also return a length
// for mapped_name.
std::string name_string(name.get(), std::min(len, name_len - 1));
mapped_name.get()[mapped_name_len - 1] = '\0';
ShaderTranslator::VariableInfo info(type, size, name_string);
(*var_map)[mapped_name.get()] = info;
}
}
} // namespace
namespace gpu {
namespace gles2 {
ShaderTranslator::ShaderTranslator()
: compiler_(NULL),
implementation_is_glsl_es_(false),
needs_built_in_function_emulation_(false) {
}
ShaderTranslator::~ShaderTranslator() {
if (compiler_ != NULL)
ShDestruct(compiler_);
}
bool ShaderTranslator::Init(
ShShaderType shader_type,
ShShaderSpec shader_spec,
const ShBuiltInResources* resources,
ShaderTranslatorInterface::GlslImplementationType glsl_implementation_type,
ShaderTranslatorInterface::GlslBuiltInFunctionBehavior
glsl_built_in_function_behavior) {
// Make sure Init is called only once.
DCHECK(compiler_ == NULL);
DCHECK(shader_type == SH_FRAGMENT_SHADER || shader_type == SH_VERTEX_SHADER);
DCHECK(shader_spec == SH_GLES2_SPEC || shader_spec == SH_WEBGL_SPEC);
DCHECK(resources != NULL);
if (!InitializeShaderTranslator())
return false;
ShShaderOutput shader_output =
(glsl_implementation_type == kGlslES ? SH_ESSL_OUTPUT : SH_GLSL_OUTPUT);
compiler_ = ShConstructCompiler(
shader_type, shader_spec, shader_output, resources);
implementation_is_glsl_es_ = (glsl_implementation_type == kGlslES);
needs_built_in_function_emulation_ =
(glsl_built_in_function_behavior == kGlslBuiltInFunctionEmulated);
return compiler_ != NULL;
}
bool ShaderTranslator::Translate(const char* shader) {
// Make sure this instance is initialized.
DCHECK(compiler_ != NULL);
DCHECK(shader != NULL);
ClearResults();
bool success = false;
int compile_options =
SH_OBJECT_CODE | SH_ATTRIBUTES_UNIFORMS | SH_MAP_LONG_VARIABLE_NAMES;
if (needs_built_in_function_emulation_)
compile_options |= SH_EMULATE_BUILT_IN_FUNCTIONS;
if (ShCompile(compiler_, &shader, 1, compile_options)) {
success = true;
// Get translated shader.
int obj_code_len = 0;
ShGetInfo(compiler_, SH_OBJECT_CODE_LENGTH, &obj_code_len);
if (obj_code_len > 1) {
translated_shader_.reset(new char[obj_code_len]);
ShGetObjectCode(compiler_, translated_shader_.get());
}
// Get info for attribs and uniforms.
GetVariableInfo(compiler_, SH_ACTIVE_ATTRIBUTES, &attrib_map_);
GetVariableInfo(compiler_, SH_ACTIVE_UNIFORMS, &uniform_map_);
}
// Get info log.
int info_log_len = 0;
ShGetInfo(compiler_, SH_INFO_LOG_LENGTH, &info_log_len);
if (info_log_len > 1) {
info_log_.reset(new char[info_log_len]);
ShGetInfoLog(compiler_, info_log_.get());
} else {
info_log_.reset();
}
return success;
}
const char* ShaderTranslator::translated_shader() const {
return translated_shader_.get();
}
const char* ShaderTranslator::info_log() const {
return info_log_.get();
}
const ShaderTranslatorInterface::VariableMap&
ShaderTranslator::attrib_map() const {
return attrib_map_;
}
const ShaderTranslatorInterface::VariableMap&
ShaderTranslator::uniform_map() const {
return uniform_map_;
}
void ShaderTranslator::ClearResults() {
translated_shader_.reset();
info_log_.reset();
attrib_map_.clear();
uniform_map_.clear();
}
} // namespace gles2
} // namespace gpu
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Exception.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Visibility.h"
#include "cling/Utils/Validation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
extern "C" {
/// Throw an InvalidDerefException if the Arg pointer is invalid.
///\param Interp: The interpreter that has compiled the code.
///\param Expr: The expression corresponding determining the pointer value.
///\param Arg: The pointer to be checked.
///\returns void*, const-cast from Arg, to reduce the complexity in the
/// calling AST nodes, at the expense of possibly doing a
/// T* -> const void* -> const_cast<void*> -> T* round trip.
CLING_LIB_EXPORT
void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr,
const void* Arg) {
const clang::Expr* const E = (const clang::Expr*)Expr;
#if defined(__APPLE__) && defined(__arm64__)
// See https://github.com/root-project/root/issues/7541 and
// https://bugs.llvm.org/show_bug.cgi?id=49692 :
// llvm JIT fails to catch exceptions on M1, so let's throw less.
// This might still better than `terminate`...
(void)Interp;
(void)Expr;
#else
// The isValidAddress function return true even when the pointer is
// null thus the checks have to be done before returning successfully from the
// function in this specific order.
if (!Arg) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::NULL_DEREF);
} else if (!cling::utils::isAddressValid(Arg)) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::INVALID_MEM);
}
#endif
return const_cast<void*>(Arg);
}
}
namespace cling {
InterpreterException::InterpreterException(const std::string& What) :
std::runtime_error(What), m_Sema(nullptr) {}
InterpreterException::InterpreterException(const char* What, clang::Sema* S) :
std::runtime_error(What), m_Sema(S) {}
bool InterpreterException::diagnose() const { return false; }
InterpreterException::~InterpreterException() noexcept {}
InvalidDerefException::InvalidDerefException(clang::Sema* S,
const clang::Expr* E,
DerefType type)
: InterpreterException(type == INVALID_MEM ?
"Trying to access a pointer that points to an invalid memory address." :
"Trying to dereference null pointer or trying to call routine taking "
"non-null arguments", S),
m_Arg(E), m_Type(type) {}
InvalidDerefException::~InvalidDerefException() noexcept {}
bool InvalidDerefException::diagnose() const {
// Construct custom diagnostic: warning for invalid memory address;
// no equivalent in clang.
if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) {
clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics();
unsigned DiagID =
Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"invalid memory pointer passed to a callee:");
Diags.Report(m_Arg->getBeginLoc(), DiagID) << m_Arg->getSourceRange();
}
else
m_Sema->Diag(m_Arg->getBeginLoc(), clang::diag::warn_null_arg)
<< m_Arg->getSourceRange();
return true;
}
CompilationException::CompilationException(const std::string& Reason) :
InterpreterException(Reason) {}
CompilationException::~CompilationException() noexcept {}
void CompilationException::throwingHandler(void * /*user_data*/,
const std::string& reason,
bool /*gen_crash_diag*/) {
#ifndef _MSC_VER
throw cling::CompilationException(reason);
#endif
}
} // end namespace cling
<commit_msg>[cling] Remove backtrace on invalid ptr:<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Exception.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Visibility.h"
#include "cling/Utils/Validation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
extern "C" {
/// Throw an InvalidDerefException if the Arg pointer is invalid.
///\param Interp: The interpreter that has compiled the code.
///\param Expr: The expression corresponding determining the pointer value.
///\param Arg: The pointer to be checked.
///\returns void*, const-cast from Arg, to reduce the complexity in the
/// calling AST nodes, at the expense of possibly doing a
/// T* -> const void* -> const_cast<void*> -> T* round trip.
CLING_LIB_EXPORT
void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr,
const void* Arg) {
const clang::Expr* const E = (const clang::Expr*)Expr;
#if defined(__APPLE__) && defined(__arm64__)
// See https://github.com/root-project/root/issues/7541 and
// https://bugs.llvm.org/show_bug.cgi?id=49692 :
// llvm JIT fails to catch exceptions on M1, so let's throw less.
// This might still better than `terminate`...
(void)Interp;
(void)Expr;
#else
// The isValidAddress function return true even when the pointer is
// null thus the checks have to be done before returning successfully from the
// function in this specific order.
if (!Arg) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::NULL_DEREF);
} else if (!cling::utils::isAddressValid(Arg)) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::INVALID_MEM);
}
#endif
return const_cast<void*>(Arg);
}
}
namespace cling {
InterpreterException::InterpreterException(const std::string& What) :
std::runtime_error(What), m_Sema(nullptr) {}
InterpreterException::InterpreterException(const char* What, clang::Sema* S) :
std::runtime_error(What), m_Sema(S) {}
bool InterpreterException::diagnose() const { return false; }
InterpreterException::~InterpreterException() noexcept {}
InvalidDerefException::InvalidDerefException(clang::Sema* S,
const clang::Expr* E,
DerefType type)
: InterpreterException(type == INVALID_MEM ?
"Trying to access a pointer that points to an invalid memory address." :
"Trying to dereference null pointer or trying to call routine taking "
"non-null arguments", S),
m_Arg(E), m_Type(type) {}
InvalidDerefException::~InvalidDerefException() noexcept {}
bool InvalidDerefException::diagnose() const {
// Construct custom diagnostic: warning for invalid memory address;
// no equivalent in clang.
if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) {
clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics();
unsigned DiagID =
Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"invalid memory pointer passed to a callee:");
Diags.Report(m_Arg->getBeginLoc(), DiagID) << m_Arg->getSourceRange();
}
else
m_Sema->Diag(m_Arg->getBeginLoc(), clang::diag::warn_null_arg)
<< m_Arg->getSourceRange();
return true;
}
CompilationException::CompilationException(const std::string& Reason) :
InterpreterException(Reason) {}
CompilationException::~CompilationException() noexcept {}
void CompilationException::throwingHandler(void * /*user_data*/,
const std::string& reason,
bool /*gen_crash_diag*/) {
#ifndef _MSC_VER
throw cling::CompilationException(reason);
#endif
}
} // end namespace cling
<|endoftext|>
|
<commit_before>// btlso_tcptimereventmanager.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <btlso_tcptimereventmanager.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(btlso_tcptimereventmanager_cpp,"$Id$ $CSID$")
#include <btlso_defaulteventmanager.h>
#include <btlso_defaulteventmanager_devpoll.h>
#include <btlso_defaulteventmanager_epoll.h>
#include <btlso_defaulteventmanager_poll.h>
#include <btlso_defaulteventmanager_select.h>
#include <btlso_flag.h>
#include <btlso_platform.h>
#include <bslma_default.h>
#include <bsls_timeinterval.h>
#include <bdlt_currenttime.h>
#include <bdlcc_timequeue.h>
#include <bsls_assert.h>
#include <bsls_types.h>
#include <bsl_functional.h>
#include <bsl_vector.h>
namespace BloombergLP {
enum {
k_CPU_BOUND = btlso::TimeMetrics::e_CPU_BOUND,
k_NUM_CATEGORIES = 2
};
namespace btlso {
// --------------------------
// class TcpTimerEventManager
// --------------------------
// CREATORS
TcpTimerEventManager::TcpTimerEventManager(bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_isManagedFlag(1)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::SELECT>(
&d_metrics,
basicAllocator);
#else
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
#endif
}
TcpTimerEventManager::TcpTimerEventManager(Hint hint,
bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_isManagedFlag(1)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::SELECT>(
&d_metrics,
basicAllocator);
#elif defined(BSLS_PLATFORM_OS_SOLARIS)
switch (hint) {
case e_NO_HINT: {
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
} break;
case e_INFREQUENT_REGISTRATION: {
d_manager_p = new (*d_allocator_p)
DefaultEventManager<Platform::DEVPOLL>(&d_metrics,
basicAllocator);
} break;
default: {
BSLS_ASSERT(0);
}
}
#elif defined(BSLS_PLATFORM_OS_LINUX)
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::EPOLL>(
&d_metrics,
basicAllocator);
#else
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
#endif
}
TcpTimerEventManager::TcpTimerEventManager(EventManager *manager,
bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_manager_p(manager)
, d_isManagedFlag(0)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
BSLS_ASSERT(d_manager_p);
}
TcpTimerEventManager::~TcpTimerEventManager()
{
if (d_isManagedFlag) {
d_allocator_p->deleteObjectRaw(d_manager_p);
}
}
// MANIPULATORS
int TcpTimerEventManager::dispatch(int flags)
{
int ret;
if (d_timers.length()) {
bsls::TimeInterval minTime;
if (d_timers.minTime(&minTime)) {
return -1; // RETURN
}
ret = d_manager_p->dispatch(minTime, flags);
bsls::TimeInterval now = bdlt::CurrentTime::now();
if (now >= minTime) {
bsl::vector<bdlcc::TimeQueueItem<bsl::function<void()> > >
requests(d_allocator_p);
d_timers.popLE(now, &requests);
int numTimers = static_cast<int>(requests.size());
for (int i = 0; i < numTimers; ++i) {
requests[i].data()();
}
return numTimers + (ret >= 0 ? ret : 0); // RETURN
}
else {
return ret; // RETURN
}
}
else {
if (!d_manager_p->numEvents()) {
return 0; // RETURN
}
return d_manager_p->dispatch(flags); // RETURN
}
}
int TcpTimerEventManager::registerSocketEvent(
const SocketHandle::Handle& handle,
EventType::Type eventType,
const Callback& callBack)
{
return d_manager_p->registerSocketEvent(handle, eventType, callBack);
}
void *TcpTimerEventManager::registerTimer(const bsls::TimeInterval& timeout,
const Callback& callback)
{
return reinterpret_cast<void *>(d_timers.add(timeout, callback));
}
int TcpTimerEventManager::rescheduleTimer(const void *timerId,
const bsls::TimeInterval& time)
{
return d_timers.update(static_cast<int>(
reinterpret_cast<bsls::Types::IntPtr>(timerId)),
time);
}
void TcpTimerEventManager::deregisterSocketEvent(
const SocketHandle::Handle& handle,
EventType::Type event)
{
d_manager_p->deregisterSocketEvent(handle, event);
}
void TcpTimerEventManager::deregisterSocket(const SocketHandle::Handle& handle)
{
d_manager_p->deregisterSocket(handle);
}
void TcpTimerEventManager::deregisterAllSocketEvents()
{
d_manager_p->deregisterAll();
}
void TcpTimerEventManager::deregisterTimer(const void *handle)
{
d_timers.remove(static_cast<int>(
reinterpret_cast<bsls::Types::IntPtr>(handle)));
}
void TcpTimerEventManager::deregisterAllTimers()
{
d_timers.removeAll();
}
void TcpTimerEventManager::deregisterAll()
{
deregisterAllSocketEvents();
deregisterAllTimers();
}
// ACCESSORS
int TcpTimerEventManager::isRegistered(
const SocketHandle::Handle& handle,
EventType::Type eventType) const
{
return d_manager_p->isRegistered(handle, eventType);
}
int TcpTimerEventManager::numEvents() const
{
return d_timers.length() + d_manager_p->numEvents();
}
int TcpTimerEventManager::numSocketEvents(
const SocketHandle::Handle& handle) const
{
return d_manager_p->numSocketEvents(handle);
}
int TcpTimerEventManager::numTimers() const
{
return d_timers.length();
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Adopt commit a718e24c3 from master: Merge pull request #1053 from dschuman/review/dschumann-drqs-93495627<commit_after>// btlso_tcptimereventmanager.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <btlso_tcptimereventmanager.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(btlso_tcptimereventmanager_cpp,"$Id$ $CSID$")
#include <btlso_defaulteventmanager.h>
#include <btlso_defaulteventmanager_devpoll.h>
#include <btlso_defaulteventmanager_epoll.h>
#include <btlso_defaulteventmanager_poll.h>
#include <btlso_defaulteventmanager_select.h>
#include <btlso_flag.h>
#include <btlso_platform.h>
#include <bslma_default.h>
#include <bsls_timeinterval.h>
#include <bdlt_currenttime.h>
#include <bdlcc_timequeue.h>
#include <bsls_assert.h>
#include <bsls_types.h>
#include <bsl_functional.h>
#include <bsl_vector.h>
namespace BloombergLP {
enum {
k_CPU_BOUND = btlso::TimeMetrics::e_CPU_BOUND,
k_NUM_CATEGORIES = 2
};
namespace btlso {
// --------------------------
// class TcpTimerEventManager
// --------------------------
// CREATORS
TcpTimerEventManager::TcpTimerEventManager(bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_isManagedFlag(1)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::SELECT>(
&d_metrics,
basicAllocator);
#else
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
#endif
}
TcpTimerEventManager::TcpTimerEventManager(Hint hint,
bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_isManagedFlag(1)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::SELECT>(
&d_metrics,
basicAllocator);
#elif defined(BSLS_PLATFORM_OS_SOLARIS)
switch (hint) {
case e_NO_HINT: {
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
} break;
case e_INFREQUENT_REGISTRATION: {
d_manager_p = new (*d_allocator_p)
DefaultEventManager<Platform::DEVPOLL>(&d_metrics,
basicAllocator);
} break;
default: {
BSLS_ASSERT(0);
}
}
#elif defined(BSLS_PLATFORM_OS_LINUX)
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::EPOLL>(
&d_metrics,
basicAllocator);
#else
(void) hint; // silence unused warning
d_manager_p = new (*d_allocator_p) DefaultEventManager<Platform::POLL>(
&d_metrics,
basicAllocator);
#endif
}
TcpTimerEventManager::TcpTimerEventManager(EventManager *manager,
bslma::Allocator *basicAllocator)
: d_timers(basicAllocator)
, d_manager_p(manager)
, d_isManagedFlag(0)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
, d_metrics(k_NUM_CATEGORIES, k_CPU_BOUND, basicAllocator)
{
BSLS_ASSERT(d_manager_p);
}
TcpTimerEventManager::~TcpTimerEventManager()
{
if (d_isManagedFlag) {
d_allocator_p->deleteObjectRaw(d_manager_p);
}
}
// MANIPULATORS
int TcpTimerEventManager::dispatch(int flags)
{
typedef bsl::vector<bdlcc::TimeQueueItem<bsl::function<void() > > >
TimerArray;
if (d_timers.length()) {
bsls::TimeInterval minTime;
if (d_timers.minTime(&minTime)) {
return -1; // RETURN
}
int ret = d_manager_p->dispatch(minTime, flags);
bsls::TimeInterval now = bdlt::CurrentTime::now();
if (now >= minTime) {
TimerArray timers;
d_timers.popLE(now, &timers);
int numTimers = static_cast<int>(timers.size());
for (int i = 0; i < numTimers; ++i) {
timers[i].data()();
}
return numTimers + (ret >= 0 ? ret : 0); // RETURN
}
else {
return ret; // RETURN
}
}
else {
if (!d_manager_p->numEvents()) {
return 0; // RETURN
}
return d_manager_p->dispatch(flags); // RETURN
}
}
int TcpTimerEventManager::registerSocketEvent(
const SocketHandle::Handle& handle,
EventType::Type eventType,
const Callback& callBack)
{
return d_manager_p->registerSocketEvent(handle, eventType, callBack);
}
void *TcpTimerEventManager::registerTimer(const bsls::TimeInterval& timeout,
const Callback& callback)
{
return reinterpret_cast<void *>(d_timers.add(timeout, callback));
}
int TcpTimerEventManager::rescheduleTimer(const void *timerId,
const bsls::TimeInterval& time)
{
return d_timers.update(static_cast<int>(
reinterpret_cast<bsls::Types::IntPtr>(timerId)),
time);
}
void TcpTimerEventManager::deregisterSocketEvent(
const SocketHandle::Handle& handle,
EventType::Type event)
{
d_manager_p->deregisterSocketEvent(handle, event);
}
void TcpTimerEventManager::deregisterSocket(const SocketHandle::Handle& handle)
{
d_manager_p->deregisterSocket(handle);
}
void TcpTimerEventManager::deregisterAllSocketEvents()
{
d_manager_p->deregisterAll();
}
void TcpTimerEventManager::deregisterTimer(const void *handle)
{
d_timers.remove(static_cast<int>(
reinterpret_cast<bsls::Types::IntPtr>(handle)));
}
void TcpTimerEventManager::deregisterAllTimers()
{
d_timers.removeAll();
}
void TcpTimerEventManager::deregisterAll()
{
deregisterAllSocketEvents();
deregisterAllTimers();
}
// ACCESSORS
int TcpTimerEventManager::isRegistered(
const SocketHandle::Handle& handle,
EventType::Type eventType) const
{
return d_manager_p->isRegistered(handle, eventType);
}
int TcpTimerEventManager::numEvents() const
{
return d_timers.length() + d_manager_p->numEvents();
}
int TcpTimerEventManager::numSocketEvents(
const SocketHandle::Handle& handle) const
{
return d_manager_p->numSocketEvents(handle);
}
int TcpTimerEventManager::numTimers() const
{
return d_timers.length();
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>#include "sharedmemorysource.h"
#include "shared/guiconst.h"
#include "shmtypes/sharedmemorysourcebasewidget.h"
#include "shmtypes/sharedmemconnector.h"
#include "shmtypes/sharedmemposix.h"
#ifdef Q_OS_UNIX
#include "shmtypes/sysv_shm.h"
#endif
const QString SharedMemorySource::ID = QString("SharedMemory");
SharedMemorySource::SharedMemorySource(QObject *parent) : BlocksSource(parent)
{
running = false;
sid = BlocksSource::newSourceID(this);
memConn = nullptr;
localGui = nullptr;
flags = WANTS_TRACKING;
type = BlocksSource::CLIENT;
timerInterval = 200;
checkTimer.setSingleShot(false);
checkTimer.setInterval(timerInterval);
checkTimer.moveToThread(&workerThread);
connect(&checkTimer, &QTimer::timeout, this, &SharedMemorySource::checkData);
connect(this, &SharedMemorySource::stopped, &checkTimer, &QTimer::stop, Qt::QueuedConnection);
updateConnectionsTimer.moveToThread(&workerThread);
moveToThread(&workerThread);
workerThread.start();
}
SharedMemorySource::~SharedMemorySource()
{
checkTimer.stop();
workerThread.quit();
workerThread.wait();
BlocksSource::releaseID(sid);
delete memConn;
}
QWidget *SharedMemorySource::getAdditionnalCtrls(QWidget *)
{
return nullptr;
}
QString SharedMemorySource::getName()
{
return ID;
}
QString SharedMemorySource::getDescription()
{
return QString("Listener for Shared Memory");
}
bool SharedMemorySource::isStarted()
{
return running;
}
QHash<QString, QString> SharedMemorySource::getConfiguration()
{
QHash<QString, QString> ret = BlocksSource::getConfiguration();
if (memConn != nullptr) {
ret.insert(memConn->getConfiguration());
}
return ret;
}
void SharedMemorySource::setConfiguration(const QHash<QString, QString> &conf)
{
BlocksSource::setConfiguration(conf);
if (conf.contains(GuiConst::STATE_TYPE)) {
bool ok = false;
int val = conf.value(GuiConst::STATE_TYPE).toInt(&ok);
if (ok) {
setShmType(val);
}
}
if (memConn != nullptr) {
memConn->setConfiguration(conf);
}
}
QStringList SharedMemorySource::getAvailableSHMTypes()
{
QStringList ret;
ret << SharedMemPosix::ID;
#ifdef Q_OS_UNIX
ret << SysV_Shm::ID;
#endif
return ret;
}
void SharedMemorySource::setShmType(int smtype)
{
SharedmemConnector * oldm = memConn;
memConn = nullptr;
switch (smtype) {
case SharedmemConnector::POSIX_NATIVE_SHM:
memConn = new(std::nothrow) SharedMemPosix();
if (memConn == nullptr) {
qFatal("%s", GuiConst::MEM_ALLOC_ERROR_STR);
}
shmType = smtype;
break;
case SharedmemConnector::SYSV_SHM:
#ifdef Q_OS_UNIX
memConn = new(std::nothrow) SysV_Shm();
if (memConn == nullptr) {
qFatal("%s", GuiConst::MEM_ALLOC_ERROR_STR);
}
shmType = smtype;
break;
#else
qCritical() << tr("Ssytem V shm unsupported on this platform");
#endif
default:
qCritical() << tr("[SharedMemorySource::setType] Unknown type : %1");
break;
}
if (memConn == nullptr) {
memConn = oldm;
} else {
if (localGui != nullptr) {
localGui->addWidget(memConn->getGui());
}
memConn->moveToThread(&workerThread);
connect(memConn, &SharedmemConnector::reset, this, &SharedMemorySource::onShmReset, Qt::QueuedConnection);
connect(memConn, &SharedmemConnector::log, this , &SharedMemorySource::log, Qt::QueuedConnection);
delete oldm;
}
}
int SharedMemorySource::getShmType() const
{
return shmType;
}
void SharedMemorySource::sendBlock(Block *block)
{
if (running && memConn != nullptr) {
int sid = block->getSourceid();
if (!extsources.contains(sid)) {
extsources.append(sid);
}
memConn->writeData(block->getData());
currentData = block->getData();
} else {
qCritical() << tr("[SharedMemorySource::sendBlock] Not running and/or shared mem obj is null");
}
delete block;
}
void SharedMemorySource::checkData()
{
if (running && memConn != nullptr) {
QByteArray data;
if (memConn->readData(data)) {
if (currentData != data) {
currentData = data;
Block * bl = new(std::nothrow) Block(data,Block::INVALID_ID);
if (bl == nullptr) {
qFatal("Cannot allocate memory");
}
emit blockReceived(bl);
// for (int i = 0; i < extsources.size(); i++) {
// int bid = extsources.at(i);
// Block * bl = new(std::nothrow) Block(data,bid);
// if (bl == nullptr) {
// qFatal("Cannot allocate memory");
// }
// emit blockReceived(bl);
// }
}
}
}
}
void SharedMemorySource::onShmReset()
{
stopListening();
startListening();
}
bool SharedMemorySource::startListening()
{
if (!running) {
currentData.clear();
if (memConn != nullptr) {
running = memConn->connectToMem();
if (running) {
checkTimer.start(timerInterval);
emit started();
updateConnectionsInfo();
emit log("Started monitoring", memConn->name(),Pip3lineConst::PLSTATUS);
}
} else {
qCritical() << tr("[SharedMemorySource::startListening] Shared memory object is null");
}
}
return running;
}
void SharedMemorySource::stopListening()
{
if (running) {
if (memConn != nullptr) {
memConn->disconnectFromMem();
emit log("Stopped monitoring", memConn->name(),Pip3lineConst::PLSTATUS);
} else {
qCritical() << tr("[SharedMemorySource::stopListening] Shared memory object is null");
}
running = false;
currentData.clear();
emit stopped();
triggerUpdate();
}
}
void SharedMemorySource::onGuiDestroyed()
{
localGui = nullptr;
}
void SharedMemorySource::onConnectionClosed(int cid)
{
if (!extsources.contains(cid)) {
extsources.removeAll(cid);
}
}
QWidget *SharedMemorySource::requestGui(QWidget *parent)
{
if (localGui == nullptr) {
localGui = new(std::nothrow) SharedMemorySourceBaseWidget(this, parent);
connect(localGui, &SharedMemorySourceBaseWidget::destroyed, this , &SharedMemorySource::onGuiDestroyed);
if (localGui == nullptr) {
qFatal("Cannot allocate memory");
}
}
if (memConn != nullptr) {
localGui->addWidget(memConn->getGui());
}
return localGui;
}
void SharedMemorySource::internalUpdateConnectionsInfo()
{
connectionsInfo.clear();
if (running) { // accepting new connections
Target<BlocksSource *> tac;
QString desc = memConn->name();
if (memConn != nullptr) {
desc.append(": ").append(memConn->getCurrentID());
} else {
desc.append(": Unitialized");
}
tac.setDescription(desc);
tac.setConnectionID(sid);
tac.setSource(this);
connectionsInfo.append(tac);
}
}
<commit_msg>Fix for older libraries<commit_after>#include "sharedmemorysource.h"
#include "shared/guiconst.h"
#include "shmtypes/sharedmemorysourcebasewidget.h"
#include "shmtypes/sharedmemconnector.h"
#include "shmtypes/sharedmemposix.h"
#ifdef Q_OS_UNIX
#include "shmtypes/sysv_shm.h"
#endif
const QString SharedMemorySource::ID = QString("SharedMemory");
SharedMemorySource::SharedMemorySource(QObject *parent) : BlocksSource(parent)
{
running = false;
sid = BlocksSource::newSourceID(this);
memConn = nullptr;
localGui = nullptr;
flags = WANTS_TRACKING;
type = BlocksSource::CLIENT;
timerInterval = 200;
checkTimer.setSingleShot(false);
checkTimer.setInterval(timerInterval);
checkTimer.moveToThread(&workerThread);
connect(&checkTimer, &QTimer::timeout, this, &SharedMemorySource::checkData);
connect(this, &SharedMemorySource::stopped, &checkTimer, &QTimer::stop, Qt::QueuedConnection);
updateConnectionsTimer.moveToThread(&workerThread);
moveToThread(&workerThread);
workerThread.start();
}
SharedMemorySource::~SharedMemorySource()
{
checkTimer.stop();
workerThread.quit();
workerThread.wait();
BlocksSource::releaseID(sid);
delete memConn;
}
QWidget *SharedMemorySource::getAdditionnalCtrls(QWidget *)
{
return nullptr;
}
QString SharedMemorySource::getName()
{
return ID;
}
QString SharedMemorySource::getDescription()
{
return QString("Listener for Shared Memory");
}
bool SharedMemorySource::isStarted()
{
return running;
}
QHash<QString, QString> SharedMemorySource::getConfiguration()
{
QHash<QString, QString> ret = BlocksSource::getConfiguration();
if (memConn != nullptr) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
ret.insert(memConn->getConfiguration());
#else
ret.unite(memConn->getConfiguration());
#endif
}
return ret;
}
void SharedMemorySource::setConfiguration(const QHash<QString, QString> &conf)
{
BlocksSource::setConfiguration(conf);
if (conf.contains(GuiConst::STATE_TYPE)) {
bool ok = false;
int val = conf.value(GuiConst::STATE_TYPE).toInt(&ok);
if (ok) {
setShmType(val);
}
}
if (memConn != nullptr) {
memConn->setConfiguration(conf);
}
}
QStringList SharedMemorySource::getAvailableSHMTypes()
{
QStringList ret;
ret << SharedMemPosix::ID;
#ifdef Q_OS_UNIX
ret << SysV_Shm::ID;
#endif
return ret;
}
void SharedMemorySource::setShmType(int smtype)
{
SharedmemConnector * oldm = memConn;
memConn = nullptr;
switch (smtype) {
case SharedmemConnector::POSIX_NATIVE_SHM:
memConn = new(std::nothrow) SharedMemPosix();
if (memConn == nullptr) {
qFatal("%s", GuiConst::MEM_ALLOC_ERROR_STR);
}
shmType = smtype;
break;
case SharedmemConnector::SYSV_SHM:
#ifdef Q_OS_UNIX
memConn = new(std::nothrow) SysV_Shm();
if (memConn == nullptr) {
qFatal("%s", GuiConst::MEM_ALLOC_ERROR_STR);
}
shmType = smtype;
break;
#else
qCritical() << tr("Ssytem V shm unsupported on this platform");
#endif
default:
qCritical() << tr("[SharedMemorySource::setType] Unknown type : %1");
break;
}
if (memConn == nullptr) {
memConn = oldm;
} else {
if (localGui != nullptr) {
localGui->addWidget(memConn->getGui());
}
memConn->moveToThread(&workerThread);
connect(memConn, &SharedmemConnector::reset, this, &SharedMemorySource::onShmReset, Qt::QueuedConnection);
connect(memConn, &SharedmemConnector::log, this , &SharedMemorySource::log, Qt::QueuedConnection);
delete oldm;
}
}
int SharedMemorySource::getShmType() const
{
return shmType;
}
void SharedMemorySource::sendBlock(Block *block)
{
if (running && memConn != nullptr) {
int sid = block->getSourceid();
if (!extsources.contains(sid)) {
extsources.append(sid);
}
memConn->writeData(block->getData());
currentData = block->getData();
} else {
qCritical() << tr("[SharedMemorySource::sendBlock] Not running and/or shared mem obj is null");
}
delete block;
}
void SharedMemorySource::checkData()
{
if (running && memConn != nullptr) {
QByteArray data;
if (memConn->readData(data)) {
if (currentData != data) {
currentData = data;
Block * bl = new(std::nothrow) Block(data,Block::INVALID_ID);
if (bl == nullptr) {
qFatal("Cannot allocate memory");
}
emit blockReceived(bl);
// for (int i = 0; i < extsources.size(); i++) {
// int bid = extsources.at(i);
// Block * bl = new(std::nothrow) Block(data,bid);
// if (bl == nullptr) {
// qFatal("Cannot allocate memory");
// }
// emit blockReceived(bl);
// }
}
}
}
}
void SharedMemorySource::onShmReset()
{
stopListening();
startListening();
}
bool SharedMemorySource::startListening()
{
if (!running) {
currentData.clear();
if (memConn != nullptr) {
running = memConn->connectToMem();
if (running) {
checkTimer.start(timerInterval);
emit started();
updateConnectionsInfo();
emit log("Started monitoring", memConn->name(),Pip3lineConst::PLSTATUS);
}
} else {
qCritical() << tr("[SharedMemorySource::startListening] Shared memory object is null");
}
}
return running;
}
void SharedMemorySource::stopListening()
{
if (running) {
if (memConn != nullptr) {
memConn->disconnectFromMem();
emit log("Stopped monitoring", memConn->name(),Pip3lineConst::PLSTATUS);
} else {
qCritical() << tr("[SharedMemorySource::stopListening] Shared memory object is null");
}
running = false;
currentData.clear();
emit stopped();
triggerUpdate();
}
}
void SharedMemorySource::onGuiDestroyed()
{
localGui = nullptr;
}
void SharedMemorySource::onConnectionClosed(int cid)
{
if (!extsources.contains(cid)) {
extsources.removeAll(cid);
}
}
QWidget *SharedMemorySource::requestGui(QWidget *parent)
{
if (localGui == nullptr) {
localGui = new(std::nothrow) SharedMemorySourceBaseWidget(this, parent);
connect(localGui, &SharedMemorySourceBaseWidget::destroyed, this , &SharedMemorySource::onGuiDestroyed);
if (localGui == nullptr) {
qFatal("Cannot allocate memory");
}
}
if (memConn != nullptr) {
localGui->addWidget(memConn->getGui());
}
return localGui;
}
void SharedMemorySource::internalUpdateConnectionsInfo()
{
connectionsInfo.clear();
if (running) { // accepting new connections
Target<BlocksSource *> tac;
QString desc = memConn->name();
if (memConn != nullptr) {
desc.append(": ").append(memConn->getCurrentID());
} else {
desc.append(": Unitialized");
}
tac.setDescription(desc);
tac.setConnectionID(sid);
tac.setSource(this);
connectionsInfo.append(tac);
}
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include <string>
#include "command.h"
#include "exception.h"
#include "mrtrix.h"
#include "thread_queue.h"
#include "types.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/roi.h"
#include "dwi/tractography/weights.h"
#include "dwi/tractography/editing/editing.h"
#include "dwi/tractography/editing/loader.h"
#include "dwi/tractography/editing/receiver.h"
#include "dwi/tractography/editing/worker.h"
using namespace MR;
using namespace App;
using namespace MR::DWI;
using namespace MR::DWI::Tractography;
using namespace MR::DWI::Tractography::Editing;
void usage ()
{
AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Perform various editing operations on track files";
DESCRIPTION
+ "This command can be used to perform various types of manipulations "
"on track data. A range of such manipulations are demonstrated in the "
"examples provided below."
+ DWI::Tractography::preserve_track_order_desc;
EXAMPLES
+ Example ("Concatenate data from multiple track files into one",
"tckedit *.tck all_tracks.tck",
"Here the wildcard operator is used to select all files in the "
"current working directory that have the .tck filetype suffix; but "
"input files can equivalently be specified one at a time explicitly.")
+ Example ("Extract a reduced number of streamlines",
"tckedit in_many.tck out_few.tck -number 1k -skip 500",
"The number of streamlines requested would typically be less "
"than the number of streamlines in the input track file(s); if it "
"is instead greater, then the command will issue a warning upon "
"completion. By default the streamlines for the output file are "
"extracted from the start of the input file(s); in this example the "
"command is instead instructed to skip the first 500 streamlines, and "
"write to the output file streamlines 501-1500.")
+ Example ("Extract streamlines based on selection criteria",
"tckedit in.tck out.tck -include ROI1.mif -include ROI2.mif -minlength 25",
"Multiple criteria can be added in a single invocation of tckedit, "
"and a streamline must satisfy all criteria imposed in order to be "
"written to the output file. Note that both -include and -exclude "
"options can be specified multiple times to provide multiple "
"waypoints / exclusion masks.")
+ Example ("Select only those streamline vertices within a mask",
"tckedit in.tck cropped.tck -mask mask.mif",
"The -mask option is applied to each streamline vertex independently, "
"rather than to each streamline, retaining only those streamline vertices "
"within the mask. As such, use of this option may result in a greater "
"number of output streamlines than input streamlines, as a single input "
"streamline may have the vertices at either endpoint retained but some "
"vertices at its midpoint removed, effectively cutting one long streamline "
"into multiple shorter streamlines.");
ARGUMENTS
+ Argument ("tracks_in", "the input track file(s)").type_tracks_in().allow_multiple()
+ Argument ("tracks_out", "the output track file").type_tracks_out();
OPTIONS
+ ROIOption
+ LengthOption
+ TruncateOption
+ WeightsOption
+ OptionGroup ("Other options specific to tckedit")
+ Option ("inverse", "output the inverse selection of streamlines based on the criteria provided, "
"i.e. only those streamlines that fail at least one criterion will be written to file.")
+ Option ("ends_only", "only test the ends of each streamline against the provided include/exclude ROIs")
// TODO Input weights with multiple input files currently not supported
+ OptionGroup ("Options for handling streamline weights")
+ Tractography::TrackWeightsInOption
+ Tractography::TrackWeightsOutOption;
// TODO Additional options?
// - Peak curvature threshold
// - Mean curvature threshold
}
void erase_if_present (Tractography::Properties& p, const std::string s)
{
auto i = p.find (s);
if (i != p.end())
p.erase (i);
}
void run ()
{
const size_t num_inputs = argument.size() - 1;
const std::string output_path = argument[num_inputs];
// Make sure configuration is sensible
if (get_options("tck_weights_in").size() && num_inputs > 1)
throw Exception ("Cannot use per-streamline weighting with multiple input files");
// Get the consensus streamline properties from among the multiple input files
Tractography::Properties properties;
size_t count = 0;
vector<std::string> input_file_list;
for (size_t file_index = 0; file_index != num_inputs; ++file_index) {
input_file_list.push_back (argument[file_index]);
Properties p;
Reader<float> (argument[file_index], p);
for (vector<std::string>::const_iterator i = p.comments.begin(); i != p.comments.end(); ++i) {
bool present = false;
for (vector<std::string>::const_iterator j = properties.comments.begin(); !present && j != properties.comments.end(); ++j)
present = (*i == *j);
if (!present)
properties.comments.push_back (*i);
}
for (std::multimap<std::string, std::string>::const_iterator i = p.prior_rois.begin(); i != p.prior_rois.end(); ++i) {
auto potential_matches = properties.prior_rois.equal_range (i->first);
bool present = false;
for (std::multimap<std::string, std::string>::const_iterator j = potential_matches.first; !present && j != potential_matches.second; ++j)
present = (i->second == j->second);
if (!present)
properties.prior_rois.insert (*i);
}
size_t this_count = 0, this_total_count = 0;
for (Properties::const_iterator i = p.begin(); i != p.end(); ++i) {
if (i->first == "count") {
this_count = to<float>(i->second);
} else if (i->first == "total_count") {
this_total_count += to<float>(i->second);
} else {
Properties::iterator existing = properties.find (i->first);
if (existing == properties.end())
properties.insert (*i);
else if (i->second != existing->second)
existing->second = "variable";
}
}
count += this_count;
}
DEBUG ("estimated number of input tracks: " + str(count));
load_rois (properties);
// Some properties from tracking may be overwritten by this editing process
// Due to the potential use of masking, we have no choice but to clear the
// properties class of any fields that would otherwise propagate through
// and be applied as part of this editing
erase_if_present (properties, "min_dist");
erase_if_present (properties, "max_dist");
erase_if_present (properties, "min_weight");
erase_if_present (properties, "max_weight");
Editing::load_properties (properties);
// Parameters that the worker threads need to be aware of, but do not appear in Properties
const bool inverse = get_options ("inverse").size();
const bool ends_only = get_options ("ends_only").size();
// Parameters that the output thread needs to be aware of
const size_t number = get_option_value ("number", size_t(0));
const size_t skip = get_option_value ("skip", size_t(0));
Loader loader (input_file_list);
Worker worker (properties, inverse, ends_only);
// This needs to be run AFTER creation of the Worker class
// (worker needs to be able to set max & min number of points based on step size in input file,
// receiver needs "output_step_size" field to have been updated before file creation)
Receiver receiver (output_path, properties, number, skip);
Thread::run_queue (
loader,
Thread::batch (Streamline<>()),
Thread::multi (worker),
Thread::batch (Streamline<>()),
receiver);
}
<commit_msg>tckedit: use C++11 range-based for loops where possible<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include <string>
#include "command.h"
#include "exception.h"
#include "mrtrix.h"
#include "thread_queue.h"
#include "types.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/roi.h"
#include "dwi/tractography/weights.h"
#include "dwi/tractography/editing/editing.h"
#include "dwi/tractography/editing/loader.h"
#include "dwi/tractography/editing/receiver.h"
#include "dwi/tractography/editing/worker.h"
using namespace MR;
using namespace App;
using namespace MR::DWI;
using namespace MR::DWI::Tractography;
using namespace MR::DWI::Tractography::Editing;
void usage ()
{
AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Perform various editing operations on track files";
DESCRIPTION
+ "This command can be used to perform various types of manipulations "
"on track data. A range of such manipulations are demonstrated in the "
"examples provided below."
+ DWI::Tractography::preserve_track_order_desc;
EXAMPLES
+ Example ("Concatenate data from multiple track files into one",
"tckedit *.tck all_tracks.tck",
"Here the wildcard operator is used to select all files in the "
"current working directory that have the .tck filetype suffix; but "
"input files can equivalently be specified one at a time explicitly.")
+ Example ("Extract a reduced number of streamlines",
"tckedit in_many.tck out_few.tck -number 1k -skip 500",
"The number of streamlines requested would typically be less "
"than the number of streamlines in the input track file(s); if it "
"is instead greater, then the command will issue a warning upon "
"completion. By default the streamlines for the output file are "
"extracted from the start of the input file(s); in this example the "
"command is instead instructed to skip the first 500 streamlines, and "
"write to the output file streamlines 501-1500.")
+ Example ("Extract streamlines based on selection criteria",
"tckedit in.tck out.tck -include ROI1.mif -include ROI2.mif -minlength 25",
"Multiple criteria can be added in a single invocation of tckedit, "
"and a streamline must satisfy all criteria imposed in order to be "
"written to the output file. Note that both -include and -exclude "
"options can be specified multiple times to provide multiple "
"waypoints / exclusion masks.")
+ Example ("Select only those streamline vertices within a mask",
"tckedit in.tck cropped.tck -mask mask.mif",
"The -mask option is applied to each streamline vertex independently, "
"rather than to each streamline, retaining only those streamline vertices "
"within the mask. As such, use of this option may result in a greater "
"number of output streamlines than input streamlines, as a single input "
"streamline may have the vertices at either endpoint retained but some "
"vertices at its midpoint removed, effectively cutting one long streamline "
"into multiple shorter streamlines.");
ARGUMENTS
+ Argument ("tracks_in", "the input track file(s)").type_tracks_in().allow_multiple()
+ Argument ("tracks_out", "the output track file").type_tracks_out();
OPTIONS
+ ROIOption
+ LengthOption
+ TruncateOption
+ WeightsOption
+ OptionGroup ("Other options specific to tckedit")
+ Option ("inverse", "output the inverse selection of streamlines based on the criteria provided, "
"i.e. only those streamlines that fail at least one criterion will be written to file.")
+ Option ("ends_only", "only test the ends of each streamline against the provided include/exclude ROIs")
// TODO Input weights with multiple input files currently not supported
+ OptionGroup ("Options for handling streamline weights")
+ Tractography::TrackWeightsInOption
+ Tractography::TrackWeightsOutOption;
// TODO Additional options?
// - Peak curvature threshold
// - Mean curvature threshold
}
void erase_if_present (Tractography::Properties& p, const std::string s)
{
auto i = p.find (s);
if (i != p.end())
p.erase (i);
}
void run ()
{
const size_t num_inputs = argument.size() - 1;
const std::string output_path = argument[num_inputs];
// Make sure configuration is sensible
if (get_options("tck_weights_in").size() && num_inputs > 1)
throw Exception ("Cannot use per-streamline weighting with multiple input files");
// Get the consensus streamline properties from among the multiple input files
Tractography::Properties properties;
size_t count = 0;
vector<std::string> input_file_list;
for (size_t file_index = 0; file_index != num_inputs; ++file_index) {
input_file_list.push_back (argument[file_index]);
Properties p;
Reader<float> (argument[file_index], p);
for (const auto& i : p.comments) {
bool present = false;
for (const auto& j: properties.comments)
if ( (present = (i == j)) )
break;
if (!present)
properties.comments.push_back (i);
}
for (const auto& i : p.prior_rois) {
const auto potential_matches = properties.prior_rois.equal_range (i.first);
bool present = false;
for (auto j = potential_matches.first; !present && j != potential_matches.second; ++j)
present = (i.second == j->second);
if (!present)
properties.prior_rois.insert (i);
}
size_t this_count = 0, this_total_count = 0;
for (const auto& i : p) {
if (i.first == "count") {
this_count = to<float> (i.second);
} else if (i.first == "total_count") {
this_total_count += to<float> (i.second);
} else {
auto existing = properties.find (i.first);
if (existing == properties.end())
properties.insert (i);
else if (i.second != existing->second)
existing->second = "variable";
}
}
count += this_count;
}
DEBUG ("estimated number of input tracks: " + str(count));
load_rois (properties);
// Some properties from tracking may be overwritten by this editing process
// Due to the potential use of masking, we have no choice but to clear the
// properties class of any fields that would otherwise propagate through
// and be applied as part of this editing
erase_if_present (properties, "min_dist");
erase_if_present (properties, "max_dist");
erase_if_present (properties, "min_weight");
erase_if_present (properties, "max_weight");
Editing::load_properties (properties);
// Parameters that the worker threads need to be aware of, but do not appear in Properties
const bool inverse = get_options ("inverse").size();
const bool ends_only = get_options ("ends_only").size();
// Parameters that the output thread needs to be aware of
const size_t number = get_option_value ("number", size_t(0));
const size_t skip = get_option_value ("skip", size_t(0));
Loader loader (input_file_list);
Worker worker (properties, inverse, ends_only);
// This needs to be run AFTER creation of the Worker class
// (worker needs to be able to set max & min number of points based on step size in input file,
// receiver needs "output_step_size" field to have been updated before file creation)
Receiver receiver (output_path, properties, number, skip);
Thread::run_queue (
loader,
Thread::batch (Streamline<>()),
Thread::multi (worker),
Thread::batch (Streamline<>()),
receiver);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (c) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* 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 "mainwindow.h"
#include "lib/models/gameitemsmodel.h"
#include "input/inputmanager.h"
#include "engine/game.h"
#include "engine/gameproject.h"
#include "engine/scene.h"
#include "graphics/renderwidget.h"
#include <QtGui/QFileDialog>
#include <QtGui/QStatusBar>
#include <QtGui/QApplication>
#include <QtGui/QListView>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include <QtCore/QTimer>
using namespace GluonPlayer;
class MainWindow::MainWindowPrivate
{
public:
GluonEngine::GameProject* project;
GluonGraphics::RenderWidget* widget;
QAbstractItemModel* model;
QString title;
QString fileName;
int msecElapsed;
int frameCount;
};
GluonPlayer::MainWindow::MainWindow( int argc, char** argv, QWidget* parent, Qt::WindowFlags flags )
: QMainWindow( parent, flags )
, d( new MainWindowPrivate )
{
d->msecElapsed = 0;
d->frameCount = 0;
if( argc > 1 )
{
d->fileName = argv[1];
QTimer::singleShot( 0, this, SLOT( openProject() ) );
}
else
{
QWidget* base = new QWidget( this );
QVBoxLayout* layout = new QVBoxLayout();
base->setLayout( layout );
setCentralWidget( base );
QLabel* header = new QLabel( tr( "Please select a Project" ), base );
header->setAlignment( Qt::AlignCenter );
QFont font;
font.setBold( true );
header->setFont( font );
layout->addWidget( header );
QListView* view = new QListView( base );
layout->addWidget( view );
d->model = new GameItemsModel( view );
view->setModel( d->model );
connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );
QPushButton* button = new QPushButton( tr( "Open other project..." ), base );
layout->addWidget( button );
connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );
}
resize( 500, 500 );
}
MainWindow::~MainWindow()
{
delete d;
}
void MainWindow::activated( QModelIndex index )
{
if( index.isValid() )
{
openProject( d->model->data( index, GluonPlayer::GameItemsModel::ProjectFileNameRole ).toString() );
}
}
void MainWindow::openClicked( bool toggled )
{
Q_UNUSED( toggled )
QString fileName = QFileDialog::getOpenFileName( this, tr( "Select a Project" ), QString(), QString( "*%1|Gluon Project Files" ).arg( GluonEngine::projectFilename ) );
if( !fileName.isEmpty() )
openProject( fileName );
}
void MainWindow::openProject( const QString& fileName )
{
QString file = fileName;
if( file.isEmpty() )
file = d->fileName;
d->widget = new GluonGraphics::RenderWidget( this );
setCentralWidget( d->widget );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );
GluonInput::InputManager::instance()->setFilteredObject(d->widget);
QTimer::singleShot( 100, this, SLOT( startGame() ) );
d->fileName = file;
}
void MainWindow::startGame()
{
GluonCore::GluonObjectFactory::instance()->loadPlugins();
d->project = new GluonEngine::GameProject();
d->project->loadFromFile( d->fileName );
setWindowFilePath( d->fileName );
d->title = windowTitle();
GluonEngine::Game::instance()->setGameProject( d->project );
GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );
d->widget->setFocus();
GluonEngine::Game::instance()->runGame();
QApplication::instance()->exit();
}
void MainWindow::closeEvent( QCloseEvent* event )
{
GluonEngine::Game::instance()->stopGame();
QWidget::closeEvent( event );
}
void MainWindow::updateTitle( int msec )
{
d->msecElapsed += msec;
static int fps = 0;
if( d->msecElapsed > 1000 )
{
fps = d->frameCount;
d->frameCount = 0;
d->msecElapsed = 0;
}
setWindowTitle( d->title + QString( " (%1 FPS)" ).arg( fps ) );
}
void MainWindow::countFrames( int time )
{
Q_UNUSED( time )
d->frameCount++;
}
#include "mainwindow.moc"
<commit_msg>BUG: 268506 - gluon_qtplayer crashes with testproject<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (c) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* 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 "mainwindow.h"
#include "lib/models/gameitemsmodel.h"
#include "input/inputmanager.h"
#include "engine/game.h"
#include "engine/gameproject.h"
#include "engine/scene.h"
#include "graphics/renderwidget.h"
#include <QtGui/QFileDialog>
#include <QtGui/QStatusBar>
#include <QtGui/QApplication>
#include <QtGui/QListView>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include <QtCore/QTimer>
using namespace GluonPlayer;
class MainWindow::MainWindowPrivate
{
public:
GluonEngine::GameProject* project;
GluonGraphics::RenderWidget* widget;
QAbstractItemModel* model;
QString title;
QString fileName;
int msecElapsed;
int frameCount;
};
GluonPlayer::MainWindow::MainWindow( int argc, char** argv, QWidget* parent, Qt::WindowFlags flags )
: QMainWindow( parent, flags )
, d( new MainWindowPrivate )
{
d->msecElapsed = 0;
d->frameCount = 0;
if( argc > 1 )
{
QFileInfo fi = QFileInfo( argv[1] );
if( fi.isRelative() )
d->fileName = fi.canonicalFilePath();
else
d->fileName = argv[1];
QTimer::singleShot( 0, this, SLOT( openProject() ) );
}
else
{
QWidget* base = new QWidget( this );
QVBoxLayout* layout = new QVBoxLayout();
base->setLayout( layout );
setCentralWidget( base );
QLabel* header = new QLabel( tr( "Please select a Project" ), base );
header->setAlignment( Qt::AlignCenter );
QFont font;
font.setBold( true );
header->setFont( font );
layout->addWidget( header );
QListView* view = new QListView( base );
layout->addWidget( view );
d->model = new GameItemsModel( view );
view->setModel( d->model );
connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );
QPushButton* button = new QPushButton( tr( "Open other project..." ), base );
layout->addWidget( button );
connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );
}
resize( 500, 500 );
}
MainWindow::~MainWindow()
{
delete d;
}
void MainWindow::activated( QModelIndex index )
{
if( index.isValid() )
{
openProject( d->model->data( index, GluonPlayer::GameItemsModel::ProjectFileNameRole ).toString() );
}
}
void MainWindow::openClicked( bool toggled )
{
Q_UNUSED( toggled )
QString fileName = QFileDialog::getOpenFileName( this, tr( "Select a Project" ), QString(), QString( "*%1|Gluon Project Files" ).arg( GluonEngine::projectFilename ) );
if( !fileName.isEmpty() )
openProject( fileName );
}
void MainWindow::openProject( const QString& fileName )
{
QString file = fileName;
if( file.isEmpty() )
file = d->fileName;
d->widget = new GluonGraphics::RenderWidget( this );
setCentralWidget( d->widget );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );
GluonInput::InputManager::instance()->setFilteredObject(d->widget);
QTimer::singleShot( 100, this, SLOT( startGame() ) );
d->fileName = file;
}
void MainWindow::startGame()
{
GluonCore::GluonObjectFactory::instance()->loadPlugins();
d->project = new GluonEngine::GameProject();
d->project->loadFromFile( d->fileName );
setWindowFilePath( d->fileName );
d->title = windowTitle();
GluonEngine::Game::instance()->setGameProject( d->project );
GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );
d->widget->setFocus();
GluonEngine::Game::instance()->runGame();
QApplication::instance()->exit();
}
void MainWindow::closeEvent( QCloseEvent* event )
{
GluonEngine::Game::instance()->stopGame();
QWidget::closeEvent( event );
}
void MainWindow::updateTitle( int msec )
{
d->msecElapsed += msec;
static int fps = 0;
if( d->msecElapsed > 1000 )
{
fps = d->frameCount;
d->frameCount = 0;
d->msecElapsed = 0;
}
setWindowTitle( d->title + QString( " (%1 FPS)" ).arg( fps ) );
}
void MainWindow::countFrames( int time )
{
Q_UNUSED( time )
d->frameCount++;
}
#include "mainwindow.moc"
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2015 Vladimir "allejo" Jimenez
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 <map>
#include <memory>
#include <sstream>
#include <vector>
#include "bzfsAPI.h"
#include "plugin_utils.h"
// Define plugin name
const std::string PLUGIN_NAME = "Player Join Handler";
// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 0;
const int REV = 0;
const int BUILD = 2;
class PlayerJoinHandler : public bz_Plugin
{
public:
virtual const char* Name ();
virtual void Init (const char* config);
virtual void Event (bz_EventData *eventData);
virtual void Cleanup (void);
std::map<std::string, double> playerSessions;
std::string bzdbVariable;
};
BZ_PLUGIN(PlayerJoinHandler)
const char* PlayerJoinHandler::Name (void)
{
static std::string pluginBuild = "";
if (!pluginBuild.size())
{
std::ostringstream pluginBuildStream;
pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")";
pluginBuild = pluginBuildStream.str();
}
return pluginBuild.c_str();
}
void PlayerJoinHandler::Init (const char* /*commandLine*/)
{
Register(bz_eGetAutoTeamEvent);
Register(bz_ePlayerPartEvent);
bzdbVariable = "_sessionTime";
if (!bz_BZDBItemExists(bzdbVariable.c_str()))
{
bz_setBZDBInt(bzdbVariable.c_str(), 120);
}
}
void PlayerJoinHandler::Cleanup (void)
{
Flush();
}
void PlayerJoinHandler::Event (bz_EventData *eventData)
{
switch (eventData->eventType)
{
case bz_eGetAutoTeamEvent: // This event is called for each new player is added to a team
{
bz_GetAutoTeamEventData_V1* autoTeamData = (bz_GetAutoTeamEventData_V1*)eventData;
std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(autoTeamData->playerID));
int rejoinTime = bz_getBZDBInt(bzdbVariable.c_str());
std::string bzID = pr->bzID.c_str();
if ((bz_isCountDownActive() || bz_isCountDownInProgress() || bz_isCountDownPaused()) && autoTeamData->team != eObservers)
{
if (!pr->verified)
{
autoTeamData->handled = true;
autoTeamData->team = eObservers;
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "Your callsign is not verified, you will not be able to join any non-observer team during a match.");
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "Please register your callsign or ensure you are authenticating properly.");
}
else
{
if ((playerSessions.find(bzID) == playerSessions.end()) || (playerSessions[bzID] + rejoinTime < bz_getCurrentTime()))
{
autoTeamData->handled = true;
autoTeamData->team = eObservers;
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "An active match is currently in progress. You have been automatically moved to the observer team to avoid disruption.");
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "If you intend to substitute another player, you may now rejoin as a player.");
}
}
}
}
break;
case bz_ePlayerPartEvent: // This event is called each time a player leaves a game
{
bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;
bz_BasePlayerRecord* &pr = partData->record;
if (pr->verified)
{
std::string bzID = pr->bzID.c_str();
playerSessions[bzID] = bz_getCurrentTime();
}
}
break;
default: break;
}
}
<commit_msg>Add support for allowing unregistered to join matches<commit_after>/*
Copyright (C) 2016 Vladimir "allejo" Jimenez
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 <map>
#include <memory>
#include <sstream>
#include "bzfsAPI.h"
#include "plugin_utils.h"
// Define plugin name
const std::string PLUGIN_NAME = "Player Join Handler";
// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 0;
const int REV = 1;
const int BUILD = 12;
class PlayerJoinHandler : public bz_Plugin
{
public:
virtual const char* Name ();
virtual void Init (const char* config);
virtual void Event (bz_EventData *eventData);
virtual void Cleanup (void);
typedef std::map<std::string, double> SessionList;
virtual bool checkSession(SessionList &list, std::string target);
SessionList bzidSessions, ipSessions;
std::string bzdb_SessionTime, bzdb_AllowUnregistered;
};
BZ_PLUGIN(PlayerJoinHandler)
const char* PlayerJoinHandler::Name (void)
{
static std::string pluginBuild = "";
if (!pluginBuild.size())
{
std::ostringstream pluginBuildStream;
pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")";
pluginBuild = pluginBuildStream.str();
}
return pluginBuild.c_str();
}
void PlayerJoinHandler::Init (const char* /*commandLine*/)
{
Register(bz_eGetAutoTeamEvent);
Register(bz_ePlayerPartEvent);
bzdb_SessionTime = "_sessionTime";
bzdb_AllowUnregistered = "_allowVerified";
if (!bz_BZDBItemExists(bzdb_SessionTime.c_str()))
{
bz_setBZDBInt(bzdb_SessionTime.c_str(), 120);
}
if (!bz_BZDBItemExists(bzdb_AllowUnregistered.c_str()))
{
bz_setBZDBBool(bzdb_AllowUnregistered.c_str(), false);
}
}
void PlayerJoinHandler::Cleanup (void)
{
Flush();
}
void PlayerJoinHandler::Event (bz_EventData *eventData)
{
switch (eventData->eventType)
{
case bz_eGetAutoTeamEvent:
{
bz_GetAutoTeamEventData_V1* autoTeamData = (bz_GetAutoTeamEventData_V1*)eventData;
std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(autoTeamData->playerID));
std::string bzID = pr->bzID.c_str();
std::string ipAddress = pr->ipAddress.c_str();
bool allowUnregistered = bz_getBZDBBool(bzdb_AllowUnregistered.c_str());
if ((bz_isCountDownActive() || bz_isCountDownInProgress() || bz_isCountDownPaused()) && autoTeamData->team != eObservers)
{
autoTeamData->handled = true;
autoTeamData->team = eObservers;
if ((pr->verified && checkSession(bzidSessions, bzID)) ||
(!pr->verified && checkSession(ipSessions, ipAddress)) ||
(!pr->verified && !allowUnregistered))
{
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "An active match is currently in progress. You have been automatically moved to the observer team to avoid disruption.");
bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "If you intend to substitute another player, you may now rejoin as a player.");
}
}
}
break;
case bz_ePlayerPartEvent:
{
bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;
bz_BasePlayerRecord* &pr = partData->record;
std::string ipAddress = pr->ipAddress.c_str();
std::string bzID = pr->bzID.c_str();
if (pr->verified)
{
bzidSessions[bzID] = bz_getCurrentTime();
}
else
{
ipSessions[ipAddress] = bz_getCurrentTime();
}
}
break;
default: break;
}
}
bool PlayerJoinHandler::checkSession(SessionList &list, std::string target)
{
int rejoinTime = bz_getBZDBInt(bzdb_SessionTime.c_str());
return (list.find(target) == list.end()) || (list[target] + rejoinTime < bz_getCurrentTime());
}
<|endoftext|>
|
<commit_before>/* ptptest.cc - PLIC Test Program
* Copyright (C) 2008 Tim Janik
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this program; if not, see http://www.gnu.org/copyleft/.
*/
// include PLIC TypeMap Parser
#include "../../rcore/plicutils.hh"
#include "../../rcore/plicutils.cc"
#define error(...) do { fputs ("ERROR: ", stderr); fprintf (stderr, __VA_ARGS__); fputs ("\n", stderr); abort(); } while (0)
using namespace Plic;
using Plic::uint8;
using Plic::uint;
using Plic::vector;
using Plic::String;
#ifndef MAX
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define MAX(a,b) ((a) >= (b) ? (a) : (b))
#endif
/* --- option parsing --- */
static bool
parse_str_option (char **argv,
uint &i,
const char *arg,
const char **strp,
uint argc)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
const char *equal = argv[i] + length;
if (*equal == '=') /* -x=Arg */
*strp = equal + 1;
else if (*equal) /* -xArg */
*strp = equal;
else if (i + 1 < argc) /* -x Arg */
{
argv[i++] = NULL;
*strp = argv[i];
}
argv[i] = NULL;
if (*strp)
return true;
}
return false;
}
static bool
parse_bool_option (char **argv,
uint &i,
const char *arg)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
argv[i] = NULL;
return true;
}
return false;
}
/* --- test program --- */
static void
aux_check (std::string type_map_file,
vector<String> auxtests)
{
// read type map
TypeMap tp = TypeMap::load (type_map_file);
if (tp.error_status())
error ("%s: open failed: %s", type_map_file.c_str(), strerror (tp.error_status()));
// print types and match auxtests
for (size_t i = 0; i < tp.type_count(); i++)
{
const TypeCode tc = tp.type (i);
printf ("%s %s;\n", tc.kind_name().c_str(), tc.name().c_str());
for (size_t k = 0; k < tc.aux_count(); k++)
{
String aux = tc.aux_data (k);
uint c = ' ';
for (size_t q = 0; q < auxtests.size(); q++)
if (strstr (aux.c_str(), auxtests[q].c_str()))
{
auxtests.erase (auxtests.begin() + q);
c = '*';
break;
}
printf (" %c %s\n", c, aux.c_str());
}
}
// fail for unmatched auxtests
if (auxtests.size())
{
fprintf (stderr, "ERROR: unmatched aux-tests:\n");
for (uint q = 0; q < auxtests.size(); q++)
fprintf (stderr, " %s\n", auxtests[q].c_str());
abort();
}
}
static void
list_types (std::string type_map_file)
{
TypeMap tmap = TypeMap::load_local (type_map_file);
if (tmap.error_status())
error ("%s: open failed: %s", type_map_file.c_str(), strerror (tmap.error_status()));
errno = 0;
printf ("TYPES: %zu\n", tmap.type_count());
for (uint i = 0; i < tmap.type_count(); i++)
{
const TypeCode tcode = tmap.type (i);
printf ("%s\n", tcode.pretty (" ").c_str());
// verify type search
const TypeCode other = tmap.lookup_local (tcode.name());
if (other != tcode)
{
errno = ENXIO;
perror (std::string ("searching type: " + tcode.name()).c_str()), abort();
}
}
if (errno)
perror ("checking type package"), abort();
}
static void
standard_tests ()
{
TypeCode tcint = TypeMap::lookup ("int");
assert (tcint.kind() == INT);
assert (tcint.name() == "int");
TypeCode tcfloat = TypeMap::lookup ("float");
assert (tcfloat.kind() == FLOAT);
assert (tcfloat.name() == "float");
TypeCode tcstring = TypeMap::lookup ("string");
assert (tcstring.kind() == STRING);
assert (tcstring.name() == "string");
TypeCode tcany = TypeMap::lookup ("any");
assert (tcany.kind() == ANY);
assert (tcany.name() == "any");
printf (" TEST Plic standard types OK\n");
}
static void
test_any()
{
String s;
const double dbl = 7.76576e-306;
Any a, a2;
a2 <<= "SecondAny";
const size_t cases = 13;
for (size_t j = 0; j <= cases; j++)
for (size_t k = 0; k <= cases; k++)
{
size_t cs[2] = { j, k };
for (size_t cc = 0; cc < 2; cc++)
switch (cs[cc])
{
typedef unsigned char uchar;
bool b; char c; uchar uc; int i; uint ui; long l; ulong ul; int64 i6; uint64 u6; double d; const Any *p;
case 0: a <<= bool (0); a >>= b; assert (b == 0); break;
case 1: a <<= bool (false); a >>= b; assert (b == false); break;
case 2: a <<= bool (true); a >>= b; assert (b == true); break;
case 3: a <<= char (-117); a >>= c; assert (c == -117); break;
case 4: a <<= uchar (250); a >>= uc; assert (uc == 250); break;
case 5: a <<= int (-134217728); a >>= i; assert (i == -134217728); break;
case 6: a <<= uint (4294967295U); a >>= ui; assert (ui == 4294967295U); break;
case 7: a <<= long (-2147483648); a >>= l; assert (l == -2147483648); break;
case 8: a <<= ulong (4294967295U); a >>= ul; assert (ul == 4294967295U); break;
case 9: a <<= int64 (-0xc0ffeec0ffeeLL); a >>= i6; assert (i6 == -0xc0ffeec0ffeeLL); break;
case 10: a <<= int64 (0xffffffffffffffffULL); a >>= u6; assert (u6 == 0xffffffffffffffffULL); break;
case 11: a <<= "Test4test"; a >>= s; assert (s == "Test4test"); break;
case 12: a <<= dbl; a >>= d; assert (d = dbl); break;
case 13: a <<= a2; a >>= p; *p >>= s; assert (s == "SecondAny"); break;
}
}
printf (" TEST Plic Any uses OK\n");
}
int
main (int argc,
char *argv[])
{
vector<String> auxtests;
/* parse args */
for (uint i = 1; i < uint (argc); i++)
{
const char *str = NULL;
if (strcmp (argv[i], "--tests") == 0)
{
standard_tests();
test_any();
return 0;
}
else if (strcmp (argv[i], "--") == 0)
{
argv[i] = NULL;
break;
}
else if (parse_bool_option (argv, i, "--help"))
{
printf ("Usage: %s [options] TypeMap.typ\n", argv[0]);
printf ("Options:\n");
printf (" --tests Carry out various tests\n");
printf (" --help Print usage summary\n");
printf (" --aux-test=x Find 'x' in auxillary type data\n");
exit (0);
}
else if (parse_str_option (argv, i, "--aux-test", &str, argc))
auxtests.push_back (str);
}
/* collapse parsed args */
uint e = 1;
for (uint i = 1; i < uint (argc); i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
argc = e;
/* validate mandatory arg */
if (argc < 2)
error ("Usage: %s TypeMap.typ\n", argv[0]);
if (auxtests.size())
aux_check (argv[1], auxtests);
else
list_types (argv[1]);
return 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out typemap.typ
<commit_msg>PLIC: test failing TypeCode lookups<commit_after>/* ptptest.cc - PLIC Test Program
* Copyright (C) 2008 Tim Janik
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this program; if not, see http://www.gnu.org/copyleft/.
*/
// include PLIC TypeMap Parser
#include "../../rcore/plicutils.hh"
#include "../../rcore/plicutils.cc"
#define error(...) do { fputs ("ERROR: ", stderr); fprintf (stderr, __VA_ARGS__); fputs ("\n", stderr); abort(); } while (0)
using namespace Plic;
using Plic::uint8;
using Plic::uint;
using Plic::vector;
using Plic::String;
#ifndef MAX
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define MAX(a,b) ((a) >= (b) ? (a) : (b))
#endif
/* --- option parsing --- */
static bool
parse_str_option (char **argv,
uint &i,
const char *arg,
const char **strp,
uint argc)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
const char *equal = argv[i] + length;
if (*equal == '=') /* -x=Arg */
*strp = equal + 1;
else if (*equal) /* -xArg */
*strp = equal;
else if (i + 1 < argc) /* -x Arg */
{
argv[i++] = NULL;
*strp = argv[i];
}
argv[i] = NULL;
if (*strp)
return true;
}
return false;
}
static bool
parse_bool_option (char **argv,
uint &i,
const char *arg)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
argv[i] = NULL;
return true;
}
return false;
}
/* --- test program --- */
static void
aux_check (std::string type_map_file,
vector<String> auxtests)
{
// read type map
TypeMap tp = TypeMap::load (type_map_file);
if (tp.error_status())
error ("%s: open failed: %s", type_map_file.c_str(), strerror (tp.error_status()));
// print types and match auxtests
for (size_t i = 0; i < tp.type_count(); i++)
{
const TypeCode tc = tp.type (i);
printf ("%s %s;\n", tc.kind_name().c_str(), tc.name().c_str());
for (size_t k = 0; k < tc.aux_count(); k++)
{
String aux = tc.aux_data (k);
uint c = ' ';
for (size_t q = 0; q < auxtests.size(); q++)
if (strstr (aux.c_str(), auxtests[q].c_str()))
{
auxtests.erase (auxtests.begin() + q);
c = '*';
break;
}
printf (" %c %s\n", c, aux.c_str());
}
}
// fail for unmatched auxtests
if (auxtests.size())
{
fprintf (stderr, "ERROR: unmatched aux-tests:\n");
for (uint q = 0; q < auxtests.size(); q++)
fprintf (stderr, " %s\n", auxtests[q].c_str());
abort();
}
}
static void
list_types (std::string type_map_file)
{
TypeMap tmap = TypeMap::load_local (type_map_file);
if (tmap.error_status())
error ("%s: open failed: %s", type_map_file.c_str(), strerror (tmap.error_status()));
errno = 0;
printf ("TYPES: %zu\n", tmap.type_count());
for (uint i = 0; i < tmap.type_count(); i++)
{
const TypeCode tcode = tmap.type (i);
printf ("%s\n", tcode.pretty (" ").c_str());
// verify type search
const TypeCode other = tmap.lookup_local (tcode.name());
if (other != tcode)
{
errno = ENXIO;
perror (std::string ("searching type: " + tcode.name()).c_str()), abort();
}
}
if (errno)
perror ("checking type package"), abort();
}
static void
standard_tests ()
{
TypeCode tcint = TypeMap::lookup ("int");
assert (tcint.kind() == INT);
assert (tcint.name() == "int");
TypeCode tcfloat = TypeMap::lookup ("float");
assert (tcfloat.kind() == FLOAT);
assert (tcfloat.name() == "float");
TypeCode tcstring = TypeMap::lookup ("string");
assert (tcstring.kind() == STRING);
assert (tcstring.name() == "string");
TypeCode tcany = TypeMap::lookup ("any");
assert (tcany.kind() == ANY);
assert (tcany.name() == "any");
TypeCode tcnot = TypeMap::lookup (".@-nosuchtype?");
assert (tcnot.untyped() == true);
printf (" TEST Plic standard types OK\n");
}
static void
test_any()
{
String s;
const double dbl = 7.76576e-306;
Any a, a2;
a2 <<= "SecondAny";
const size_t cases = 13;
for (size_t j = 0; j <= cases; j++)
for (size_t k = 0; k <= cases; k++)
{
size_t cs[2] = { j, k };
for (size_t cc = 0; cc < 2; cc++)
switch (cs[cc])
{
typedef unsigned char uchar;
bool b; char c; uchar uc; int i; uint ui; long l; ulong ul; int64 i6; uint64 u6; double d; const Any *p;
case 0: a <<= bool (0); a >>= b; assert (b == 0); break;
case 1: a <<= bool (false); a >>= b; assert (b == false); break;
case 2: a <<= bool (true); a >>= b; assert (b == true); break;
case 3: a <<= char (-117); a >>= c; assert (c == -117); break;
case 4: a <<= uchar (250); a >>= uc; assert (uc == 250); break;
case 5: a <<= int (-134217728); a >>= i; assert (i == -134217728); break;
case 6: a <<= uint (4294967295U); a >>= ui; assert (ui == 4294967295U); break;
case 7: a <<= long (-2147483648); a >>= l; assert (l == -2147483648); break;
case 8: a <<= ulong (4294967295U); a >>= ul; assert (ul == 4294967295U); break;
case 9: a <<= int64 (-0xc0ffeec0ffeeLL); a >>= i6; assert (i6 == -0xc0ffeec0ffeeLL); break;
case 10: a <<= int64 (0xffffffffffffffffULL); a >>= u6; assert (u6 == 0xffffffffffffffffULL); break;
case 11: a <<= "Test4test"; a >>= s; assert (s == "Test4test"); break;
case 12: a <<= dbl; a >>= d; assert (d = dbl); break;
case 13: a <<= a2; a >>= p; *p >>= s; assert (s == "SecondAny"); break;
}
}
printf (" TEST Plic Any uses OK\n");
}
int
main (int argc,
char *argv[])
{
vector<String> auxtests;
/* parse args */
for (uint i = 1; i < uint (argc); i++)
{
const char *str = NULL;
if (strcmp (argv[i], "--tests") == 0)
{
standard_tests();
test_any();
return 0;
}
else if (strcmp (argv[i], "--") == 0)
{
argv[i] = NULL;
break;
}
else if (parse_bool_option (argv, i, "--help"))
{
printf ("Usage: %s [options] TypeMap.typ\n", argv[0]);
printf ("Options:\n");
printf (" --tests Carry out various tests\n");
printf (" --help Print usage summary\n");
printf (" --aux-test=x Find 'x' in auxillary type data\n");
exit (0);
}
else if (parse_str_option (argv, i, "--aux-test", &str, argc))
auxtests.push_back (str);
}
/* collapse parsed args */
uint e = 1;
for (uint i = 1; i < uint (argc); i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
argc = e;
/* validate mandatory arg */
if (argc < 2)
error ("Usage: %s TypeMap.typ\n", argv[0]);
if (auxtests.size())
aux_check (argv[1], auxtests);
else
list_types (argv[1]);
return 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out typemap.typ
<|endoftext|>
|
<commit_before>#include <curses.h>
#include <stdio.h>
#include "debugC.h"
#include "machine.h"
using namespace std;
debugC::debugC(machine* BFM){
localMachine = BFM;
}
debugC::~debugC(){
delete this;
}
void debugC::setupDebugger(){
initscr();
raw();
noecho();
start_color();
curs_set(0);
init_pair(1, COLOR_WHITE, COLOR_GREEN);
attron(A_BOLD);
printw("\t\t\tBr**nfuck Curses Debugger");
stackWindow = subwin(stdscr, 18, 7, 1, 0);
wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
mvwprintw(stackWindow, 0, 1, "Stack");
tapeWindow = subwin(stdscr, 5, 72, 1, 8);
wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(tapeWindow, 0, 2, "Tape");
inputWindow = subwin(stdscr, 5, 20, 14, 8);
wborder(inputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(inputWindow, 0, 2, "Input");
outputWindow = subwin(stdscr, 5, 20, 14, 29);
wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(outputWindow, 0, 2, "Output");
codeWindow = subwin(stdscr, 8, 72, 6, 8);
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
}
void debugC::tearDown(){
endwin();
}
void debugC::redrawStackWindow(int stackHeight){
//stack is only redrawn when it changes, don't waste time changing every iteration
int top = localMachine->getStackTop();
int* stack = localMachine->getStack();
for(int y = 0; y < 16; y++){
mvwprintw(stackWindow, 16-y, 1, " ");
if(y <= top){
char* currentElement;
sprintf(currentElement, "%i", stack[y]);
mvwprintw(stackWindow, 16-y, 1, currentElement);
}
}
wrefresh(stackWindow);
}
void debugC::redrawTapeWindow(){
char* tmp = (char*)malloc(20);
int n = 1;
for(int i = 0; i < 17; i++){
sprintf(tmp, "%d", localMachine->getTapeAt(i));
if(i == localMachine->getDataPointer())
wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);
mvwprintw(tapeWindow, 2, n, tmp);
wprintw(tapeWindow, "|");
wattroff(tapeWindow, COLOR_PAIR(1));
n+=4;
}
wrefresh(tapeWindow);
}
void debugC::redrawCodeWindow(){
string sourceToDraw = localMachine->getSource();
wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
while(n < localMachine->getSource().length()){
if(n == localMachine->getSourceIterator())
wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
waddch(codeWindow, sourceToDraw[n]);
wattroff(codeWindow, COLOR_PAIR(1));
//When moving to a new line, start at x=1 instead of 0
getyx(codeWindow, tmpY, tmpX);
if(tmpX == 0)
wmove(codeWindow, tmpY, 1);
n++;
}
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
wrefresh(codeWindow);
}
void debugC::redrawOutputWindow(){
int returnedOutput = localMachine->NAO();
char* output; sprintf(output, "%i", returnedOutput);
mvwprintw(outputWindow, 1, 1, " ");
mvwprintw(outputWindow, 1, 1, output);
wrefresh(outputWindow);
}
void debugC::updateScreen(){
redrawCodeWindow();
redrawTapeWindow();
refresh();
}
void debugC::step(int mod){
char retOperator = localMachine->processChar(mod);
switch(retOperator){
case '.':
redrawOutputWindow();
break;
}
}
//begin debugger, create window with curses
void debugC::start(string source){
setupDebugger();
updateScreen();
int stackHeight = -1;
int input;
while((input = getch()) != '!'){ //Exit debugger on !
//need to start working on over/underflow protection/wrapping now that I think about it
if(input == '>')
step(1);
if(input == '<')
step(-1); //for the love of god this probably won't work for a while
//Only update the stack window if it actually changes
if(stackHeight != localMachine->getStackTop()){
stackHeight = localMachine->getStackTop();
redrawStackWindow(stackHeight);
}
updateScreen();
}
tearDown();
};
<commit_msg>Input now works pretty well<commit_after>#include <curses.h>
#include <stdio.h>
#include <string.h>
#include "debugC.h"
#include "machine.h"
using namespace std;
debugC::debugC(machine* BFM){
localMachine = BFM;
}
debugC::~debugC(){
delete this;
}
void debugC::setupDebugger(){
initscr();
raw();
noecho();
start_color();
curs_set(0);
init_pair(1, COLOR_WHITE, COLOR_GREEN);
attron(A_BOLD);
printw("\t\t\tBr**nfuck Curses Debugger");
stackWindow = subwin(stdscr, 18, 7, 1, 0);
wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
mvwprintw(stackWindow, 0, 1, "Stack");
tapeWindow = subwin(stdscr, 5, 72, 1, 8);
wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(tapeWindow, 0, 2, "Tape");
inputWindow = subwin(stdscr, 5, 20, 14, 8);
wborder(inputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(inputWindow, 0, 2, "Input");
outputWindow = subwin(stdscr, 5, 20, 14, 29);
wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(outputWindow, 0, 2, "Output");
codeWindow = subwin(stdscr, 8, 72, 6, 8);
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
}
void debugC::tearDown(){
endwin();
}
void debugC::redrawStackWindow(int stackHeight){
//stack is only redrawn when it changes, don't waste time changing every iteration
int top = localMachine->getStackTop();
int* stack = localMachine->getStack();
for(int y = 0; y < 16; y++){
mvwprintw(stackWindow, 16-y, 1, " ");
if(y <= top){
char* currentElement;
sprintf(currentElement, "%i", stack[y]);
mvwprintw(stackWindow, 16-y, 1, currentElement);
}
}
wrefresh(stackWindow);
}
void debugC::redrawTapeWindow(){
char* tmp = (char*)malloc(20);
int n = 1;
for(int i = 0; i < 17; i++){
sprintf(tmp, "%d", localMachine->getTapeAt(i));
if(i == localMachine->getDataPointer())
wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);
mvwprintw(tapeWindow, 2, n, tmp);
wprintw(tapeWindow, "|");
wattroff(tapeWindow, COLOR_PAIR(1));
n+=4;
}
wrefresh(tapeWindow);
}
void debugC::redrawCodeWindow(){
string sourceToDraw = localMachine->getSource();
wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
while(n < localMachine->getSource().length()){
if(n == localMachine->getSourceIterator())
wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
waddch(codeWindow, sourceToDraw[n]);
wattroff(codeWindow, COLOR_PAIR(1));
//When moving to a new line, start at x=1 instead of 0
getyx(codeWindow, tmpY, tmpX);
if(tmpX == 0)
wmove(codeWindow, tmpY, 1);
n++;
}
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
wrefresh(codeWindow);
}
void debugC::redrawOutputWindow(){
int returnedOutput = localMachine->NAO();
char* output; sprintf(output, "%i", returnedOutput);
mvwprintw(outputWindow, 1, 1, " ");
mvwprintw(outputWindow, 1, 1, output);
wrefresh(outputWindow);
}
void debugC::updateScreen(){
redrawCodeWindow();
redrawTapeWindow();
refresh();
}
void debugC::step(int mod){
//have the machine return the operator that was just processed
char retOperator = localMachine->processChar(mod);
switch(retOperator){
case '.':
redrawOutputWindow();
break;
}
noecho();
}
//begin debugger, create window with curses
void debugC::start(string source){
setupDebugger();
updateScreen();
int stackHeight = -1;
int input;
while((input = getch()) != '!'){ //Exit debugger on !
char nextOp = source[localMachine->getSourceIterator()];
if(nextOp == ','){
endwin();
printf("\rbfsh>");
}
//need to start working on over/underflow protection/wrapping now that I think about it
if(input == '>')
step(1);
if(input == '<')
step(-1); //for the love of god this probably won't work for a while
//Only update the stack window if it actually changes
if(stackHeight != localMachine->getStackTop()){
stackHeight = localMachine->getStackTop();
redrawStackWindow(stackHeight);
}
updateScreen();
}
tearDown();
printf("\rFinished debugging\n");
};
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.ru>
*
* This program or 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 3 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
*
* END_COMMON_COPYRIGHT_HEADER */
/********************************************************************
Inspired by freedesktops tint2 ;)
*********************************************************************/
// Warning: order of those include is important.
#include <QApplication>
#include <QtDebug>
#include "trayicon.h"
#include <QX11Info>
#include "razortray.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/Xdamage.h>
#include "razorqt/xfitman.h"
#define _NET_SYSTEM_TRAY_ORIENTATION_HORZ 0
#define _NET_SYSTEM_TRAY_ORIENTATION_VERT 1
#define SYSTEM_TRAY_REQUEST_DOCK 0
#define SYSTEM_TRAY_BEGIN_MESSAGE 1
#define SYSTEM_TRAY_CANCEL_MESSAGE 2
#define XEMBED_EMBEDDED_NOTIFY 0
#define XEMBED_MAPPED (1 << 0)
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorTray)
/************************************************
************************************************/
RazorTray::RazorTray(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
mValid(false),
mTrayId(0),
mDamageError(0),
mDamageEvent(0),
mIconSize(TRAY_ICON_SIZE_DEFAULT, TRAY_ICON_SIZE_DEFAULT)
{
setObjectName("Tray");
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
mValid = startTray();
}
/************************************************
************************************************/
RazorTray::~RazorTray()
{
stopTray();
}
/************************************************
************************************************/
void RazorTray::x11EventFilter(XEvent* event)
{
TrayIcon* icon;
switch (event->type)
{
case ClientMessage:
clientMessageEvent(&(event->xclient));
break;
// case ConfigureNotify:
// icon = findIcon(event->xconfigure.window);
// if (icon)
// icon->configureEvent(&(event->xconfigure));
// break;
case DestroyNotify:
icon = findIcon(event->xany.window);
if (icon)
{
mIcons.removeAll(icon);
delete icon;
}
break;
default:
if (event->type == mDamageEvent + XDamageNotify)
{
XDamageNotifyEvent* dmg = reinterpret_cast<XDamageNotifyEvent*>(event);
icon = findIcon(dmg->drawable);
if (icon)
icon->update();
}
break;
}
}
/************************************************
************************************************/
void RazorTray::clientMessageEvent(XClientMessageEvent* e)
{
unsigned long opcode;
opcode = e->data.l[1];
Window id;
switch (opcode)
{
case SYSTEM_TRAY_REQUEST_DOCK:
id = e->data.l[2];
if (id)
addIcon(id);
break;
case SYSTEM_TRAY_BEGIN_MESSAGE:
case SYSTEM_TRAY_CANCEL_MESSAGE:
qDebug() << "we don't show baloons messages.";
break;
default:
if (opcode == xfitMan().atom("_NET_SYSTEM_TRAY_MESSAGE_DATA"))
qDebug() << "message from dockapp:" << e->data.b;
// else
// qDebug() << "SYSTEM_TRAY : unknown message type" << opcode;
break;
}
}
/************************************************
************************************************/
TrayIcon* RazorTray::findIcon(Window id)
{
foreach(TrayIcon* icon, mIcons)
{
if (icon->iconId() == id || icon->windowId() == id)
return icon;
}
return 0;
}
/************************************************
************************************************/
void RazorTray::setIconSize(QSize iconSize)
{
mIconSize = iconSize;
foreach(TrayIcon* icon, mIcons)
icon->setIconSize(mIconSize);
}
/************************************************
************************************************/
Visual* RazorTray::getVisual()
{
Display* dsp = QX11Info::display();
XVisualInfo templ;
templ.screen=QX11Info::appScreen();
templ.depth=32;
templ.c_class=TrueColor;
int nvi;
XVisualInfo* xvi = XGetVisualInfo(dsp, VisualScreenMask|VisualDepthMask|VisualClassMask, &templ, &nvi);
Visual* visual = 0;
if (xvi)
{
int i;
XRenderPictFormat* format;
for (i = 0; i < nvi; i++)
{
format = XRenderFindVisualFormat(dsp, xvi[i].visual);
if (format->type == PictTypeDirect && format->direct.alphaMask)
{
visual = xvi[i].visual;
break;
}
}
XFree (xvi);
}
return visual;
// check composite manager
// Window composite_manager = XGetSelectionOwner(dsp, xfitMan().atom("_NET_WM_CM_S0"));
// if (mColormap)
// XFreeColormap(dsp, mColormap);
// if (mColormap32)
// XFreeColormap(dsp, mColormap32);
// if (visual)
// {
// mVisual32 = visual;
// mColormap32 = XCreateColormap(dsp, QX11Info::appRootWindow(), visual, AllocNone);
// }
// if (visual && composite_manager != None)
// {
// XSetWindowAttributes attrs;
// attrs.event_mask = StructureNotifyMask;
// XChangeWindowAttributes (dsp, composite_manager, CWEventMask, &attrs);
// //server.real_transparency = 1;
// mDepth = 32;
// qDebug() << "Real transparency on... depth:" << mDepth;
// mColormap = XCreateColormap(dsp, QX11Info::appRootWindow(), visual, AllocNone);
// mVisual = visual;
// }
// else
// {
// no composite manager or snapshot mode => fake transparency
//server.real_transparency = 0;
// mDepth = DefaultDepth(dsp, QX11Info::appScreen());
// qDebug() << "Real transparency off.... depth:" << mDepth;
// mColormap = DefaultColormap(dsp, QX11Info::appScreen());
// mVisual = DefaultVisual(dsp, QX11Info::appScreen());
// }
}
/************************************************
freedesktop systray specification
************************************************/
bool RazorTray::startTray()
{
Display* dsp = QX11Info::display();
Window root = QX11Info::appRootWindow();
QString s = QString("_NET_SYSTEM_TRAY_S%1").arg(DefaultScreen(dsp));
Atom _NET_SYSTEM_TRAY_S = xfitMan().atom(s.toAscii());
if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != None)
{
qWarning() << "Another systray is running";
return false;
}
// init systray protocol
mTrayId = XCreateSimpleWindow(dsp, root, -1, -1, 1, 1, 0, 0, 0);
int orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
XChangeProperty(dsp,
mTrayId,
xfitMan().atom("_NET_SYSTEM_TRAY_ORIENTATION"),
XA_CARDINAL,
32,
PropModeReplace,
(unsigned char *) &orientation,
1);
// ** Visual ********************************
Visual* visual = getVisual();
if (visual)
{
VisualID vid = XVisualIDFromVisual(visual);
XChangeProperty(QX11Info::display(),
mTrayId,
xfitMan().atom("_NET_SYSTEM_TRAY_VISUAL"),
XA_VISUALID,
32,
PropModeReplace,
(unsigned char*)&vid,
1);
}
// ******************************************
XSetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S, mTrayId, CurrentTime);
if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != mTrayId) {
stopTray();
qWarning() << "Can't get systray manager";
return false;
}
XClientMessageEvent ev;
ev.type = ClientMessage;
ev.window = root;
ev.message_type = xfitMan().atom("MANAGER");
ev.format = 32;
ev.data.l[0] = CurrentTime;
ev.data.l[1] = _NET_SYSTEM_TRAY_S;
ev.data.l[2] = mTrayId;
ev.data.l[3] = 0;
ev.data.l[4] = 0;
XSendEvent(dsp, root, False, StructureNotifyMask, (XEvent*)&ev);
XDamageQueryExtension(QX11Info::display(), &mDamageEvent, &mDamageError);
qDebug() << "Systray started";
return true;
}
/************************************************
************************************************/
void RazorTray::stopTray()
{
qDeleteAll(mIcons);
if (mTrayId) {
XDestroyWindow(QX11Info::display(), mTrayId);
mTrayId = 0;
}
mValid = false;
}
/************************************************
************************************************/
void RazorTray::addIcon(Window winId)
{
TrayIcon* icon = new TrayIcon(winId, this);
if (!icon->isValid())
{
delete icon;
return;
}
icon->setIconSize(mIconSize);
mIcons.append(icon);
addWidget(icon);
}
<commit_msg>Initialize order fixed<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.ru>
*
* This program or 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 3 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
*
* END_COMMON_COPYRIGHT_HEADER */
/********************************************************************
Inspired by freedesktops tint2 ;)
*********************************************************************/
// Warning: order of those include is important.
#include <QApplication>
#include <QtDebug>
#include "trayicon.h"
#include <QX11Info>
#include "razortray.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/Xdamage.h>
#include "razorqt/xfitman.h"
#define _NET_SYSTEM_TRAY_ORIENTATION_HORZ 0
#define _NET_SYSTEM_TRAY_ORIENTATION_VERT 1
#define SYSTEM_TRAY_REQUEST_DOCK 0
#define SYSTEM_TRAY_BEGIN_MESSAGE 1
#define SYSTEM_TRAY_CANCEL_MESSAGE 2
#define XEMBED_EMBEDDED_NOTIFY 0
#define XEMBED_MAPPED (1 << 0)
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorTray)
/************************************************
************************************************/
RazorTray::RazorTray(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
mValid(false),
mTrayId(0),
mDamageEvent(0),
mDamageError(0),
mIconSize(TRAY_ICON_SIZE_DEFAULT, TRAY_ICON_SIZE_DEFAULT)
{
setObjectName("Tray");
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
mValid = startTray();
}
/************************************************
************************************************/
RazorTray::~RazorTray()
{
stopTray();
}
/************************************************
************************************************/
void RazorTray::x11EventFilter(XEvent* event)
{
TrayIcon* icon;
switch (event->type)
{
case ClientMessage:
clientMessageEvent(&(event->xclient));
break;
// case ConfigureNotify:
// icon = findIcon(event->xconfigure.window);
// if (icon)
// icon->configureEvent(&(event->xconfigure));
// break;
case DestroyNotify:
icon = findIcon(event->xany.window);
if (icon)
{
mIcons.removeAll(icon);
delete icon;
}
break;
default:
if (event->type == mDamageEvent + XDamageNotify)
{
XDamageNotifyEvent* dmg = reinterpret_cast<XDamageNotifyEvent*>(event);
icon = findIcon(dmg->drawable);
if (icon)
icon->update();
}
break;
}
}
/************************************************
************************************************/
void RazorTray::clientMessageEvent(XClientMessageEvent* e)
{
unsigned long opcode;
opcode = e->data.l[1];
Window id;
switch (opcode)
{
case SYSTEM_TRAY_REQUEST_DOCK:
id = e->data.l[2];
if (id)
addIcon(id);
break;
case SYSTEM_TRAY_BEGIN_MESSAGE:
case SYSTEM_TRAY_CANCEL_MESSAGE:
qDebug() << "we don't show baloons messages.";
break;
default:
if (opcode == xfitMan().atom("_NET_SYSTEM_TRAY_MESSAGE_DATA"))
qDebug() << "message from dockapp:" << e->data.b;
// else
// qDebug() << "SYSTEM_TRAY : unknown message type" << opcode;
break;
}
}
/************************************************
************************************************/
TrayIcon* RazorTray::findIcon(Window id)
{
foreach(TrayIcon* icon, mIcons)
{
if (icon->iconId() == id || icon->windowId() == id)
return icon;
}
return 0;
}
/************************************************
************************************************/
void RazorTray::setIconSize(QSize iconSize)
{
mIconSize = iconSize;
foreach(TrayIcon* icon, mIcons)
icon->setIconSize(mIconSize);
}
/************************************************
************************************************/
Visual* RazorTray::getVisual()
{
Display* dsp = QX11Info::display();
XVisualInfo templ;
templ.screen=QX11Info::appScreen();
templ.depth=32;
templ.c_class=TrueColor;
int nvi;
XVisualInfo* xvi = XGetVisualInfo(dsp, VisualScreenMask|VisualDepthMask|VisualClassMask, &templ, &nvi);
Visual* visual = 0;
if (xvi)
{
int i;
XRenderPictFormat* format;
for (i = 0; i < nvi; i++)
{
format = XRenderFindVisualFormat(dsp, xvi[i].visual);
if (format->type == PictTypeDirect && format->direct.alphaMask)
{
visual = xvi[i].visual;
break;
}
}
XFree (xvi);
}
return visual;
// check composite manager
// Window composite_manager = XGetSelectionOwner(dsp, xfitMan().atom("_NET_WM_CM_S0"));
// if (mColormap)
// XFreeColormap(dsp, mColormap);
// if (mColormap32)
// XFreeColormap(dsp, mColormap32);
// if (visual)
// {
// mVisual32 = visual;
// mColormap32 = XCreateColormap(dsp, QX11Info::appRootWindow(), visual, AllocNone);
// }
// if (visual && composite_manager != None)
// {
// XSetWindowAttributes attrs;
// attrs.event_mask = StructureNotifyMask;
// XChangeWindowAttributes (dsp, composite_manager, CWEventMask, &attrs);
// //server.real_transparency = 1;
// mDepth = 32;
// qDebug() << "Real transparency on... depth:" << mDepth;
// mColormap = XCreateColormap(dsp, QX11Info::appRootWindow(), visual, AllocNone);
// mVisual = visual;
// }
// else
// {
// no composite manager or snapshot mode => fake transparency
//server.real_transparency = 0;
// mDepth = DefaultDepth(dsp, QX11Info::appScreen());
// qDebug() << "Real transparency off.... depth:" << mDepth;
// mColormap = DefaultColormap(dsp, QX11Info::appScreen());
// mVisual = DefaultVisual(dsp, QX11Info::appScreen());
// }
}
/************************************************
freedesktop systray specification
************************************************/
bool RazorTray::startTray()
{
Display* dsp = QX11Info::display();
Window root = QX11Info::appRootWindow();
QString s = QString("_NET_SYSTEM_TRAY_S%1").arg(DefaultScreen(dsp));
Atom _NET_SYSTEM_TRAY_S = xfitMan().atom(s.toAscii());
if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != None)
{
qWarning() << "Another systray is running";
return false;
}
// init systray protocol
mTrayId = XCreateSimpleWindow(dsp, root, -1, -1, 1, 1, 0, 0, 0);
int orientation = _NET_SYSTEM_TRAY_ORIENTATION_HORZ;
XChangeProperty(dsp,
mTrayId,
xfitMan().atom("_NET_SYSTEM_TRAY_ORIENTATION"),
XA_CARDINAL,
32,
PropModeReplace,
(unsigned char *) &orientation,
1);
// ** Visual ********************************
Visual* visual = getVisual();
if (visual)
{
VisualID vid = XVisualIDFromVisual(visual);
XChangeProperty(QX11Info::display(),
mTrayId,
xfitMan().atom("_NET_SYSTEM_TRAY_VISUAL"),
XA_VISUALID,
32,
PropModeReplace,
(unsigned char*)&vid,
1);
}
// ******************************************
XSetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S, mTrayId, CurrentTime);
if (XGetSelectionOwner(dsp, _NET_SYSTEM_TRAY_S) != mTrayId) {
stopTray();
qWarning() << "Can't get systray manager";
return false;
}
XClientMessageEvent ev;
ev.type = ClientMessage;
ev.window = root;
ev.message_type = xfitMan().atom("MANAGER");
ev.format = 32;
ev.data.l[0] = CurrentTime;
ev.data.l[1] = _NET_SYSTEM_TRAY_S;
ev.data.l[2] = mTrayId;
ev.data.l[3] = 0;
ev.data.l[4] = 0;
XSendEvent(dsp, root, False, StructureNotifyMask, (XEvent*)&ev);
XDamageQueryExtension(QX11Info::display(), &mDamageEvent, &mDamageError);
qDebug() << "Systray started";
return true;
}
/************************************************
************************************************/
void RazorTray::stopTray()
{
qDeleteAll(mIcons);
if (mTrayId) {
XDestroyWindow(QX11Info::display(), mTrayId);
mTrayId = 0;
}
mValid = false;
}
/************************************************
************************************************/
void RazorTray::addIcon(Window winId)
{
TrayIcon* icon = new TrayIcon(winId, this);
if (!icon->isValid())
{
delete icon;
return;
}
icon->setIconSize(mIconSize);
mIcons.append(icon);
addWidget(icon);
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/io/p10_io_init_done.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p10_io_init_done.C
/// @brief Wait for dccal done and power-up all configured links/lanes
///-----------------------------------------------------------------------------
/// *HW HW Maintainer: Chris Steffen <cwsteffen@us.ibm.com>
/// *HW FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HW Consumed by : HB
///-----------------------------------------------------------------------------
#include <p10_io_init_done.H>
#include <p10_io_ppe_lib.H>
#include <p10_io_ppe_regs.H>
#include <p10_scom_pauc_0.H>
#include <p10_io_init_start_ppe.H>
#include <p10_io_lib.H>
///
/// @brief Check done status for reg_init, dccal, lane power on, and fifo init for a thread
///
/// @param[in] i_pauc_target The PAUC target to read from
/// @param[in] i_thread The thread to read
/// @param[out] o_done Set to false if something isn't done
///
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode p10_io_init_done_check_thread_done(
const fapi2::Target<fapi2::TARGET_TYPE_PAUC>& i_pauc_target,
const int& i_thread,
bool& o_done)
{
fapi2::buffer<uint64_t> l_data = 0;
FAPI_TRY(p10_io_ppe_ext_cmd_done_hw_reg_init_pg[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_hw_reg_init: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_dccal_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_dccal: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_zcal_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_zcal_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_ffe_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_ffe_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_power_on_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_power_on_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_fifo_init_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_fifo_init_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Wait for dccal done and power-up all configured links/lanes
///
/// @param[in] i_target Chip target to start
///
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode p10_io_init_done(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
bool l_done = false;
auto l_pauc_targets = i_target.getChildren<fapi2::TARGET_TYPE_PAUC>();
//Poll for done
const int POLLING_LOOPS = 200;
for (int l_try = 0; l_try < POLLING_LOOPS && !l_done; l_try++)
{
l_done = true;
for (auto l_pauc_target : l_pauc_targets)
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_pauc_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_pauc_target, l_pauc_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_DBG("Getting DCCAL status for PAUC: %d", l_pauc_num);
auto l_iohs_targets = l_pauc_target.getChildren<fapi2::TARGET_TYPE_IOHS>();
auto l_omic_targets = l_pauc_target.getChildren<fapi2::TARGET_TYPE_OMIC>();
for (auto l_iohs_target : l_iohs_targets)
{
int l_thread = 0;
fapi2::ATTR_CHIP_UNIT_POS_Type l_iohs_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_iohs_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(p10_io_get_iohs_thread(l_iohs_target, l_thread));
FAPI_TRY(p10_io_init_done_check_thread_done(l_pauc_target, l_thread, l_done ));
}
for (auto l_omic_target : l_omic_targets)
{
std::vector<int> l_lanes;
int l_thread = 0;
fapi2::ATTR_CHIP_UNIT_POS_Type l_omic_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_omic_target, l_omic_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(p10_io_get_omic_thread(l_omic_target, l_thread));
FAPI_TRY(p10_io_init_done_check_thread_done(l_pauc_target, l_thread, l_done));
}
}
fapi2::delay(100, 10000000);
}
FAPI_ASSERT(l_done,
fapi2::P10_IO_INIT_DONE_TIMEOUT_ERROR(),
"Timeout waiting on io init to complete");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Add missing var setting to p10_io_init_done failure path<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/io/p10_io_init_done.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p10_io_init_done.C
/// @brief Wait for dccal done and power-up all configured links/lanes
///-----------------------------------------------------------------------------
/// *HW HW Maintainer: Chris Steffen <cwsteffen@us.ibm.com>
/// *HW FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HW Consumed by : HB
///-----------------------------------------------------------------------------
#include <p10_io_init_done.H>
#include <p10_io_ppe_lib.H>
#include <p10_io_ppe_regs.H>
#include <p10_scom_pauc_0.H>
#include <p10_io_init_start_ppe.H>
#include <p10_io_lib.H>
///
/// @brief Check done status for reg_init, dccal, lane power on, and fifo init for a thread
///
/// @param[in] i_pauc_target The PAUC target to read from
/// @param[in] i_thread The thread to read
/// @param[out] o_done Set to false if something isn't done
///
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode p10_io_init_done_check_thread_done(
const fapi2::Target<fapi2::TARGET_TYPE_PAUC>& i_pauc_target,
const int& i_thread,
bool& o_done)
{
fapi2::buffer<uint64_t> l_data = 0;
FAPI_TRY(p10_io_ppe_ext_cmd_done_hw_reg_init_pg[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_hw_reg_init: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_dccal_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_dccal: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_zcal_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_zcal_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_ffe_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_ffe_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_power_on_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_power_on_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
FAPI_TRY(p10_io_ppe_ext_cmd_done_tx_fifo_init_pl[i_thread].getData(i_pauc_target, l_data, true));
FAPI_DBG("Thread: %d, ext_cmd_done_tx_fifo_init_pl: 0x%llx", i_thread, l_data);
if (l_data == 0)
{
o_done = false;
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Wait for dccal done and power-up all configured links/lanes
///
/// @param[in] i_target Chip target to start
///
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode p10_io_init_done(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
bool l_done = false;
auto l_pauc_targets = i_target.getChildren<fapi2::TARGET_TYPE_PAUC>();
//Poll for done
const int POLLING_LOOPS = 200;
for (int l_try = 0; l_try < POLLING_LOOPS && !l_done; l_try++)
{
l_done = true;
for (auto l_pauc_target : l_pauc_targets)
{
fapi2::ATTR_CHIP_UNIT_POS_Type l_pauc_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_pauc_target, l_pauc_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_DBG("Getting DCCAL status for PAUC: %d", l_pauc_num);
auto l_iohs_targets = l_pauc_target.getChildren<fapi2::TARGET_TYPE_IOHS>();
auto l_omic_targets = l_pauc_target.getChildren<fapi2::TARGET_TYPE_OMIC>();
for (auto l_iohs_target : l_iohs_targets)
{
int l_thread = 0;
fapi2::ATTR_CHIP_UNIT_POS_Type l_iohs_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_iohs_target, l_iohs_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(p10_io_get_iohs_thread(l_iohs_target, l_thread));
FAPI_TRY(p10_io_init_done_check_thread_done(l_pauc_target, l_thread, l_done ));
}
for (auto l_omic_target : l_omic_targets)
{
std::vector<int> l_lanes;
int l_thread = 0;
fapi2::ATTR_CHIP_UNIT_POS_Type l_omic_num;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_omic_target, l_omic_num),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
FAPI_TRY(p10_io_get_omic_thread(l_omic_target, l_thread));
FAPI_TRY(p10_io_init_done_check_thread_done(l_pauc_target, l_thread, l_done));
}
}
fapi2::delay(100, 10000000);
}
FAPI_ASSERT(l_done,
fapi2::P10_IO_INIT_DONE_TIMEOUT_ERROR()
.set_TARGET(i_target),
"Timeout waiting on io init to complete");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_utils.H
/// @brief Main include file for the Memory Subsystem
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_P9_ATTR_UTILS_H_
#define _MSS_P9_ATTR_UTILS_H_
//TK: what is this for? BRS
#include <lib/utils/index.H>
#include <generic/memory/lib/utils/c_str.H>
#endif // _MSS_P9_ATTR_UTILS_H_
<commit_msg>Move index API to generic/memory folder<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_utils.H
/// @brief Main include file for the Memory Subsystem
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_P9_ATTR_UTILS_H_
#define _MSS_P9_ATTR_UTILS_H_
//TK: what is this for? BRS
#include <generic/memory/lib/utils/index.H>
#include <generic/memory/lib/utils/c_str.H>
#endif // _MSS_P9_ATTR_UTILS_H_
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qfeedbackactuator.h>
#include "qfeedback.h"
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <QtGui/QApplication>
Q_EXPORT_PLUGIN2(feedback_symbian, QFeedbackSymbian)
#define VIBRA_DEVICE 0
#define TOUCH_DEVICE 1
//TODO: is activeWindow good enough
//or should we create a widget for that?
CCoeControl *QFeedbackSymbian::defaultWidget()
{
QWidget *w = QApplication::activeWindow();
return w ? w->winId() : 0;
}
#ifndef NO_TACTILE_SUPPORT
#include <touchfeedback.h>
#include <touchlogicalfeedback.h>
static TTouchLogicalFeedback convertToSymbian(QFeedbackEffect::ThemeEffect effect)
{
TTouchLogicalFeedback themeFeedbackSymbian = ETouchFeedbackBasic;
switch (effect) {
case QFeedbackEffect::ThemeBasic:
themeFeedbackSymbian = ETouchFeedbackBasic;
break;
case QFeedbackEffect::ThemeSensitive:
themeFeedbackSymbian = ETouchFeedbackSensitive;
break;
#ifdef ADVANCED_TACTILE_SUPPORT
case QFeedbackEffect::ThemeBasicButton:
themeFeedbackSymbian = ETouchFeedbackBasicButton;
break;
case QFeedbackEffect::ThemeSensitiveButton:
themeFeedbackSymbian = ETouchFeedbackSensitiveButton;
break;
case QFeedbackEffect::ThemeBasicItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBounceEffect:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupOpen:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupClose:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeStopFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeEditor:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeTextSelection:
themeFeedbackSymbian = ETouchFeedbackTextSelection;
break;
case QFeedbackEffect::ThemeBlankSelection:
themeFeedbackSymbian = ETouchFeedbackBlankSelection;
break;
case QFeedbackEffect::ThemeLineSelection:
themeFeedbackSymbian = ETouchFeedbackLineSelection;
break;
case QFeedbackEffect::ThemeEmptyLineSelection:
themeFeedbackSymbian = ETouchFeedbackEmptyLineSelection;
break;
case QFeedbackEffect::ThemeCheckBox:
themeFeedbackSymbian = ETouchFeedbackCheckbox;
break;
case QFeedbackEffect::ThemeMultipleCheckBox:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeMultitouchActivate:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeRotateStep:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemDrop:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemMoveOver:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemPick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemScroll:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopUp:
themeFeedbackSymbian = ETouchFeedbackPopUp;
break;
case QFeedbackEffect::ThemeLongPress:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
#endif //ADVANCED_TACTILE_SUPPORT
default:
break;
}
return themeFeedbackSymbian;
}
#ifdef ADVANCED_TACTILE_SUPPORT
typedef MTouchFeedback QTouchFeedback;
#else
class QTouchFeedback : public MTouchFeedback
{
public:
static QTouchFeedback *Instance()
{
return static_cast<QTouchFeedback*>(MTouchFeedback::Instance());
}
void StopFeedback(const CCoeControl* dummy)
{
Q_UNUSED(dummy);
}
void ModifyFeedback(const CCoeControl* dummy, int intensity)
{
Q_UNUSED(dummy);
Q_UNUSED(intensity);
}
void StartFeedback(const CCoeControl* dummy, int effect, void *event, int intensity, int duration)
{
Q_UNUSED(dummy);
Q_UNUSED(effect);
Q_UNUSED(event);
Q_UNUSED(intensity);
Q_UNUSED(duration);
//if there is no advanced feedback, we just do the normal one and return -1
MTouchFeedback::Instance()->InstantFeedback(ETouchFeedbackSensitive);
}
};
#endif //ADVANCED_TACTILE_SUPPORT
bool QFeedbackSymbian::play(QFeedbackEffect::ThemeEffect effect)
{
QTouchFeedback::Instance()->InstantFeedback(convertToSymbian(effect));
return true; //there is no way to know if there was a failure
}
#endif //NO_TACTILE_SUPPORT
QFeedbackInterface::PluginPriority QFeedbackSymbian::pluginPriority()
{
return PluginLowPriority;
}
QFeedbackSymbian::QFeedbackSymbian() : m_vibra(0), m_vibraActive(true)
{
}
QFeedbackSymbian::~QFeedbackSymbian()
{
delete m_vibra;
}
CHWRMVibra *QFeedbackSymbian::vibra()
{
if (!m_vibra)
m_vibra = CHWRMVibra::NewL();
return m_vibra;
}
QList<QFeedbackActuator> QFeedbackSymbian::actuators()
{
QList<QFeedbackActuator> ret;
#ifndef NO_TACTILE_SUPPORT
//if we don't have advanced tactile support then the MTouchFeedback doesn't really support custom effects
if (QTouchFeedback::Instance()->TouchFeedbackSupported()) {
ret << createFeedbackActuator(TOUCH_DEVICE);
}
#endif //NO_TACTILE_SUPPORT
ret << createFeedbackActuator(VIBRA_DEVICE);
return ret;
}
void QFeedbackSymbian::setActuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop, const QVariant &value)
{
switch(prop)
{
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
m_vibraActive = value.toBool();
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->SetFeedbackEnabledForThisApp(value.toBool());
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
}
QVariant QFeedbackSymbian::actuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop)
{
switch(prop)
{
case Name:
switch(actuator.id())
{
case VIBRA_DEVICE:
return QLatin1String("Vibra");
case TOUCH_DEVICE:
return QLatin1String("Touch");
default:
return QString();
}
case State:
{
QFeedbackActuator::State ret = QFeedbackActuator::Unknown;
switch(actuator.id())
{
case VIBRA_DEVICE:
switch (vibra()->VibraStatus())
{
case CHWRMVibra::EVibraStatusStopped:
return QFeedbackActuator::Ready;
case CHWRMVibra::EVibraStatusOn:
return QFeedbackActuator::Busy;
default:
return QFeedbackActuator::Unknown;
}
case TOUCH_DEVICE:
//there is no way of getting the state of the device!
default:
return QFeedbackActuator::Unknown;
}
return ret;
}
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
return m_vibraActive;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
return QTouchFeedback::Instance()->FeedbackEnabledForThisApp();
#endif //NO_TACTILE_SUPPORT
default:
return false;
}
default:
return QVariant();
}
}
bool QFeedbackSymbian::isActuatorCapabilitySupported(const QFeedbackActuator &, QFeedbackActuator::Capability)
{
return false;
}
void QFeedbackSymbian::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty prop)
{
switch(prop)
{
case Intensity:
if (!m_elapsed.contains(effect) || m_elapsed[effect].isPaused())
break;
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->ModifyFeedback(defaultWidget(), qRound(100 * effect->intensity()));
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
break;
}
}
void QFeedbackSymbian::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State newState)
{
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
m_elapsed[effect].start();
break;
}
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
QTouchFeedback::Instance()->StartFeedback(defaultWidget(),
(TTouchContinuousFeedback)0x300, // ETouchContinuousSmooth
0, qRound(effect->intensity() * 100), qMax(0, (effect->duration() - m_elapsed[effect].elapsed()) * 1000));
m_elapsed[effect].start();
break;
}
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
QFeedbackEffect::State QFeedbackSymbian::effectState(const QFeedbackHapticsEffect *effect)
{
if (m_elapsed.contains(effect) && m_elapsed[effect].elapsed() < effect->duration()) {
return m_elapsed[effect].isPaused() ? QFeedbackEffect::Paused : QFeedbackEffect::Running;
}
return QFeedbackEffect::Stopped;
}
<commit_msg>Fourth time lucky with the build fix for symbian 5.0/3/4<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qfeedbackactuator.h>
#include "qfeedback.h"
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <QtGui/QApplication>
Q_EXPORT_PLUGIN2(feedback_symbian, QFeedbackSymbian)
#define VIBRA_DEVICE 0
#define TOUCH_DEVICE 1
//TODO: is activeWindow good enough
//or should we create a widget for that?
CCoeControl *QFeedbackSymbian::defaultWidget()
{
QWidget *w = QApplication::activeWindow();
return w ? w->winId() : 0;
}
#ifndef NO_TACTILE_SUPPORT
#include <touchfeedback.h>
static TTouchLogicalFeedback convertToSymbian(QFeedbackEffect::ThemeEffect effect)
{
TTouchLogicalFeedback themeFeedbackSymbian = ETouchFeedbackBasic;
switch (effect) {
case QFeedbackEffect::ThemeBasic:
themeFeedbackSymbian = ETouchFeedbackBasic;
break;
case QFeedbackEffect::ThemeSensitive:
themeFeedbackSymbian = ETouchFeedbackSensitive;
break;
#ifdef ADVANCED_TACTILE_SUPPORT
case QFeedbackEffect::ThemeBasicButton:
themeFeedbackSymbian = ETouchFeedbackBasicButton;
break;
case QFeedbackEffect::ThemeSensitiveButton:
themeFeedbackSymbian = ETouchFeedbackSensitiveButton;
break;
case QFeedbackEffect::ThemeBasicItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBounceEffect:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupOpen:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupClose:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeStopFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeEditor:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeTextSelection:
themeFeedbackSymbian = ETouchFeedbackTextSelection;
break;
case QFeedbackEffect::ThemeBlankSelection:
themeFeedbackSymbian = ETouchFeedbackBlankSelection;
break;
case QFeedbackEffect::ThemeLineSelection:
themeFeedbackSymbian = ETouchFeedbackLineSelection;
break;
case QFeedbackEffect::ThemeEmptyLineSelection:
themeFeedbackSymbian = ETouchFeedbackEmptyLineSelection;
break;
case QFeedbackEffect::ThemeCheckBox:
themeFeedbackSymbian = ETouchFeedbackCheckbox;
break;
case QFeedbackEffect::ThemeMultipleCheckBox:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeMultitouchActivate:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeRotateStep:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemDrop:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemMoveOver:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemPick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemScroll:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopUp:
themeFeedbackSymbian = ETouchFeedbackPopUp;
break;
case QFeedbackEffect::ThemeLongPress:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
#endif //ADVANCED_TACTILE_SUPPORT
default:
break;
}
return themeFeedbackSymbian;
}
#ifdef ADVANCED_TACTILE_SUPPORT
typedef MTouchFeedback QTouchFeedback;
// This define is for the second parameter of StartFeedback, which needs to be of type
// TTouchContinuousFeedback in platforms with ADVANCED_TACTILE_SUPPORT
#define DEFAULT_CONTINUOUS_EFFECT ETouchContinuousSmooth
#else
class QTouchFeedback : public MTouchFeedback
{
public:
static QTouchFeedback *Instance()
{
return static_cast<QTouchFeedback*>(MTouchFeedback::Instance());
}
void StopFeedback(const CCoeControl* dummy)
{
Q_UNUSED(dummy);
}
void ModifyFeedback(const CCoeControl* dummy, int intensity)
{
Q_UNUSED(dummy);
Q_UNUSED(intensity);
}
void StartFeedback(const CCoeControl* dummy, int effect, void *event, int intensity, int duration)
{
Q_UNUSED(dummy);
Q_UNUSED(effect);
Q_UNUSED(event);
Q_UNUSED(intensity);
Q_UNUSED(duration);
//if there is no advanced feedback, we just do the normal one and return -1
MTouchFeedback::Instance()->InstantFeedback(ETouchFeedbackSensitive);
}
};
// The second parameter of StartFeedback: an int
#define DEFAULT_CONTINUOUS_EFFECT 0
#endif //ADVANCED_TACTILE_SUPPORT
bool QFeedbackSymbian::play(QFeedbackEffect::ThemeEffect effect)
{
QTouchFeedback::Instance()->InstantFeedback(convertToSymbian(effect));
return true; //there is no way to know if there was a failure
}
#endif //NO_TACTILE_SUPPORT
QFeedbackInterface::PluginPriority QFeedbackSymbian::pluginPriority()
{
return PluginLowPriority;
}
QFeedbackSymbian::QFeedbackSymbian() : m_vibra(0), m_vibraActive(true)
{
}
QFeedbackSymbian::~QFeedbackSymbian()
{
delete m_vibra;
}
CHWRMVibra *QFeedbackSymbian::vibra()
{
if (!m_vibra)
m_vibra = CHWRMVibra::NewL();
return m_vibra;
}
QList<QFeedbackActuator> QFeedbackSymbian::actuators()
{
QList<QFeedbackActuator> ret;
#ifndef NO_TACTILE_SUPPORT
//if we don't have advanced tactile support then the MTouchFeedback doesn't really support custom effects
if (QTouchFeedback::Instance()->TouchFeedbackSupported()) {
ret << createFeedbackActuator(TOUCH_DEVICE);
}
#endif //NO_TACTILE_SUPPORT
ret << createFeedbackActuator(VIBRA_DEVICE);
return ret;
}
void QFeedbackSymbian::setActuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop, const QVariant &value)
{
switch(prop)
{
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
m_vibraActive = value.toBool();
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->SetFeedbackEnabledForThisApp(value.toBool());
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
}
QVariant QFeedbackSymbian::actuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop)
{
switch(prop)
{
case Name:
switch(actuator.id())
{
case VIBRA_DEVICE:
return QLatin1String("Vibra");
case TOUCH_DEVICE:
return QLatin1String("Touch");
default:
return QString();
}
case State:
{
QFeedbackActuator::State ret = QFeedbackActuator::Unknown;
switch(actuator.id())
{
case VIBRA_DEVICE:
switch (vibra()->VibraStatus())
{
case CHWRMVibra::EVibraStatusStopped:
return QFeedbackActuator::Ready;
case CHWRMVibra::EVibraStatusOn:
return QFeedbackActuator::Busy;
default:
return QFeedbackActuator::Unknown;
}
case TOUCH_DEVICE:
//there is no way of getting the state of the device!
default:
return QFeedbackActuator::Unknown;
}
return ret;
}
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
return m_vibraActive;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
return QTouchFeedback::Instance()->FeedbackEnabledForThisApp();
#endif //NO_TACTILE_SUPPORT
default:
return false;
}
default:
return QVariant();
}
}
bool QFeedbackSymbian::isActuatorCapabilitySupported(const QFeedbackActuator &, QFeedbackActuator::Capability)
{
return false;
}
void QFeedbackSymbian::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty prop)
{
switch(prop)
{
case Intensity:
if (!m_elapsed.contains(effect) || m_elapsed[effect].isPaused())
break;
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->ModifyFeedback(defaultWidget(), qRound(100 * effect->intensity()));
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
break;
}
}
void QFeedbackSymbian::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State newState)
{
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
m_elapsed[effect].start();
break;
}
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
QTouchFeedback::Instance()->StartFeedback(defaultWidget(),
DEFAULT_CONTINUOUS_EFFECT,
0, qRound(effect->intensity() * 100), qMax(0, (effect->duration() - m_elapsed[effect].elapsed()) * 1000));
m_elapsed[effect].start();
break;
}
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
QFeedbackEffect::State QFeedbackSymbian::effectState(const QFeedbackHapticsEffect *effect)
{
if (m_elapsed.contains(effect) && m_elapsed[effect].elapsed() < effect->duration()) {
return m_elapsed[effect].isPaused() ? QFeedbackEffect::Paused : QFeedbackEffect::Running;
}
return QFeedbackEffect::Stopped;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qfeedbackactuator.h>
#include "qfeedback.h"
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <QtGui/QApplication>
Q_EXPORT_PLUGIN2(feedback_symbian, QFeedbackSymbian)
#define VIBRA_DEVICE 0
#define TOUCH_DEVICE 1
//TODO: is activeWindow good enough
//or should we create a widget for that?
CCoeControl *QFeedbackSymbian::defaultWidget()
{
QWidget *w = QApplication::activeWindow();
return w ? w->winId() : 0;
}
#ifndef NO_TACTILE_SUPPORT
#include <touchfeedback.h>
static TTouchLogicalFeedback convertToSymbian(QFeedbackEffect::ThemeEffect effect)
{
TTouchLogicalFeedback themeFeedbackSymbian = ETouchFeedbackBasic;
switch (effect) {
case QFeedbackEffect::ThemeBasic:
themeFeedbackSymbian = ETouchFeedbackBasic;
break;
case QFeedbackEffect::ThemeSensitive:
themeFeedbackSymbian = ETouchFeedbackSensitive;
break;
#ifdef ADVANCED_TACTILE_SUPPORT
case QFeedbackEffect::ThemeBasicButton:
themeFeedbackSymbian = ETouchFeedbackBasicButton;
break;
case QFeedbackEffect::ThemeSensitiveButton:
themeFeedbackSymbian = ETouchFeedbackSensitiveButton;
break;
case QFeedbackEffect::ThemeBasicItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBounceEffect:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupOpen:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupClose:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeStopFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeEditor:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeTextSelection:
themeFeedbackSymbian = ETouchFeedbackTextSelection;
break;
case QFeedbackEffect::ThemeBlankSelection:
themeFeedbackSymbian = ETouchFeedbackBlankSelection;
break;
case QFeedbackEffect::ThemeLineSelection:
themeFeedbackSymbian = ETouchFeedbackLineSelection;
break;
case QFeedbackEffect::ThemeEmptyLineSelection:
themeFeedbackSymbian = ETouchFeedbackEmptyLineSelection;
break;
case QFeedbackEffect::ThemeCheckBox:
themeFeedbackSymbian = ETouchFeedbackCheckbox;
break;
case QFeedbackEffect::ThemeMultipleCheckBox:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeMultitouchActivate:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeRotateStep:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemDrop:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemMoveOver:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemPick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemScroll:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopUp:
themeFeedbackSymbian = ETouchFeedbackPopUp;
break;
case QFeedbackEffect::ThemeLongPress:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
#endif //ADVANCED_TACTILE_SUPPORT
default:
break;
}
return themeFeedbackSymbian;
}
#ifdef ADVANCED_TACTILE_SUPPORT
typedef MTouchFeedback QTouchFeedback;
#else
class QTouchFeedback : public MTouchFeedback
{
public:
static QTouchFeedback *Instance()
{
return static_cast<QTouchFeedback*>(MTouchFeedback::Instance());
}
void StopFeedback(const CCoeControl* dummy)
{
Q_UNUSED(dummy);
}
void ModifyFeedback(const CCoeControl* dummy, int intensity)
{
Q_UNUSED(dummy);
Q_UNUSED(intensity);
}
void StartFeedback(const CCoeControl* dummy, int effect, void *event, int intensity, int duration)
{
Q_UNUSED(dummy);
Q_UNUSED(effect);
Q_UNUSED(event);
Q_UNUSED(intensity);
Q_UNUSED(duration);
//if there is no advanced feedback, we just do the normal one and return -1
MTouchFeedback::Instance()->InstantFeedback(ETouchFeedbackSensitive);
}
};
#endif //ADVANCED_TACTILE_SUPPORT
bool QFeedbackSymbian::play(QFeedbackEffect::ThemeEffect effect)
{
QTouchFeedback::Instance()->InstantFeedback(convertToSymbian(effect));
return true; //there is no way to know if there was a failure
}
#endif //NO_TACTILE_SUPPORT
QFeedbackInterface::PluginPriority QFeedbackSymbian::pluginPriority()
{
return PluginLowPriority;
}
QFeedbackSymbian::QFeedbackSymbian() : m_vibra(0), m_vibraActive(true)
{
}
QFeedbackSymbian::~QFeedbackSymbian()
{
delete m_vibra;
}
CHWRMVibra *QFeedbackSymbian::vibra()
{
if (!m_vibra)
m_vibra = CHWRMVibra::NewL();
return m_vibra;
}
QList<QFeedbackActuator> QFeedbackSymbian::actuators()
{
QList<QFeedbackActuator> ret;
#ifndef NO_TACTILE_SUPPORT
//if we don't have advanced tactile support then the MTouchFeedback doesn't really support custom effects
if (QTouchFeedback::Instance()->TouchFeedbackSupported()) {
ret << createFeedbackActuator(TOUCH_DEVICE);
}
#endif //NO_TACTILE_SUPPORT
ret << createFeedbackActuator(VIBRA_DEVICE);
return ret;
}
void QFeedbackSymbian::setActuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop, const QVariant &value)
{
switch(prop)
{
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
m_vibraActive = value.toBool();
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->SetFeedbackEnabledForThisApp(value.toBool());
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
}
QVariant QFeedbackSymbian::actuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop)
{
switch(prop)
{
case Name:
switch(actuator.id())
{
case VIBRA_DEVICE:
return QLatin1String("Vibra");
case TOUCH_DEVICE:
return QLatin1String("Touch");
default:
return QString();
}
case State:
{
QFeedbackActuator::State ret = QFeedbackActuator::Unknown;
switch(actuator.id())
{
case VIBRA_DEVICE:
switch (vibra()->VibraStatus())
{
case CHWRMVibra::EVibraStatusStopped:
return QFeedbackActuator::Ready;
case CHWRMVibra::EVibraStatusOn:
return QFeedbackActuator::Busy;
default:
return QFeedbackActuator::Unknown;
}
case TOUCH_DEVICE:
//there is no way of getting the state of the device!
default:
return QFeedbackActuator::Unknown;
}
return ret;
}
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
return m_vibraActive;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
return QTouchFeedback::Instance()->FeedbackEnabledForThisApp();
#endif //NO_TACTILE_SUPPORT
default:
return false;
}
default:
return QVariant();
}
}
bool QFeedbackSymbian::isActuatorCapabilitySupported(const QFeedbackActuator &, QFeedbackActuator::Capability)
{
return false;
}
void QFeedbackSymbian::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty prop)
{
switch(prop)
{
case Intensity:
if (!m_elapsed.contains(effect) || m_elapsed[effect].isPaused())
break;
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->ModifyFeedback(defaultWidget(), qRound(100 * effect->intensity()));
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
break;
}
}
void QFeedbackSymbian::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State newState)
{
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
m_elapsed[effect].start();
break;
}
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
QTouchFeedback::Instance()->StartFeedback(defaultWidget(),
0, // XXX TODO FIXME: ETouchContinuousSmooth,
0, qRound(effect->intensity() * 100), qMax(0, (effect->duration() - m_elapsed[effect].elapsed()) * 1000));
m_elapsed[effect].start();
break;
}
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
QFeedbackEffect::State QFeedbackSymbian::effectState(const QFeedbackHapticsEffect *effect)
{
if (m_elapsed.contains(effect) && m_elapsed[effect].elapsed() < effect->duration()) {
return m_elapsed[effect].isPaused() ? QFeedbackEffect::Paused : QFeedbackEffect::Running;
}
return QFeedbackEffect::Stopped;
}
<commit_msg>Another attempt at fixing symbian4 - include touchlogicalfeedback.h<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qfeedbackactuator.h>
#include "qfeedback.h"
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
#include <QtGui/QApplication>
Q_EXPORT_PLUGIN2(feedback_symbian, QFeedbackSymbian)
#define VIBRA_DEVICE 0
#define TOUCH_DEVICE 1
//TODO: is activeWindow good enough
//or should we create a widget for that?
CCoeControl *QFeedbackSymbian::defaultWidget()
{
QWidget *w = QApplication::activeWindow();
return w ? w->winId() : 0;
}
#ifndef NO_TACTILE_SUPPORT
#include <touchfeedback.h>
#include <touchlogicalfeedback.h>
static TTouchLogicalFeedback convertToSymbian(QFeedbackEffect::ThemeEffect effect)
{
TTouchLogicalFeedback themeFeedbackSymbian = ETouchFeedbackBasic;
switch (effect) {
case QFeedbackEffect::ThemeBasic:
themeFeedbackSymbian = ETouchFeedbackBasic;
break;
case QFeedbackEffect::ThemeSensitive:
themeFeedbackSymbian = ETouchFeedbackSensitive;
break;
#ifdef ADVANCED_TACTILE_SUPPORT
case QFeedbackEffect::ThemeBasicButton:
themeFeedbackSymbian = ETouchFeedbackBasicButton;
break;
case QFeedbackEffect::ThemeSensitiveButton:
themeFeedbackSymbian = ETouchFeedbackSensitiveButton;
break;
case QFeedbackEffect::ThemeBasicItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveItem:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBounceEffect:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupOpen:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopupClose:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveSlider:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeStopFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeFlick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeEditor:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeTextSelection:
themeFeedbackSymbian = ETouchFeedbackTextSelection;
break;
case QFeedbackEffect::ThemeBlankSelection:
themeFeedbackSymbian = ETouchFeedbackBlankSelection;
break;
case QFeedbackEffect::ThemeLineSelection:
themeFeedbackSymbian = ETouchFeedbackLineSelection;
break;
case QFeedbackEffect::ThemeEmptyLineSelection:
themeFeedbackSymbian = ETouchFeedbackEmptyLineSelection;
break;
case QFeedbackEffect::ThemeCheckBox:
themeFeedbackSymbian = ETouchFeedbackCheckbox;
break;
case QFeedbackEffect::ThemeMultipleCheckBox:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeSensitiveKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeBasicKeypad:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeMultitouchActivate:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeRotateStep:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemDrop:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemMoveOver:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemPick:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemeItemScroll:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
case QFeedbackEffect::ThemePopUp:
themeFeedbackSymbian = ETouchFeedbackPopUp;
break;
case QFeedbackEffect::ThemeLongPress:
themeFeedbackSymbian = ETouchFeedbackBasic; // Effects changing in 10.1 are mapped to basic.
break;
#endif //ADVANCED_TACTILE_SUPPORT
default:
break;
}
return themeFeedbackSymbian;
}
#ifdef ADVANCED_TACTILE_SUPPORT
typedef MTouchFeedback QTouchFeedback;
#else
class QTouchFeedback : public MTouchFeedback
{
public:
static QTouchFeedback *Instance()
{
return static_cast<QTouchFeedback*>(MTouchFeedback::Instance());
}
void StopFeedback(const CCoeControl* dummy)
{
Q_UNUSED(dummy);
}
void ModifyFeedback(const CCoeControl* dummy, int intensity)
{
Q_UNUSED(dummy);
Q_UNUSED(intensity);
}
void StartFeedback(const CCoeControl* dummy, int effect, void *event, int intensity, int duration)
{
Q_UNUSED(dummy);
Q_UNUSED(effect);
Q_UNUSED(event);
Q_UNUSED(intensity);
Q_UNUSED(duration);
//if there is no advanced feedback, we just do the normal one and return -1
MTouchFeedback::Instance()->InstantFeedback(ETouchFeedbackSensitive);
}
};
#endif //ADVANCED_TACTILE_SUPPORT
bool QFeedbackSymbian::play(QFeedbackEffect::ThemeEffect effect)
{
QTouchFeedback::Instance()->InstantFeedback(convertToSymbian(effect));
return true; //there is no way to know if there was a failure
}
#endif //NO_TACTILE_SUPPORT
QFeedbackInterface::PluginPriority QFeedbackSymbian::pluginPriority()
{
return PluginLowPriority;
}
QFeedbackSymbian::QFeedbackSymbian() : m_vibra(0), m_vibraActive(true)
{
}
QFeedbackSymbian::~QFeedbackSymbian()
{
delete m_vibra;
}
CHWRMVibra *QFeedbackSymbian::vibra()
{
if (!m_vibra)
m_vibra = CHWRMVibra::NewL();
return m_vibra;
}
QList<QFeedbackActuator> QFeedbackSymbian::actuators()
{
QList<QFeedbackActuator> ret;
#ifndef NO_TACTILE_SUPPORT
//if we don't have advanced tactile support then the MTouchFeedback doesn't really support custom effects
if (QTouchFeedback::Instance()->TouchFeedbackSupported()) {
ret << createFeedbackActuator(TOUCH_DEVICE);
}
#endif //NO_TACTILE_SUPPORT
ret << createFeedbackActuator(VIBRA_DEVICE);
return ret;
}
void QFeedbackSymbian::setActuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop, const QVariant &value)
{
switch(prop)
{
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
m_vibraActive = value.toBool();
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->SetFeedbackEnabledForThisApp(value.toBool());
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
}
QVariant QFeedbackSymbian::actuatorProperty(const QFeedbackActuator &actuator, ActuatorProperty prop)
{
switch(prop)
{
case Name:
switch(actuator.id())
{
case VIBRA_DEVICE:
return QLatin1String("Vibra");
case TOUCH_DEVICE:
return QLatin1String("Touch");
default:
return QString();
}
case State:
{
QFeedbackActuator::State ret = QFeedbackActuator::Unknown;
switch(actuator.id())
{
case VIBRA_DEVICE:
switch (vibra()->VibraStatus())
{
case CHWRMVibra::EVibraStatusStopped:
return QFeedbackActuator::Ready;
case CHWRMVibra::EVibraStatusOn:
return QFeedbackActuator::Busy;
default:
return QFeedbackActuator::Unknown;
}
case TOUCH_DEVICE:
//there is no way of getting the state of the device!
default:
return QFeedbackActuator::Unknown;
}
return ret;
}
case Enabled:
switch(actuator.id())
{
case VIBRA_DEVICE:
return m_vibraActive;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
return QTouchFeedback::Instance()->FeedbackEnabledForThisApp();
#endif //NO_TACTILE_SUPPORT
default:
return false;
}
default:
return QVariant();
}
}
bool QFeedbackSymbian::isActuatorCapabilitySupported(const QFeedbackActuator &, QFeedbackActuator::Capability)
{
return false;
}
void QFeedbackSymbian::updateEffectProperty(const QFeedbackHapticsEffect *effect, EffectProperty prop)
{
switch(prop)
{
case Intensity:
if (!m_elapsed.contains(effect) || m_elapsed[effect].isPaused())
break;
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
QTouchFeedback::Instance()->ModifyFeedback(defaultWidget(), qRound(100 * effect->intensity()));
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
break;
}
}
void QFeedbackSymbian::setEffectState(const QFeedbackHapticsEffect *effect, QFeedbackEffect::State newState)
{
switch(effect->actuator().id())
{
case VIBRA_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
vibra()->StopVibraL();
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
vibra()->StartVibraL(effect->duration() - m_elapsed[effect].elapsed(), qRound(100 * effect->intensity()));
m_elapsed[effect].start();
break;
}
break;
#ifndef NO_TACTILE_SUPPORT
case TOUCH_DEVICE:
switch(newState)
{
case QFeedbackEffect::Stopped:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed.remove(effect);
}
break;
case QFeedbackEffect::Paused:
if (m_elapsed.contains(effect)) {
QTouchFeedback::Instance()->StopFeedback(defaultWidget());
m_elapsed[effect].pause();
}
break;
case QFeedbackEffect::Running:
if (m_elapsed[effect].elapsed() >= effect->duration())
m_elapsed.remove(effect); //we reached the end. it's time to restart
QTouchFeedback::Instance()->StartFeedback(defaultWidget(),
ETouchContinuousSmooth,
0, qRound(effect->intensity() * 100), qMax(0, (effect->duration() - m_elapsed[effect].elapsed()) * 1000));
m_elapsed[effect].start();
break;
}
break;
#endif //NO_TACTILE_SUPPORT
default:
break;
}
}
QFeedbackEffect::State QFeedbackSymbian::effectState(const QFeedbackHapticsEffect *effect)
{
if (m_elapsed.contains(effect) && m_elapsed[effect].elapsed() < effect->duration()) {
return m_elapsed[effect].isPaused() ? QFeedbackEffect::Paused : QFeedbackEffect::Running;
}
return QFeedbackEffect::Stopped;
}
<|endoftext|>
|
<commit_before>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_STATEWRAPPER_H_
#define LUWRA_STATEWRAPPER_H_
#include "common.hpp"
#include "auxiliary.hpp"
#include <string>
#include <utility>
LUWRA_NS_BEGIN
/**
* Accessor for an entry in the global namespace
*/
struct GlobalAccessor {
State* state;
std::string key;
inline
GlobalAccessor(State* state, const std::string& key): state(state), key(key) {}
/**
* Assign a new value.
*/
template <typename V> inline
GlobalAccessor& set(V value) {
setGlobal(state, key, value);
return *this;
}
/**
* Shortcut for `set()`
*/
template <typename V> inline
GlobalAccessor& operator =(V value) {
return set<V>(value);
}
/**
* Retrieve the associated value.
*/
template <typename V> inline
V get() {
return getGlobal<V>(state, key);
}
/**
* Shortcut for `get()`
*/
template <typename V> inline
operator V() {
return get<V>();
}
/**
* Update the fields of an existing table.
*/
inline
void updateFields(const luwra::FieldVector& fields) {
lua_getglobal(state, key.c_str());
luwra::setFields(state, -1, fields);
lua_pop(state, 1);
}
};
/**
* Wrapper for a Lua state
*/
struct StateWrapper {
State* state;
bool close_state;
/**
* Operate on a foreign state instance.
*/
inline
StateWrapper(State* state): state(state), close_state(false) {}
/**
* Create a new Lua state.
*/
inline
StateWrapper(): state(luaL_newstate()), close_state(true) {}
inline
~StateWrapper() {
if (close_state)
lua_close(state);
}
inline
operator State*() {
return state;
}
inline
void loadStandardLibrary() {
luaL_openlibs(state);
}
/**
* Retrieve a global value.
*/
template <typename V> inline
V getGlobal(const std::string& key) const {
return ::luwra::getGlobal<V>(state, key);
}
/**
* Assign a global value.
*/
template <typename V> inline
void setGlobal(const std::string& key, V value) const {
::luwra::setGlobal(state, key, value);
}
/**
* Create an accessor to a global value.
*/
inline
GlobalAccessor operator [](const std::string& key) const {
return GlobalAccessor(state, key);
}
/**
* See [luwra::registerUserType](@ref luwra::registerUserType).
*/
template <typename T> inline
void registerUserType(
const std::string& ctor_name,
const FieldVector& methods = FieldVector(),
const FieldVector& meta_methods = FieldVector()
) {
::luwra::registerUserType<T>(state, ctor_name, methods, meta_methods);
}
/**
* Execute a piece of code.
*/
inline
int runString(const std::string& code) {
return luaL_dostring(state, code.c_str());
}
/**
* Execute a file.
*/
inline
int runFile(const std::string& filepath) {
return luaL_dofile(state, filepath.c_str());
}
};
LUWRA_NS_END
#endif
<commit_msg>Rename GlobalAccessor::get to GlobalAccessor::read<commit_after>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_STATEWRAPPER_H_
#define LUWRA_STATEWRAPPER_H_
#include "common.hpp"
#include "auxiliary.hpp"
#include <string>
#include <utility>
LUWRA_NS_BEGIN
/**
* Accessor for an entry in the global namespace
*/
struct GlobalAccessor {
State* state;
std::string key;
inline
GlobalAccessor(State* state, const std::string& key): state(state), key(key) {}
/**
* Assign a new value.
*/
template <typename V> inline
GlobalAccessor& set(V value) {
setGlobal(state, key, value);
return *this;
}
/**
* Shortcut for `set()`
*/
template <typename V> inline
GlobalAccessor& operator =(V value) {
return set<V>(value);
}
/**
* Retrieve the associated value.
*/
template <typename V> inline
V read() {
return getGlobal<V>(state, key);
}
/**
* Shortcut for `read()`
*/
template <typename V> inline
operator V() {
return read<V>();
}
/**
* Update the fields of an existing table.
*/
inline
void updateFields(const luwra::FieldVector& fields) {
lua_getglobal(state, key.c_str());
luwra::setFields(state, -1, fields);
lua_pop(state, 1);
}
};
/**
* Wrapper for a Lua state
*/
struct StateWrapper {
State* state;
bool close_state;
/**
* Operate on a foreign state instance.
*/
inline
StateWrapper(State* state): state(state), close_state(false) {}
/**
* Create a new Lua state.
*/
inline
StateWrapper(): state(luaL_newstate()), close_state(true) {}
inline
~StateWrapper() {
if (close_state)
lua_close(state);
}
inline
operator State*() {
return state;
}
inline
void loadStandardLibrary() {
luaL_openlibs(state);
}
/**
* Retrieve a global value.
*/
template <typename V> inline
V getGlobal(const std::string& key) const {
return ::luwra::getGlobal<V>(state, key);
}
/**
* Assign a global value.
*/
template <typename V> inline
void setGlobal(const std::string& key, V value) const {
::luwra::setGlobal(state, key, value);
}
/**
* Create an accessor to a global value.
*/
inline
GlobalAccessor operator [](const std::string& key) const {
return GlobalAccessor(state, key);
}
/**
* See [luwra::registerUserType](@ref luwra::registerUserType).
*/
template <typename T> inline
void registerUserType(
const std::string& ctor_name,
const FieldVector& methods = FieldVector(),
const FieldVector& meta_methods = FieldVector()
) {
::luwra::registerUserType<T>(state, ctor_name, methods, meta_methods);
}
/**
* Execute a piece of code.
*/
inline
int runString(const std::string& code) {
return luaL_dostring(state, code.c_str());
}
/**
* Execute a file.
*/
inline
int runFile(const std::string& filepath) {
return luaL_dofile(state, filepath.c_str());
}
};
LUWRA_NS_END
#endif
<|endoftext|>
|
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_io_UsbAsyncControlEndpoint.h"
#include "jnc_Error.h"
namespace jnc {
namespace io {
//..............................................................................
UsbAsyncControlEndpoint::UsbAsyncControlEndpoint (axl::io::UsbDevice* device)
{
m_runtime = getCurrentThreadRuntime ();
ASSERT (m_runtime);
m_device = device;
m_flags = 0;
}
void
UsbAsyncControlEndpoint::markOpaqueGcRoots (jnc::GcHeap* gcHeap)
{
sl::Iterator <Transfer> it = m_activeTransferList.getHead ();
for (; it; it++)
markTransferGcRoots (gcHeap, *it);
it = m_completedTransferList.getHead ();
for (; it; it++)
markTransferGcRoots (gcHeap, *it);
}
void
UsbAsyncControlEndpoint::markTransferGcRoots (
GcHeap* gcHeap,
Transfer* transfer
)
{
gcHeap->markClass (transfer->m_completionFuncPtr.m_closure->m_box);
if (transfer->m_inBufferPtr.m_validator)
{
gcHeap->weakMark (transfer->m_inBufferPtr.m_validator->m_validatorBox);
gcHeap->markData (transfer->m_inBufferPtr.m_validator->m_targetBox);
}
}
bool
UsbAsyncControlEndpoint::start ()
{
ASSERT (isIdle ());
m_flags = 0;
m_idleEvent.signal ();
return m_completionThread.start ();
}
void
UsbAsyncControlEndpoint::stop ()
{
m_lock.lock ();
m_flags |= Flag_Stop;
m_event.signal ();
m_lock.unlock ();
m_completionThread.waitAndClose ();
}
bool
JNC_CDECL
UsbAsyncControlEndpoint::transfer (
uint_t requestType,
uint_t requestCode,
uint_t value,
uint_t index,
DataPtr ptr,
size_t size,
uint_t timeout,
FunctionPtr completionFuncPtr
)
{
bool result;
m_lock.lock ();
ASSERT (!m_flags & Flag_Stop);
Transfer* transfer = m_transferPool.get ();
m_lock.unlock ();
result = transfer->m_usbTransfer.create ();
libusb_control_setup* setup = transfer->m_buffer.createBuffer (sizeof (libusb_control_setup) + size);
if (!result || !setup)
{
m_lock.lock ();
m_transferPool.put (transfer);
m_lock.unlock ();
callCompletionFunc (completionFuncPtr, -1, err::getLastError ());
return false;
}
transfer->m_usbTransfer.fillControlSetup (
setup,
requestType,
requestCode,
value,
index,
size
);
transfer->m_usbTransfer.fillControlTransfer (
m_device->getOpenHandle (),
setup,
onTransferCompleted,
transfer,
timeout
);
if (requestType & LIBUSB_ENDPOINT_IN)
{
transfer->m_inBufferPtr = ptr;
}
else
{
transfer->m_inBufferPtr = g_nullPtr;
memcpy (setup + 1, ptr.m_p, size);
}
transfer->m_completionFuncPtr = completionFuncPtr;
m_lock.lock ();
if (isIdle ())
m_idleEvent.reset ();
m_activeTransferList.insertTail (transfer);
m_lock.unlock ();
transfer->m_self = this;
result = transfer->m_usbTransfer.submit ();
if (result)
return true;
m_lock.lock ();
m_activeTransferList.remove (transfer);
m_transferPool.put (transfer);
m_lock.unlock ();
callCompletionFunc (completionFuncPtr, -1, err::getLastError ());
return false;
}
void
UsbAsyncControlEndpoint::cancelTransfers ()
{
char buffer [256];
sl::Array <Transfer*> activeTransferArray (ref::BufKind_Stack, buffer, sizeof (buffer));
m_lock.lock ();
ASSERT (!m_flags & Flag_Stop);
m_flags |= Flag_CancelTransfers;
m_event.signal ();
m_lock.unlock ();
m_idleEvent.wait ();
}
void
UsbAsyncControlEndpoint::completionThreadFunc ()
{
for (;;)
{
m_event.wait ();
m_lock.lock ();
if (m_flags & Flag_Stop)
break;
if (m_flags & Flag_CancelTransfers)
{
m_flags &= ~Flag_CancelTransfers;
cancelAllActiveTransfers_l ();
}
else
{
finalizeTransfers_l ();
}
}
cancelAllActiveTransfers_l ();
}
void
UsbAsyncControlEndpoint::cancelAllActiveTransfers_l ()
{
char buffer [256];
sl::Array <Transfer*> activeTransferArray (ref::BufKind_Stack, buffer, sizeof (buffer));
sl::Iterator <Transfer> it = m_activeTransferList.getHead ();
for (; it; it++)
activeTransferArray.append (*it);
m_lock.unlock ();
size_t count = activeTransferArray.getCount ();
for (size_t i = 0; i < count; i++)
activeTransferArray [i]->m_usbTransfer.cancel (); // may fail if already completed
// wait for all transfers to complete
m_lock.lock ();
while (!m_activeTransferList.isEmpty ())
{
m_lock.unlock ();
m_event.wait ();
m_lock.lock ();
}
finalizeTransfers_l ();
}
void
UsbAsyncControlEndpoint::finalizeTransfers_l ()
{
sl::List <Transfer> transferList;
sl::takeOver (&transferList, &m_completedTransferList);
m_lock.unlock ();
sl::Iterator <Transfer> it = transferList.getHead ();
for (; it; it++)
{
switch (it->m_usbTransfer->status)
{
case LIBUSB_TRANSFER_COMPLETED:
ASSERT ((size_t) it->m_usbTransfer->actual_length <= it->m_buffer.getSize () - sizeof (libusb_control_setup));
if (it->m_inBufferPtr.m_p)
memcpy (it->m_inBufferPtr.m_p, it->m_buffer + 1, it->m_usbTransfer->actual_length);
callCompletionFunc (it->m_completionFuncPtr, it->m_usbTransfer->actual_length);
break;
case LIBUSB_TRANSFER_CANCELLED:
callCompletionFunc (it->m_completionFuncPtr, -1, err::SystemErrorCode_Cancelled);
break;
default:
callCompletionFunc (it->m_completionFuncPtr, -1, axl::io::UsbError (LIBUSB_ERROR_IO));
break;
}
it->m_inBufferPtr = g_nullPtr;
it->m_completionFuncPtr = g_nullFunctionPtr;
}
m_lock.lock ();
m_transferPool.put (&transferList);
if (isIdle ())
m_idleEvent.signal ();
m_lock.unlock ();
}
bool
UsbAsyncControlEndpoint::callCompletionFunc (
FunctionPtr completionFuncPtr,
size_t resultSize,
const err::ErrorRef& error
)
{
bool result = true;
JNC_BEGIN_CALL_SITE (m_runtime)
DataPtr errorPtr = g_nullPtr;
if (error)
errorPtr = jnc::memDup (error, error->m_size);
jnc::callVoidFunctionPtr (completionFuncPtr, resultSize, errorPtr);
JNC_CALL_SITE_CATCH ()
AXL_TRACE ("USB completion func failed: %s\n", err::getLastErrorDescription ().sz ());
result = false;
JNC_END_CALL_SITE ()
return result;
}
void
LIBUSB_CALL
UsbAsyncControlEndpoint::onTransferCompleted (libusb_transfer* usbTransfer)
{
Transfer* transfer = (Transfer*) usbTransfer->user_data;
ASSERT (transfer->m_usbTransfer == usbTransfer);
UsbAsyncControlEndpoint* self = transfer->m_self;
self->m_lock.lock ();
self->m_activeTransferList.remove (transfer);
self->m_completedTransferList.insertTail (transfer);
self->m_event.signal ();
self->m_lock.unlock ();
}
//..............................................................................
} // namespace io
} // namespace jnc
<commit_msg>[jnc_io_usb] fix: UsbAsyncControlEndpoint::markOpaqueGcRoots should lock prior walking the list (libusb completion can modify the list any time)<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_io_UsbAsyncControlEndpoint.h"
#include "jnc_Error.h"
namespace jnc {
namespace io {
//..............................................................................
UsbAsyncControlEndpoint::UsbAsyncControlEndpoint (axl::io::UsbDevice* device)
{
m_runtime = getCurrentThreadRuntime ();
ASSERT (m_runtime);
m_device = device;
m_flags = 0;
}
void
UsbAsyncControlEndpoint::markOpaqueGcRoots (jnc::GcHeap* gcHeap)
{
m_lock.lock ();
sl::Iterator <Transfer> it = m_activeTransferList.getHead ();
for (; it; it++)
markTransferGcRoots (gcHeap, *it);
it = m_completedTransferList.getHead ();
for (; it; it++)
markTransferGcRoots (gcHeap, *it);
m_lock.unlock ();
}
void
UsbAsyncControlEndpoint::markTransferGcRoots (
GcHeap* gcHeap,
Transfer* transfer
)
{
gcHeap->markClass (transfer->m_completionFuncPtr.m_closure->m_box);
if (transfer->m_inBufferPtr.m_validator)
{
gcHeap->weakMark (transfer->m_inBufferPtr.m_validator->m_validatorBox);
gcHeap->markData (transfer->m_inBufferPtr.m_validator->m_targetBox);
}
}
bool
UsbAsyncControlEndpoint::start ()
{
ASSERT (isIdle ());
m_flags = 0;
m_idleEvent.signal ();
return m_completionThread.start ();
}
void
UsbAsyncControlEndpoint::stop ()
{
m_lock.lock ();
m_flags |= Flag_Stop;
m_event.signal ();
m_lock.unlock ();
m_completionThread.waitAndClose ();
}
bool
JNC_CDECL
UsbAsyncControlEndpoint::transfer (
uint_t requestType,
uint_t requestCode,
uint_t value,
uint_t index,
DataPtr ptr,
size_t size,
uint_t timeout,
FunctionPtr completionFuncPtr
)
{
bool result;
m_lock.lock ();
ASSERT (!m_flags & Flag_Stop);
Transfer* transfer = m_transferPool.get ();
m_lock.unlock ();
result = transfer->m_usbTransfer.create ();
libusb_control_setup* setup = transfer->m_buffer.createBuffer (sizeof (libusb_control_setup) + size);
if (!result || !setup)
{
m_lock.lock ();
m_transferPool.put (transfer);
m_lock.unlock ();
callCompletionFunc (completionFuncPtr, -1, err::getLastError ());
return false;
}
transfer->m_usbTransfer.fillControlSetup (
setup,
requestType,
requestCode,
value,
index,
size
);
transfer->m_usbTransfer.fillControlTransfer (
m_device->getOpenHandle (),
setup,
onTransferCompleted,
transfer,
timeout
);
if (requestType & LIBUSB_ENDPOINT_IN)
{
transfer->m_inBufferPtr = ptr;
}
else
{
transfer->m_inBufferPtr = g_nullPtr;
memcpy (setup + 1, ptr.m_p, size);
}
transfer->m_completionFuncPtr = completionFuncPtr;
m_lock.lock ();
if (isIdle ())
m_idleEvent.reset ();
m_activeTransferList.insertTail (transfer);
m_lock.unlock ();
transfer->m_self = this;
result = transfer->m_usbTransfer.submit ();
if (result)
return true;
m_lock.lock ();
m_activeTransferList.remove (transfer);
m_transferPool.put (transfer);
m_lock.unlock ();
callCompletionFunc (completionFuncPtr, -1, err::getLastError ());
return false;
}
void
UsbAsyncControlEndpoint::cancelTransfers ()
{
char buffer [256];
sl::Array <Transfer*> activeTransferArray (ref::BufKind_Stack, buffer, sizeof (buffer));
m_lock.lock ();
ASSERT (!m_flags & Flag_Stop);
m_flags |= Flag_CancelTransfers;
m_event.signal ();
m_lock.unlock ();
m_idleEvent.wait ();
}
void
UsbAsyncControlEndpoint::completionThreadFunc ()
{
for (;;)
{
m_event.wait ();
m_lock.lock ();
if (m_flags & Flag_Stop)
break;
if (m_flags & Flag_CancelTransfers)
{
m_flags &= ~Flag_CancelTransfers;
cancelAllActiveTransfers_l ();
}
else
{
finalizeTransfers_l ();
}
}
cancelAllActiveTransfers_l ();
}
void
UsbAsyncControlEndpoint::cancelAllActiveTransfers_l ()
{
char buffer [256];
sl::Array <Transfer*> activeTransferArray (ref::BufKind_Stack, buffer, sizeof (buffer));
sl::Iterator <Transfer> it = m_activeTransferList.getHead ();
for (; it; it++)
activeTransferArray.append (*it);
m_lock.unlock ();
size_t count = activeTransferArray.getCount ();
for (size_t i = 0; i < count; i++)
activeTransferArray [i]->m_usbTransfer.cancel (); // may fail if already completed
// wait for all transfers to complete
m_lock.lock ();
while (!m_activeTransferList.isEmpty ())
{
m_lock.unlock ();
m_event.wait ();
m_lock.lock ();
}
finalizeTransfers_l ();
}
void
UsbAsyncControlEndpoint::finalizeTransfers_l ()
{
sl::List <Transfer> transferList;
sl::takeOver (&transferList, &m_completedTransferList);
m_lock.unlock ();
sl::Iterator <Transfer> it = transferList.getHead ();
for (; it; it++)
{
switch (it->m_usbTransfer->status)
{
case LIBUSB_TRANSFER_COMPLETED:
ASSERT ((size_t) it->m_usbTransfer->actual_length <= it->m_buffer.getSize () - sizeof (libusb_control_setup));
if (it->m_inBufferPtr.m_p)
memcpy (it->m_inBufferPtr.m_p, it->m_buffer + 1, it->m_usbTransfer->actual_length);
callCompletionFunc (it->m_completionFuncPtr, it->m_usbTransfer->actual_length);
break;
case LIBUSB_TRANSFER_CANCELLED:
callCompletionFunc (it->m_completionFuncPtr, -1, err::SystemErrorCode_Cancelled);
break;
default:
callCompletionFunc (it->m_completionFuncPtr, -1, axl::io::UsbError (LIBUSB_ERROR_IO));
break;
}
it->m_inBufferPtr = g_nullPtr;
it->m_completionFuncPtr = g_nullFunctionPtr;
}
m_lock.lock ();
m_transferPool.put (&transferList);
if (isIdle ())
m_idleEvent.signal ();
m_lock.unlock ();
}
bool
UsbAsyncControlEndpoint::callCompletionFunc (
FunctionPtr completionFuncPtr,
size_t resultSize,
const err::ErrorRef& error
)
{
bool result = true;
JNC_BEGIN_CALL_SITE (m_runtime)
DataPtr errorPtr = g_nullPtr;
if (error)
errorPtr = jnc::memDup (error, error->m_size);
jnc::callVoidFunctionPtr (completionFuncPtr, resultSize, errorPtr);
JNC_CALL_SITE_CATCH ()
AXL_TRACE ("USB completion func failed: %s\n", err::getLastErrorDescription ().sz ());
result = false;
JNC_END_CALL_SITE ()
return result;
}
void
LIBUSB_CALL
UsbAsyncControlEndpoint::onTransferCompleted (libusb_transfer* usbTransfer)
{
Transfer* transfer = (Transfer*) usbTransfer->user_data;
ASSERT (transfer->m_usbTransfer == usbTransfer);
UsbAsyncControlEndpoint* self = transfer->m_self;
self->m_lock.lock ();
self->m_activeTransferList.remove (transfer);
self->m_completedTransferList.insertTail (transfer);
self->m_event.signal ();
self->m_lock.unlock ();
}
//..............................................................................
} // namespace io
} // namespace jnc
<|endoftext|>
|
<commit_before>/*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
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 "ch.h"
#include "hal.h"
#include "chprintf.h"
#include "blink.h"
#include "usbconfig.h"
#include "bicycle.h"
#include "kalman.h"
#include "parameters.h"
#include "analog.h"
#include "encoder.h"
#include <boost/math/constants/constants.hpp>
#include <type_traits>
namespace {
using bicycle_t = model::Bicycle;
using kalman_t = observer::Kalman<bicycle_t>;
const float fs = 200; // sample rate [Hz]
const float dt = 1.0/fs; // sample time [s]
const float v0 = 5.0; // forward speed [m/s]
/* Kalman filter variance values */
const float sigma0 = 1 * constants::as_radians; // yaw angle measurement noise variance
const float sigma1 = 0.008 * constants::as_radians; // steer angle measurement noise variance
bicycle_t::input_t u; /* roll torque, steer torque */
bicycle_t::state_t x; /* yaw angle, roll angle, steer angle, roll rate, steer rate */
bicycle_t::output_t z; /* yaw angle, steer angle */
/* sensors */
Analog analog;
Encoder encoder(&GPTD5, /* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h */
{PAL_NOLINE, /* no index channel */
152000, /* counts per revolution */
EncoderConfig::filter_t::CAPTURE_64}); /* 64 * 42 MHz (TIM3 on APB1) = 1.52 us
* for valid edge */
const float max_kistler_torque = 25.0f; /* maximum measured steer torque */
/*
* The voltage output of the Kistler torque sensor is ±10V. With the 12-bit ADC,
* resolution for LSB is 4.88 mV/bit or 12.2 mNm/bit.
*/
model::real_t wrap_angle(model::real_t angle) {
/*
* Angle magnitude is assumed to small enough to NOT require multiple
* additions/subtractions of 2pi.
*/
if (angle >= boost::math::constants::pi<float>()) {
angle -= boost::math::constants::two_pi<float>();
}
if (angle < -boost::math::constants::pi<float>()) {
angle += boost::math::constants::two_pi<float>();
}
return angle;
}
} // namespace
/*
* Application entry point.
*/
int main(void) {
/*
* System initializations.
* - HAL initialization, this also initializes the configured device drivers
* and performs the board-specific initializations.
* - Kernel initialization, the main() function becomes a thread and the
* RTOS is active.
*/
halInit();
chSysInit();
/*
* Initializes a serial-over-USB CDC driver.
*/
sduObjectInit(&SDU1);
sduStart(&SDU1, &serusbcfg);
/*
* Activates the USB driver and then the USB bus pull-up on D+.
* Note, a delay is inserted in order to not have to disconnect the cable
* after a reset.
*/
board_usb_lld_disconnect_bus(); //usbDisconnectBus(serusbcfg.usbp);
chThdSleepMilliseconds(1500);
usbStart(serusbcfg.usbp, &usbcfg);
board_usb_lld_connect_bus(); //usbConnectBus(serusbcfg.usbp);
/* create the example thread */
chBlinkThreadCreateStatic();
/* initialize bicycle model and states */
model::Bicycle bicycle(v0, dt);
x.setZero();
/* initialize Kalman filter */
kalman_t kalman(bicycle,
parameters::defaultvalue::kalman::Q(dt), /* process noise cov */
(kalman_t::measurement_noise_covariance_t() <<
sigma0, 0,
0, sigma1).finished(),
bicycle_t::state_t::Zero(), /* set initial state estimate to zero */
std::pow(x[1]/2, 2) * bicycle_t::state_matrix_t::Identity()); /* error cov */
/*
* Start sensors.
* Encoder:
* Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).
*/
palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
encoder.start();
analog.start(1000); /* trigger ADC conversion at 1 kHz */
/*
* Set torque measurement enable line low.
* The output of the Kistler torque sensor is not valid until after a falling edge
* on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is
* reversed due to NPN switch Q1.
*/
palClearLine(LINE_TORQUE_MEAS_EN);
chThdSleepMilliseconds(1);
palSetLine(LINE_TORQUE_MEAS_EN);
/*
* Normal main() thread activity, in this demo it simulates the bicycle
* dynamics in real-time (roughly).
*/
rtcnt_t kalman_update_time = 0;
while (true) {
u.setZero(); /* set both roll and steer torques to zero */
/* pulse torque measure signal and read steer torque value */
u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque/4096 -
max_kistler_torque);
/* set measurement vector */
z[0] = x[0]; /* yaw angle, just use previous state value */
/*
* Steer angle, read from encoder (enccnt_t is uint32_t)
* Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative
* values for any count over half a revolution.
*/
auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());
auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);
if (position > rev / 2) {
position -= rev;
}
z[1] = static_cast<float>(position) /
boost::math::constants::two_pi<float>();
/* observer time/measurement update (~80 us with real_t = float) */
kalman_update_time = chSysGetRealtimeCounterX();
kalman.time_update(u);
kalman.measurement_update(z);
x = kalman.x();
x[0] = wrap_angle(x[0]);
x[1] = wrap_angle(x[1]);
x[2] = wrap_angle(x[2]);
kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;
chprintf((BaseSequentialStream*)&SDU1,
"adc12 avg:\t%d\r\n", analog.get_adc12());
chprintf((BaseSequentialStream*)&SDU1,
"sensors:\t%0.2f\t%0.2f\t%0.2f\r\n",
u[1], z[0], z[1]);
chprintf((BaseSequentialStream*)&SDU1,
"state:\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\r\n",
x[0], x[1], x[2], x[3], x[4]);
chprintf((BaseSequentialStream*)&SDU1,
"kalman update time: %d us\r\n",
RTC2US(STM32_SYSCLK, kalman_update_time));
chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));
}
}
<commit_msg>Increase resolution of sensor measurements<commit_after>/*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
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 "ch.h"
#include "hal.h"
#include "chprintf.h"
#include "blink.h"
#include "usbconfig.h"
#include "bicycle.h"
#include "kalman.h"
#include "parameters.h"
#include "analog.h"
#include "encoder.h"
#include <boost/math/constants/constants.hpp>
#include <type_traits>
namespace {
using bicycle_t = model::Bicycle;
using kalman_t = observer::Kalman<bicycle_t>;
const float fs = 200; // sample rate [Hz]
const float dt = 1.0/fs; // sample time [s]
const float v0 = 5.0; // forward speed [m/s]
/* Kalman filter variance values */
const float sigma0 = 1 * constants::as_radians; // yaw angle measurement noise variance
const float sigma1 = 0.008 * constants::as_radians; // steer angle measurement noise variance
bicycle_t::input_t u; /* roll torque, steer torque */
bicycle_t::state_t x; /* yaw angle, roll angle, steer angle, roll rate, steer rate */
bicycle_t::output_t z; /* yaw angle, steer angle */
/* sensors */
Analog analog;
Encoder encoder(&GPTD5, /* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h */
{PAL_NOLINE, /* no index channel */
152000, /* counts per revolution */
EncoderConfig::filter_t::CAPTURE_64}); /* 64 * 42 MHz (TIM3 on APB1) = 1.52 us
* for valid edge */
const float max_kistler_torque = 25.0f; /* maximum measured steer torque */
/*
* The voltage output of the Kistler torque sensor is ±10V. With the 12-bit ADC,
* resolution for LSB is 4.88 mV/bit or 12.2 mNm/bit.
*/
model::real_t wrap_angle(model::real_t angle) {
/*
* Angle magnitude is assumed to small enough to NOT require multiple
* additions/subtractions of 2pi.
*/
if (angle >= boost::math::constants::pi<float>()) {
angle -= boost::math::constants::two_pi<float>();
}
if (angle < -boost::math::constants::pi<float>()) {
angle += boost::math::constants::two_pi<float>();
}
return angle;
}
} // namespace
/*
* Application entry point.
*/
int main(void) {
/*
* System initializations.
* - HAL initialization, this also initializes the configured device drivers
* and performs the board-specific initializations.
* - Kernel initialization, the main() function becomes a thread and the
* RTOS is active.
*/
halInit();
chSysInit();
/*
* Initializes a serial-over-USB CDC driver.
*/
sduObjectInit(&SDU1);
sduStart(&SDU1, &serusbcfg);
/*
* Activates the USB driver and then the USB bus pull-up on D+.
* Note, a delay is inserted in order to not have to disconnect the cable
* after a reset.
*/
board_usb_lld_disconnect_bus(); //usbDisconnectBus(serusbcfg.usbp);
chThdSleepMilliseconds(1500);
usbStart(serusbcfg.usbp, &usbcfg);
board_usb_lld_connect_bus(); //usbConnectBus(serusbcfg.usbp);
/* create the example thread */
chBlinkThreadCreateStatic();
/* initialize bicycle model and states */
model::Bicycle bicycle(v0, dt);
x.setZero();
/* initialize Kalman filter */
kalman_t kalman(bicycle,
parameters::defaultvalue::kalman::Q(dt), /* process noise cov */
(kalman_t::measurement_noise_covariance_t() <<
sigma0, 0,
0, sigma1).finished(),
bicycle_t::state_t::Zero(), /* set initial state estimate to zero */
std::pow(x[1]/2, 2) * bicycle_t::state_matrix_t::Identity()); /* error cov */
/*
* Start sensors.
* Encoder:
* Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).
*/
palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
encoder.start();
analog.start(1000); /* trigger ADC conversion at 1 kHz */
/*
* Set torque measurement enable line low.
* The output of the Kistler torque sensor is not valid until after a falling edge
* on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is
* reversed due to NPN switch Q1.
*/
palClearLine(LINE_TORQUE_MEAS_EN);
chThdSleepMilliseconds(1);
palSetLine(LINE_TORQUE_MEAS_EN);
/*
* Normal main() thread activity, in this demo it simulates the bicycle
* dynamics in real-time (roughly).
*/
rtcnt_t kalman_update_time = 0;
while (true) {
u.setZero(); /* set both roll and steer torques to zero */
/* pulse torque measure signal and read steer torque value */
u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque/4096 -
max_kistler_torque);
/* set measurement vector */
z[0] = x[0]; /* yaw angle, just use previous state value */
/*
* Steer angle, read from encoder (enccnt_t is uint32_t)
* Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative
* values for any count over half a revolution.
*/
auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());
auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);
if (position > rev / 2) {
position -= rev;
}
z[1] = static_cast<float>(position) /
boost::math::constants::two_pi<float>();
/* observer time/measurement update (~80 us with real_t = float) */
kalman_update_time = chSysGetRealtimeCounterX();
kalman.time_update(u);
kalman.measurement_update(z);
x = kalman.x();
x[0] = wrap_angle(x[0]);
x[1] = wrap_angle(x[1]);
x[2] = wrap_angle(x[2]);
kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;
chprintf((BaseSequentialStream*)&SDU1,
"adc12 avg:\t%d\r\n", analog.get_adc12());
chprintf((BaseSequentialStream*)&SDU1,
"sensors:\t%0.3f\t%0.3f\t%0.3f\r\n",
u[1], z[0], z[1]);
chprintf((BaseSequentialStream*)&SDU1,
"state:\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\r\n",
x[0], x[1], x[2], x[3], x[4]);
chprintf((BaseSequentialStream*)&SDU1,
"kalman update time: %d us\r\n",
RTC2US(STM32_SYSCLK, kalman_update_time));
chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));
}
}
<|endoftext|>
|
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Deniz Erbilgin 2016
*/
#include "OTRN2483Link_OTRN2483Link.h"
namespace OTRN2483Link
{
// TODO proper constructor
OTRN2483Link::OTRN2483Link(uint8_t _nRstPin, uint8_t rxPin, uint8_t txPin) : config(NULL), ser(rxPin, txPin), nRstPin(_nRstPin) {
bAvailable = false;
// Init OTSoftSerial
}
bool OTRN2483Link::begin() {
char buffer[5];
memset(buffer, 0, 5);
// init resetPin
pinMode(nRstPin, INPUT); // TODO This is shorting on my board
// Begin OTSoftSerial
ser.begin();
// Reset
// print("sys factoryRESET\r\n");
// factoryReset();
// set baudrate
setBaud();
// todo check RN2483 is present and communicative here
// Set up for TTN
#ifndef RN2483_CONFIG_IN_EEPROM
// // Set Device Address
setDevAddr(NULL); // TODO not needed if saved to EEPROM
//
// // Set keys
setKeys(NULL, NULL); // TODO not needed if saved to EEPROM
#endif
// join network
joinABP();
// get status (returns 0001 when connected and not Txing)
getStatus();
// Set data rate.
setDataRate(0);
// Send
return true;
}
/**
* @brief End LoRaWAN connection
*/
bool OTRN2483Link::end()
{
return true;
}
/**
* @brief Sends a raw frame
* @param buf Send buffer.
*/
bool OTRN2483Link::sendRaw(const uint8_t* buf, uint8_t buflen,
int8_t channel, TXpower power, bool listenAfter)
{
char dataBuf[16];
memset(dataBuf, 0, sizeof(dataBuf));
#ifdef RN2483_ALLOW_SLEEP
setBaud();
OTV0P2BASE::nap(WDTO_15MS, true);
#endif // RN2483_ALLOW_SLEEP
#if 0
print(MAC_START);
print(RN2483_GET);
print("dr"); // todo fix command name
print(RN2483_END);
timedBlockingRead(dataBuf, sizeof(dataBuf));
OTV0P2BASE::serialPrintAndFlush(dataBuf);
#endif // 1
uint8_t outputBuf[buflen * 2];
getHex(buf, outputBuf, sizeof(outputBuf));
print(MAC_START);
print(MAC_SEND);
write((const char *)outputBuf, sizeof(outputBuf));
print(RN2483_END);
#if 1
timedBlockingRead(dataBuf, sizeof(dataBuf));
OTV0P2BASE::serialPrintAndFlush(dataBuf);
#endif
#ifdef RN2483_ALLOW_SLEEP
OTV0P2BASE::nap(WDTO_120MS, true);
print(SYS_START);
print(SYS_SLEEP);
print("300000"); // FIXME sleeps for 4 mins
print(RN2483_END);
#endif // RN2483_ALLOW_SLEEP
return true;
}
void OTRN2483Link::poll()
{
}
uint8_t OTRN2483Link::timedBlockingRead(char *data, uint8_t length)
{
// clear buffer, get time and init i to 0
memset(data, 0, length);
uint8_t i = 0;
i = ser.read((uint8_t *)data, length);
#if 1 //OTRN2483LINK_DEBUG
OTV0P2BASE::serialPrintAndFlush(F("\n--Buffer Length: "));
OTV0P2BASE::serialPrintAndFlush(i);
OTV0P2BASE::serialPrintlnAndFlush();
#endif // OTRN2483LINK_DEBUG
return i;
}
/**
* @brief Write a buffer to the RN2483
* @param data Buffer to write
* @param length Length of data buffer
*/
void OTRN2483Link::write(const char *data, uint8_t length)
{
ser.write(data, length);
}
/**
* @brief Prints a single character to RN2483
* @param data character to print
*/
void OTRN2483Link::print(const char data)
{
ser.print(data);
}
/**
* @brief Prints a string to the RN2483
* @param pointer to a \0 terminated char string
*/
void OTRN2483Link::print(const char *string)
{
ser.print(string);
}
/**
* @brief Sends a 5 ms break
*/
void OTRN2483Link::setBaud()
{
ser.sendBreak();
print('U'); // send syncro character
}
/**
* @brief reset device and eeprom to factory defaults
* @note Currently using software reset as there is a short on my REV14
* @fixme Currently non-functional
*/
void OTRN2483Link::factoryReset()
{
print(SYS_START);
// print(SYS_RESET);
print(RN2483_END);
}
/**
* @brief reset device
* @note Currently using software reset as there is a short on my REV14
*/
void OTRN2483Link::reset()
{
print(SYS_START);
print(SYS_RESET);
print(RN2483_END);
// fastDigitalWrite(nRstPin, LOW); // reset pin
// delay(10); // wait a bit
// fastDigitalWrite(nRstPin, HIGH);
}
/**
* @brief sets device address
* @param pointer to 4 byte buffer containing address
* @note OpenTRV has temporarily reserved the block 02:01:11:xx
* and is using addresses 00-04 (as of 2016-01-29)
* @todo Confirm this is in hex
*/
void OTRN2483Link::setDevAddr(const uint8_t *address)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_DEVADDR);
print("02011121"); // TODO this will be stored as number in config
// print(address);
print(RN2483_END);
}
/**
* @brief sets LoRa keys
* @param appKey pointer to a 16 byte buffer containing application key.
* This is specific to the OpenTRV server and should be kept secret.
* @param networkKey pointer to a 16 byte buffer containing the network key.
* This should be the Thing Network key and can be made public.
* The key is: 2B7E151628AED2A6ABF7158809CF4F3C
* @note The RN2483 takes numbers as HEX values.
*/
void OTRN2483Link::setKeys(const uint8_t *appKey, const uint8_t *networkKey)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_APPSKEY);
print("2B7E151628AED2A6ABF7158809CF4F3C"); // TODO this will be stored as number in config
print(RN2483_END);
print(MAC_START);
print(RN2483_SET);
print(MAC_NWKSKEY);
print("2B7E151628AED2A6ABF7158809CF4F3C"); // TODO this will be stored as number in config
print(RN2483_END);
}
/**
* @brief Sets adaptive data rate depending on config and activates connection by personalisation
* @todo Move adaptive data rate out.
*/
void OTRN2483Link::joinABP()
{
print(MAC_START);
print(RN2483_SET);
print(MAC_ADR); // Adaptive data rate
print(RN2483_END);
print(MAC_START);
print(MAC_JOINABP); // Join by ABP (activation by personalisation)
print(RN2483_END);
}
/**
* @brief Return status
* @retval
* @todo Find out what status messages mean and document.
* Do logic
*/
bool OTRN2483Link::getStatus()
{
print(MAC_START);
print(RN2483_GET);
print(MAC_STATUS);
print(RN2483_END);
}
/**
* @brief Saves current mac state
*/
void OTRN2483Link::save()
{
print(MAC_START);
print(MAC_SAVE);
print(RN2483_END);
}
/**
* @brief Sets data rate range
* @note Syntax:
* - <ch> <minRate> <maxRate>
* - 0 is SF12
* - 2 is SF10
* - 5 is SF7
*/
void OTRN2483Link::setDataRate(uint8_t dataRate)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_SET_DR);
print("1");
print(RN2483_END);
}
/**
* @brief converts a string to hex representation
* @param string String to convert
* @param output buffer to hold output. This should be twice the length of string
* @param outputLen Length of output
* @retval returns true if output success
* @note This function only checks output bounds. If input string is too short
* it will overrun.
* Will terminate if passed a null pointer.
* @todo Possibly better to make part of send function and send as byte is converted
*/
bool OTRN2483Link::getHex(const uint8_t *input, uint8_t *output, uint8_t outputLen)
{
if((input == NULL) || (output == NULL)) return false; // check for null pointer
uint8_t counter = outputLen;
// convert to hex
while(counter) {
uint8_t highValue = *input >> 4;
uint8_t lowValue = *input & 0x0f;
uint8_t temp;
temp = highValue;
if(temp <= 9) temp += '0';
else temp += ('A' - 10);
*output++ = temp;
temp = lowValue;
if(temp <= 9) temp += '0';
else temp += ('A'-10);
*output++ = temp;
input++;
counter -= 2;
}
#if 1
OTV0P2BASE::serialPrintAndFlush("hex out: ");
OTV0P2BASE::serialPrintAndFlush((const char *)output);
OTV0P2BASE::serialPrintlnAndFlush();
#endif
return true;
}
/****************************** Unused Virtual methods ***************************/
void OTRN2483Link::getCapacity(uint8_t& queueRXMsgsMin,
uint8_t& maxRXMsgLen, uint8_t& maxTXMsgLen) const {
queueRXMsgsMin = 0;
maxRXMsgLen = 0;
maxTXMsgLen = 0;
}
uint8_t OTRN2483Link::getRXMsgsQueued() const {
return 0;
}
const volatile uint8_t* OTRN2483Link::peekRXMsg() const {
return NULL;
}
const char OTRN2483Link::SYS_START[5] = "sys ";
const char OTRN2483Link::SYS_SLEEP[7] = "sleep ";
const char OTRN2483Link::SYS_RESET[6] = "reset"; // FIXME this can be removed on board with working reset line
const char OTRN2483Link::MAC_START[5] = "mac ";
#ifndef RN2483_CONFIG_IN_EEPROM
const char OTRN2483Link::MAC_DEVADDR[9] = "devaddr ";
const char OTRN2483Link::MAC_APPSKEY[9] = "appskey ";
const char OTRN2483Link::MAC_NWKSKEY[9] = "nwkskey ";
#ifdef RN2483_ENABLE_ADR
const char OTRN2483Link::MAC_ADR[7] = "adr on";
#else
const char OTRN2483Link::MAC_ADR[8] = "adr off";
#endif
const char OTRN2483Link::MAC_SET_DR[4] = "dr ";
#endif // RN2483_CONFIG_IN_EEPROM
const char OTRN2483Link::MAC_JOINABP[9] = "join abp";
const char OTRN2483Link::MAC_STATUS[7] = "status";
const char OTRN2483Link::MAC_SEND[12] = "tx uncnf 1 "; // Sends an unconfirmed packet on channel 1
const char OTRN2483Link::MAC_SAVE[5] = "save";
const char OTRN2483Link::RN2483_SET[5] = "set ";
const char OTRN2483Link::RN2483_GET[5] = "get ";
const char OTRN2483Link::RN2483_END[3] = "\r\n";
} // namespace OTRN2483Link
<commit_msg>removed nonfunctional debug<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Deniz Erbilgin 2016
*/
#include "OTRN2483Link_OTRN2483Link.h"
namespace OTRN2483Link
{
// TODO proper constructor
OTRN2483Link::OTRN2483Link(uint8_t _nRstPin, uint8_t rxPin, uint8_t txPin) : config(NULL), ser(rxPin, txPin), nRstPin(_nRstPin) {
bAvailable = false;
// Init OTSoftSerial
}
bool OTRN2483Link::begin() {
char buffer[5];
memset(buffer, 0, 5);
// init resetPin
pinMode(nRstPin, INPUT); // TODO This is shorting on my board
// Begin OTSoftSerial
ser.begin();
// Reset
// print("sys factoryRESET\r\n");
// factoryReset();
// set baudrate
setBaud();
// todo check RN2483 is present and communicative here
// Set up for TTN
#ifndef RN2483_CONFIG_IN_EEPROM
// // Set Device Address
setDevAddr(NULL); // TODO not needed if saved to EEPROM
//
// // Set keys
setKeys(NULL, NULL); // TODO not needed if saved to EEPROM
#endif
// join network
joinABP();
// get status (returns 0001 when connected and not Txing)
getStatus();
// Set data rate.
setDataRate(0);
// Send
return true;
}
/**
* @brief End LoRaWAN connection
*/
bool OTRN2483Link::end()
{
return true;
}
/**
* @brief Sends a raw frame
* @param buf Send buffer.
*/
bool OTRN2483Link::sendRaw(const uint8_t* buf, uint8_t buflen,
int8_t channel, TXpower power, bool listenAfter)
{
char dataBuf[16];
memset(dataBuf, 0, sizeof(dataBuf));
#ifdef RN2483_ALLOW_SLEEP
setBaud();
OTV0P2BASE::nap(WDTO_15MS, true);
#endif // RN2483_ALLOW_SLEEP
#if 0
print(MAC_START);
print(RN2483_GET);
print("dr"); // todo fix command name
print(RN2483_END);
timedBlockingRead(dataBuf, sizeof(dataBuf));
OTV0P2BASE::serialPrintAndFlush(dataBuf);
#endif // 1
uint8_t outputBuf[buflen * 2];
getHex(buf, outputBuf, sizeof(outputBuf));
print(MAC_START);
print(MAC_SEND);
write((const char *)outputBuf, sizeof(outputBuf));
print(RN2483_END);
#if 1
timedBlockingRead(dataBuf, sizeof(dataBuf));
OTV0P2BASE::serialPrintAndFlush(dataBuf);
#endif
#ifdef RN2483_ALLOW_SLEEP
OTV0P2BASE::nap(WDTO_120MS, true);
print(SYS_START);
print(SYS_SLEEP);
print("300000"); // FIXME sleeps for 4 mins
print(RN2483_END);
#endif // RN2483_ALLOW_SLEEP
return true;
}
void OTRN2483Link::poll()
{
}
uint8_t OTRN2483Link::timedBlockingRead(char *data, uint8_t length)
{
// clear buffer, get time and init i to 0
memset(data, 0, length);
uint8_t i = 0;
i = ser.read((uint8_t *)data, length);
#if 0 //OTRN2483LINK_DEBUG
OTV0P2BASE::serialPrintAndFlush(F("\n--Buffer Length: "));
OTV0P2BASE::serialPrintAndFlush(i);
OTV0P2BASE::serialPrintlnAndFlush();
#endif // OTRN2483LINK_DEBUG
return i;
}
/**
* @brief Write a buffer to the RN2483
* @param data Buffer to write
* @param length Length of data buffer
*/
void OTRN2483Link::write(const char *data, uint8_t length)
{
ser.write(data, length);
}
/**
* @brief Prints a single character to RN2483
* @param data character to print
*/
void OTRN2483Link::print(const char data)
{
ser.print(data);
}
/**
* @brief Prints a string to the RN2483
* @param pointer to a \0 terminated char string
*/
void OTRN2483Link::print(const char *string)
{
ser.print(string);
}
/**
* @brief Sends a 5 ms break
*/
void OTRN2483Link::setBaud()
{
ser.sendBreak();
print('U'); // send syncro character
}
/**
* @brief reset device and eeprom to factory defaults
* @note Currently using software reset as there is a short on my REV14
* @fixme Currently non-functional
*/
void OTRN2483Link::factoryReset()
{
print(SYS_START);
// print(SYS_RESET);
print(RN2483_END);
}
/**
* @brief reset device
* @note Currently using software reset as there is a short on my REV14
*/
void OTRN2483Link::reset()
{
print(SYS_START);
print(SYS_RESET);
print(RN2483_END);
// fastDigitalWrite(nRstPin, LOW); // reset pin
// delay(10); // wait a bit
// fastDigitalWrite(nRstPin, HIGH);
}
/**
* @brief sets device address
* @param pointer to 4 byte buffer containing address
* @note OpenTRV has temporarily reserved the block 02:01:11:xx
* and is using addresses 00-04 (as of 2016-01-29)
* @todo Confirm this is in hex
*/
void OTRN2483Link::setDevAddr(const uint8_t *address)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_DEVADDR);
print("02011121"); // TODO this will be stored as number in config
// print(address);
print(RN2483_END);
}
/**
* @brief sets LoRa keys
* @param appKey pointer to a 16 byte buffer containing application key.
* This is specific to the OpenTRV server and should be kept secret.
* @param networkKey pointer to a 16 byte buffer containing the network key.
* This should be the Thing Network key and can be made public.
* The key is: 2B7E151628AED2A6ABF7158809CF4F3C
* @note The RN2483 takes numbers as HEX values.
*/
void OTRN2483Link::setKeys(const uint8_t *appKey, const uint8_t *networkKey)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_APPSKEY);
print("2B7E151628AED2A6ABF7158809CF4F3C"); // TODO this will be stored as number in config
print(RN2483_END);
print(MAC_START);
print(RN2483_SET);
print(MAC_NWKSKEY);
print("2B7E151628AED2A6ABF7158809CF4F3C"); // TODO this will be stored as number in config
print(RN2483_END);
}
/**
* @brief Sets adaptive data rate depending on config and activates connection by personalisation
* @todo Move adaptive data rate out.
*/
void OTRN2483Link::joinABP()
{
print(MAC_START);
print(RN2483_SET);
print(MAC_ADR); // Adaptive data rate
print(RN2483_END);
print(MAC_START);
print(MAC_JOINABP); // Join by ABP (activation by personalisation)
print(RN2483_END);
}
/**
* @brief Return status
* @retval
* @todo Find out what status messages mean and document.
* Do logic
*/
bool OTRN2483Link::getStatus()
{
print(MAC_START);
print(RN2483_GET);
print(MAC_STATUS);
print(RN2483_END);
}
/**
* @brief Saves current mac state
*/
void OTRN2483Link::save()
{
print(MAC_START);
print(MAC_SAVE);
print(RN2483_END);
}
/**
* @brief Sets data rate range
* @note Syntax:
* - <ch> <minRate> <maxRate>
* - 0 is SF12
* - 2 is SF10
* - 5 is SF7
*/
void OTRN2483Link::setDataRate(uint8_t dataRate)
{
print(MAC_START);
print(RN2483_SET);
print(MAC_SET_DR);
print("1");
print(RN2483_END);
}
/**
* @brief converts a string to hex representation
* @param string String to convert
* @param output buffer to hold output. This should be twice the length of string
* @param outputLen Length of output
* @retval returns true if output success
* @note This function only checks output bounds. If input string is too short
* it will overrun.
* Will terminate if passed a null pointer.
* @todo Possibly better to make part of send function and send as byte is converted
*/
bool OTRN2483Link::getHex(const uint8_t *input, uint8_t *output, uint8_t outputLen)
{
if((input == NULL) || (output == NULL)) return false; // check for null pointer
uint8_t counter = outputLen;
// convert to hex
while(counter) {
uint8_t highValue = *input >> 4;
uint8_t lowValue = *input & 0x0f;
uint8_t temp;
temp = highValue;
if(temp <= 9) temp += '0';
else temp += ('A' - 10);
*output++ = temp;
temp = lowValue;
if(temp <= 9) temp += '0';
else temp += ('A'-10);
*output++ = temp;
input++;
counter -= 2;
}
#if 0
OTV0P2BASE::serialPrintAndFlush("hex out: ");
OTV0P2BASE::serialPrintAndFlush((const char *)output);
OTV0P2BASE::serialPrintlnAndFlush();
#endif
return true;
}
/****************************** Unused Virtual methods ***************************/
void OTRN2483Link::getCapacity(uint8_t& queueRXMsgsMin,
uint8_t& maxRXMsgLen, uint8_t& maxTXMsgLen) const {
queueRXMsgsMin = 0;
maxRXMsgLen = 0;
maxTXMsgLen = 0;
}
uint8_t OTRN2483Link::getRXMsgsQueued() const {
return 0;
}
const volatile uint8_t* OTRN2483Link::peekRXMsg() const {
return NULL;
}
const char OTRN2483Link::SYS_START[5] = "sys ";
const char OTRN2483Link::SYS_SLEEP[7] = "sleep ";
const char OTRN2483Link::SYS_RESET[6] = "reset"; // FIXME this can be removed on board with working reset line
const char OTRN2483Link::MAC_START[5] = "mac ";
#ifndef RN2483_CONFIG_IN_EEPROM
const char OTRN2483Link::MAC_DEVADDR[9] = "devaddr ";
const char OTRN2483Link::MAC_APPSKEY[9] = "appskey ";
const char OTRN2483Link::MAC_NWKSKEY[9] = "nwkskey ";
#ifdef RN2483_ENABLE_ADR
const char OTRN2483Link::MAC_ADR[7] = "adr on";
#else
const char OTRN2483Link::MAC_ADR[8] = "adr off";
#endif
const char OTRN2483Link::MAC_SET_DR[4] = "dr ";
#endif // RN2483_CONFIG_IN_EEPROM
const char OTRN2483Link::MAC_JOINABP[9] = "join abp";
const char OTRN2483Link::MAC_STATUS[7] = "status";
const char OTRN2483Link::MAC_SEND[12] = "tx uncnf 1 "; // Sends an unconfirmed packet on channel 1
const char OTRN2483Link::MAC_SAVE[5] = "save";
const char OTRN2483Link::RN2483_SET[5] = "set ";
const char OTRN2483Link::RN2483_GET[5] = "get ";
const char OTRN2483Link::RN2483_END[3] = "\r\n";
} // namespace OTRN2483Link
<|endoftext|>
|
<commit_before>#ifndef REFLEXION_STRUCT2_HPP
#define REFLEXION_STRUCT2_HPP
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/cat.hpp>
#define RXN_GENERATE_FIELDS(r, fields, generator) generator(fields)
#define RXN_REFLECT(generators, ...) \
BOOST_PP_SEQ_FOR_EACH(RXN_GENERATE_FIELDS, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__), generators)
#define RXN_IDENTITY(...) __VA_ARGS__
#define RXN_HEAD(head, ...) head
#define RXN_TAIL(head, ...) __VA_ARGS__
#define RXN_IGNORE(...)
#define RXN_ADD_PARENS(...) ((__VA_ARGS__))
#define RXN_REMOVE_PARENS(...) RXN_IDENTITY __VA_ARGS__
#define ADD_PAREN_1(...) ((__VA_ARGS__)) ADD_PAREN_2
#define ADD_PAREN_2(...) ((__VA_ARGS__)) ADD_PAREN_1
#define ADD_PAREN_1_END
#define ADD_PAREN_2_END
#define OUTPUT BOOST_PP_CAT(ADD_PAREN_1 INPUT,_END)
#define RXN_NORMALIZE_FIELD(field) BOOST_PP_CAT(ADD_PAREN_1 field, _END)
#define RXN_GENERATE_FIELD_3(generator, name_type_tuple, annotations_3) \
generator( \
BOOST_PP_TUPLE_ELEM(2, 0, name_type_tuple), \
(RXN_TAIL name_type_tuple), \
annotations_3 \
)
#define RXN_GENERATE_FIELD_2(generator, normalized_field) \
RXN_GENERATE_FIELD_3( \
generator, \
BOOST_PP_SEQ_HEAD(normalized_field), \
BOOST_PP_SEQ_TAIL(normalized_field))
#define RXN_GENERATE_FIELD(r, generator, i, field) \
RXN_GENERATE_FIELD_2(generator, RXN_NORMALIZE_FIELD(field))
#define RXN_MEMBER(name, type, annotations) RXN_IDENTITY type name;
#define RXN_MEMBERS(fields) BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_MEMBER, fields)
#define RXN_VISIT(name, type, annotations) \
visitor.template accept<RXN_REMOVE_PARENS(BOOST_PP_SEQ_ELEM(0, annotations))> \
(this->name);
#define RXN_ITERATE(fields) \
template <class Visitor> \
void iterate(Visitor &visitor) { \
BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_VISIT, fields) \
} \
template <class Visitor> \
void iterate(Visitor &visitor) const { \
BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_VISIT, fields) \
}
#endif
<commit_msg>remove unused macro<commit_after>#ifndef REFLEXION_STRUCT2_HPP
#define REFLEXION_STRUCT2_HPP
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/cat.hpp>
#define RXN_GENERATE_FIELDS(r, fields, generator) generator(fields)
#define RXN_REFLECT(generators, ...) \
BOOST_PP_SEQ_FOR_EACH(RXN_GENERATE_FIELDS, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__), generators)
#define RXN_IDENTITY(...) __VA_ARGS__
#define RXN_HEAD(head, ...) head
#define RXN_TAIL(head, ...) __VA_ARGS__
#define RXN_IGNORE(...)
#define RXN_REMOVE_PARENS(...) RXN_IDENTITY __VA_ARGS__
#define ADD_PAREN_1(...) ((__VA_ARGS__)) ADD_PAREN_2
#define ADD_PAREN_2(...) ((__VA_ARGS__)) ADD_PAREN_1
#define ADD_PAREN_1_END
#define ADD_PAREN_2_END
#define OUTPUT BOOST_PP_CAT(ADD_PAREN_1 INPUT,_END)
#define RXN_NORMALIZE_FIELD(field) BOOST_PP_CAT(ADD_PAREN_1 field, _END)
#define RXN_GENERATE_FIELD_3(generator, name_type_tuple, annotations_3) \
generator( \
BOOST_PP_TUPLE_ELEM(2, 0, name_type_tuple), \
(RXN_TAIL name_type_tuple), \
annotations_3 \
)
#define RXN_GENERATE_FIELD_2(generator, normalized_field) \
RXN_GENERATE_FIELD_3( \
generator, \
BOOST_PP_SEQ_HEAD(normalized_field), \
BOOST_PP_SEQ_TAIL(normalized_field))
#define RXN_GENERATE_FIELD(r, generator, i, field) \
RXN_GENERATE_FIELD_2(generator, RXN_NORMALIZE_FIELD(field))
#define RXN_MEMBER(name, type, annotations) RXN_IDENTITY type name;
#define RXN_MEMBERS(fields) BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_MEMBER, fields)
#define RXN_VISIT(name, type, annotations) \
visitor.template accept<RXN_REMOVE_PARENS(BOOST_PP_SEQ_ELEM(0, annotations))> \
(this->name);
#define RXN_ITERATE(fields) \
template <class Visitor> \
void iterate(Visitor &visitor) { \
BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_VISIT, fields) \
} \
template <class Visitor> \
void iterate(Visitor &visitor) const { \
BOOST_PP_SEQ_FOR_EACH_I(RXN_GENERATE_FIELD, RXN_VISIT, fields) \
}
#endif
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Common definitions for parsing sample data.
******************************************************************************/
#include "sys/time.h"
#include "sample_data.hpp"
//Get the time in milliseconds
uint64_t msecTime() {
//Set this to the real timestamp, milliseconds since 1970
timeval tval;
gettimeofday(&tval, NULL);
//Cast to uint64_t to prevent rounding problems on 32 bit systems
return (uint64_t)tval.tv_sec*(uint64_t)1000 + tval.tv_usec/1000;
}
bool operator==(const uint128_t& a, const uint128_t& b) {
return a.upper == b.upper and a.lower == b.lower;
}
std::ostream& operator<<(std::ostream& os, const uint128_t& val) {
//The packed struct seems to have problems with the stream operators
//so pull out the upper and lower values into temporary variables before
//applying the << operator.
uint64_t upper = val.upper;
uint64_t lower = val.lower;
//return os<<"0x"<<std::hex<<upper<<lower<<std::dec;
//TODO FIXME This assumes that the number is actually only 64 bits long.
return os<<lower<<std::dec;
}
//TODO FIXME This assumes that the input number is actually only 64 bits long.
std::istream& operator>>(std::istream& is, uint128_t& val) {
//The packed nature of the structure seems to cause errors with the
//stream operator so make a temporary variable to read data into.
uint64_t newval;
is >> newval;
val.lower = newval;
return is;
//return is>>val.lower;
}
uint128_t operator&(const uint128_t& a, const uint128_t& b) {
uint128_t c;
c.upper = a.upper & b.upper;
c.lower = a.lower & b.lower;
return c;
}
bool operator<(const uint128_t& a, const uint128_t& b) {
return (a.upper < b.upper or (a.upper == b.upper and a.lower < b.lower));
}
uint128_t::uint128_t(const uint128_t& val) {
this->upper = val.upper;
this->lower = val.lower;
}
uint128_t::uint128_t(uint64_t val) {
this->upper = 0;
this->lower = val;
}
std::string to_string(uint128_t val) {
return std::to_string(val.lower);
}
std::u16string to_u16string(uint128_t val) {
std::string str = to_string(val);
return std::u16string(str.begin(), str.end());
}
<commit_msg>Fixing warning (formatting 128 numeric output as hex).<commit_after>/*******************************************************************************
* Common definitions for parsing sample data.
******************************************************************************/
#include "sys/time.h"
#include "sample_data.hpp"
//Get the time in milliseconds
uint64_t msecTime() {
//Set this to the real timestamp, milliseconds since 1970
timeval tval;
gettimeofday(&tval, NULL);
//Cast to uint64_t to prevent rounding problems on 32 bit systems
return (uint64_t)tval.tv_sec*(uint64_t)1000 + tval.tv_usec/1000;
}
bool operator==(const uint128_t& a, const uint128_t& b) {
return a.upper == b.upper and a.lower == b.lower;
}
std::ostream& operator<<(std::ostream& os, const uint128_t& val) {
//The packed struct seems to have problems with the stream operators
//so pull out the upper and lower values into temporary variables before
//applying the << operator.
uint64_t upper = val.upper;
uint64_t lower = val.lower;
//Save current format flags
std::ios_base::fmtflags flags = os.flags();
return os<<std::hex<<std::showbase<<upper<<lower<<std::dec;
//Reset format flags
os.flags(flags);
//TODO FIXME This assumes that the number is actually only 64 bits long.
//return os<<lower<<std::dec;
}
//TODO FIXME This assumes that the input number is actually only 64 bits long.
std::istream& operator>>(std::istream& is, uint128_t& val) {
//The packed nature of the structure seems to cause errors with the
//stream operator so make a temporary variable to read data into.
uint64_t newval;
is >> newval;
val.lower = newval;
return is;
//return is>>val.lower;
}
uint128_t operator&(const uint128_t& a, const uint128_t& b) {
uint128_t c;
c.upper = a.upper & b.upper;
c.lower = a.lower & b.lower;
return c;
}
bool operator<(const uint128_t& a, const uint128_t& b) {
return (a.upper < b.upper or (a.upper == b.upper and a.lower < b.lower));
}
uint128_t::uint128_t(const uint128_t& val) {
this->upper = val.upper;
this->lower = val.lower;
}
uint128_t::uint128_t(uint64_t val) {
this->upper = 0;
this->lower = val;
}
std::string to_string(uint128_t val) {
return std::to_string(val.lower);
}
std::u16string to_u16string(uint128_t val) {
std::string str = to_string(val);
return std::u16string(str.begin(), str.end());
}
<|endoftext|>
|
<commit_before>#include <numeric>
#include <ros/ros.h>
#include <algorithm>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <pcl/point_types.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_cloud.h>
#include <tf/transform_listener.h>
#include <opencv/cv.h>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <pcl_ros/transforms.h>
#include <pixel_2_3d/Pixel23d.h>
namespace pixel_2_3d {
class Pixel23dServer {
public:
ros::NodeHandle nh;
tf::TransformListener tf_listener;
ros::Subscriber pc_sub;
ros::Publisher pt3d_pub;
ros::ServiceServer pix_srv;
image_transport::ImageTransport img_trans;
image_transport::CameraSubscriber camera_sub;
image_geometry::PinholeCameraModel cam_model;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cur_pc;
Pixel23dServer();
void onInit();
void cameraCallback(const sensor_msgs::ImageConstPtr& img_msg,
const sensor_msgs::CameraInfoConstPtr& info_msg);
void pcCallback(sensor_msgs::PointCloud2::ConstPtr pc_msg);
bool pixCallback(Pixel23d::Request& req, Pixel23d::Response& resp);
};
Pixel23dServer::Pixel23dServer() : img_trans(nh),
cur_pc(new pcl::PointCloud<pcl::PointXYZRGB>) {
onInit();
}
void Pixel23dServer::onInit() {
camera_sub = img_trans.subscribeCamera<Pixel23dServer>
("image", 1,
&Pixel23dServer::cameraCallback, this);
pc_sub = nh.subscribe("point_cloud", 1, &Pixel23dServer::pcCallback, this);
pix_srv = nh.advertiseService("pixel_2_3d", &Pixel23dServer::pixCallback, this);
pt3d_pub = nh.advertise<geometry_msgs::PoseStamped>("pixel3d", 1);
ros::Duration(1).sleep();
}
void Pixel23dServer::cameraCallback(const sensor_msgs::ImageConstPtr& img_msg,
const sensor_msgs::CameraInfoConstPtr& info_msg) {
cam_model.fromCameraInfo(info_msg);
}
void Pixel23dServer::pcCallback(sensor_msgs::PointCloud2::ConstPtr pc_msg) {
pcl::fromROSMsg(*pc_msg, *cur_pc);
}
double pixDist(cv::Point2d& a, cv::Point2d& b) {
double dist = std::sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
if(dist != dist)
return 1e8;
return dist;
}
bool Pixel23dServer::pixCallback(Pixel23d::Request& req, Pixel23d::Response& resp) {
pcl_ros::transformPointCloud(cam_model.tfFrame(), *cur_pc, *cur_pc, tf_listener);
cv::Point2d img_pix(req.pixel.point.x, req.pixel.point.y);
std::vector<double> dists;
for(uint32_t i=0;i<cur_pc->points.size();i++) {
cv::Point3d pt3d(cur_pc->points[i].x, cur_pc->points[i].y, cur_pc->points[i].z);
cv::Point2d pt_pix = cam_model.project3dToPixel(pt3d);
dists.push_back(pixDist(pt_pix, img_pix));
}
uint32_t min_ind = std::min_element(dists.begin(), dists.end()) - dists.begin();
resp.pixel3d.header.frame_id = cur_pc->header.frame_id;
resp.pixel3d.header.stamp = cur_pc->header.stamp;
resp.pixel3d.point.x = cur_pc->points[min_ind].x;
resp.pixel3d.point.y = cur_pc->points[min_ind].y;
resp.pixel3d.point.z = cur_pc->points[min_ind].z;
geometry_msgs::PoseStamped pt3d;
tf_listener.transformPoint("/base_footprint", resp.pixel3d, resp.pixel3d);
pt3d.header.frame_id = resp.pixel3d.header.frame_id;
pt3d.header.stamp = ros::Time::now();
pt3d.pose.position.x = resp.pixel3d.point.x;
pt3d.pose.position.y = resp.pixel3d.point.y;
pt3d.pose.position.z = resp.pixel3d.point.z;
pt3d.pose.orientation.w = 1;
pt3d_pub.publish(pt3d);
return true;
}
};
using namespace pixel_2_3d;
int main(int argc, char **argv)
{
ros::init(argc, argv, "pixel_2_3d");
Pixel23dServer p3d;
ros::spin();
return 0;
}
<commit_msg>pixel_2_3d change: point in base_footprint frame instead of image frame<commit_after>#include <numeric>
#include <ros/ros.h>
#include <algorithm>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <pcl/point_types.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_cloud.h>
#include <tf/transform_listener.h>
#include <opencv/cv.h>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <pcl_ros/transforms.h>
#include <pixel_2_3d/Pixel23d.h>
namespace pixel_2_3d {
class Pixel23dServer {
public:
ros::NodeHandle nh;
tf::TransformListener tf_listener;
ros::Subscriber pc_sub;
ros::Publisher pt3d_pub;
ros::ServiceServer pix_srv;
image_transport::ImageTransport img_trans;
image_transport::CameraSubscriber camera_sub;
image_geometry::PinholeCameraModel cam_model;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cur_pc;
Pixel23dServer();
void onInit();
void cameraCallback(const sensor_msgs::ImageConstPtr& img_msg,
const sensor_msgs::CameraInfoConstPtr& info_msg);
void pcCallback(sensor_msgs::PointCloud2::ConstPtr pc_msg);
bool pixCallback(Pixel23d::Request& req, Pixel23d::Response& resp);
};
Pixel23dServer::Pixel23dServer() : img_trans(nh),
cur_pc(new pcl::PointCloud<pcl::PointXYZRGB>) {
onInit();
}
void Pixel23dServer::onInit() {
camera_sub = img_trans.subscribeCamera<Pixel23dServer>
("image", 1,
&Pixel23dServer::cameraCallback, this);
pc_sub = nh.subscribe("point_cloud", 1, &Pixel23dServer::pcCallback, this);
pix_srv = nh.advertiseService("pixel_2_3d", &Pixel23dServer::pixCallback, this);
pt3d_pub = nh.advertise<geometry_msgs::PoseStamped>("pixel3d", 1);
ROS_INFO("[pixel_2_3d] Pixel23dServer loaded");
ros::Duration(1).sleep();
}
void Pixel23dServer::cameraCallback(const sensor_msgs::ImageConstPtr& img_msg,
const sensor_msgs::CameraInfoConstPtr& info_msg) {
cam_model.fromCameraInfo(info_msg);
}
void Pixel23dServer::pcCallback(sensor_msgs::PointCloud2::ConstPtr pc_msg) {
pcl::fromROSMsg(*pc_msg, *cur_pc);
}
double pixDist(cv::Point2d& a, cv::Point2d& b) {
double dist = std::sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
if(dist != dist)
return 1e8;
return dist;
}
bool Pixel23dServer::pixCallback(Pixel23d::Request& req, Pixel23d::Response& resp) {
pcl_ros::transformPointCloud(cam_model.tfFrame(), *cur_pc, *cur_pc, tf_listener);
cv::Point2d img_pix(req.pixel.point.x, req.pixel.point.y);
std::vector<double> dists;
for(uint32_t i=0;i<cur_pc->points.size();i++) {
cv::Point3d pt3d(cur_pc->points[i].x, cur_pc->points[i].y, cur_pc->points[i].z);
cv::Point2d pt_pix = cam_model.project3dToPixel(pt3d);
dists.push_back(pixDist(pt_pix, img_pix));
}
uint32_t min_ind = std::min_element(dists.begin(), dists.end()) - dists.begin();
geometry_msgs::PointStamped pt3d, pt3d_trans;
pt3d_trans.header.frame_id = cur_pc->header.frame_id;
pt3d_trans.header.stamp = ros::Time::now();
pt3d_trans.point.x = cur_pc->points[min_ind].x;
pt3d_trans.point.y = cur_pc->points[min_ind].y;
pt3d_trans.point.z = cur_pc->points[min_ind].z;
//tf_listener.transformPoint("/base_footprint", pt3d, pt3d_trans);
resp.pixel3d.header.frame_id = pt3d_trans.header.frame_id;
resp.pixel3d.header.stamp = pt3d_trans.header.stamp;
resp.pixel3d.point.x = pt3d_trans.point.x;
resp.pixel3d.point.y = pt3d_trans.point.y;
resp.pixel3d.point.z = pt3d_trans.point.z;
geometry_msgs::PoseStamped pt3d_pose;
pt3d_pose.header.frame_id = pt3d_trans.header.frame_id;
pt3d_pose.header.stamp = pt3d_trans.header.stamp;
pt3d_pose.pose.position.x = pt3d_trans.point.x;
pt3d_pose.pose.position.y = pt3d_trans.point.y;
pt3d_pose.pose.position.z = pt3d_trans.point.z;
pt3d_pose.pose.orientation.w = 1;
pt3d_pub.publish(pt3d_pose);
return true;
}
};
using namespace pixel_2_3d;
int main(int argc, char **argv)
{
ros::init(argc, argv, "pixel_2_3d");
Pixel23dServer p3d;
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include <ioxdds/gateway/iox2dds.hpp>
#include <iceoryx_posh/runtime/posh_runtime.hpp>
class ShutdownManager
{
public:
static void scheduleShutdown(int num)
{
std::lock_guard<std::mutex> lock(m_mutex);
char reason;
psignal(num, &reason);
m_shutdownFlag.store(true, std::memory_order_relaxed);
}
static bool shouldShutdown()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_shutdownFlag.load(std::memory_order_relaxed);
}
private:
static std::mutex m_mutex;
static std::atomic_bool m_shutdownFlag;
ShutdownManager() = default;
};
std::mutex ShutdownManager::m_mutex;
std::atomic_bool ShutdownManager::m_shutdownFlag(false);
int main(int argc, char* argv[])
{
// Set OS signal handlers
signal(SIGINT, ShutdownManager::scheduleShutdown);
signal(SIGTERM, ShutdownManager::scheduleShutdown);
// // Start gateway
iox::runtime::PoshRuntime::getInstance("/gateway_iox2dds");
iox::gateway::dds::Iceoryx2DDSGateway<> gateway;
auto discoveryThread = std::thread([&gateway] { gateway.discoveryLoop(); });
auto forwardingThread = std::thread([&gateway] { gateway.forwardingLoop(); });
// Run until SIGINT or SIGTERM
while (!ShutdownManager::shouldShutdown())
{
std::this_thread::sleep_for(std::chrono::seconds(1));
};
// Shutdown gracefully
gateway.shutdown();
discoveryThread.join();
forwardingThread.join();
return 0;
}
<commit_msg>iox-#64 Store gateway instance in data segment, not on stack.<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include <ioxdds/gateway/iox2dds.hpp>
#include <iceoryx_utils/cxx/helplets.hpp>
#include <iceoryx_utils/cxx/optional.hpp>
#include <iceoryx_posh/runtime/posh_runtime.hpp>
class ShutdownManager
{
public:
static void scheduleShutdown(int num)
{
std::lock_guard<std::mutex> lock(m_mutex);
char reason;
psignal(num, &reason);
m_shutdownFlag.store(true, std::memory_order_relaxed);
}
static bool shouldShutdown()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_shutdownFlag.load(std::memory_order_relaxed);
}
private:
static std::mutex m_mutex;
static std::atomic_bool m_shutdownFlag;
ShutdownManager() = default;
};
std::mutex ShutdownManager::m_mutex;
std::atomic_bool ShutdownManager::m_shutdownFlag(false);
int main(int argc, char* argv[])
{
// Set OS signal handlers
signal(SIGINT, ShutdownManager::scheduleShutdown);
signal(SIGTERM, ShutdownManager::scheduleShutdown);
// Start application
iox::runtime::PoshRuntime::getInstance("/gateway_iox2dds");
//iox::gateway::dds::Iceoryx2DDSGateway<> gateway;
static iox::cxx::optional<iox::gateway::dds::Iceoryx2DDSGateway<>> gateway;
auto gatewayScopeGuard = iox::cxx::makeScopedStatic(gateway);
auto discoveryThread = std::thread([] { gateway.value().discoveryLoop(); });
auto forwardingThread = std::thread([] { gateway.value().forwardingLoop(); });
// Run until SIGINT or SIGTERM
while (!ShutdownManager::shouldShutdown())
{
std::this_thread::sleep_for(std::chrono::seconds(1));
};
// Shutdown gracefully
gateway.value().shutdown();
discoveryThread.join();
forwardingThread.join();
return 0;
}
<|endoftext|>
|
<commit_before>// Hossein Moein
// July 24, 2019
/*
Copyright (c) 2019-2022, Hossein Moein
All rights reserved.
Redistribution and use in source and binary forms, with or without
odification, 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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h>
#include <sstream>
// ----------------------------------------------------------------------------
namespace hmdf
{
template<typename I, typename H>
template<typename ... Ts>
bool DataFrame<I, H>::
write(const char *file_name, io_format iof, bool columns_only) const {
std::ofstream stream;
stream.open(file_name, std::ios::out); // Open for writing
if (stream.fail()) {
String1K err;
err.printf("write(): ERROR: Unable to open file '%s'", file_name);
throw DataFrameError(err.c_str());
}
write<std::ostream, Ts ...>(stream, iof, columns_only);
stream.close();
return (true);
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::string
DataFrame<I, H>::to_string(io_format iof) const {
std::stringstream ss (std::ios_base::out);
write<std::ostream, Ts ...>(ss, iof, false);
return (ss.str());
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename S, typename ... Ts>
bool DataFrame<I, H>::write (S &o, io_format iof, bool columns_only) const {
if (iof != io_format::csv &&
iof != io_format::json &&
iof != io_format::csv2)
throw NotImplemented("write(): This io_format is not implemented");
if (iof == io_format::json)
o << "{\n";
bool need_pre_comma = false;
const size_type index_s = indices_.size();
if (iof == io_format::json) {
if (! columns_only) {
_write_json_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
o << "\"D\":[";
if (index_s != 0) {
_write_json_df_index_(o, indices_[0]);
for (size_type i = 1; i < index_s; ++i) {
o << ',';
_write_json_df_index_(o, indices_[i]);
}
}
o << "]}";
need_pre_comma = true;
}
for (const auto &iter : column_list_) {
print_json_functor_<Ts ...> functor (iter.first.c_str(),
need_pre_comma,
o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
need_pre_comma = true;
}
}
else if (iof == io_format::csv) {
if (! columns_only) {
_write_csv_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
for (size_type i = 0; i < index_s; ++i)
_write_csv_df_index_(o, indices_[i]) << ',';
o << '\n';
}
for (const auto &iter : column_list_) {
print_csv_functor_<Ts ...> functor (iter.first.c_str(), o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
}
}
else if (iof == io_format::csv2) {
if (! columns_only) {
_write_csv2_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
need_pre_comma = true;
}
for (const auto &iter : column_list_) {
if (need_pre_comma) o << ',';
else need_pre_comma = true;
print_csv2_header_functor_<S, Ts ...> functor(
iter.first.c_str(), o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
}
o << '\n';
need_pre_comma = false;
for (size_type i = 0; i < index_s; ++i) {
size_type count = 0;
if (! columns_only) {
o << indices_[i];
need_pre_comma = true;
count += 1;
}
for (auto citer = column_list_.begin();
citer != column_list_.end(); ++citer, ++count) {
print_csv2_data_functor_<S, Ts ...> functor (i, o);
const SpinGuard guard(lock_);
if (need_pre_comma && count > 0) o << ',';
else need_pre_comma = true;
data_[citer->second].change(functor);
}
o << '\n';
}
}
if (iof == io_format::json)
o << "\n}";
o << std::endl;
return (true);
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::future<bool> DataFrame<I, H>::
write_async (const char *file_name, io_format iof, bool columns_only) const {
return (std::async(std::launch::async,
[file_name, iof, columns_only, this] () -> bool {
return (this->write<Ts ...>(file_name,
iof,
columns_only));
}));
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename S, typename ... Ts>
std::future<bool> DataFrame<I, H>::
write_async (S &o, io_format iof, bool columns_only) const {
return (std::async(std::launch::async,
[&o, iof, columns_only, this] () -> bool {
return (this->write<S, Ts ...>(o,
iof,
columns_only));
}));
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::future<std::string>
DataFrame<I, H>::to_string_async (io_format iof) const {
return (std::async(std::launch::async,
&DataFrame::to_string<Ts ...>, this, iof));
}
} // namespace hmdf
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<commit_msg>Fixed typo<commit_after>// Hossein Moein
// July 24, 2019
/*
Copyright (c) 2019-2022, Hossein Moein
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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h>
#include <sstream>
// ----------------------------------------------------------------------------
namespace hmdf
{
template<typename I, typename H>
template<typename ... Ts>
bool DataFrame<I, H>::
write(const char *file_name, io_format iof, bool columns_only) const {
std::ofstream stream;
stream.open(file_name, std::ios::out); // Open for writing
if (stream.fail()) {
String1K err;
err.printf("write(): ERROR: Unable to open file '%s'", file_name);
throw DataFrameError(err.c_str());
}
write<std::ostream, Ts ...>(stream, iof, columns_only);
stream.close();
return (true);
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::string
DataFrame<I, H>::to_string(io_format iof) const {
std::stringstream ss (std::ios_base::out);
write<std::ostream, Ts ...>(ss, iof, false);
return (ss.str());
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename S, typename ... Ts>
bool DataFrame<I, H>::write (S &o, io_format iof, bool columns_only) const {
if (iof != io_format::csv &&
iof != io_format::json &&
iof != io_format::csv2)
throw NotImplemented("write(): This io_format is not implemented");
if (iof == io_format::json)
o << "{\n";
bool need_pre_comma = false;
const size_type index_s = indices_.size();
if (iof == io_format::json) {
if (! columns_only) {
_write_json_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
o << "\"D\":[";
if (index_s != 0) {
_write_json_df_index_(o, indices_[0]);
for (size_type i = 1; i < index_s; ++i) {
o << ',';
_write_json_df_index_(o, indices_[i]);
}
}
o << "]}";
need_pre_comma = true;
}
for (const auto &iter : column_list_) {
print_json_functor_<Ts ...> functor (iter.first.c_str(),
need_pre_comma,
o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
need_pre_comma = true;
}
}
else if (iof == io_format::csv) {
if (! columns_only) {
_write_csv_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
for (size_type i = 0; i < index_s; ++i)
_write_csv_df_index_(o, indices_[i]) << ',';
o << '\n';
}
for (const auto &iter : column_list_) {
print_csv_functor_<Ts ...> functor (iter.first.c_str(), o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
}
}
else if (iof == io_format::csv2) {
if (! columns_only) {
_write_csv2_df_header_<S, IndexType>(o, DF_INDEX_COL_NAME, index_s);
need_pre_comma = true;
}
for (const auto &iter : column_list_) {
if (need_pre_comma) o << ',';
else need_pre_comma = true;
print_csv2_header_functor_<S, Ts ...> functor(
iter.first.c_str(), o);
const SpinGuard guard(lock_);
data_[iter.second].change(functor);
}
o << '\n';
need_pre_comma = false;
for (size_type i = 0; i < index_s; ++i) {
size_type count = 0;
if (! columns_only) {
o << indices_[i];
need_pre_comma = true;
count += 1;
}
for (auto citer = column_list_.begin();
citer != column_list_.end(); ++citer, ++count) {
print_csv2_data_functor_<S, Ts ...> functor (i, o);
const SpinGuard guard(lock_);
if (need_pre_comma && count > 0) o << ',';
else need_pre_comma = true;
data_[citer->second].change(functor);
}
o << '\n';
}
}
if (iof == io_format::json)
o << "\n}";
o << std::endl;
return (true);
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::future<bool> DataFrame<I, H>::
write_async (const char *file_name, io_format iof, bool columns_only) const {
return (std::async(std::launch::async,
[file_name, iof, columns_only, this] () -> bool {
return (this->write<Ts ...>(file_name,
iof,
columns_only));
}));
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename S, typename ... Ts>
std::future<bool> DataFrame<I, H>::
write_async (S &o, io_format iof, bool columns_only) const {
return (std::async(std::launch::async,
[&o, iof, columns_only, this] () -> bool {
return (this->write<S, Ts ...>(o,
iof,
columns_only));
}));
}
// ----------------------------------------------------------------------------
template<typename I, typename H>
template<typename ... Ts>
std::future<std::string>
DataFrame<I, H>::to_string_async (io_format iof) const {
return (std::async(std::launch::async,
&DataFrame::to_string<Ts ...>, this, iof));
}
} // namespace hmdf
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<|endoftext|>
|
<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CALCULATION_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CALCULATION_HH__
#include <aleph/config/Defaults.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistenceDiagrams/Calculation.hh>
#include <aleph/persistentHomology/PersistencePairing.hh>
#include <aleph/topology/Conversions.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <algorithm>
#include <limits>
#include <tuple>
#include <unordered_set>
#include <vector>
namespace aleph
{
/**
Given a boundary matrix, reduces it and reads off the resulting
persistence pairing. An optional parameter can be used to force
the algorithm to stop processing a part of the pairing. This is
especially relevant for intersection homology, which sets upper
limits for the validity of an index in the matrix.
@param M Boundary matrix to reduce
@param includeAllUnpairedCreators Flag indicating whether all unpaired creators should
be included (regardless of their dimension). If set,
this increases the size of the resulting pairing, as
the highest-dimensional columns of the matrix cannot
be reduced any more. The flag is useful, however, in
case one wants to calculate ordinary homology, where
high-dimensional simplices are used for Betti number
calculations.
@param max Optional maximum index after which simplices are not
considered any more. If the pairing of a simplex has
an index larger than the maximum one, such simplices
will not be considered in the pairing. All simplices
are used by default.
@tparam ReductionAlgorithm Specifies a reduction algorithm to use for reducing
the input matrix. Aleph provides a default value in
order to simplify the usage of this function.
@tparam Representation The representation of the boundary matrix, i.e. how
columns are stored. This parameter is automatically
determined from the input data.
*/
template <
class ReductionAlgorithm = aleph::defaults::ReductionAlgorithm,
class Representation = aleph::defaults::Representation
> PersistencePairing<typename Representation::Index> calculatePersistencePairing( const topology::BoundaryMatrix<Representation>& M,
bool includeAllUnpairedCreators = false,
typename Representation::Index max = std::numeric_limits<typename Representation::Index>::max() )
{
using namespace topology;
using Index = typename Representation::Index;
using PersistencePairing = PersistencePairing<Index>;
BoundaryMatrix<Representation> B = M;
ReductionAlgorithm reductionAlgorithm;
reductionAlgorithm( B );
PersistencePairing pairing;
auto numColumns = max <= B.getNumColumns() ? max : B.getNumColumns();
std::unordered_set<Index> creators;
for( Index j = Index(0); j < numColumns; j++ )
{
Index i;
bool valid;
std::tie( i, valid ) = B.getMaximumIndex( j );
if( valid )
{
auto u = i;
auto v = j;
auto w = u;
// Column j is non-zero. It destroys the feature created by its
// lowest 1. Hence, i does not remain a creator.
creators.erase( i );
if( B.isDualized() )
{
u = numColumns - 1 - v;
v = numColumns - 1 - w; // Yes, this is correct!
}
if( max > B.getNumColumns() || i < max )
pairing.add( u, v );
}
// An invalid maximum index indicates that the corresponding column
// is empty. Hence, we need to think about whether it signifies one
// feature with infinite persistence.
else
{
// Only add creators that do not belong to the largest dimension
// of the boundary matrix. Else, there will be a lot of spurious
// features that cannot be destroyed due to their dimensions. If
// the client wants to have them, however, we let them.
if( ( !B.isDualized() && B.getDimension(j) != B.getDimension() )
|| ( B.isDualized() && B.getDimension(j) != Index(0) )
|| includeAllUnpairedCreators )
{
creators.insert( j );
}
}
}
for( auto&& creator : creators )
{
if( B.isDualized() )
pairing.add( numColumns - 1 - creator );
else
pairing.add( creator );
}
std::sort( pairing.begin(), pairing.end() );
return pairing;
}
/**
Calculates a set of persistence diagrams from a simplicial complex in
filtration order, while permitting some additional parameters. Notice
that this is a *convenience* function that performs *all* conversions
automatically.
@param K Simplicial complex
@param dualize Indicates that boundary matrix dualization is desired
@param includeAllUnpairedCreators Indicates that *all* unpaired creators detected during a single pass
of the simplicial complex should be included. This is useful when it
is clear that the simplicial complex models a topological object for
which top-level simplices are meaningful. For Vietoris--Rips complex
calculations, this is usually *not* the case.
@tparam ReductionAlgorithm Algorithm for reducing the boundary matrix
@tparam Representation Representation of the boundary matrix
@tparam Simplex Simplex data type (usually inferred from the other parameters)
*/
template <
class ReductionAlgorithm = defaults::ReductionAlgorithm,
class Representation = defaults::Representation,
class Simplex
> std::vector< PersistenceDiagram<typename Simplex::DataType> > calculatePersistenceDiagrams( const topology::SimplicialComplex<Simplex>& K, bool dualize = true, bool includeAllUnpairedCreators = false )
{
using namespace topology;
auto boundaryMatrix = makeBoundaryMatrix<Representation>( K );
auto pairing = calculatePersistencePairing<ReductionAlgorithm>( dualize ? boundaryMatrix.dualize() : boundaryMatrix, includeAllUnpairedCreators );
return makePersistenceDiagrams( pairing, K );
}
/**
Calculates a persistence diagram from a boundary matrix and a set of
function values. This function is meant to permit quick calculations
for one-dimensional functions where a matrix and a vector of values,
denoting the \f$y\f$-values of the function, are sufficient.
@param boundaryMatrix Boundary matrix to reduce
@param functionValues Vector of values to assign to the persistence diagram
@returns Persistence diagram
@tparam ReductionAlgorithm Algorithm for reducing the boundary matrix
@tparam Representation Representation of the boundary matrix
@tparam DataType Data type (usually inferred from the other parameters)
*/
template <
class ReductionAlgorithm = defaults::ReductionAlgorithm,
class Representation = defaults::Representation,
class DataType
> PersistenceDiagram<DataType> calculatePersistenceDiagram( const topology::BoundaryMatrix<Representation>& boundaryMatrix,
const std::vector<DataType>& functionValues )
{
auto pairing = calculatePersistencePairing<ReductionAlgorithm>( boundaryMatrix );
return makePersistenceDiagram( pairing, functionValues );
}
}
#endif
<commit_msg>Fixed cut-off criterion for boundary matrices<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CALCULATION_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CALCULATION_HH__
#include <aleph/config/Defaults.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistenceDiagrams/Calculation.hh>
#include <aleph/persistentHomology/PersistencePairing.hh>
#include <aleph/topology/Conversions.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <algorithm>
#include <limits>
#include <tuple>
#include <unordered_set>
#include <vector>
namespace aleph
{
/**
Given a boundary matrix, reduces it and reads off the resulting
persistence pairing. An optional parameter can be used to force
the algorithm to stop processing a part of the pairing. This is
especially relevant for intersection homology, which sets upper
limits for the validity of an index in the matrix.
@param M Boundary matrix to reduce
@param includeAllUnpairedCreators Flag indicating whether all unpaired creators should
be included (regardless of their dimension). If set,
this increases the size of the resulting pairing, as
the highest-dimensional columns of the matrix cannot
be reduced any more. The flag is useful, however, in
case one wants to calculate ordinary homology, where
high-dimensional simplices are used for Betti number
calculations.
@param max Optional maximum index after which simplices are not
considered any more. If the pairing of a simplex has
an index larger than the maximum one, such simplices
will not be considered in the pairing. All simplices
are used by default.
@tparam ReductionAlgorithm Specifies a reduction algorithm to use for reducing
the input matrix. Aleph provides a default value in
order to simplify the usage of this function.
@tparam Representation The representation of the boundary matrix, i.e. how
columns are stored. This parameter is automatically
determined from the input data.
*/
template <
class ReductionAlgorithm = aleph::defaults::ReductionAlgorithm,
class Representation = aleph::defaults::Representation
> PersistencePairing<typename Representation::Index> calculatePersistencePairing( const topology::BoundaryMatrix<Representation>& M,
bool includeAllUnpairedCreators = false,
typename Representation::Index max = std::numeric_limits<typename Representation::Index>::max() )
{
using namespace topology;
using Index = typename Representation::Index;
using PersistencePairing = PersistencePairing<Index>;
BoundaryMatrix<Representation> B = M;
ReductionAlgorithm reductionAlgorithm;
reductionAlgorithm( B );
PersistencePairing pairing; // resulting pairing
std::unordered_set<Index> creators; // keeps track of (potential) creators
auto numColumns = B.getNumColumns();
for( Index j = Index(0); j < numColumns; j++ )
{
Index i;
bool valid;
std::tie( i, valid ) = B.getMaximumIndex( j );
if( valid )
{
auto u = i;
auto v = j;
auto w = u;
// Column j is non-zero. It destroys the feature created by its
// lowest 1. Hence, i does not remain a creator.
creators.erase( i );
if( B.isDualized() )
{
u = numColumns - 1 - v;
v = numColumns - 1 - w; // Yes, this is correct!
}
// u is checked here because it contains the correct index of
// a simplex with respect to its simplicial complex. Even for
// a dualized matrix, this index is correctly transformed.
if( max > numColumns || u < max )
pairing.add( u, v );
}
// An invalid maximum index indicates that the corresponding column
// is empty. Hence, we need to think about whether it signifies one
// feature with infinite persistence.
else
{
// Only add creators that do not belong to the largest dimension
// of the boundary matrix. Else, there will be a lot of spurious
// features that cannot be destroyed due to their dimensions. If
// the client wants to have them, however, we let them.
if( ( !B.isDualized() && B.getDimension(j) != B.getDimension() )
|| ( B.isDualized() && B.getDimension(j) != Index(0) )
|| includeAllUnpairedCreators )
{
creators.insert( j );
}
}
}
for( auto&& creator : creators )
{
auto c = B.isDualized() ? numColumns - 1 - creator : creator;
// Again, check whether the transformed index value needs to be
// included in the data. We are not interested in keeping track
// of simplices that are not allowable (with respect to `max`).
if( max > numColumns || c < max )
pairing.add( c );
}
std::sort( pairing.begin(), pairing.end() );
return pairing;
}
/**
Calculates a set of persistence diagrams from a simplicial complex in
filtration order, while permitting some additional parameters. Notice
that this is a *convenience* function that performs *all* conversions
automatically.
@param K Simplicial complex
@param dualize Indicates that boundary matrix dualization is desired
@param includeAllUnpairedCreators Indicates that *all* unpaired creators detected during a single pass
of the simplicial complex should be included. This is useful when it
is clear that the simplicial complex models a topological object for
which top-level simplices are meaningful. For Vietoris--Rips complex
calculations, this is usually *not* the case.
@tparam ReductionAlgorithm Algorithm for reducing the boundary matrix
@tparam Representation Representation of the boundary matrix
@tparam Simplex Simplex data type (usually inferred from the other parameters)
*/
template <
class ReductionAlgorithm = defaults::ReductionAlgorithm,
class Representation = defaults::Representation,
class Simplex
> std::vector< PersistenceDiagram<typename Simplex::DataType> > calculatePersistenceDiagrams( const topology::SimplicialComplex<Simplex>& K, bool dualize = true, bool includeAllUnpairedCreators = false )
{
using namespace topology;
auto boundaryMatrix = makeBoundaryMatrix<Representation>( K );
auto pairing = calculatePersistencePairing<ReductionAlgorithm>( dualize ? boundaryMatrix.dualize() : boundaryMatrix, includeAllUnpairedCreators );
return makePersistenceDiagrams( pairing, K );
}
/**
Calculates a persistence diagram from a boundary matrix and a set of
function values. This function is meant to permit quick calculations
for one-dimensional functions where a matrix and a vector of values,
denoting the \f$y\f$-values of the function, are sufficient.
@param boundaryMatrix Boundary matrix to reduce
@param functionValues Vector of values to assign to the persistence diagram
@returns Persistence diagram
@tparam ReductionAlgorithm Algorithm for reducing the boundary matrix
@tparam Representation Representation of the boundary matrix
@tparam DataType Data type (usually inferred from the other parameters)
*/
template <
class ReductionAlgorithm = defaults::ReductionAlgorithm,
class Representation = defaults::Representation,
class DataType
> PersistenceDiagram<DataType> calculatePersistenceDiagram( const topology::BoundaryMatrix<Representation>& boundaryMatrix,
const std::vector<DataType>& functionValues )
{
auto pairing = calculatePersistencePairing<ReductionAlgorithm>( boundaryMatrix );
return makePersistenceDiagram( pairing, functionValues );
}
}
#endif
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_CORE_MAIN_MENU_MENU_START_HPP
#define RJ_CORE_MAIN_MENU_MENU_START_HPP
#include "items.hpp"
#include "menu_component.hpp"
#include <rectojump/game/components/player.hpp>
#include <rectojump/game/factory.hpp>
#include <mlk/time/simple_timer.h>
#include <mlk/tools/random_utl.h>
namespace rj
{
template<typename Main_Menu>
class menu_start : public menu_component<Main_Menu>
{
items m_items;
// player preview
factory::eptr<player> m_player_prev{factory::create<player>(vec2f{this->m_center.x, this->m_center.y / 0.55f})};
mlk::tm::simple_timer m_player_timer{500};
public:
menu_start(Main_Menu& mm, menu_state type, game& g, const sf::Font& font, const vec2f& center) :
menu_component<Main_Menu>{mm, type, g, font, center},
m_items{g, font, center,this->m_mainmenu.get_def_fontcolor(),
this->m_mainmenu.get_act_fontcolor()}
{this->init();}
item get_current_selected() const noexcept
{return m_items.get_current_selected();}
void update(dur duration) override
{
m_items.update(duration);
// update player
if(m_player_timer.timed_out())
{
simulate_keypress(key::Space);
m_player_timer.restart(mlk::rnd<mlk::ullong>(500, 5000));
}
m_player_prev->update(duration);
}
void render() override
{
m_items.render();
m_player_prev->render();
}
void on_key_up() override
{
m_items.on_key_up();
}
void on_key_down() override
{
m_items.on_key_down();
}
void call_current_event() override
{m_items.call_current_event();}
items& get_items() noexcept
{return m_items;}
private:
void init()
{
// add entrys to menu 'items'
m_items.add_item("play", "Play");
m_items.add_item("options", "Options");
m_items.add_item("credits", "Credits");
m_items.add_item("quit", "Quit");
m_player_prev->init();
m_player_prev->set_game(&this->m_game);
m_player_prev->render_object().setFillColor(this->m_mainmenu.get_act_fontcolor());
m_player_timer.run();
}
};
}
#endif // RJ_CORE_MAIN_MENU_MENU_START_HPP
<commit_msg>menu_start: adapted items<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_CORE_MAIN_MENU_MENU_START_HPP
#define RJ_CORE_MAIN_MENU_MENU_START_HPP
#include "items.hpp"
#include "menu_component.hpp"
#include <rectojump/game/components/player.hpp>
#include <rectojump/game/factory.hpp>
#include <mlk/time/simple_timer.h>
#include <mlk/tools/random_utl.h>
namespace rj
{
template<typename Main_Menu>
class menu_start : public menu_component<Main_Menu>
{
items<Main_Menu> m_items;
// player preview
factory::eptr<player> m_player_prev{factory::create<player>(vec2f{this->m_center.x, this->m_center.y / 0.55f})};
mlk::tm::simple_timer m_player_timer{500};
public:
menu_start(Main_Menu& mm, menu_state type, game& g, const sf::Font& font, const vec2f& center) :
menu_component<Main_Menu>{mm, type, g, font, center},
m_items{mm}
{this->init();}
item get_current_selected() const noexcept
{return m_items.get_current_selected();}
void update(dur duration) override
{
m_items.update(duration);
// update player
if(m_player_timer.timed_out())
{
simulate_keypress(key::Space);
m_player_timer.restart(mlk::rnd<mlk::ullong>(500, 5000));
}
m_player_prev->update(duration);
}
void render() override
{
m_items.render();
m_player_prev->render();
}
void on_key_up() override
{
m_items.on_key_up();
}
void on_key_down() override
{
m_items.on_key_down();
}
void call_current_event() override
{m_items.call_current_event();}
auto get_items() noexcept
-> decltype(m_items)&
{return m_items;}
private:
void init()
{
// add entrys to menu 'items'
m_items.add_item("play", "Play");
m_items.add_item("options", "Options");
m_items.add_item("credits", "Credits");
m_items.add_item("quit", "Quit");
m_player_prev->init();
m_player_prev->set_game(&this->m_game);
m_player_prev->render_object().setFillColor(this->m_mainmenu.get_act_fontcolor());
m_player_timer.run();
}
};
}
#endif // RJ_CORE_MAIN_MENU_MENU_START_HPP
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cronet/android/cronet_library_loader.h"
#include <jni.h>
#include "base/android/base_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/at_exit.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "components/cronet/android/chromium_url_request.h"
#include "components/cronet/android/chromium_url_request_context.h"
#include "components/cronet/android/cronet_histogram_manager.h"
#include "components/cronet/android/cronet_upload_data_stream_delegate.h"
#include "components/cronet/android/cronet_url_request.h"
#include "components/cronet/android/cronet_url_request_context_adapter.h"
#include "jni/CronetLibraryLoader_jni.h"
#include "net/android/net_jni_registrar.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "url/android/url_jni_registrar.h"
#include "url/url_util.h"
#if !defined(USE_ICU_ALTERNATIVES_ON_ANDROID)
#include "base/i18n/icu_util.h"
#endif
namespace cronet {
namespace {
const base::android::RegistrationMethod kCronetRegisteredMethods[] = {
{"BaseAndroid", base::android::RegisterJni},
{"ChromiumUrlRequest", ChromiumUrlRequestRegisterJni},
{"ChromiumUrlRequestContext", ChromiumUrlRequestContextRegisterJni},
{"CronetHistogramManager", CronetHistogramManagerRegisterJni},
{"CronetLibraryLoader", RegisterNativesImpl},
{"CronetUploadDataStreamDelegate",
CronetUploadDataStreamDelegateRegisterJni},
{"CronetUrlRequest", CronetUrlRequestRegisterJni},
{"CronetUrlRequestContextAdapter",
CronetUrlRequestContextAdapterRegisterJni},
{"NetAndroid", net::android::RegisterJni},
{"UrlAndroid", url::android::RegisterJni},
};
base::AtExitManager* g_at_exit_manager = NULL;
// MessageLoop on the main thread, which is where objects that receive Java
// notifications generally live.
base::MessageLoop* g_main_message_loop = nullptr;
net::NetworkChangeNotifier* g_network_change_notifier = nullptr;
} // namespace
// Checks the available version of JNI. Also, caches Java reflection artifacts.
jint CronetOnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
base::android::InitVM(vm);
if (!base::android::RegisterNativeMethods(
env, kCronetRegisteredMethods, arraysize(kCronetRegisteredMethods))) {
return -1;
}
g_at_exit_manager = new base::AtExitManager();
url::Initialize();
return JNI_VERSION_1_6;
}
void CronetOnUnLoad(JavaVM* jvm, void* reserved) {
if (g_at_exit_manager) {
delete g_at_exit_manager;
g_at_exit_manager = NULL;
}
}
void CronetInitOnMainThread(JNIEnv* env, jclass jcaller, jobject jcontext) {
// Set application context.
base::android::ScopedJavaLocalRef<jobject> scoped_context(env, jcontext);
base::android::InitApplicationContext(env, scoped_context);
#if !defined(USE_ICU_ALTERNATIVES_ON_ANDROID)
base::i18n::InitializeICU();
#endif
DCHECK(!base::MessageLoop::current());
DCHECK(!g_main_message_loop);
g_main_message_loop = new base::MessageLoopForUI();
base::MessageLoopForUI::current()->Start();
DCHECK(!g_network_change_notifier);
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
g_network_change_notifier = net::NetworkChangeNotifier::Create();
}
} // namespace cronet
<commit_msg>[Cronet] fix NoClassDefFoundError crash<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cronet/android/cronet_library_loader.h"
#include <jni.h>
#include "base/android/base_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/android/jni_utils.h"
#include "base/at_exit.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "components/cronet/android/chromium_url_request.h"
#include "components/cronet/android/chromium_url_request_context.h"
#include "components/cronet/android/cronet_histogram_manager.h"
#include "components/cronet/android/cronet_upload_data_stream_delegate.h"
#include "components/cronet/android/cronet_url_request.h"
#include "components/cronet/android/cronet_url_request_context_adapter.h"
#include "jni/CronetLibraryLoader_jni.h"
#include "net/android/net_jni_registrar.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "url/android/url_jni_registrar.h"
#include "url/url_util.h"
#if !defined(USE_ICU_ALTERNATIVES_ON_ANDROID)
#include "base/i18n/icu_util.h"
#endif
namespace cronet {
namespace {
const base::android::RegistrationMethod kCronetRegisteredMethods[] = {
{"BaseAndroid", base::android::RegisterJni},
{"ChromiumUrlRequest", ChromiumUrlRequestRegisterJni},
{"ChromiumUrlRequestContext", ChromiumUrlRequestContextRegisterJni},
{"CronetHistogramManager", CronetHistogramManagerRegisterJni},
{"CronetLibraryLoader", RegisterNativesImpl},
{"CronetUploadDataStreamDelegate",
CronetUploadDataStreamDelegateRegisterJni},
{"CronetUrlRequest", CronetUrlRequestRegisterJni},
{"CronetUrlRequestContextAdapter",
CronetUrlRequestContextAdapterRegisterJni},
{"NetAndroid", net::android::RegisterJni},
{"UrlAndroid", url::android::RegisterJni},
};
base::AtExitManager* g_at_exit_manager = NULL;
// MessageLoop on the main thread, which is where objects that receive Java
// notifications generally live.
base::MessageLoop* g_main_message_loop = nullptr;
net::NetworkChangeNotifier* g_network_change_notifier = nullptr;
} // namespace
// Checks the available version of JNI. Also, caches Java reflection artifacts.
jint CronetOnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
base::android::InitVM(vm);
if (!base::android::RegisterNativeMethods(
env, kCronetRegisteredMethods, arraysize(kCronetRegisteredMethods))) {
return -1;
}
g_at_exit_manager = new base::AtExitManager();
base::android::InitReplacementClassLoader(env,
base::android::GetClassLoader(env));
url::Initialize();
return JNI_VERSION_1_6;
}
void CronetOnUnLoad(JavaVM* jvm, void* reserved) {
if (g_at_exit_manager) {
delete g_at_exit_manager;
g_at_exit_manager = NULL;
}
}
void CronetInitOnMainThread(JNIEnv* env, jclass jcaller, jobject jcontext) {
// Set application context.
base::android::ScopedJavaLocalRef<jobject> scoped_context(env, jcontext);
base::android::InitApplicationContext(env, scoped_context);
#if !defined(USE_ICU_ALTERNATIVES_ON_ANDROID)
base::i18n::InitializeICU();
#endif
DCHECK(!base::MessageLoop::current());
DCHECK(!g_main_message_loop);
g_main_message_loop = new base::MessageLoopForUI();
base::MessageLoopForUI::current()->Start();
DCHECK(!g_network_change_notifier);
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
g_network_change_notifier = net::NetworkChangeNotifier::Create();
}
} // namespace cronet
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.cpp
* CollisionPrevention controller.
*
*/
#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;
CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
ModuleParams(parent)
{
}
CollisionPrevention::~CollisionPrevention()
{
//unadvertise publishers
if (_mavlink_log_pub != nullptr) {
orb_unadvertise(_mavlink_log_pub);
}
}
void CollisionPrevention::_publishConstrainedSetpoint(const Vector2f &original_setpoint,
const Vector2f &adapted_setpoint)
{
collision_constraints_s constraints{}; /**< collision constraints message */
//fill in values
constraints.timestamp = hrt_absolute_time();
constraints.original_setpoint[0] = original_setpoint(0);
constraints.original_setpoint[1] = original_setpoint(1);
constraints.adapted_setpoint[0] = adapted_setpoint(0);
constraints.adapted_setpoint[1] = adapted_setpoint(1);
// publish constraints
if (_constraints_pub != nullptr) {
orb_publish(ORB_ID(collision_constraints), _constraints_pub, &constraints);
} else {
_constraints_pub = orb_advertise(ORB_ID(collision_constraints), &constraints);
}
}
void CollisionPrevention::_publishObstacleDistance(obstacle_distance_s &obstacle)
{
// publish fused obtacle distance message with data from offboard obstacle_distance and distance sensor
if (_obstacle_distance_pub != nullptr) {
orb_publish(ORB_ID(obstacle_distance_fused), _obstacle_distance_pub, &obstacle);
} else {
_obstacle_distance_pub = orb_advertise(ORB_ID(obstacle_distance_fused), &obstacle);
}
}
void CollisionPrevention::_updateOffboardObstacleDistance(obstacle_distance_s &obstacle)
{
_sub_obstacle_distance.update();
const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance.get();
// Update with offboard data if the data is not stale
if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US) {
obstacle = obstacle_distance;
}
}
void CollisionPrevention::_updateDistanceSensor(obstacle_distance_s &obstacle)
{
for (unsigned i = 0; i < ORB_MULTI_MAX_INSTANCES; i++) {
distance_sensor_s distance_sensor;
_sub_distance_sensor[i].copy(&distance_sensor);
// consider only instaces with updated, valid data and orientations useful for collision prevention
if ((hrt_elapsed_time(&distance_sensor.timestamp) < RANGE_STREAM_TIMEOUT_US) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_DOWNWARD_FACING) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_UPWARD_FACING)) {
if (obstacle.increment > 0) {
// data from companion
obstacle.timestamp = math::max(obstacle.timestamp, distance_sensor.timestamp);
obstacle.max_distance = math::max((int)obstacle.max_distance,
(int)distance_sensor.max_distance * 100);
obstacle.min_distance = math::min((int)obstacle.min_distance,
(int)distance_sensor.min_distance * 100);
// since the data from the companion are already in the distances data structure,
// keep the increment that is sent
obstacle.angle_offset = 0.f; //companion not sending this field (needs mavros update)
} else {
obstacle.timestamp = distance_sensor.timestamp;
obstacle.max_distance = distance_sensor.max_distance * 100; // convert to cm
obstacle.min_distance = distance_sensor.min_distance * 100; // convert to cm
memset(&obstacle.distances[0], 0xff, sizeof(obstacle.distances));
obstacle.increment = math::degrees(distance_sensor.h_fov);
obstacle.angle_offset = 0.f;
}
if ((distance_sensor.current_distance > distance_sensor.min_distance) &&
(distance_sensor.current_distance < distance_sensor.max_distance)) {
float sensor_yaw_body_rad = _sensorOrientationToYawOffset(distance_sensor, obstacle.angle_offset);
matrix::Quatf attitude = Quatf(_sub_vehicle_attitude.get().q);
// convert the sensor orientation from body to local frame in the range [0, 360]
float sensor_yaw_local_deg = math::degrees(wrap_2pi(Eulerf(attitude).psi() + sensor_yaw_body_rad));
// calculate the field of view boundary bin indices
int lower_bound = (int)floor((sensor_yaw_local_deg - math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
int upper_bound = (int)floor((sensor_yaw_local_deg + math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
// if increment is lower than 5deg, use an offset
const int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
if (((lower_bound < 0 || upper_bound < 0) || (lower_bound >= distances_array_size
|| upper_bound >= distances_array_size)) && obstacle.increment < 5.f) {
obstacle.angle_offset = sensor_yaw_local_deg ;
upper_bound = abs(upper_bound - lower_bound);
lower_bound = 0;
}
// rotate vehicle attitude into the sensor body frame
matrix::Quatf attitude_sensor_frame = attitude;
attitude_sensor_frame.rotate(Vector3f(0.f, 0.f, sensor_yaw_body_rad));
float attitude_sensor_frame_pitch = cosf(Eulerf(attitude_sensor_frame).theta());
for (int bin = lower_bound; bin <= upper_bound; ++bin) {
int wrap_bin = bin;
if (wrap_bin < 0) {
// wrap bin index around the array
wrap_bin = (int)floor(360.f / obstacle.increment) + bin;
}
if (wrap_bin >= distances_array_size) {
// wrap bin index around the array
wrap_bin = bin - distances_array_size;
}
// compensate measurement for vehicle tilt and convert to cm
obstacle.distances[wrap_bin] = math::min((int)obstacle.distances[wrap_bin],
(int)(100 * distance_sensor.current_distance * attitude_sensor_frame_pitch));
}
}
}
}
_publishObstacleDistance(obstacle);
}
void CollisionPrevention::_calculateConstrainedSetpoint(Vector2f &setpoint,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
obstacle_distance_s obstacle{};
_updateOffboardObstacleDistance(obstacle);
_updateDistanceSensor(obstacle);
//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
//that way the root does not have to be calculated for every range bin but once at the end.
float setpoint_length = setpoint.norm();
Vector2f setpoint_sqrd = setpoint * setpoint_length;
//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
float max_slide_angle_rad = 0.5f;
if (hrt_elapsed_time(&obstacle.timestamp) < RANGE_STREAM_TIMEOUT_US) {
if (setpoint_length > 0.001f) {
int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
for (int i = 0; i < distances_array_size; i++) {
if (obstacle.distances[i] < obstacle.max_distance &&
obstacle.distances[i] > obstacle.min_distance && (float)i * obstacle.increment < 360.f) {
float distance = obstacle.distances[i] / 100.0f; //convert to meters
float angle = math::radians((float)i * obstacle.increment);
if (obstacle.angle_offset > 0.f) {
angle += math::radians(obstacle.angle_offset);
}
//split current setpoint into parallel and orthogonal components with respect to the current bin direction
Vector2f bin_direction = {cos(angle), sin(angle)};
Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
float sp_parallel = setpoint_sqrd.dot(bin_direction);
float sp_orth = setpoint_sqrd.dot(orth_direction);
float curr_vel_parallel = math::max(0.f, curr_vel.dot(bin_direction));
//calculate max allowed velocity with a P-controller (same gain as in the position controller)
float delay_distance = curr_vel_parallel * _param_mpc_col_prev_dly.get();
float vel_max_posctrl = math::max(0.f,
_param_mpc_xy_p.get() * (distance - _param_mpc_col_prev_d.get() - delay_distance));
float vel_max_sqrd = vel_max_posctrl * vel_max_posctrl;
//limit the setpoint to respect vel_max by subtracting from the parallel component
if (sp_parallel > vel_max_sqrd) {
Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
float setpoint_temp_length = setpoint_temp.norm();
//limit sliding angle
float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);
if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);
if (sp_orth > 0) {
setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;
} else {
setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
}
}
setpoint_sqrd = setpoint_temp;
}
}
}
//take the squared root
if (setpoint_sqrd.norm() > 0.001f) {
setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());
} else {
setpoint.zero();
}
}
} else {
// if distance data are stale, switch to Loiter
_publishVehicleCmdDoLoiter();
mavlink_log_critical(&_mavlink_log_pub, "No range data received, loitering.");
}
}
void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
//calculate movement constraints based on range data
Vector2f new_setpoint = original_setpoint;
_calculateConstrainedSetpoint(new_setpoint, curr_pos, curr_vel);
//warn user if collision prevention starts to interfere
bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
|| new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
|| new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
|| new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);
if (currently_interfering && (currently_interfering != _interfering)) {
mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
}
_interfering = currently_interfering;
_publishConstrainedSetpoint(original_setpoint, new_setpoint);
original_setpoint = new_setpoint;
}
void CollisionPrevention::_publishVehicleCmdDoLoiter()
{
vehicle_command_s command{};
command.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
command.param1 = (float)1; // base mode
command.param3 = (float)0; // sub mode
command.target_system = 1;
command.target_component = 1;
command.source_system = 1;
command.source_component = 1;
command.confirmation = false;
command.from_external = false;
command.param2 = (float)PX4_CUSTOM_MAIN_MODE_AUTO;
command.param3 = (float)PX4_CUSTOM_SUB_MODE_AUTO_LOITER;
// publish the vehicle command
if (_pub_vehicle_command == nullptr) {
_pub_vehicle_command = orb_advertise_queue(ORB_ID(vehicle_command), &command,
vehicle_command_s::ORB_QUEUE_LENGTH);
} else {
orb_publish(ORB_ID(vehicle_command), _pub_vehicle_command, &command);
}
}
<commit_msg>CollisionPrevention only process distance_sensor updates<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.cpp
* CollisionPrevention controller.
*
*/
#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;
CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
ModuleParams(parent)
{
}
CollisionPrevention::~CollisionPrevention()
{
//unadvertise publishers
if (_mavlink_log_pub != nullptr) {
orb_unadvertise(_mavlink_log_pub);
}
}
void CollisionPrevention::_publishConstrainedSetpoint(const Vector2f &original_setpoint,
const Vector2f &adapted_setpoint)
{
collision_constraints_s constraints{}; /**< collision constraints message */
//fill in values
constraints.timestamp = hrt_absolute_time();
constraints.original_setpoint[0] = original_setpoint(0);
constraints.original_setpoint[1] = original_setpoint(1);
constraints.adapted_setpoint[0] = adapted_setpoint(0);
constraints.adapted_setpoint[1] = adapted_setpoint(1);
// publish constraints
if (_constraints_pub != nullptr) {
orb_publish(ORB_ID(collision_constraints), _constraints_pub, &constraints);
} else {
_constraints_pub = orb_advertise(ORB_ID(collision_constraints), &constraints);
}
}
void CollisionPrevention::_publishObstacleDistance(obstacle_distance_s &obstacle)
{
// publish fused obtacle distance message with data from offboard obstacle_distance and distance sensor
if (_obstacle_distance_pub != nullptr) {
orb_publish(ORB_ID(obstacle_distance_fused), _obstacle_distance_pub, &obstacle);
} else {
_obstacle_distance_pub = orb_advertise(ORB_ID(obstacle_distance_fused), &obstacle);
}
}
void CollisionPrevention::_updateOffboardObstacleDistance(obstacle_distance_s &obstacle)
{
_sub_obstacle_distance.update();
const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance.get();
// Update with offboard data if the data is not stale
if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US) {
obstacle = obstacle_distance;
}
}
void CollisionPrevention::_updateDistanceSensor(obstacle_distance_s &obstacle)
{
for (unsigned i = 0; i < ORB_MULTI_MAX_INSTANCES; i++) {
distance_sensor_s distance_sensor;
if (_sub_distance_sensor[i].update(&distance_sensor)) {
// consider only instaces with updated, valid data and orientations useful for collision prevention
if ((hrt_elapsed_time(&distance_sensor.timestamp) < RANGE_STREAM_TIMEOUT_US) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_DOWNWARD_FACING) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_UPWARD_FACING)) {
if (obstacle.increment > 0) {
// data from companion
obstacle.timestamp = math::max(obstacle.timestamp, distance_sensor.timestamp);
obstacle.max_distance = math::max((int)obstacle.max_distance,
(int)distance_sensor.max_distance * 100);
obstacle.min_distance = math::min((int)obstacle.min_distance,
(int)distance_sensor.min_distance * 100);
// since the data from the companion are already in the distances data structure,
// keep the increment that is sent
obstacle.angle_offset = 0.f; //companion not sending this field (needs mavros update)
} else {
obstacle.timestamp = distance_sensor.timestamp;
obstacle.max_distance = distance_sensor.max_distance * 100; // convert to cm
obstacle.min_distance = distance_sensor.min_distance * 100; // convert to cm
memset(&obstacle.distances[0], 0xff, sizeof(obstacle.distances));
obstacle.increment = math::degrees(distance_sensor.h_fov);
obstacle.angle_offset = 0.f;
}
if ((distance_sensor.current_distance > distance_sensor.min_distance) &&
(distance_sensor.current_distance < distance_sensor.max_distance)) {
float sensor_yaw_body_rad = _sensorOrientationToYawOffset(distance_sensor, obstacle.angle_offset);
matrix::Quatf attitude = Quatf(_sub_vehicle_attitude.get().q);
// convert the sensor orientation from body to local frame in the range [0, 360]
float sensor_yaw_local_deg = math::degrees(wrap_2pi(Eulerf(attitude).psi() + sensor_yaw_body_rad));
// calculate the field of view boundary bin indices
int lower_bound = (int)floor((sensor_yaw_local_deg - math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
int upper_bound = (int)floor((sensor_yaw_local_deg + math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
// if increment is lower than 5deg, use an offset
const int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
if (((lower_bound < 0 || upper_bound < 0) || (lower_bound >= distances_array_size
|| upper_bound >= distances_array_size)) && obstacle.increment < 5.f) {
obstacle.angle_offset = sensor_yaw_local_deg ;
upper_bound = abs(upper_bound - lower_bound);
lower_bound = 0;
}
// rotate vehicle attitude into the sensor body frame
matrix::Quatf attitude_sensor_frame = attitude;
attitude_sensor_frame.rotate(Vector3f(0.f, 0.f, sensor_yaw_body_rad));
float attitude_sensor_frame_pitch = cosf(Eulerf(attitude_sensor_frame).theta());
for (int bin = lower_bound; bin <= upper_bound; ++bin) {
int wrap_bin = bin;
if (wrap_bin < 0) {
// wrap bin index around the array
wrap_bin = (int)floor(360.f / obstacle.increment) + bin;
}
if (wrap_bin >= distances_array_size) {
// wrap bin index around the array
wrap_bin = bin - distances_array_size;
}
// compensate measurement for vehicle tilt and convert to cm
obstacle.distances[wrap_bin] = math::min((int)obstacle.distances[wrap_bin],
(int)(100 * distance_sensor.current_distance * attitude_sensor_frame_pitch));
}
}
}
}
}
_publishObstacleDistance(obstacle);
}
void CollisionPrevention::_calculateConstrainedSetpoint(Vector2f &setpoint,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
obstacle_distance_s obstacle{};
_updateOffboardObstacleDistance(obstacle);
_updateDistanceSensor(obstacle);
//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
//that way the root does not have to be calculated for every range bin but once at the end.
float setpoint_length = setpoint.norm();
Vector2f setpoint_sqrd = setpoint * setpoint_length;
//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
float max_slide_angle_rad = 0.5f;
if (hrt_elapsed_time(&obstacle.timestamp) < RANGE_STREAM_TIMEOUT_US) {
if (setpoint_length > 0.001f) {
int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
for (int i = 0; i < distances_array_size; i++) {
if (obstacle.distances[i] < obstacle.max_distance &&
obstacle.distances[i] > obstacle.min_distance && (float)i * obstacle.increment < 360.f) {
float distance = obstacle.distances[i] / 100.0f; //convert to meters
float angle = math::radians((float)i * obstacle.increment);
if (obstacle.angle_offset > 0.f) {
angle += math::radians(obstacle.angle_offset);
}
//split current setpoint into parallel and orthogonal components with respect to the current bin direction
Vector2f bin_direction = {cos(angle), sin(angle)};
Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
float sp_parallel = setpoint_sqrd.dot(bin_direction);
float sp_orth = setpoint_sqrd.dot(orth_direction);
float curr_vel_parallel = math::max(0.f, curr_vel.dot(bin_direction));
//calculate max allowed velocity with a P-controller (same gain as in the position controller)
float delay_distance = curr_vel_parallel * _param_mpc_col_prev_dly.get();
float vel_max_posctrl = math::max(0.f,
_param_mpc_xy_p.get() * (distance - _param_mpc_col_prev_d.get() - delay_distance));
float vel_max_sqrd = vel_max_posctrl * vel_max_posctrl;
//limit the setpoint to respect vel_max by subtracting from the parallel component
if (sp_parallel > vel_max_sqrd) {
Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
float setpoint_temp_length = setpoint_temp.norm();
//limit sliding angle
float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);
if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);
if (sp_orth > 0) {
setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;
} else {
setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
}
}
setpoint_sqrd = setpoint_temp;
}
}
}
//take the squared root
if (setpoint_sqrd.norm() > 0.001f) {
setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());
} else {
setpoint.zero();
}
}
} else {
// if distance data are stale, switch to Loiter
_publishVehicleCmdDoLoiter();
mavlink_log_critical(&_mavlink_log_pub, "No range data received, loitering.");
}
}
void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
//calculate movement constraints based on range data
Vector2f new_setpoint = original_setpoint;
_calculateConstrainedSetpoint(new_setpoint, curr_pos, curr_vel);
//warn user if collision prevention starts to interfere
bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
|| new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
|| new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
|| new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);
if (currently_interfering && (currently_interfering != _interfering)) {
mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
}
_interfering = currently_interfering;
_publishConstrainedSetpoint(original_setpoint, new_setpoint);
original_setpoint = new_setpoint;
}
void CollisionPrevention::_publishVehicleCmdDoLoiter()
{
vehicle_command_s command{};
command.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
command.param1 = (float)1; // base mode
command.param3 = (float)0; // sub mode
command.target_system = 1;
command.target_component = 1;
command.source_system = 1;
command.source_component = 1;
command.confirmation = false;
command.from_external = false;
command.param2 = (float)PX4_CUSTOM_MAIN_MODE_AUTO;
command.param3 = (float)PX4_CUSTOM_SUB_MODE_AUTO_LOITER;
// publish the vehicle command
if (_pub_vehicle_command == nullptr) {
_pub_vehicle_command = orb_advertise_queue(ORB_ID(vehicle_command), &command,
vehicle_command_s::ORB_QUEUE_LENGTH);
} else {
orb_publish(ORB_ID(vehicle_command), _pub_vehicle_command, &command);
}
}
<|endoftext|>
|
<commit_before>#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/errqueue.h>
#include <linux/icmp.h>
#include <sys/socket.h>
#include <sys/time.h>
#include "udpping.h"
namespace
{
bool getAddress(const QString &address, sockaddr_any *addr)
{
struct addrinfo hints;
struct addrinfo *rp = NULL, *result = NULL;
memset(&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result))
{
return false;
}
for (rp = result; rp && rp->ai_family != AF_INET; rp = rp->ai_next)
{
}
if (!rp)
{
rp = result;
}
memcpy(addr, rp->ai_addr, rp->ai_addrlen);
freeaddrinfo(result);
return true;
}
void randomizePayload(char *payload, const quint32 size)
{
char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for (quint32 i = 0; i < size; i++)
{
payload[i] = chars[qrand() % strlen(chars)];
}
if (size > 15)
{
// ignore terminating null character
strncpy(&payload[size - 15], " measure-it.net", 15);
}
}
}
UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress()
, m_payload(NULL)
{
}
UdpPing::~UdpPing()
{
}
Measurement::Status UdpPing::status() const
{
return currentStatus;
}
void UdpPing::setStatus(Status status)
{
if (currentStatus != status)
{
currentStatus = status;
emit statusChanged(status);
}
}
bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition)
{
Q_UNUSED(networkManager);
definition = measurementDefinition.dynamicCast<UdpPingDefinition>();
memset(&m_destAddress, 0, sizeof(m_destAddress));
// resolve
if (!getAddress(definition->url, &m_destAddress))
{
return false;
}
m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
return true;
}
bool UdpPing::start()
{
PingProbe probe;
// include null-character
m_payload = new char[definition->payload + 1];
if (m_payload == NULL)
{
return false;
}
memset(m_payload, 0, definition->payload + 1);
setStartDateTime(QDateTime::currentDateTime());
setStatus(UdpPing::Running);
memset(&probe, 0, sizeof(probe));
probe.sock = initSocket();
if (probe.sock < 0)
{
emit error("socket: " + QString(strerror(errno)));
free(m_payload);
return false;
}
for (quint32 i = 0; i < definition->count; i++)
{
ping(&probe);
m_pingProbes.append(probe);
}
close(probe.sock);
setStatus(UdpPing::Finished);
free(m_payload);
emit finished();
return true;
}
bool UdpPing::stop()
{
return true;
}
ResultPtr UdpPing::result() const
{
QVariantList res;
foreach (const PingProbe &probe, m_pingProbes)
{
if (probe.sendTime > 0 && probe.recvTime > 0)
{
res << probe.recvTime - probe.sendTime;
}
}
return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant()));
}
int UdpPing::initSocket()
{
int n = 0;
int sock = 0;
int ttl = definition->ttl ? definition->ttl : 64;
sockaddr_any src_addr;
memset(&src_addr, 0, sizeof(src_addr));
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock < 0)
{
emit error("socket: " + QString(strerror(errno)));
return -1;
}
src_addr.sa.sa_family = AF_INET;
src_addr.sin.sin_port = htons(definition->sourcePort);
if (bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr)) < 0)
{
emit error("bind: " + QString(strerror(errno)));
goto cleanup;
}
n = 1;
if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0)
{
emit error("setsockopt SOL_TIMESTAMP: " + QString(strerror(errno)));
goto cleanup;
}
// set TTL
if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
{
emit error("setsockopt IP_TTL: " + QString(strerror(errno)));
goto cleanup;
}
if (::connect(sock, (struct sockaddr *) &m_destAddress, sizeof(m_destAddress)) < 0)
{
emit error("connect: " + QString(strerror(errno)));
goto cleanup;
}
// use RECVRR
n = 1;
if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0)
{
emit error("setsockopt IP_RECVERR: " + QString(strerror(errno)));
goto cleanup;
}
return sock;
cleanup:
close(sock);
return -1;
}
bool UdpPing::sendData(PingProbe *probe)
{
struct timeval tv;
memset(&tv, 0, sizeof(tv));
gettimeofday(&tv, NULL);
probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec;
// randomize payload to prevent caching
randomizePayload(m_payload, definition->payload);
if (send(probe->sock, m_payload, definition->payload, 0) < 0)
{
emit error("send: " + QString(strerror(errno)));
return false;
}
return true;
}
void UdpPing::receiveData(PingProbe *probe)
{
struct msghdr msg;
sockaddr_any from;
struct iovec iov;
char buf[1280];
char control[1024];
struct cmsghdr *cm;
struct sock_extended_err *ee = NULL;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &from;
msg.msg_namelen = sizeof(from);
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
iov.iov_base = buf;
iov.iov_len = sizeof(buf);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
// poll here
struct pollfd pfd;
memset(&pfd, 0, sizeof(pfd));
pfd.fd = probe->sock;
pfd.events = POLLIN | POLLERR;
if (poll(&pfd, 1, definition->receiveTimeout) < 0)
{
emit error("poll: " + QString(strerror(errno)));
goto cleanup;
}
if (!pfd.revents)
{
emit timeout(*probe);
goto cleanup;
}
if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0)
{
emit error("recvmsg: " + QString(strerror(errno)));
goto cleanup;
}
for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm))
{
void *ptr = CMSG_DATA(cm);
if (cm->cmsg_level == SOL_SOCKET)
{
if (cm->cmsg_type == SO_TIMESTAMP)
{
struct timeval *tv = (struct timeval *) ptr;
probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec;
}
}
else if (cm->cmsg_level == SOL_IP)
{
if (cm->cmsg_type == IP_RECVERR)
{
ee = (struct sock_extended_err *) ptr;
if (ee->ee_origin != SO_EE_ORIGIN_ICMP)
{
ee = NULL;
}
if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT)
{
goto cleanup;
}
}
}
}
if (ee)
{
memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source));
if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL)
{
emit ttlExceeded(*probe);
} else if (ee->ee_type == ICMP_DEST_UNREACH)
{
emit destinationUnreachable(*probe);
}
}
cleanup:
return;
}
void UdpPing::ping(PingProbe *probe)
{
// send
if (sendData(probe))
{
receiveData(probe);
}
}
// vim: set sts=4 sw=4 et:
<commit_msg>udpping: fix possible NPE<commit_after>#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/errqueue.h>
#include <linux/icmp.h>
#include <sys/socket.h>
#include <sys/time.h>
#include "udpping.h"
namespace
{
bool getAddress(const QString &address, sockaddr_any *addr)
{
struct addrinfo hints;
struct addrinfo *rp = NULL, *result = NULL;
memset(&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result))
{
return false;
}
for (rp = result; rp && rp->ai_family != AF_INET; rp = rp->ai_next)
{
}
if (!rp)
{
rp = result;
}
memcpy(addr, rp->ai_addr, rp->ai_addrlen);
freeaddrinfo(result);
return true;
}
void randomizePayload(char *payload, const quint32 size)
{
char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for (quint32 i = 0; i < size; i++)
{
payload[i] = chars[qrand() % strlen(chars)];
}
if (size > 15)
{
// ignore terminating null character
strncpy(&payload[size - 15], " measure-it.net", 15);
}
}
}
UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress()
, m_payload(NULL)
{
}
UdpPing::~UdpPing()
{
}
Measurement::Status UdpPing::status() const
{
return currentStatus;
}
void UdpPing::setStatus(Status status)
{
if (currentStatus != status)
{
currentStatus = status;
emit statusChanged(status);
}
}
bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition)
{
Q_UNUSED(networkManager);
definition = measurementDefinition.dynamicCast<UdpPingDefinition>();
memset(&m_destAddress, 0, sizeof(m_destAddress));
// resolve
if (!getAddress(definition->url, &m_destAddress))
{
return false;
}
m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434);
return true;
}
bool UdpPing::start()
{
PingProbe probe;
// include null-character
m_payload = new char[definition->payload + 1];
if (m_payload == NULL)
{
return false;
}
memset(m_payload, 0, definition->payload + 1);
setStartDateTime(QDateTime::currentDateTime());
setStatus(UdpPing::Running);
memset(&probe, 0, sizeof(probe));
probe.sock = initSocket();
if (probe.sock < 0)
{
emit error("socket: " + QString(strerror(errno)));
free(m_payload);
return false;
}
for (quint32 i = 0; i < definition->count; i++)
{
ping(&probe);
m_pingProbes.append(probe);
}
close(probe.sock);
setStatus(UdpPing::Finished);
free(m_payload);
emit finished();
return true;
}
bool UdpPing::stop()
{
return true;
}
ResultPtr UdpPing::result() const
{
QVariantList res;
foreach (const PingProbe &probe, m_pingProbes)
{
if (probe.sendTime > 0 && probe.recvTime > 0)
{
res << probe.recvTime - probe.sendTime;
}
}
return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant()));
}
int UdpPing::initSocket()
{
int n = 0;
int sock = 0;
int ttl = definition->ttl ? definition->ttl : 64;
sockaddr_any src_addr;
memset(&src_addr, 0, sizeof(src_addr));
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock < 0)
{
emit error("socket: " + QString(strerror(errno)));
return -1;
}
src_addr.sa.sa_family = AF_INET;
src_addr.sin.sin_port = htons(definition->sourcePort);
if (bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr)) < 0)
{
emit error("bind: " + QString(strerror(errno)));
goto cleanup;
}
n = 1;
if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0)
{
emit error("setsockopt SOL_TIMESTAMP: " + QString(strerror(errno)));
goto cleanup;
}
// set TTL
if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
{
emit error("setsockopt IP_TTL: " + QString(strerror(errno)));
goto cleanup;
}
if (::connect(sock, (struct sockaddr *) &m_destAddress, sizeof(m_destAddress)) < 0)
{
emit error("connect: " + QString(strerror(errno)));
goto cleanup;
}
// use RECVRR
n = 1;
if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0)
{
emit error("setsockopt IP_RECVERR: " + QString(strerror(errno)));
goto cleanup;
}
return sock;
cleanup:
close(sock);
return -1;
}
bool UdpPing::sendData(PingProbe *probe)
{
struct timeval tv;
memset(&tv, 0, sizeof(tv));
gettimeofday(&tv, NULL);
probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec;
// randomize payload to prevent caching
randomizePayload(m_payload, definition->payload);
if (send(probe->sock, m_payload, definition->payload, 0) < 0)
{
emit error("send: " + QString(strerror(errno)));
return false;
}
return true;
}
void UdpPing::receiveData(PingProbe *probe)
{
struct msghdr msg;
sockaddr_any from;
struct iovec iov;
char buf[1280];
char control[1024];
struct cmsghdr *cm;
struct sock_extended_err *ee = NULL;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &from;
msg.msg_namelen = sizeof(from);
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
iov.iov_base = buf;
iov.iov_len = sizeof(buf);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
// poll here
struct pollfd pfd;
memset(&pfd, 0, sizeof(pfd));
pfd.fd = probe->sock;
pfd.events = POLLIN | POLLERR;
if (poll(&pfd, 1, definition->receiveTimeout) < 0)
{
emit error("poll: " + QString(strerror(errno)));
goto cleanup;
}
if (!pfd.revents)
{
emit timeout(*probe);
goto cleanup;
}
if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0)
{
emit error("recvmsg: " + QString(strerror(errno)));
goto cleanup;
}
for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm))
{
void *ptr = CMSG_DATA(cm);
if (cm->cmsg_level == SOL_SOCKET)
{
if (cm->cmsg_type == SO_TIMESTAMP)
{
struct timeval *tv = (struct timeval *) ptr;
probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec;
}
}
else if (cm->cmsg_level == SOL_IP)
{
if (cm->cmsg_type == IP_RECVERR)
{
ee = (struct sock_extended_err *) ptr;
if (ee->ee_origin != SO_EE_ORIGIN_ICMP)
{
ee = NULL;
continue;
}
if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT)
{
goto cleanup;
}
}
}
}
if (ee)
{
memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source));
if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL)
{
emit ttlExceeded(*probe);
} else if (ee->ee_type == ICMP_DEST_UNREACH)
{
emit destinationUnreachable(*probe);
}
}
cleanup:
return;
}
void UdpPing::ping(PingProbe *probe)
{
// send
if (sendData(probe))
{
receiveData(probe);
}
}
// vim: set sts=4 sw=4 et:
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "common_types.h" // NOLINT(build/include)
#include <string.h>
#include <algorithm>
#include <limits>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/stringutils.h"
namespace webrtc {
VideoCodec::VideoCodec()
: codecType(kVideoCodecUnknown),
plName(),
plType(0),
width(0),
height(0),
startBitrate(0),
maxBitrate(0),
minBitrate(0),
targetBitrate(0),
maxFramerate(0),
active(true),
qpMax(0),
numberOfSimulcastStreams(0),
simulcastStream(),
spatialLayers(),
mode(kRealtimeVideo),
expect_encode_from_texture(false),
timing_frame_thresholds({0, 0}),
codec_specific_() {}
VideoCodecVP8* VideoCodec::VP8() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return &codec_specific_.VP8;
}
const VideoCodecVP8& VideoCodec::VP8() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return codec_specific_.VP8;
}
VideoCodecVP9* VideoCodec::VP9() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return &codec_specific_.VP9;
}
const VideoCodecVP9& VideoCodec::VP9() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return codec_specific_.VP9;
}
VideoCodecH264* VideoCodec::H264() {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return &codec_specific_.H264;
}
const VideoCodecH264& VideoCodec::H264() const {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return codec_specific_.H264;
}
static const char* kPayloadNameVp8 = "VP8";
static const char* kPayloadNameVp9 = "VP9";
static const char* kPayloadNameH264 = "H264";
static const char* kPayloadNameI420 = "I420";
static const char* kPayloadNameRED = "RED";
static const char* kPayloadNameULPFEC = "ULPFEC";
static const char* kPayloadNameGeneric = "Generic";
static const char* kPayloadNameMultiplex = "Multiplex";
static bool CodecNamesEq(const char* name1, const char* name2) {
return _stricmp(name1, name2) == 0;
}
const char* CodecTypeToPayloadString(VideoCodecType type) {
switch (type) {
case kVideoCodecVP8:
return kPayloadNameVp8;
case kVideoCodecVP9:
return kPayloadNameVp9;
case kVideoCodecH264:
return kPayloadNameH264;
case kVideoCodecI420:
return kPayloadNameI420;
case kVideoCodecRED:
return kPayloadNameRED;
case kVideoCodecULPFEC:
return kPayloadNameULPFEC;
// Other codecs default to generic.
case kVideoCodecMultiplex:
case kVideoCodecFlexfec:
case kVideoCodecGeneric:
case kVideoCodecUnknown:
return kPayloadNameGeneric;
}
return kPayloadNameGeneric;
}
VideoCodecType PayloadStringToCodecType(const std::string& name) {
if (CodecNamesEq(name.c_str(), kPayloadNameVp8))
return kVideoCodecVP8;
if (CodecNamesEq(name.c_str(), kPayloadNameVp9))
return kVideoCodecVP9;
if (CodecNamesEq(name.c_str(), kPayloadNameH264))
return kVideoCodecH264;
if (CodecNamesEq(name.c_str(), kPayloadNameI420))
return kVideoCodecI420;
if (CodecNamesEq(name.c_str(), kPayloadNameRED))
return kVideoCodecRED;
if (CodecNamesEq(name.c_str(), kPayloadNameULPFEC))
return kVideoCodecULPFEC;
if (CodecNamesEq(name.c_str(), kPayloadNameMultiplex))
return kVideoCodecMultiplex;
return kVideoCodecGeneric;
}
const uint32_t BitrateAllocation::kMaxBitrateBps =
std::numeric_limits<uint32_t>::max();
BitrateAllocation::BitrateAllocation() : sum_(0), bitrates_{}, has_bitrate_{} {}
bool BitrateAllocation::SetBitrate(size_t spatial_index,
size_t temporal_index,
uint32_t bitrate_bps) {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
RTC_CHECK_LE(bitrates_[spatial_index][temporal_index], sum_);
uint64_t new_bitrate_sum_bps = sum_;
new_bitrate_sum_bps -= bitrates_[spatial_index][temporal_index];
new_bitrate_sum_bps += bitrate_bps;
if (new_bitrate_sum_bps > kMaxBitrateBps)
return false;
bitrates_[spatial_index][temporal_index] = bitrate_bps;
has_bitrate_[spatial_index][temporal_index] = true;
sum_ = static_cast<uint32_t>(new_bitrate_sum_bps);
return true;
}
bool BitrateAllocation::HasBitrate(size_t spatial_index,
size_t temporal_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
return has_bitrate_[spatial_index][temporal_index];
}
uint32_t BitrateAllocation::GetBitrate(size_t spatial_index,
size_t temporal_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
return bitrates_[spatial_index][temporal_index];
}
// Whether the specific spatial layers has the bitrate set in any of its
// temporal layers.
bool BitrateAllocation::IsSpatialLayerUsed(size_t spatial_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
for (int i = 0; i < kMaxTemporalStreams; ++i) {
if (has_bitrate_[spatial_index][i])
return true;
}
return false;
}
// Get the sum of all the temporal layer for a specific spatial layer.
uint32_t BitrateAllocation::GetSpatialLayerSum(size_t spatial_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
uint32_t sum = 0;
for (int i = 0; i < kMaxTemporalStreams; ++i)
sum += bitrates_[spatial_index][i];
return sum;
}
std::string BitrateAllocation::ToString() const {
if (sum_ == 0)
return "BitrateAllocation [ [] ]";
// TODO(sprang): Replace this stringstream with something cheaper.
std::ostringstream oss;
oss << "BitrateAllocation [";
uint32_t spatial_cumulator = 0;
for (int si = 0; si < kMaxSpatialLayers; ++si) {
RTC_DCHECK_LE(spatial_cumulator, sum_);
if (spatial_cumulator == sum_)
break;
const uint32_t layer_sum = GetSpatialLayerSum(si);
if (layer_sum == sum_) {
oss << " [";
} else {
if (si > 0)
oss << ",";
oss << std::endl << " [";
}
spatial_cumulator += layer_sum;
uint32_t temporal_cumulator = 0;
for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
RTC_DCHECK_LE(temporal_cumulator, layer_sum);
if (temporal_cumulator == layer_sum)
break;
if (ti > 0)
oss << ", ";
uint32_t bitrate = bitrates_[si][ti];
oss << bitrate;
temporal_cumulator += bitrate;
}
oss << "]";
}
RTC_DCHECK_EQ(spatial_cumulator, sum_);
oss << " ]";
return oss.str();
}
std::ostream& BitrateAllocation::operator<<(std::ostream& os) const {
os << ToString();
return os;
}
} // namespace webrtc
<commit_msg>Add flexfec payload name to string-type conversions<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "common_types.h" // NOLINT(build/include)
#include <string.h>
#include <algorithm>
#include <limits>
#include <type_traits>
#include "rtc_base/checks.h"
#include "rtc_base/stringutils.h"
namespace webrtc {
VideoCodec::VideoCodec()
: codecType(kVideoCodecUnknown),
plName(),
plType(0),
width(0),
height(0),
startBitrate(0),
maxBitrate(0),
minBitrate(0),
targetBitrate(0),
maxFramerate(0),
active(true),
qpMax(0),
numberOfSimulcastStreams(0),
simulcastStream(),
spatialLayers(),
mode(kRealtimeVideo),
expect_encode_from_texture(false),
timing_frame_thresholds({0, 0}),
codec_specific_() {}
VideoCodecVP8* VideoCodec::VP8() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return &codec_specific_.VP8;
}
const VideoCodecVP8& VideoCodec::VP8() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP8);
return codec_specific_.VP8;
}
VideoCodecVP9* VideoCodec::VP9() {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return &codec_specific_.VP9;
}
const VideoCodecVP9& VideoCodec::VP9() const {
RTC_DCHECK_EQ(codecType, kVideoCodecVP9);
return codec_specific_.VP9;
}
VideoCodecH264* VideoCodec::H264() {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return &codec_specific_.H264;
}
const VideoCodecH264& VideoCodec::H264() const {
RTC_DCHECK_EQ(codecType, kVideoCodecH264);
return codec_specific_.H264;
}
static const char* kPayloadNameVp8 = "VP8";
static const char* kPayloadNameVp9 = "VP9";
static const char* kPayloadNameH264 = "H264";
static const char* kPayloadNameI420 = "I420";
static const char* kPayloadNameRED = "RED";
static const char* kPayloadNameULPFEC = "ULPFEC";
static const char* kPayloadNameFlexfec = "flexfec-03";
static const char* kPayloadNameGeneric = "Generic";
static const char* kPayloadNameMultiplex = "Multiplex";
static bool CodecNamesEq(const char* name1, const char* name2) {
return _stricmp(name1, name2) == 0;
}
const char* CodecTypeToPayloadString(VideoCodecType type) {
switch (type) {
case kVideoCodecVP8:
return kPayloadNameVp8;
case kVideoCodecVP9:
return kPayloadNameVp9;
case kVideoCodecH264:
return kPayloadNameH264;
case kVideoCodecI420:
return kPayloadNameI420;
case kVideoCodecRED:
return kPayloadNameRED;
case kVideoCodecULPFEC:
return kPayloadNameULPFEC;
case kVideoCodecFlexfec:
return kPayloadNameFlexfec;
// Other codecs default to generic.
case kVideoCodecMultiplex:
case kVideoCodecGeneric:
case kVideoCodecUnknown:
return kPayloadNameGeneric;
}
return kPayloadNameGeneric;
}
VideoCodecType PayloadStringToCodecType(const std::string& name) {
if (CodecNamesEq(name.c_str(), kPayloadNameVp8))
return kVideoCodecVP8;
if (CodecNamesEq(name.c_str(), kPayloadNameVp9))
return kVideoCodecVP9;
if (CodecNamesEq(name.c_str(), kPayloadNameH264))
return kVideoCodecH264;
if (CodecNamesEq(name.c_str(), kPayloadNameI420))
return kVideoCodecI420;
if (CodecNamesEq(name.c_str(), kPayloadNameRED))
return kVideoCodecRED;
if (CodecNamesEq(name.c_str(), kPayloadNameULPFEC))
return kVideoCodecULPFEC;
if (CodecNamesEq(name.c_str(), kPayloadNameFlexfec))
return kVideoCodecFlexfec;
if (CodecNamesEq(name.c_str(), kPayloadNameMultiplex))
return kVideoCodecMultiplex;
return kVideoCodecGeneric;
}
const uint32_t BitrateAllocation::kMaxBitrateBps =
std::numeric_limits<uint32_t>::max();
BitrateAllocation::BitrateAllocation() : sum_(0), bitrates_{}, has_bitrate_{} {}
bool BitrateAllocation::SetBitrate(size_t spatial_index,
size_t temporal_index,
uint32_t bitrate_bps) {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
RTC_CHECK_LE(bitrates_[spatial_index][temporal_index], sum_);
uint64_t new_bitrate_sum_bps = sum_;
new_bitrate_sum_bps -= bitrates_[spatial_index][temporal_index];
new_bitrate_sum_bps += bitrate_bps;
if (new_bitrate_sum_bps > kMaxBitrateBps)
return false;
bitrates_[spatial_index][temporal_index] = bitrate_bps;
has_bitrate_[spatial_index][temporal_index] = true;
sum_ = static_cast<uint32_t>(new_bitrate_sum_bps);
return true;
}
bool BitrateAllocation::HasBitrate(size_t spatial_index,
size_t temporal_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
return has_bitrate_[spatial_index][temporal_index];
}
uint32_t BitrateAllocation::GetBitrate(size_t spatial_index,
size_t temporal_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
RTC_CHECK_LT(temporal_index, kMaxTemporalStreams);
return bitrates_[spatial_index][temporal_index];
}
// Whether the specific spatial layers has the bitrate set in any of its
// temporal layers.
bool BitrateAllocation::IsSpatialLayerUsed(size_t spatial_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
for (int i = 0; i < kMaxTemporalStreams; ++i) {
if (has_bitrate_[spatial_index][i])
return true;
}
return false;
}
// Get the sum of all the temporal layer for a specific spatial layer.
uint32_t BitrateAllocation::GetSpatialLayerSum(size_t spatial_index) const {
RTC_CHECK_LT(spatial_index, kMaxSpatialLayers);
uint32_t sum = 0;
for (int i = 0; i < kMaxTemporalStreams; ++i)
sum += bitrates_[spatial_index][i];
return sum;
}
std::string BitrateAllocation::ToString() const {
if (sum_ == 0)
return "BitrateAllocation [ [] ]";
// TODO(sprang): Replace this stringstream with something cheaper.
std::ostringstream oss;
oss << "BitrateAllocation [";
uint32_t spatial_cumulator = 0;
for (int si = 0; si < kMaxSpatialLayers; ++si) {
RTC_DCHECK_LE(spatial_cumulator, sum_);
if (spatial_cumulator == sum_)
break;
const uint32_t layer_sum = GetSpatialLayerSum(si);
if (layer_sum == sum_) {
oss << " [";
} else {
if (si > 0)
oss << ",";
oss << std::endl << " [";
}
spatial_cumulator += layer_sum;
uint32_t temporal_cumulator = 0;
for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
RTC_DCHECK_LE(temporal_cumulator, layer_sum);
if (temporal_cumulator == layer_sum)
break;
if (ti > 0)
oss << ", ";
uint32_t bitrate = bitrates_[si][ti];
oss << bitrate;
temporal_cumulator += bitrate;
}
oss << "]";
}
RTC_DCHECK_EQ(spatial_cumulator, sum_);
oss << " ]";
return oss.str();
}
std::ostream& BitrateAllocation::operator<<(std::ostream& os) const {
os << ToString();
return os;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Boulanger Guillaume, Chathura Namalgamuwa
* The file is distributed under the MIT license
* The license is available in the LICENSE file or at https://github.com/boulangg/phoenix/blob/master/LICENSE
*/
#include <mm/VirtualArea.hpp>
#include <include/constant.h>
#include <algorithm>
VirtualArea::VirtualArea(uint64_t* addrStart, uint64_t* addrEnd, uint64_t flags,
File* file, uint64_t offset, uint64_t fileSize) {
this->addrStart = addrStart;
this->addrEnd = addrEnd;
this->flags = flags;
this->file = file;
this->offset = offset;
this->fileSize = fileSize;
if ((flags & FLAGS::VM_WRITE)
&& !(flags & FLAGS::VM_SHARED) ) {
uint64_t nbPages = (((uint64_t)addrEnd)+PAGE_SIZE-1)/PAGE_SIZE
- ((uint64_t)addrStart)/PAGE_SIZE;
physicalPages = new PhysicalMapping(nbPages);
}
}
VirtualArea::~VirtualArea() {
delete this->physicalPages;
}
Page* VirtualArea::getPage(uint64_t index) {
if (physicalPages != nullptr) {
Page* page = physicalPages->getPage(index);
if (page == nullptr) {
page = PhysicalAllocator::allocZeroedPage();
physicalPages->setPage(index, page);
// Copy page if it comes from a file
if (file != nullptr) {
int64_t startPageOffset = (offset/PAGE_SIZE + index)*PAGE_SIZE;
int64_t startOffsetLimit = (int64_t)offset-startPageOffset;
int64_t startCpy = std::max(startOffsetLimit, (int64_t)0);
int64_t endOffsetLimit = startOffsetLimit + fileSize;
int64_t endCpy = std::min((int64_t)PAGE_SIZE, endOffsetLimit);
int fileIndex = offset/PAGE_SIZE + index;
Page* filePage = file->getPage(fileIndex);
for (int64_t i = startCpy; i < endCpy; ++i) {
((char*)(page->kernelMappAddr))[i] = ((char*)(filePage->kernelMappAddr))[i];
}
/*int fileIndex = offset/PAGE_SIZE + index;
Page* filePage = file->getPage(fileIndex);
for (uint64_t i = 0; i < PAGE_SIZE/sizeof(uint64_t); ++i) {
page->kernelMappAddr[i] = filePage->kernelMappAddr[i];
}*/
}
}
return page;
} else {
int fileIndex = offset/PAGE_SIZE + index;
return file->getPage(fileIndex);
}
}
bool VirtualArea::tryMergeArea(VirtualArea* area) {
if (this->flags != area->flags) {
return false;
}
if ((this->addrEnd != area->addrStart)
& (this->file == area->file)){
return false;
}
if (this->file == nullptr) {
this->addrEnd = area->addrEnd;
this->physicalPages->pushBack(area->physicalPages);
return true;
}
if ((offset + (uint64_t)addrEnd - (uint64_t)addrStart) == area->offset) {
this->addrEnd = area->addrEnd;
return true;
}
return false;
}
<commit_msg>Small correction in initalisation of VirtualArea<commit_after>/*
* Copyright (c) 2016 Boulanger Guillaume, Chathura Namalgamuwa
* The file is distributed under the MIT license
* The license is available in the LICENSE file or at https://github.com/boulangg/phoenix/blob/master/LICENSE
*/
#include <mm/VirtualArea.hpp>
#include <include/constant.h>
#include <algorithm>
VirtualArea::VirtualArea(uint64_t* addrStart, uint64_t* addrEnd, uint64_t flags,
File* file, uint64_t offset, uint64_t fileSize) {
this->addrStart = addrStart;
this->addrEnd = addrEnd;
this->flags = flags;
this->file = file;
this->offset = offset;
this->fileSize = fileSize;
if ((flags & FLAGS::VM_WRITE)
&& !(flags & FLAGS::VM_SHARED) ) {
uint64_t nbPages = (((uint64_t)addrEnd)+PAGE_SIZE-1)/PAGE_SIZE
- ((uint64_t)addrStart)/PAGE_SIZE;
physicalPages = new PhysicalMapping(nbPages);
} else {
physicalPages = nullptr;
}
}
VirtualArea::~VirtualArea() {
delete this->physicalPages;
}
Page* VirtualArea::getPage(uint64_t index) {
if (physicalPages != nullptr) {
Page* page = physicalPages->getPage(index);
if (page == nullptr) {
page = PhysicalAllocator::allocZeroedPage();
physicalPages->setPage(index, page);
// Copy page if it comes from a file
if (file != nullptr) {
int64_t startPageOffset = (offset/PAGE_SIZE + index)*PAGE_SIZE;
int64_t startOffsetLimit = (int64_t)offset-startPageOffset;
int64_t startCpy = std::max(startOffsetLimit, (int64_t)0);
int64_t endOffsetLimit = startOffsetLimit + fileSize;
int64_t endCpy = std::min((int64_t)PAGE_SIZE, endOffsetLimit);
int fileIndex = offset/PAGE_SIZE + index;
Page* filePage = file->getPage(fileIndex);
for (int64_t i = startCpy; i < endCpy; ++i) {
((char*)(page->kernelMappAddr))[i] = ((char*)(filePage->kernelMappAddr))[i];
}
/*int fileIndex = offset/PAGE_SIZE + index;
Page* filePage = file->getPage(fileIndex);
for (uint64_t i = 0; i < PAGE_SIZE/sizeof(uint64_t); ++i) {
page->kernelMappAddr[i] = filePage->kernelMappAddr[i];
}*/
}
}
return page;
} else {
int fileIndex = offset/PAGE_SIZE + index;
return file->getPage(fileIndex);
}
}
bool VirtualArea::tryMergeArea(VirtualArea* area) {
if (this->flags != area->flags) {
return false;
}
if ((this->addrEnd != area->addrStart)
& (this->file == area->file)){
return false;
}
if (this->file == nullptr) {
this->addrEnd = area->addrEnd;
this->physicalPages->pushBack(area->physicalPages);
return true;
}
if ((offset + (uint64_t)addrEnd - (uint64_t)addrStart) == area->offset) {
this->addrEnd = area->addrEnd;
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#include "twitter.h"
#include <QUrl>
#include <QNetworkAccessManager>
#define STR__(x) #x
#define STR_(x) STR__(x) // うーむ、
static const int dataStreamVersion = QDataStream::Qt_5_8;
static const QString keyAuthToken = "token";
static const QString keyAuthTokenSecret = "tokenSecret";
static const QString keyTwitterId = "id";
static const QString keyTwitterName = "name";
static const QString keyTwitterScreenName = "screenName";
static const QString keyTwitterProfileImage = "profileImage"; // QIcon
class QNetworkReply_
: public QNetworkReply
{
public:
QNetworkReply_(QObject *parent)
: QNetworkReply(parent)
{
}
void setHeader(const QByteArray &headerName, const QByteArray &value)
{
setRawHeader(headerName, value);
}
};
Twitter::Twitter(QObject *parent)
: QOAuth1(new QNetworkAccessManager(parent), parent)
, httpReplyHandler(nullptr)
{
// 実行するとすぐにポートを開きに行くので遅延させる
//setReplyHandler(new QOAuthHttpServerReplyHandler(this));
// https://dev.twitter.com/oauth/reference/post/oauth/request_token
setTemporaryCredentialsUrl(QUrl("https://api.twitter.com/oauth/request_token"));
// https://dev.twitter.com/oauth/reference/get/oauth/authorize
setAuthorizationUrl(QUrl("https://api.twitter.com/oauth/authenticate"));
// https://dev.twitter.com/oauth/reference/post/oauth/access_token
setTokenCredentialsUrl(QUrl("https://api.twitter.com/oauth/access_token"));
connect(this, &QAbstractOAuth::authorizeWithBrowser, [=](QUrl url) {
qDebug() << __FUNCTION__ << __LINE__ << url;
QUrlQuery query(url);
query.addQueryItem("force_login", "true");
//if (!screenName.isEmpty()) {
// query.addQueryItem("screen_name", screenName);
//}
url.setQuery(query);
QDesktopServices::openUrl(url);
});
connect(this, &QOAuth1::granted, this, &Twitter::authenticated);
connect(this, &QOAuth1::granted, this, [=]() {
verifyCredentials();
});
connect(this, &QOAuth1::requestFailed, [=](const Error error) {
qDebug() << "QOAuth1::requestFailed" << (int)error;
});
#ifndef QT_NO_DEBUG
qDebug() << "TWITTER_APP_KEY" << QString(STR_(TWITTER_APP_KEY));
qDebug() << "TWITTER_APP_SECRET" << QString(STR_(TWITTER_APP_SECRET));
#endif
// QAbstractOAuth::setClientIdentifier()
// > qmake ... DEFINES+=TWITTER_APP_KEY="{App key}"
// --> https://apps.twitter.com/app/{App key}/keys
setClientIdentifier(STR_(TWITTER_APP_KEY));
// QAbstractOAuth::setClientSharedSecret()
// > qmake ... DEFINES+=TWITTER_APP_SECRET="{App secret}"
// --> https://apps.twitter.com/app/{App key}/keys
setClientSharedSecret(STR_(TWITTER_APP_SECRET));
}
const QString Twitter::serialize() const
{
QMap<QString, QVariant> serialized;
QByteArray dataBytes;
QDataStream out(&dataBytes, QIODevice::WriteOnly);
out.setVersion(dataStreamVersion);
if (QAbstractOAuth::Status::Granted == status()) {
#ifndef QT_NO_DEBUG
qDebug() << "save" << keyAuthToken << token();
qDebug() << "save" << keyAuthTokenSecret << tokenSecret();
#endif
serialized.insert(keyAuthToken, token());
serialized.insert(keyAuthTokenSecret, tokenSecret());
}
serialized.insert(keyTwitterId, m_id);
serialized.insert(keyTwitterName, m_name);
serialized.insert(keyTwitterScreenName, m_screenName);
serialized.insert(keyTwitterProfileImage, m_icon);
out << serialized;
return dataBytes.toBase64();
}
void Twitter::deserialize(const QString& data)
{
QMap<QString, QVariant> deserialized;
QByteArray dataBytes = QByteArray::fromBase64(data.toUtf8());
QDataStream in(&dataBytes, QIODevice::ReadOnly);
in.setVersion(dataStreamVersion);
in >> deserialized;
m_id = deserialized.value(keyTwitterId).toString();
m_name = deserialized.value(keyTwitterName).toString();
m_screenName = deserialized.value(keyTwitterScreenName).toString();
m_icon = deserialized.value(keyTwitterProfileImage).value<QIcon>();
QString userToken = deserialized.value(keyAuthToken).toString();
QString userTokenSecret = deserialized.value(keyAuthTokenSecret).toString();
if (userToken.isEmpty() ||
userTokenSecret.isEmpty()) {
setTokenCredentials("", "");
setStatus(QAbstractOAuth::Status::NotAuthenticated);
}
else {
#ifndef QT_NO_DEBUG
qDebug() << keyAuthToken << userToken;
qDebug() << keyAuthTokenSecret << userTokenSecret;
#endif
setTokenCredentials(userToken, userTokenSecret);
setStatus(QAbstractOAuth::Status::Granted);
}
}
void Twitter::authenticate()
{
// ポートをここでオープン
if (!httpReplyHandler) {
httpReplyHandler = new QOAuthHttpServerReplyHandler(this);
const QString messageHtml
= QString("<style>" \
"html, body { padding: 0; margin: 0; } " \
"body { background-color: #f5f8fb; padding: 1em; } " \
"body > div { vertical-align: middle; text-align: center; margin: auto 0; }" \
"</style>" \
"<div><h1>%1</h1><div>%2</div></div>")
.arg(qApp->applicationName())
.arg("コールバックを受け取りました。<br />このページは閉じていただいて問題ありません。");
#if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0))
// https://bugreports.qt.io/browse/QTBUG-59725 が修正されるまでこのまま
const QString postfixTag = "</body></html>";
const int fixedPaddingSize = messageHtml.toUtf8().length() - messageHtml.length() - postfixTag.length();
httpReplyHandler->setCallbackText(messageHtml + postfixTag + QString(fixedPaddingSize, '*'));
#else // fix in "5.9.0 Beta 2"
// 本来はこのようにしたかった
httpReplyHandler->setCallbackText(messageHtml);
#endif
setReplyHandler(httpReplyHandler);
}
// 認証処理開始
grant();
}
// OAuth check authentication method
bool Twitter::isAuthenticated() const
{
return
!token().isEmpty() &&
!tokenSecret().isEmpty() &&
QAbstractOAuth::Status::Granted == status();
}
const QString &Twitter::id() const
{
return m_id;
}
const QString &Twitter::screenName() const
{
return m_screenName;
}
const QString &Twitter::name() const
{
return m_name;
}
const QIcon &Twitter::icon() const
{
return m_icon;
}
QNetworkReply *Twitter::post_(const QUrl &url, const QVariantMap ¶meters)
{
if (!networkAccessManager()) {
qWarning("QOAuth1::post: QNetworkAccessManager not available");
return nullptr;
}
QNetworkRequest request(url);
qDebug() << "**url**" << QUrl::toPercentEncoding(url.toString(QUrl::RemoveQuery));
const auto queryItems = QUrlQuery(url.query()).queryItems();
for (auto it = queryItems.begin(), end = queryItems.end(); it != end; ++it)
qDebug() << "**queryItems" << it->first << it->second;
request.setRawHeader(QByteArray("accept"), QByteArray("*/*")); // accept: */*
request.setRawHeader(QByteArray("accept-language"), QByteArray("ja-jp")); // accept-language: ja-jp
request.setRawHeader(QByteArray("user-agent"), QByteArray("Jugemutter")); // user-agent: Jugemutter
request.setRawHeader(QByteArray("connection"), QByteArray("keep-alive")); // connection: keep-alive
setup(&request, parameters, QNetworkAccessManager::PostOperation);
// QByteArray authorization = request.rawHeader(QByteArray("authorization"));
// request.setRawHeader(QByteArray("authorization"), authorization.replace("\",", "\", ")); // accept: */*
QUrlQuery query;
for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it)
query.addQueryItem(it.key(), it.value().toString());
QString data = query.toString(QUrl::FullyEncoded);
//QString data = query.toString();
qDebug() << "**" << data;
QNetworkReply *reply = networkAccessManager()->post(request, data.toUtf8());
connect(reply, &QNetworkReply::finished, std::bind(&QAbstractOAuth::finished, this, reply));
return reply;
}
bool Twitter::tweet(const QString& text, const QString& inReplyToStatusId)
{
// https://dev.twitter.com/rest/reference/post/statuses/update
QUrl url("https://api.twitter.com/1.1/statuses/update.json");
QUrlQuery query(url);
#ifndef QT_NO_DEBUG
qDebug() << ">>" << keyAuthToken << token();
qDebug() << ">>" << keyAuthTokenSecret << tokenSecret();
#endif
QByteArray text_ = QUrl::toPercentEncoding(text, "", "~");
QUrl url_path(text);
qDebug() << "[Original String]:" << text;
qDebug() << "--------------------------------------------------------------------";
qDebug() << "(QUrl::toEncoded) :" << url_path.toEncoded(QUrl::FullyEncoded);
qDebug() << "(QUrl::toString) :" << url_path.toString(QUrl::FullyEncoded);
qDebug() << "(QUrl::url) :" << url_path.url();
qDebug() << "(QUrl::toString) :" << url_path.toString();
qDebug() << "(QUrl::toDisplayString) :" << url_path.toDisplayString(QUrl::FullyDecoded);
//qDebug() << "(QUrl::fromPercentEncoding):" << url_path.fromPercentEncoding(url_path.toEncoded(QUrl::FullyEncoded));
qDebug() << "text=" << text << text_;
QVariantMap data;
data.insert("status", text);
if (!inReplyToStatusId.isEmpty()) {
data.insert("in_reply_to_status_id", inReplyToStatusId);
}
url.setQuery(query);
QNetworkReply *reply = post(url, data);
// QNetworkReply_ *reply__ = (QNetworkReply_ *)reply;
// reply__->setHeader("accept", "*/*"); // accept: */*
// reply__->setHeader("accept-language", "ja-jp"); // accept-language: ja-jp
// reply__->setHeader("user-agent", "Jugemutter"); // user-agent: YoruFukurou
#ifndef QT_NO_DEBUG // 自己証明書でのhttps通信のダンプ処理用
connect(reply, &QNetworkReply::sslErrors, this, [=](QList<QSslError>) {
auto reply_ = qobject_cast<QNetworkReply*>(sender());
reply_->ignoreSslErrors();
});
#endif
connect(reply, &QNetworkReply::finished, this, [=](){
auto reply_ = qobject_cast<QNetworkReply*>(sender());
qDebug() << "finished tweet";
// {\n \"errors\": [\n {\n \"code\": 170,\n \"message\": \"Missing required parameter: status.\"\n }\n ]\n}\n
QJsonParseError parseError;
const auto resultJson = reply_->readAll();
const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError);
if (parseError.error) {
qDebug() << QString(resultJson);
qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset
<< parseError.errorString();
return;
}
else if (!resultDoc.isObject()) {
qDebug() << QString(resultJson).replace(QRegExp(" +"), " ");
return;
}
const auto result = resultDoc.object();
if (result.value("id_str").isUndefined()) {
QList<QPair<int, QString> > errors;
const QJsonArray errorsInfo
= result.contains("errors") ? result.value("errors").toArray()
: QJsonArray();
foreach (auto errorInfo, errorsInfo) {
const QJsonObject& errorInfo_ = errorInfo.toObject();
errors.push_back( qMakePair(!errorInfo_.contains("code") ? -1 : errorInfo_.value("code").toInt(),
!errorInfo_.contains("message") ? QString() : errorInfo_.value("message").toString() ) );
}
//qDebug() << "***>>" << (result.contains("errors") &&
// !result.value("errors").toArray().isEmpty() &&
// result.value("errors").toArray().at(0).toObject().contains("code")
// ? result.value("errors").toArray().at(0).toObject().value("code").toInt() : -1);
qDebug() << resultDoc.toJson();
Q_EMIT tweetFailure(errors);
return;
}
qDebug() << "****\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " ");
const auto tweetId = result.value("id_str").toString();
Q_EMIT tweeted(tweetId);
});
return true;
}
void Twitter::verifyCredentials(bool include_entities, bool skip_status, bool include_email)
{
// https://dev.twitter.com/rest/reference/get/account/verify_credentials
QUrl url("https://api.twitter.com/1.1/account/verify_credentials.json");
QUrlQuery query(url);
QVariantMap data;
query.addQueryItem("include_entities", include_entities ? "true" : "false");
query.addQueryItem("skip_status", skip_status ? "true" : "false");
query.addQueryItem("include_email", include_email ? "true" : "false");
url.setQuery(query);
QNetworkReply *reply = get(url);
connect(reply, &QNetworkReply::finished, this, [=](){
auto reply_ = qobject_cast<QNetworkReply*>(sender());
qDebug() << "verifyCredentials finished";
#ifndef QT_NO_DEBUG
qDebug() << keyAuthToken << token();
qDebug() << keyAuthTokenSecret << tokenSecret();
#endif
QJsonParseError parseError;
const auto resultJson = reply_->readAll();
const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError);
if (parseError.error) {
qDebug() << QString(resultJson);
qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset
<< parseError.errorString();
return;
}
else if (!resultDoc.isObject()) {
qDebug() << "!resultDoc.isObject()\n" << QString(resultJson).replace(QRegExp(" +"), " ");
return;
}
const auto result = resultDoc.object();
if (result.value("id_str").isUndefined() ||
result.value("name").isUndefined() ||
result.value("screen_name").isUndefined() ||
result.value("profile_image_url_https").isUndefined()) {
qDebug() << "!result.value(\"id_str\").isUndefined()\n" << resultDoc.toJson();
return;
}
qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " ");
m_id = result.value("id_str").toString();
m_screenName = result.value("screen_name").toString();
m_name = result.value("name").toString();
const auto profileImageUrlHttps = result.value("profile_image_url_https").toString();
qDebug() << m_id;
qDebug() << profileImageUrlHttps;
// アイコン取得
QNetworkAccessManager *netManager = networkAccessManager();
QNetworkRequest reqIcon;
reqIcon.setUrl(QUrl(profileImageUrlHttps));
QNetworkReply *replyIcon = netManager->get(reqIcon);
connect(replyIcon, &QNetworkReply::finished, this, [=](){
QImage profileImage;
profileImage.loadFromData(replyIcon->readAll());
m_icon = QIcon(QPixmap::fromImage(profileImage));
Q_EMIT verified();
});
});
}
<commit_msg>利用しなくなったコードを削除<commit_after>#include "twitter.h"
#include <QUrl>
#include <QNetworkAccessManager>
#define STR__(x) #x
#define STR_(x) STR__(x) // うーむ、
static const int dataStreamVersion = QDataStream::Qt_5_8;
static const QString keyAuthToken = "token";
static const QString keyAuthTokenSecret = "tokenSecret";
static const QString keyTwitterId = "id";
static const QString keyTwitterName = "name";
static const QString keyTwitterScreenName = "screenName";
static const QString keyTwitterProfileImage = "profileImage"; // QIcon
class QNetworkReply_
: public QNetworkReply
{
public:
QNetworkReply_(QObject *parent)
: QNetworkReply(parent)
{
}
void setHeader(const QByteArray &headerName, const QByteArray &value)
{
setRawHeader(headerName, value);
}
};
Twitter::Twitter(QObject *parent)
: QOAuth1(new QNetworkAccessManager(parent), parent)
, httpReplyHandler(nullptr)
{
// 実行するとすぐにポートを開きに行くので遅延させる
//setReplyHandler(new QOAuthHttpServerReplyHandler(this));
// https://dev.twitter.com/oauth/reference/post/oauth/request_token
setTemporaryCredentialsUrl(QUrl("https://api.twitter.com/oauth/request_token"));
// https://dev.twitter.com/oauth/reference/get/oauth/authorize
setAuthorizationUrl(QUrl("https://api.twitter.com/oauth/authenticate"));
// https://dev.twitter.com/oauth/reference/post/oauth/access_token
setTokenCredentialsUrl(QUrl("https://api.twitter.com/oauth/access_token"));
connect(this, &QAbstractOAuth::authorizeWithBrowser, [=](QUrl url) {
qDebug() << __FUNCTION__ << __LINE__ << url;
QUrlQuery query(url);
query.addQueryItem("force_login", "true");
//if (!screenName.isEmpty()) {
// query.addQueryItem("screen_name", screenName);
//}
url.setQuery(query);
QDesktopServices::openUrl(url);
});
connect(this, &QOAuth1::granted, this, &Twitter::authenticated);
connect(this, &QOAuth1::granted, this, [=]() {
verifyCredentials();
});
connect(this, &QOAuth1::requestFailed, [=](const Error error) {
qDebug() << "QOAuth1::requestFailed" << (int)error;
});
#ifndef QT_NO_DEBUG
qDebug() << "TWITTER_APP_KEY" << QString(STR_(TWITTER_APP_KEY));
qDebug() << "TWITTER_APP_SECRET" << QString(STR_(TWITTER_APP_SECRET));
#endif
// QAbstractOAuth::setClientIdentifier()
// > qmake ... DEFINES+=TWITTER_APP_KEY="{App key}"
// --> https://apps.twitter.com/app/{App key}/keys
setClientIdentifier(STR_(TWITTER_APP_KEY));
// QAbstractOAuth::setClientSharedSecret()
// > qmake ... DEFINES+=TWITTER_APP_SECRET="{App secret}"
// --> https://apps.twitter.com/app/{App key}/keys
setClientSharedSecret(STR_(TWITTER_APP_SECRET));
}
const QString Twitter::serialize() const
{
QMap<QString, QVariant> serialized;
QByteArray dataBytes;
QDataStream out(&dataBytes, QIODevice::WriteOnly);
out.setVersion(dataStreamVersion);
if (QAbstractOAuth::Status::Granted == status()) {
#ifndef QT_NO_DEBUG
qDebug() << "save" << keyAuthToken << token();
qDebug() << "save" << keyAuthTokenSecret << tokenSecret();
#endif
serialized.insert(keyAuthToken, token());
serialized.insert(keyAuthTokenSecret, tokenSecret());
}
serialized.insert(keyTwitterId, m_id);
serialized.insert(keyTwitterName, m_name);
serialized.insert(keyTwitterScreenName, m_screenName);
serialized.insert(keyTwitterProfileImage, m_icon);
out << serialized;
return dataBytes.toBase64();
}
void Twitter::deserialize(const QString& data)
{
QMap<QString, QVariant> deserialized;
QByteArray dataBytes = QByteArray::fromBase64(data.toUtf8());
QDataStream in(&dataBytes, QIODevice::ReadOnly);
in.setVersion(dataStreamVersion);
in >> deserialized;
m_id = deserialized.value(keyTwitterId).toString();
m_name = deserialized.value(keyTwitterName).toString();
m_screenName = deserialized.value(keyTwitterScreenName).toString();
m_icon = deserialized.value(keyTwitterProfileImage).value<QIcon>();
QString userToken = deserialized.value(keyAuthToken).toString();
QString userTokenSecret = deserialized.value(keyAuthTokenSecret).toString();
if (userToken.isEmpty() ||
userTokenSecret.isEmpty()) {
setTokenCredentials("", "");
setStatus(QAbstractOAuth::Status::NotAuthenticated);
}
else {
#ifndef QT_NO_DEBUG
qDebug() << keyAuthToken << userToken;
qDebug() << keyAuthTokenSecret << userTokenSecret;
#endif
setTokenCredentials(userToken, userTokenSecret);
setStatus(QAbstractOAuth::Status::Granted);
}
}
void Twitter::authenticate()
{
// ポートをここでオープン
if (!httpReplyHandler) {
httpReplyHandler = new QOAuthHttpServerReplyHandler(this);
const QString messageHtml
= QString("<style>" \
"html, body { padding: 0; margin: 0; } " \
"body { background-color: #f5f8fb; padding: 1em; } " \
"body > div { vertical-align: middle; text-align: center; margin: auto 0; }" \
"</style>" \
"<div><h1>%1</h1><div>%2</div></div>")
.arg(qApp->applicationName())
.arg("コールバックを受け取りました。<br />このページは閉じていただいて問題ありません。");
#if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0))
// https://bugreports.qt.io/browse/QTBUG-59725 が修正されるまでこのまま
const QString postfixTag = "</body></html>";
const int fixedPaddingSize = messageHtml.toUtf8().length() - messageHtml.length() - postfixTag.length();
httpReplyHandler->setCallbackText(messageHtml + postfixTag + QString(fixedPaddingSize, '*'));
#else // fix in "5.9.0 Beta 2"
// 本来はこのようにしたかった
httpReplyHandler->setCallbackText(messageHtml);
#endif
setReplyHandler(httpReplyHandler);
}
// 認証処理開始
grant();
}
// OAuth check authentication method
bool Twitter::isAuthenticated() const
{
return
!token().isEmpty() &&
!tokenSecret().isEmpty() &&
QAbstractOAuth::Status::Granted == status();
}
const QString &Twitter::id() const
{
return m_id;
}
const QString &Twitter::screenName() const
{
return m_screenName;
}
const QString &Twitter::name() const
{
return m_name;
}
const QIcon &Twitter::icon() const
{
return m_icon;
}
QNetworkReply *Twitter::post_(const QUrl &url, const QVariantMap ¶meters)
{
if (!networkAccessManager()) {
qWarning("QOAuth1::post: QNetworkAccessManager not available");
return nullptr;
}
QNetworkRequest request(url);
qDebug() << "**url**" << QUrl::toPercentEncoding(url.toString(QUrl::RemoveQuery));
const auto queryItems = QUrlQuery(url.query()).queryItems();
for (auto it = queryItems.begin(), end = queryItems.end(); it != end; ++it)
qDebug() << "**queryItems" << it->first << it->second;
request.setRawHeader(QByteArray("accept"), QByteArray("*/*")); // accept: */*
request.setRawHeader(QByteArray("accept-language"), QByteArray("ja-jp")); // accept-language: ja-jp
request.setRawHeader(QByteArray("user-agent"), QByteArray("Jugemutter")); // user-agent: Jugemutter
request.setRawHeader(QByteArray("connection"), QByteArray("keep-alive")); // connection: keep-alive
setup(&request, parameters, QNetworkAccessManager::PostOperation);
// QByteArray authorization = request.rawHeader(QByteArray("authorization"));
// request.setRawHeader(QByteArray("authorization"), authorization.replace("\",", "\", ")); // accept: */*
QUrlQuery query;
for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it)
query.addQueryItem(it.key(), it.value().toString());
QString data = query.toString(QUrl::FullyEncoded);
//QString data = query.toString();
qDebug() << "**" << data;
QNetworkReply *reply = networkAccessManager()->post(request, data.toUtf8());
connect(reply, &QNetworkReply::finished, std::bind(&QAbstractOAuth::finished, this, reply));
return reply;
}
bool Twitter::tweet(const QString& text, const QString& inReplyToStatusId)
{
// https://dev.twitter.com/rest/reference/post/statuses/update
QUrl url("https://api.twitter.com/1.1/statuses/update.json");
QUrlQuery query(url);
#ifndef QT_NO_DEBUG
qDebug() << ">>" << keyAuthToken << token();
qDebug() << ">>" << keyAuthTokenSecret << tokenSecret();
#endif
QByteArray text_ = QUrl::toPercentEncoding(text, "", "~");
QUrl url_path(text);
qDebug() << "[Original String]:" << text;
qDebug() << "--------------------------------------------------------------------";
qDebug() << "(QUrl::toEncoded) :" << url_path.toEncoded(QUrl::FullyEncoded);
qDebug() << "(QUrl::toString) :" << url_path.toString(QUrl::FullyEncoded);
qDebug() << "(QUrl::url) :" << url_path.url();
qDebug() << "(QUrl::toString) :" << url_path.toString();
qDebug() << "(QUrl::toDisplayString) :" << url_path.toDisplayString(QUrl::FullyDecoded);
//qDebug() << "(QUrl::fromPercentEncoding):" << url_path.fromPercentEncoding(url_path.toEncoded(QUrl::FullyEncoded));
qDebug() << "text=" << text << text_;
QVariantMap data;
data.insert("status", text);
if (!inReplyToStatusId.isEmpty()) {
data.insert("in_reply_to_status_id", inReplyToStatusId);
}
url.setQuery(query);
QNetworkReply *reply = post(url, data);
// QNetworkReply_ *reply__ = (QNetworkReply_ *)reply;
// reply__->setHeader("accept", "*/*"); // accept: */*
// reply__->setHeader("accept-language", "ja-jp"); // accept-language: ja-jp
// reply__->setHeader("user-agent", "Jugemutter"); // user-agent: YoruFukurou
connect(reply, &QNetworkReply::finished, this, [=](){
auto reply_ = qobject_cast<QNetworkReply*>(sender());
qDebug() << "finished tweet";
// {\n \"errors\": [\n {\n \"code\": 170,\n \"message\": \"Missing required parameter: status.\"\n }\n ]\n}\n
QJsonParseError parseError;
const auto resultJson = reply_->readAll();
const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError);
if (parseError.error) {
qDebug() << QString(resultJson);
qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset
<< parseError.errorString();
return;
}
else if (!resultDoc.isObject()) {
qDebug() << QString(resultJson).replace(QRegExp(" +"), " ");
return;
}
const auto result = resultDoc.object();
if (result.value("id_str").isUndefined()) {
QList<QPair<int, QString> > errors;
const QJsonArray errorsInfo
= result.contains("errors") ? result.value("errors").toArray()
: QJsonArray();
foreach (auto errorInfo, errorsInfo) {
const QJsonObject& errorInfo_ = errorInfo.toObject();
errors.push_back( qMakePair(!errorInfo_.contains("code") ? -1 : errorInfo_.value("code").toInt(),
!errorInfo_.contains("message") ? QString() : errorInfo_.value("message").toString() ) );
}
//qDebug() << "***>>" << (result.contains("errors") &&
// !result.value("errors").toArray().isEmpty() &&
// result.value("errors").toArray().at(0).toObject().contains("code")
// ? result.value("errors").toArray().at(0).toObject().value("code").toInt() : -1);
qDebug() << resultDoc.toJson();
Q_EMIT tweetFailure(errors);
return;
}
qDebug() << "****\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " ");
const auto tweetId = result.value("id_str").toString();
Q_EMIT tweeted(tweetId);
});
return true;
}
void Twitter::verifyCredentials(bool include_entities, bool skip_status, bool include_email)
{
// https://dev.twitter.com/rest/reference/get/account/verify_credentials
QUrl url("https://api.twitter.com/1.1/account/verify_credentials.json");
QUrlQuery query(url);
QVariantMap data;
query.addQueryItem("include_entities", include_entities ? "true" : "false");
query.addQueryItem("skip_status", skip_status ? "true" : "false");
query.addQueryItem("include_email", include_email ? "true" : "false");
url.setQuery(query);
QNetworkReply *reply = get(url);
connect(reply, &QNetworkReply::finished, this, [=](){
auto reply_ = qobject_cast<QNetworkReply*>(sender());
qDebug() << "verifyCredentials finished";
#ifndef QT_NO_DEBUG
qDebug() << keyAuthToken << token();
qDebug() << keyAuthTokenSecret << tokenSecret();
#endif
QJsonParseError parseError;
const auto resultJson = reply_->readAll();
const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError);
if (parseError.error) {
qDebug() << QString(resultJson);
qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset
<< parseError.errorString();
return;
}
else if (!resultDoc.isObject()) {
qDebug() << "!resultDoc.isObject()\n" << QString(resultJson).replace(QRegExp(" +"), " ");
return;
}
const auto result = resultDoc.object();
if (result.value("id_str").isUndefined() ||
result.value("name").isUndefined() ||
result.value("screen_name").isUndefined() ||
result.value("profile_image_url_https").isUndefined()) {
qDebug() << "!result.value(\"id_str\").isUndefined()\n" << resultDoc.toJson();
return;
}
qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " ");
m_id = result.value("id_str").toString();
m_screenName = result.value("screen_name").toString();
m_name = result.value("name").toString();
const auto profileImageUrlHttps = result.value("profile_image_url_https").toString();
qDebug() << m_id;
qDebug() << profileImageUrlHttps;
// アイコン取得
QNetworkAccessManager *netManager = networkAccessManager();
QNetworkRequest reqIcon;
reqIcon.setUrl(QUrl(profileImageUrlHttps));
QNetworkReply *replyIcon = netManager->get(reqIcon);
connect(replyIcon, &QNetworkReply::finished, this, [=](){
QImage profileImage;
profileImage.loadFromData(replyIcon->readAll());
m_icon = QIcon(QPixmap::fromImage(profileImage));
Q_EMIT verified();
});
});
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "EratBig.h"
#include "SieveOfEratosthenes.h"
#include "WheelFactorization.h"
#include "defs.h"
#include "bithacks.h"
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <list>
EratBig::EratBig(const SieveOfEratosthenes& soe) :
Modulo210Wheel_t(soe),
lists_(NULL),
stock_(NULL),
log2SieveSize_(floorLog2(soe.getSieveSize())),
moduloSieveSize_(soe.getSieveSize() - 1)
{
// EratBig uses bitwise operations that require a power of 2 sieve size
if (!isPowerOf2(soe.getSieveSize()))
throw std::invalid_argument(
"EratBig: sieveSize must be a power of 2 (2^n).");
this->setSize(soe);
this->initBucketLists();
}
EratBig::~EratBig() {
delete[] lists_;
for (std::list<Bucket_t*>::iterator it = pointers_.begin();
it != pointers_.end(); ++it)
delete[] *it;
}
/**
* Set the size of the lists_ array.
* @remark The size is a power of 2 value which allows use of fast
* bitwise operators in sieve(uint8_t*).
*/
void EratBig::setSize(const SieveOfEratosthenes& soe) {
// MAX values in sieve(uint8_t*)
uint32_t maxSievingPrime = soe.getSquareRoot() / SieveOfEratosthenes::NUMBERS_PER_BYTE;
uint32_t maxWheelFactor = wheel(1)->nextMultipleFactor;
uint32_t maxMultipleOffset = maxSievingPrime * maxWheelFactor + maxWheelFactor;
uint32_t maxMultipleIndex = (soe.getSieveSize() - 1) + maxMultipleOffset;
uint32_t maxSegmentCount = maxMultipleIndex / soe.getSieveSize();
// 'maxSegmentCount + 1' is the smallest possible
// size for the lists_ array
size_ = nextHighestPowerOf2(maxSegmentCount + 1);
moduloListsSize_ = size_ - 1;
}
/**
* Allocate the lists_ array and initialize each list
* with an empty bucket.
*/
void EratBig::initBucketLists() {
lists_ = new Bucket_t*[size_];
for (uint32_t i = 0; i < size_; i++) {
lists_[i] = NULL;
this->pushBucket(i);
}
}
/**
* Add a prime number <= sqrt(n) for sieving to EratBig.
*/
void EratBig::addSievingPrime(uint32_t prime) {
uint32_t multipleIndex;
uint32_t wheelIndex;
if (this->getWheelPrimeData(&prime, &multipleIndex, &wheelIndex) == true) {
// indicates in how many segments the next multiple
// of prime needs to be crossed-off
uint32_t segmentCount = multipleIndex >> log2SieveSize_;
// index for the SieveOfEratosthenes::sieve_ array
multipleIndex &= moduloSieveSize_;
// calculate the list index related to the next multiple of prime
uint32_t next = segmentCount & moduloListsSize_;
// add prime to the bucket list related to
// its next multiple occurrence
if (!lists_[next]->addWheelPrime(prime, multipleIndex, wheelIndex))
this->pushBucket(next);
}
}
/**
* Add an empty bucket from the bucket stock_ to the
* front of lists_[index], if the bucket stock_ is
* empty new buckets are allocated first.
*/
void EratBig::pushBucket(uint32_t index) {
if (stock_ == NULL) {
Bucket_t* more = new Bucket_t[BUCKETS_PER_ALLOC];
stock_ = &more[0];
pointers_.push_back(more);
for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++)
more[i].setNext(&more[i + 1]);
more[BUCKETS_PER_ALLOC - 1].setNext(NULL);
}
Bucket_t* bucket = stock_;
stock_ = stock_->next();
bucket->setNext(lists_[index]);
lists_[index] = bucket;
}
/**
* Implementation of Tomas Oliveira e Silva's cache-friendly segmented
* sieve of Eratosthenes algorithm, see:
* http://www.ieeta.pt/~tos/software/prime_sieve.html
* My implementation uses a sieve array with 30 numbers per byte,
* 8 bytes per sieving prime and a modulo 210 wheel that skips
* multiples of 2, 3, 5 and 7.
*
* Removes the multiples of big sieving primes (i.e. with very few
* multiple occurrences per segment) from the sieve array.
* @see SieveOfEratosthenes::crossOffMultiples()
*/
void EratBig::sieve(uint8_t* sieve)
{
// lists_[0] contains the sieving primes that have multiple
// occurence(s) in the current segment
while (!lists_[0]->isEmpty() || lists_[0]->hasNext()) {
Bucket_t* bucket = lists_[0];
lists_[0] = NULL;
this->pushBucket(0);
// each loop iteration processes a bucket i.e. removes
// the next multiple of its sieving primes
do {
const WheelPrime_t* wPrime = bucket->begin();
const WheelPrime_t* end = bucket->end();
// iterate over the sieving primes within the current bucket
// loop unrolled 2 times, optimized for x64 CPUs
for (; wPrime + 2 <= end; wPrime += 2) {
uint32_t multipleIndex0 = wPrime[0].getMultipleIndex();
uint32_t wheelIndex0 = wPrime[0].getWheelIndex();
uint32_t sievingPrime0 = wPrime[0].getSievingPrime();
uint32_t multipleIndex1 = wPrime[1].getMultipleIndex();
uint32_t wheelIndex1 = wPrime[1].getWheelIndex();
uint32_t sievingPrime1 = wPrime[1].getSievingPrime();
// cross-off the next multiple (unset corresponding bit) of the
// current sieving primes within the sieve array
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
uint32_t next0 = (multipleIndex0 >> log2SieveSize_) & moduloListsSize_;
multipleIndex0 &= moduloSieveSize_;
uint32_t next1 = (multipleIndex1 >> log2SieveSize_) & moduloListsSize_;
multipleIndex1 &= moduloSieveSize_;
// move the current sieving primes to the bucket list
// related to their next multiple occurrence
if (!lists_[next0]->addWheelPrime(sievingPrime0, multipleIndex0, wheelIndex0))
this->pushBucket(next0);
if (!lists_[next1]->addWheelPrime(sievingPrime1, multipleIndex1, wheelIndex1))
this->pushBucket(next1);
}
// process the remaining sieving primes
for (; wPrime < end; wPrime++) {
uint32_t multipleIndex = wPrime->getMultipleIndex();
uint32_t wheelIndex = wPrime->getWheelIndex();
uint32_t sievingPrime = wPrime->getSievingPrime();
sieve[multipleIndex] &= wheel(wheelIndex)->unsetBit;
multipleIndex += wheel(wheelIndex)->nextMultipleFactor * sievingPrime;
multipleIndex += wheel(wheelIndex)->correct;
wheelIndex += wheel(wheelIndex)->next;
uint32_t next = (multipleIndex >> log2SieveSize_) & moduloListsSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[next]->addWheelPrime(sievingPrime, multipleIndex, wheelIndex))
this->pushBucket(next);
}
// reset the processed bucket and move it to the bucket stock_
Bucket_t* old = bucket;
bucket = bucket->next();
old->reset();
old->setNext(stock_);
stock_ = old;
}
while (bucket != NULL);
}
// lists_[0] has been processed, thus the list related to
// the next segment lists_[1] moves to lists_[0]
Bucket_t* tmp = lists_[0];
std::memmove(lists_, &lists_[1], (size_ - 1) * sizeof(Bucket_t*));
lists_[size_ - 1] = tmp;
}
<commit_msg>comments ...<commit_after>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "EratBig.h"
#include "SieveOfEratosthenes.h"
#include "WheelFactorization.h"
#include "defs.h"
#include "bithacks.h"
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include <list>
EratBig::EratBig(const SieveOfEratosthenes& soe) :
Modulo210Wheel_t(soe),
lists_(NULL),
stock_(NULL),
log2SieveSize_(floorLog2(soe.getSieveSize())),
moduloSieveSize_(soe.getSieveSize() - 1)
{
// EratBig uses bitwise operations that require a power of 2 sieve size
if (!isPowerOf2(soe.getSieveSize()))
throw std::invalid_argument(
"EratBig: sieveSize must be a power of 2 (2^n).");
this->setSize(soe);
this->initBucketLists();
}
EratBig::~EratBig() {
delete[] lists_;
for (std::list<Bucket_t*>::iterator it = pointers_.begin();
it != pointers_.end(); ++it)
delete[] *it;
}
/**
* Set the size of the lists_ array.
* @remark The size is a power of 2 value which allows use of fast
* bitwise operators in sieve(uint8_t*).
*/
void EratBig::setSize(const SieveOfEratosthenes& soe) {
// MAX values in sieve(uint8_t*)
uint32_t maxSievingPrime = soe.getSquareRoot() / SieveOfEratosthenes::NUMBERS_PER_BYTE;
uint32_t maxWheelFactor = wheel(1)->nextMultipleFactor;
uint32_t maxMultipleOffset = maxSievingPrime * maxWheelFactor + maxWheelFactor;
uint32_t maxMultipleIndex = (soe.getSieveSize() - 1) + maxMultipleOffset;
uint32_t maxSegmentCount = maxMultipleIndex / soe.getSieveSize();
// 'maxSegmentCount + 1' is the smallest possible
// size for the lists_ array
size_ = nextHighestPowerOf2(maxSegmentCount + 1);
moduloListsSize_ = size_ - 1;
}
/**
* Allocate the lists_ array and initialize each list
* with an empty bucket.
*/
void EratBig::initBucketLists() {
lists_ = new Bucket_t*[size_];
for (uint32_t i = 0; i < size_; i++) {
lists_[i] = NULL;
this->pushBucket(i);
}
}
/**
* Add a prime number <= sqrt(n) for sieving to EratBig.
*/
void EratBig::addSievingPrime(uint32_t prime) {
uint32_t multipleIndex;
uint32_t wheelIndex;
if (this->getWheelPrimeData(&prime, &multipleIndex, &wheelIndex) == true) {
// indicates in how many segments the next multiple
// of prime needs to be crossed-off
uint32_t segmentCount = multipleIndex >> log2SieveSize_;
// index for the SieveOfEratosthenes::sieve_ array
multipleIndex &= moduloSieveSize_;
// calculate the list index related to the next multiple of prime
uint32_t next = segmentCount & moduloListsSize_;
// add prime to the bucket list related to
// its next multiple occurrence
if (!lists_[next]->addWheelPrime(prime, multipleIndex, wheelIndex))
this->pushBucket(next);
}
}
/**
* Add an empty bucket from the bucket stock_ to the
* front of lists_[index], if the bucket stock_ is
* empty new buckets are allocated first.
*/
void EratBig::pushBucket(uint32_t index) {
if (stock_ == NULL) {
Bucket_t* more = new Bucket_t[BUCKETS_PER_ALLOC];
stock_ = &more[0];
pointers_.push_back(more);
for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++)
more[i].setNext(&more[i + 1]);
more[BUCKETS_PER_ALLOC - 1].setNext(NULL);
}
Bucket_t* bucket = stock_;
stock_ = stock_->next();
bucket->setNext(lists_[index]);
lists_[index] = bucket;
}
/**
* Implementation of Tomas Oliveira e Silva's cache-friendly segmented
* sieve of Eratosthenes algorithm, see:
* http://www.ieeta.pt/~tos/software/prime_sieve.html
* My implementation uses a sieve array with 30 numbers per byte,
* 8 bytes per sieving prime and a modulo 210 wheel that skips
* multiples of 2, 3, 5 and 7.
*
* Removes the multiples of big sieving primes (i.e. with very few
* multiple occurrences per segment) from the sieve array.
* @see SieveOfEratosthenes::crossOffMultiples()
*/
void EratBig::sieve(uint8_t* sieve)
{
// lists_[0] contains the list of buckets related to the current
// segment i.e. its buckets contain all the sieving primes that have
// multiple occurrence(s) in the current segment
while (!lists_[0]->isEmpty() || lists_[0]->hasNext()) {
Bucket_t* bucket = lists_[0];
lists_[0] = NULL;
this->pushBucket(0);
// each loop iteration processes a bucket i.e. removes
// the next multiple of its sieving primes
do {
const WheelPrime_t* wPrime = bucket->begin();
const WheelPrime_t* end = bucket->end();
// iterate over the sieving primes within the current bucket
// loop unrolled 2 times, optimized for x64 CPUs
for (; wPrime + 2 <= end; wPrime += 2) {
uint32_t multipleIndex0 = wPrime[0].getMultipleIndex();
uint32_t wheelIndex0 = wPrime[0].getWheelIndex();
uint32_t sievingPrime0 = wPrime[0].getSievingPrime();
uint32_t multipleIndex1 = wPrime[1].getMultipleIndex();
uint32_t wheelIndex1 = wPrime[1].getWheelIndex();
uint32_t sievingPrime1 = wPrime[1].getSievingPrime();
// cross-off the next multiple (unset corresponding bit) of the
// current sieving primes within the sieve array
sieve[multipleIndex0] &= wheel(wheelIndex0)->unsetBit;
multipleIndex0 += wheel(wheelIndex0)->nextMultipleFactor * sievingPrime0;
multipleIndex0 += wheel(wheelIndex0)->correct;
wheelIndex0 += wheel(wheelIndex0)->next;
sieve[multipleIndex1] &= wheel(wheelIndex1)->unsetBit;
multipleIndex1 += wheel(wheelIndex1)->nextMultipleFactor * sievingPrime1;
multipleIndex1 += wheel(wheelIndex1)->correct;
wheelIndex1 += wheel(wheelIndex1)->next;
uint32_t next0 = (multipleIndex0 >> log2SieveSize_) & moduloListsSize_;
multipleIndex0 &= moduloSieveSize_;
uint32_t next1 = (multipleIndex1 >> log2SieveSize_) & moduloListsSize_;
multipleIndex1 &= moduloSieveSize_;
// move the current sieving primes to the bucket list
// related to their next multiple occurrence
if (!lists_[next0]->addWheelPrime(sievingPrime0, multipleIndex0, wheelIndex0))
this->pushBucket(next0);
if (!lists_[next1]->addWheelPrime(sievingPrime1, multipleIndex1, wheelIndex1))
this->pushBucket(next1);
}
// process the remaining sieving primes
for (; wPrime < end; wPrime++) {
uint32_t multipleIndex = wPrime->getMultipleIndex();
uint32_t wheelIndex = wPrime->getWheelIndex();
uint32_t sievingPrime = wPrime->getSievingPrime();
sieve[multipleIndex] &= wheel(wheelIndex)->unsetBit;
multipleIndex += wheel(wheelIndex)->nextMultipleFactor * sievingPrime;
multipleIndex += wheel(wheelIndex)->correct;
wheelIndex += wheel(wheelIndex)->next;
uint32_t next = (multipleIndex >> log2SieveSize_) & moduloListsSize_;
multipleIndex &= moduloSieveSize_;
if (!lists_[next]->addWheelPrime(sievingPrime, multipleIndex, wheelIndex))
this->pushBucket(next);
}
// reset the processed bucket and move it to the bucket stock_
Bucket_t* old = bucket;
bucket = bucket->next();
old->reset();
old->setNext(stock_);
stock_ = old;
}
while (bucket != NULL);
}
// lists_[0] has been processed, thus the list related to
// the next segment lists_[1] moves to lists_[0]
Bucket_t* tmp = lists_[0];
std::memmove(lists_, &lists_[1], (size_ - 1) * sizeof(Bucket_t*));
lists_[size_ - 1] = tmp;
}
<|endoftext|>
|
<commit_before>#include "splitSolver.h"
#include "readConfig.h"
void SplitSolver::setOptions(const ConfigOptions& options_)
{
options = options_;
useBalancedSplitting = (options.splittingMethod == "balanced");
dt = options.globalTimestep;
}
void SplitSolver::resize(index_t nRows, index_t nCols)
{
state.resize(nRows, nCols);
startState.resize(nRows, nCols);
deltaConv.resize(nRows, nCols);
deltaDiff.resize(nRows, nCols);
deltaProd.resize(nRows, nCols);
ddtConv.resize(nRows, nCols);
ddtDiff.resize(nRows, nCols);
ddtProd.resize(nRows, nCols);
ddtCross.resize(nRows, nCols);
splitConstConv.setZero(nRows, nCols);
splitConstDiff.setZero(nRows, nCols);
splitConstProd.setZero(nRows, nCols);
}
void SplitSolver::calculateTimeDerivatives(double dt)
{
double split = useBalancedSplitting;
if (useBalancedSplitting) {
deltaConv -= 0.25 * dt * (ddtProd + ddtDiff + ddtCross);
deltaDiff -= 0.25 * dt * (ddtProd + ddtConv + ddtCross);
deltaProd -= 0.5 * dt * (ddtConv + ddtDiff + ddtCross);
}
ddtConv = deltaConv / dt + split * 0.75 * ddtConv;
ddtDiff = deltaDiff / dt + split * 0.75 * ddtDiff;
ddtProd = deltaProd / dt + split * 0.5 * ddtProd;
}
int SplitSolver::step()
{
setupStep();
if (useBalancedSplitting) {
splitConstDiff = 0.25 * (ddtProd + ddtConv + ddtCross - 3 * ddtDiff);
splitConstConv = 0.25 * (ddtProd + ddtDiff + ddtCross - 3 * ddtConv);
splitConstProd = 0.5 * (ddtConv + ddtDiff + ddtCross - ddtProd);
} else {
splitConstDiff = ddtCross;
}
if (t == tStart && options.outputProfiles) {
writeStateFile("", false, false);
}
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("start_t%.6f") % t).str(), true, false);
}
prepareIntegrators();
integrateSplitTerms(t, dt);
calculateTimeDerivatives(dt);
return finishStep();
}
void SplitSolver::integrateSplitTerms(double t, double dt)
{
splitTimer.start();
deltaConv.setZero();
deltaProd.setZero();
deltaDiff.setZero();
splitTimer.stop();
_integrateDiffusionTerms(t, t + 0.25*dt, 1); // step 1/4
_integrateConvectionTerms(t, t + 0.5*dt, 1); // step 1/2
_integrateDiffusionTerms(t + 0.25*dt, t + 0.5*dt, 2); // step 2/4
_integrateProductionTerms(t, t + dt, 1); // full step
_integrateDiffusionTerms(t + 0.5*dt, t + 0.75*dt, 3); // step 3/4
_integrateConvectionTerms(t + 0.5*dt, t + dt, 2); // step 2/2
_integrateDiffusionTerms(t + 0.75*dt, t + dt, 4); // step 4/4
}
void SplitSolver::_integrateDiffusionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
assert(mathUtils::notnan(state));
logFile.verboseWrite(format("diffusion terms %i/4...") % stage, false);
startState = state;
integrateDiffusionTerms();
assert(mathUtils::notnan(state));
deltaDiff += state - startState;
if (stage && options.debugIntegratorStages(tNow)) {
writeStateFile((format("diff%i_t%.6f") % stage % tNow).str(), true, false);
}
}
void SplitSolver::_integrateProductionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
logFile.verboseWrite("Source term...", false);
assert(mathUtils::notnan(state));
startState = state;
integrateProductionTerms();
assert(mathUtils::notnan(state));
deltaProd += state - startState;
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("prod_t%.6f") % tNow).str(), true, false);
}
}
void SplitSolver::_integrateConvectionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
assert(stage == 1 || stage == 2);
assert(mathUtils::notnan(state));
logFile.verboseWrite(format("convection term %i/2...") % stage, false);
startState = state;
integrateConvectionTerms();
assert(mathUtils::notnan(state));
deltaConv += state - startState;
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("conv%i_t%.6f") % stage % tNow).str(), true, false);
}
}
<commit_msg>Simplify calculation of time derivatives<commit_after>#include "splitSolver.h"
#include "readConfig.h"
void SplitSolver::setOptions(const ConfigOptions& options_)
{
options = options_;
useBalancedSplitting = (options.splittingMethod == "balanced");
dt = options.globalTimestep;
}
void SplitSolver::resize(index_t nRows, index_t nCols)
{
state.resize(nRows, nCols);
startState.resize(nRows, nCols);
deltaConv.resize(nRows, nCols);
deltaDiff.resize(nRows, nCols);
deltaProd.resize(nRows, nCols);
ddtConv.resize(nRows, nCols);
ddtDiff.resize(nRows, nCols);
ddtProd.resize(nRows, nCols);
ddtCross.resize(nRows, nCols);
splitConstConv.setZero(nRows, nCols);
splitConstDiff.setZero(nRows, nCols);
splitConstProd.setZero(nRows, nCols);
}
void SplitSolver::calculateTimeDerivatives(double dt)
{
ddtConv = deltaConv / dt - splitConstConv;
ddtDiff = deltaDiff / dt - splitConstDiff;
ddtProd = deltaProd / dt - splitConstProd;
}
int SplitSolver::step()
{
setupStep();
if (useBalancedSplitting) {
splitConstDiff = 0.25 * (ddtProd + ddtConv + ddtCross - 3 * ddtDiff);
splitConstConv = 0.25 * (ddtProd + ddtDiff + ddtCross - 3 * ddtConv);
splitConstProd = 0.5 * (ddtConv + ddtDiff + ddtCross - ddtProd);
} else {
splitConstDiff = ddtCross;
}
if (t == tStart && options.outputProfiles) {
writeStateFile("", false, false);
}
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("start_t%.6f") % t).str(), true, false);
}
prepareIntegrators();
integrateSplitTerms(t, dt);
calculateTimeDerivatives(dt);
return finishStep();
}
void SplitSolver::integrateSplitTerms(double t, double dt)
{
splitTimer.start();
deltaConv.setZero();
deltaProd.setZero();
deltaDiff.setZero();
splitTimer.stop();
_integrateDiffusionTerms(t, t + 0.25*dt, 1); // step 1/4
_integrateConvectionTerms(t, t + 0.5*dt, 1); // step 1/2
_integrateDiffusionTerms(t + 0.25*dt, t + 0.5*dt, 2); // step 2/4
_integrateProductionTerms(t, t + dt, 1); // full step
_integrateDiffusionTerms(t + 0.5*dt, t + 0.75*dt, 3); // step 3/4
_integrateConvectionTerms(t + 0.5*dt, t + dt, 2); // step 2/2
_integrateDiffusionTerms(t + 0.75*dt, t + dt, 4); // step 4/4
}
void SplitSolver::_integrateDiffusionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
assert(mathUtils::notnan(state));
logFile.verboseWrite(format("diffusion terms %i/4...") % stage, false);
startState = state;
integrateDiffusionTerms();
assert(mathUtils::notnan(state));
deltaDiff += state - startState;
if (stage && options.debugIntegratorStages(tNow)) {
writeStateFile((format("diff%i_t%.6f") % stage % tNow).str(), true, false);
}
}
void SplitSolver::_integrateProductionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
logFile.verboseWrite("Source term...", false);
assert(mathUtils::notnan(state));
startState = state;
integrateProductionTerms();
assert(mathUtils::notnan(state));
deltaProd += state - startState;
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("prod_t%.6f") % tNow).str(), true, false);
}
}
void SplitSolver::_integrateConvectionTerms(double tStart, double tEnd, int stage)
{
tStageStart = tStart;
tStageEnd = tEnd;
assert(stage == 1 || stage == 2);
assert(mathUtils::notnan(state));
logFile.verboseWrite(format("convection term %i/2...") % stage, false);
startState = state;
integrateConvectionTerms();
assert(mathUtils::notnan(state));
deltaConv += state - startState;
if (options.debugIntegratorStages(tNow)) {
writeStateFile((format("conv%i_t%.6f") % stage % tNow).str(), true, false);
}
}
<|endoftext|>
|
<commit_before>
#include "stringmanip.h"
#include "types.h"
#include <cstdio>
#include <sstream>
#include <iomanip>
#include <algorithm>
#ifdef __linux__
#include <dirent.h>
#include <sys/stat.h>
#elif _WIN32
#include <windows.h>
#endif
uint32 CountCharsInString(const std::string &strTarget, uchar8 chChar){
uint32 uiCount = 0;
for (uint32 i=0; i<strTarget.size(); i++){
if (strTarget[i] == chChar){
uiCount++;
}
}
return uiCount;
}
bool GetStringMidByBoundingChars(const std::string &strTarget, uchar8 chBound, std::string &strOutput){
if (CountCharsInString(strTarget, chBound) != 2){
return false;
}
size_t pos1 = strTarget.find(chBound);
size_t pos2 = strTarget.find(chBound, pos1+1);
if (pos1 == std::string::npos || pos2 == std::string::npos){
return false;
}
strOutput = strTarget.substr(pos1+1, pos2-pos1-1);
return true;
}
std::string TxtStrFromBuffer(pcbyte pcbBuffer, const uint32 iBuffSize){
std::string strRet = std::string(reinterpret_cast<const char *>(pcbBuffer), iBuffSize);
return strRet;
}
std::string HexStrFromBuffer(pcbyte pcbBuffer, const uint32 iBuffSize){
std::string strRet;
char chAux[3] = {0};
for (uint32 i = 0; i < iBuffSize; i++){
sprintf(chAux, "%02X", pcbBuffer[i]);
strRet += chAux;
}
return strRet;
}
std::string PopExtension(const std::string &strFilename)
{
size_t dotpos = strFilename.rfind(".");
std::string strExt;
if (dotpos != std::string::npos && dotpos < strFilename.size()-1){
strExt = strFilename.substr(0, dotpos);
}
return strExt;
}
std::string GetExtension(const std::string &strFilename)
{
size_t dotpos = strFilename.rfind(".");
std::string strExt;
if (dotpos != std::string::npos && dotpos < strFilename.size()-1){
strExt = strFilename.substr(dotpos+1);
}
return strExt;
}
bool FileExists(const std::string &strFileName){
bool bRet = false;
FILE * fp = fopen(strFileName.c_str(), "r+");
if (fp){
bRet = true;
fclose(fp);
}
return bRet;
}
#if defined(__linux__) || defined(_AIX)
bool BuildFileList(const std::string &strPath, const std::string &strInputExt, StrVecCont &svcFileList) {
svcFileList.Clear();
DIR *dp;
struct dirent *dirp;
std::string filepath;
if((dp = opendir(strPath.c_str())) == nullptr) {
return false;
}
while ((dirp = readdir(dp)) != nullptr) {
#ifdef __linux__
if (dirp->d_type == DT_DIR)
continue; // ignore folders
#else
struct stat s;
filepath = strPath + "/" + dirp->d_name;
// If the file is a directory (or is in some way invalid) we'll skip it
if (stat( filepath.c_str(), &s )) continue;
if (S_ISDIR( s.st_mode )) continue;
#endif
std::string strCurr = dirp->d_name;
if (GetExtension(strCurr) == strInputExt){
svcFileList.PushBack(strCurr);
}
}
closedir(dp);
return true;
}
#endif
#ifdef _WIN32
bool BuildFileList(const std::string &strPath, const std::string &strInputExt, StrVecCont &svcFilelist){
svcFilelist.Clear();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
DWORD dwError=0;
std::string strPathWildcard = strPath + "\\*";
hFind = FindFirstFile(strPathWildcard.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind){
return false;
}
while (FindNextFile(hFind, &ffd) != 0){
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){
std::string strCurr = ffd.cFileName;
if (GetExtension(strCurr) == strInputExt){
svcFilelist.PushBack(strCurr);
}
}
}
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
return false;
}
FindClose(hFind);
return true;
}
#endif
#if defined(__linux__) || defined(_AIX)
bool DirExists(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool DirExists(const std::string &strDirName, bool &answer)
{
DWORD ftyp = GetFileAttributesA(strDirName.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES){
return false; // invalid path - operation failed
}
if (ftyp & FILE_ATTRIBUTE_DIRECTORY){
answer = true; // this is a directory!
} else {
answer = false; // this is not a directory!
}
return true; // operation succeeded
}
#endif
#if defined(__linux__) || defined(_AIX)
bool HasWritePermission(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) != 0){
return false;
}
if (sb.st_mode & S_IWUSR){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool HasWritePermission(const std::string &strDirName){
#error "This function is unimplemented for Windows";
return false; // nag me not
}
#endif
#if defined(__linux__) || defined(_AIX)
bool HasReadPermission(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) != 0){
return false;
}
if (sb.st_mode & S_IRUSR){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool HasReadPermission(const std::string &strDirName)
{
return true; // more or less safe to make such assumption for the time being.
}
#endif
template< typename T >
std::string NumberToHexStr( T i, bool bAutoFill )
{
std::stringstream stream;
if (bAutoFill)
stream << std::setfill('0') << std::setw((i > 0xFF ? 4 : 2)) << std::hex << i;
else
stream << std::hex << i;
std::string tmp = stream.str();
MakeUppercase(tmp);
return tmp;
}
sint32 DecStrToInteger(const std::string &strSource){
int ret;
std::stringstream(strSource) >> ret;
return ret;
}
std::string IntegerToDecStr( sint32 i )
{
std::stringstream stream;
stream << std::dec << i;
std::string tmp = stream.str();
return tmp;
}
sint32 HexStrToInteger(const std::string &strSource){
sint32 ret;
std::stringstream(strSource) >> std::hex >> ret;
return ret;
}
void MakeUppercase(std::string &strTarget){
std::transform(strTarget.begin(), strTarget.end(), strTarget.begin(), ::toupper);
}
void MakeLowercase(std::string &strTarget){
std::transform(strTarget.begin(), strTarget.end(), strTarget.begin(), ::tolower);
}
sint32 CompareNoCase(const std::string &strLeft, const std::string &strRight){
std::string left = strLeft;
std::string right = strRight;
MakeLowercase(left);
MakeLowercase(right);
sint32 ret = left.compare(right);
return ret;
}
bool EqualsNoCase(const std::string &strLeft, const std::string &strRight){
if (CompareNoCase(strLeft, strRight) == 0)
return true;
else
return false;
}
bool ContainsNoCase(const std::string &strTarget, const std::string &strContent){
std::string target = strTarget;
std::string content = strContent;
MakeLowercase(target);
MakeLowercase(content);
size_t ret = target.find(content);
if (ret == std::string::npos)
return false;
else
return true;
}
bool IsNumericString(const std::string &strElement) {
std::istringstream ss(strElement);
sint32 num = 0;
if(ss >> num) {
return true;
}
return false;
}
<commit_msg>small cosmetic corrections<commit_after>
#include "stringmanip.h"
#include "types.h"
#include <cstdio>
#include <sstream>
#include <iomanip>
#include <algorithm>
#ifdef __linux__
#include <dirent.h>
#include <sys/stat.h>
#elif _WIN32
#include <windows.h>
#endif
uint32 CountCharsInString(const std::string &strTarget, uchar8 chChar){
uint32 uiCount = 0;
for (uint32 i=0; i<strTarget.size(); i++){
if (strTarget[i] == chChar){
uiCount++;
}
}
return uiCount;
}
bool GetStringMidByBoundingChars(const std::string &strTarget, uchar8 chBound, std::string &strOutput){
if (CountCharsInString(strTarget, chBound) != 2){
return false;
}
size_t pos1 = strTarget.find(chBound);
size_t pos2 = strTarget.find(chBound, pos1+1);
if (pos1 == std::string::npos || pos2 == std::string::npos){
return false;
}
strOutput = strTarget.substr(pos1+1, pos2-pos1-1);
return true;
}
std::string TxtStrFromBuffer(pcbyte pcbBuffer, const uint32 iBuffSize){
std::string strRet = std::string(reinterpret_cast<const char *>(pcbBuffer), iBuffSize);
return strRet;
}
std::string HexStrFromBuffer(pcbyte pcbBuffer, const uint32 iBuffSize){
std::string strRet;
char chAux[3] = {0};
for (uint32 i = 0; i < iBuffSize; i++){
sprintf(chAux, "%02X", pcbBuffer[i]);
strRet += chAux;
}
return strRet;
}
std::string PopExtension(const std::string &strFilename){
size_t dotpos = strFilename.rfind(".");
std::string strExt;
if (dotpos != std::string::npos && dotpos < strFilename.size()-1){
strExt = strFilename.substr(0, dotpos);
}
return strExt;
}
std::string GetExtension(const std::string &strFilename){
size_t dotpos = strFilename.rfind(".");
std::string strExt;
if (dotpos != std::string::npos && dotpos < strFilename.size()-1){
strExt = strFilename.substr(dotpos+1);
}
return strExt;
}
bool FileExists(const std::string &strFileName){
bool bRet = false;
FILE * fp = fopen(strFileName.c_str(), "r+");
if (fp){
bRet = true;
fclose(fp);
}
return bRet;
}
#if defined(__linux__) || defined(_AIX)
bool BuildFileList(const std::string &strPath, const std::string &strInputExt, StrVecCont &svcFileList) {
svcFileList.Clear();
DIR *dp;
struct dirent *dirp;
std::string filepath;
if((dp = opendir(strPath.c_str())) == nullptr) {
return false;
}
while ((dirp = readdir(dp)) != nullptr) {
#ifdef __linux__
if (dirp->d_type == DT_DIR) continue; // ignore folders
#else
struct stat s;
filepath = strPath + "/" + dirp->d_name;
// If the file is a directory (or is in some way invalid) we'll skip it
if (stat( filepath.c_str(), &s )) continue;
if (S_ISDIR( s.st_mode )) continue;
#endif
std::string strCurr = dirp->d_name;
if (GetExtension(strCurr) == strInputExt){
svcFileList.PushBack(strCurr);
}
}
closedir(dp);
return true;
}
#endif
#ifdef _WIN32
bool BuildFileList(const std::string &strPath, const std::string &strInputExt, StrVecCont &svcFilelist){
svcFilelist.Clear();
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
DWORD dwError=0;
std::string strPathWildcard = strPath + "\\*";
hFind = FindFirstFile(strPathWildcard.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind){
return false;
}
while (FindNextFile(hFind, &ffd) != 0){
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){
std::string strCurr = ffd.cFileName;
if (GetExtension(strCurr) == strInputExt){
svcFilelist.PushBack(strCurr);
}
}
}
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
return false;
}
FindClose(hFind);
return true;
}
#endif
#if defined(__linux__) || defined(_AIX)
bool DirExists(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool DirExists(const std::string &strDirName, bool &answer){
DWORD ftyp = GetFileAttributesA(strDirName.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES){
return false; // invalid path - operation failed
}
if (ftyp & FILE_ATTRIBUTE_DIRECTORY){
answer = true; // this is a directory!
} else {
answer = false; // this is not a directory!
}
return true; // operation succeeded
}
#endif
#if defined(__linux__) || defined(_AIX)
bool HasWritePermission(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) != 0){
return false;
}
if (sb.st_mode & S_IWUSR){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool HasWritePermission(const std::string &strDirName){
#error "This function is unimplemented for Windows";
return false; // nag me not
}
#endif
#if defined(__linux__) || defined(_AIX)
bool HasReadPermission(const std::string &strDirName){
struct stat sb;
if (stat(strDirName.c_str(), &sb) != 0){
return false;
}
if (sb.st_mode & S_IRUSR){
return true;
}
return false;
}
#endif
#ifdef _WIN32
bool HasReadPermission(const std::string &strDirName){
return true; // more or less safe to make such assumption for the time being.
}
#endif
template< typename T >
std::string NumberToHexStr( T i, bool bAutoFill ){
std::stringstream stream;
if (bAutoFill)
stream << std::setfill('0') << std::setw((i > 0xFF ? 4 : 2)) << std::hex << i;
else
stream << std::hex << i;
std::string tmp = stream.str();
MakeUppercase(tmp);
return tmp;
}
sint32 DecStrToInteger(const std::string &strSource){
int ret;
std::stringstream(strSource) >> ret;
return ret;
}
std::string IntegerToDecStr( sint32 i ){
std::stringstream stream;
stream << std::dec << i;
std::string tmp = stream.str();
return tmp;
}
sint32 HexStrToInteger(const std::string &strSource){
sint32 ret;
std::stringstream(strSource) >> std::hex >> ret;
return ret;
}
void MakeUppercase(std::string &strTarget){
std::transform(strTarget.begin(), strTarget.end(), strTarget.begin(), ::toupper);
}
void MakeLowercase(std::string &strTarget){
std::transform(strTarget.begin(), strTarget.end(), strTarget.begin(), ::tolower);
}
sint32 CompareNoCase(const std::string &strLeft, const std::string &strRight){
std::string left = strLeft;
std::string right = strRight;
MakeLowercase(left);
MakeLowercase(right);
sint32 ret = left.compare(right);
return ret;
}
bool EqualsNoCase(const std::string &strLeft, const std::string &strRight){
if (CompareNoCase(strLeft, strRight) == 0)
return true;
else
return false;
}
bool ContainsNoCase(const std::string &strTarget, const std::string &strContent){
std::string target = strTarget;
std::string content = strContent;
MakeLowercase(target);
MakeLowercase(content);
size_t ret = target.find(content);
if (ret == std::string::npos)
return false;
else
return true;
}
bool IsNumericString(const std::string &strElement) {
std::istringstream ss(strElement);
sint32 num = 0;
if(ss >> num) {
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Process.h"
#include <ctime>
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const llvm::opt::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir, new DeclCollector());
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir,
DeclCollector* stateCollector) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::SmallString<512> resource_path;
if (llvmdir) {
resource_path = llvmdir;
llvm::sys::path::append(resource_path,"lib", "clang", CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!llvm::sys::fs::is_directory(resource_path.str())) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions();
DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions,
DiagnosticPrinter, /*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::SmallString<512> oldResInc(Opts.ResourceDir);
llvm::sys::path::append(oldResInc, "include");
llvm::SmallString<512> newResInc(resource_path);
llvm::sys::path::append(newResInc, "include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsFramework && E.Group == clang::frontend::System
&& E.IgnoreSysRoot && oldResInc.str() == E.Path) {
E.Path = newResInc.c_str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(DiagnosticPrinter, /*ShouldOwnClient=*/ false);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getLangOpts().CPlusPlus11 == 1) {
// http://llvm.org/bugs/show_bug.cgi?id=13530
CI->getInvocation().getPreprocessorOpts()
.addMacroDef("__CLING__CXX11");
}
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
&Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) {
// clang "forgets" the basic arch part needed by winnt.h:
if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) {
CI->getInvocation().getPreprocessorOpts().addMacroDef("_X86_=1");
} else if (CI->getTarget().getTriple().getArch()
== llvm::Triple::x86_64) {
CI->getInvocation().getPreprocessorOpts().addMacroDef("__x86_64=1");
} else {
llvm::errs() << "Warning: unhandled target architecture "
<< CI->getTarget().getTriple().getArchName() << '\n';
}
}
// Set up source and file managers
CI->createFileManager();
SourceManager* SM = new SourceManager(CI->getDiagnostics(),
CI->getFileManager(),
/*UserFilesAreVolatile*/ true);
CI->setSourceManager(SM); // FIXME: SM leaks.
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
else {
// As main file we want
// * a virtual file that is claiming to be huge
// * with an empty memory buffer attached (to bring the content)
SourceManager& SM = CI->getSourceManager();
FileManager& FM = SM.getFileManager();
// Build the virtual file
const char* Filename = "InteractiveInputLineIncluder.h";
const std::string& CGOptsMainFileName
= CI->getInvocation().getCodeGenOpts().MainFileName;
if (!CGOptsMainFileName.empty())
Filename = CGOptsMainFileName.c_str();
const FileEntry* FE
= FM.getVirtualFile(Filename, 1U << 15U, time(0));
FileID MainFileID = SM.createMainFileID(FE, SrcMgr::C_User);
const SrcMgr::SLocEntry& MainFileSLocE = SM.getSLocEntry(MainFileID);
const SrcMgr::ContentCache* MainFileCC
= MainFileSLocE.getFile().getContentCache();
llvm::MemoryBuffer* MainFileMB
= llvm::MemoryBuffer::getMemBuffer("/*CLING MAIN FILE*/\n");
const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(MainFileMB);
}
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
if (stateCollector) {
// Add the callback keeping track of the macro definitions
PP.addPPCallbacks(stateCollector);
}
else
stateCollector = new DeclCollector();
// Set up the ASTConsumers
CI->setASTConsumer(stateCollector);
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
CI->takeASTConsumer(); // We transfer to ownership to the PP only
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete
// ctor to the base ctor causes
// the JIT to crash
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 0; // Otherwise if PCH attached will codegen all decls.
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
//Opts.Modules = 1;
// C++11 is turned on if cling is built with C++11: it's an interperter;
// cross-language compilation doesn't make sense.
// Extracted from Boost/config/compiler.
// SunProCC has no C++11.
// VisualC's support is not obvious to extract from Boost...
#if /*GCC*/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__)) \
|| /*clang*/ (defined(__has_feature) && __has_feature(cxx_decltype)) \
|| /*ICC*/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__))
Opts.CPlusPlus11 = 1;
#endif
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<commit_msg>Comment<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Process.h"
#include <ctime>
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const llvm::opt::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir, new DeclCollector());
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir,
DeclCollector* stateCollector) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::SmallString<512> resource_path;
if (llvmdir) {
resource_path = llvmdir;
llvm::sys::path::append(resource_path,"lib", "clang", CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!llvm::sys::fs::is_directory(resource_path.str())) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions();
DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions,
DiagnosticPrinter, /*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::SmallString<512> oldResInc(Opts.ResourceDir);
llvm::sys::path::append(oldResInc, "include");
llvm::SmallString<512> newResInc(resource_path);
llvm::sys::path::append(newResInc, "include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsFramework && E.Group == clang::frontend::System
&& E.IgnoreSysRoot && oldResInc.str() == E.Path) {
E.Path = newResInc.c_str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(DiagnosticPrinter, /*ShouldOwnClient=*/ false);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getLangOpts().CPlusPlus11 == 1) {
// http://llvm.org/bugs/show_bug.cgi?id=13530
CI->getInvocation().getPreprocessorOpts()
.addMacroDef("__CLING__CXX11");
}
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
&Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) {
// clang "forgets" the basic arch part needed by winnt.h:
if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) {
CI->getInvocation().getPreprocessorOpts().addMacroDef("_X86_=1");
} else if (CI->getTarget().getTriple().getArch()
== llvm::Triple::x86_64) {
CI->getInvocation().getPreprocessorOpts().addMacroDef("__x86_64=1");
} else {
llvm::errs() << "Warning: unhandled target architecture "
<< CI->getTarget().getTriple().getArchName() << '\n';
}
}
// Set up source and file managers
CI->createFileManager();
SourceManager* SM = new SourceManager(CI->getDiagnostics(),
CI->getFileManager(),
/*UserFilesAreVolatile*/ true);
CI->setSourceManager(SM); // FIXME: SM leaks.
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
else {
// As main file we want
// * a virtual file that is claiming to be huge
// * with an empty memory buffer attached (to bring the content)
SourceManager& SM = CI->getSourceManager();
FileManager& FM = SM.getFileManager();
// Build the virtual file
const char* Filename = "InteractiveInputLineIncluder.h";
const std::string& CGOptsMainFileName
= CI->getInvocation().getCodeGenOpts().MainFileName;
if (!CGOptsMainFileName.empty())
Filename = CGOptsMainFileName.c_str();
const FileEntry* FE
= FM.getVirtualFile(Filename, 1U << 15U, time(0));
FileID MainFileID = SM.createMainFileID(FE, SrcMgr::C_User);
const SrcMgr::SLocEntry& MainFileSLocE = SM.getSLocEntry(MainFileID);
const SrcMgr::ContentCache* MainFileCC
= MainFileSLocE.getFile().getContentCache();
llvm::MemoryBuffer* MainFileMB
= llvm::MemoryBuffer::getMemBuffer("/*CLING MAIN FILE*/\n");
const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(MainFileMB);
}
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
if (stateCollector) {
// Add the callback keeping track of the macro definitions
PP.addPPCallbacks(stateCollector);
}
else
stateCollector = new DeclCollector();
// Set up the ASTConsumers
CI->setASTConsumer(stateCollector);
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
CI->takeASTConsumer(); // Transfer to ownership to the PP only
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete
// ctor to the base ctor causes
// the JIT to crash
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 0; // Otherwise if PCH attached will codegen all decls.
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
//Opts.Modules = 1;
// C++11 is turned on if cling is built with C++11: it's an interperter;
// cross-language compilation doesn't make sense.
// Extracted from Boost/config/compiler.
// SunProCC has no C++11.
// VisualC's support is not obvious to extract from Boost...
#if /*GCC*/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__)) \
|| /*clang*/ (defined(__has_feature) && __has_feature(cxx_decltype)) \
|| /*ICC*/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__))
Opts.CPlusPlus11 = 1;
#endif
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mem/ruby/buffers/MessageBufferNode.hh"
void
MessageBufferNode::print(std::ostream& out) const
{
out << "[";
out << m_time << ", ";
out << m_msg_counter << ", ";
out << m_msgptr << "; ";
out << "]";
}
<commit_msg># User Brad Beckmann <Brad.Beckmann@amd.com> ruby: fixed msgptr print call<commit_after>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mem/ruby/buffers/MessageBufferNode.hh"
void
MessageBufferNode::print(std::ostream& out) const
{
out << "[";
out << m_time << ", ";
out << m_msg_counter << ", ";
out << *m_msgptr << "; ";
out << "]";
}
<|endoftext|>
|
<commit_before>#include "util/typedefs.hpp"
#include "util/coordinate_calculation.hpp"
#include "util/dynamic_graph.hpp"
#include "util/static_graph.hpp"
#include "util/fingerprint.hpp"
#include "util/graph_loader.hpp"
#include "util/make_unique.hpp"
#include "util/exception.hpp"
#include "util/simple_logger.hpp"
#include "util/binary_heap.hpp"
#include "engine/datafacade/internal_datafacade.hpp"
#include "util/routed_options.hpp"
#include <boost/filesystem.hpp>
#include <boost/timer/timer.hpp>
#include "osrm/coordinate.hpp"
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include <unordered_set>
namespace osrm
{
namespace tools
{
struct BoundingBox {
FixedPointCoordinate southwest;
FixedPointCoordinate northeast;
};
BoundingBox TileToBBOX(int z, int x, int y)
{
// A small box in SF near the marina covering the intersection
// of Powell and Embarcadero
return { { static_cast<int32_t>(37.80781742045232 * COORDINATE_PRECISION) , static_cast<int32_t>(-122.4139380455017 * COORDINATE_PRECISION) },
{ static_cast<int32_t>(37.809410993963944 * COORDINATE_PRECISION), static_cast<int32_t>(-122.41186738014221 * COORDINATE_PRECISION) } };
}
}
}
int main(int argc, char *argv[])
{
std::vector<osrm::extractor::QueryNode> coordinate_list;
osrm::util::LogPolicy::GetInstance().Unmute();
// enable logging
if (argc < 5)
{
osrm::util::SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " <filename.osrm> <z> <x> <y>";
return EXIT_FAILURE;
}
// Set up the datafacade for querying
std::unordered_map<std::string, boost::filesystem::path> server_paths;
server_paths["base"] = std::string(argv[1]);
osrm::util::populate_base_path(server_paths);
osrm::engine::datafacade::InternalDataFacade<osrm::contractor::QueryEdge::EdgeData> datafacade(server_paths);
// Step 1 - convert z,x,y into tile bounds
//
int z = std::stoi(argv[2]);
int x = std::stoi(argv[3]);
int y = std::stoi(argv[4]);
auto bbox = util::coordinate_calculation::mercator::TileToBBOX(z,x,y); // @karenzshea - implement this function!!
// Step 2 - Get all the features from those bounds
//
//
auto edges = datafacade.GetEdgesInBox(bbox.southwest, bbox.northeast);
// Step 3 - Encode those features as Mapbox Vector Tiles
//
//
for (const auto & edge : edges)
{
const auto a = datafacade.GetCoordinateOfNode(edge.u);
const auto b = datafacade.GetCoordinateOfNode(edge.v);
std::cout << "Feature: " << a << " to " << b << std::endl;
}
// Step 4 - Output the result
//
return EXIT_SUCCESS;
}
<commit_msg>Remove draft tiler tool, we moved everything into<commit_after><|endoftext|>
|
<commit_before>#include <sys/time.h>
#include <iostream>
#include <stack>
#define SMOOTH(s) for(int _smooth=0;_smooth<s;++_smooth)
/* Return the time spent in secs. */
inline double operator- ( const struct timeval & t1,const struct timeval & t0)
{
return (t1.tv_sec - t0.tv_sec)+1e-6*(t1.tv_usec - t0.tv_usec);
}
struct StackTicToc
{
enum Unit { S = 1, MS = 1000, US = 1000000 };
Unit DEFAULT_UNIT;
static std::string unitName(Unit u)
{ switch(u) { case S: return "s"; case MS: return "ms"; case US: return "us"; } return ""; }
std::stack<struct timeval> stack;
mutable struct timeval t0;
StackTicToc( Unit def = MS ) : DEFAULT_UNIT(def) {}
inline void tic() {
stack.push(t0);
gettimeofday(&(stack.top()),NULL);
}
inline double toc(const Unit factor)
{
gettimeofday(&t0,NULL);
double dt = (t0-stack.top())*factor;
stack.pop();
return dt;
}
inline void toc( std::ostream& os, double SMOOTH=1 )
{
os << toc(DEFAULT_UNIT)/SMOOTH << " " << unitName(DEFAULT_UNIT) << std::endl;
}
};
<commit_msg>64x correction: static cast of long to double (TODO: check this commit).<commit_after>#include <sys/time.h>
#include <iostream>
#include <stack>
#define SMOOTH(s) for(int _smooth=0;_smooth<s;++_smooth)
/* Return the time spent in secs. */
inline double operator- ( const struct timeval & t1,const struct timeval & t0)
{
/* TODO: double check the double conversion from long (on 64x). */
return double(t1.tv_sec - t0.tv_sec)+1e-6*double(t1.tv_usec - t0.tv_usec);
}
struct StackTicToc
{
enum Unit { S = 1, MS = 1000, US = 1000000 };
Unit DEFAULT_UNIT;
static std::string unitName(Unit u)
{ switch(u) { case S: return "s"; case MS: return "ms"; case US: return "us"; } return ""; }
std::stack<struct timeval> stack;
mutable struct timeval t0;
StackTicToc( Unit def = MS ) : DEFAULT_UNIT(def) {}
inline void tic() {
stack.push(t0);
gettimeofday(&(stack.top()),NULL);
}
inline double toc(const Unit factor)
{
gettimeofday(&t0,NULL);
double dt = (t0-stack.top())*factor;
stack.pop();
return dt;
}
inline void toc( std::ostream& os, double SMOOTH=1 )
{
os << toc(DEFAULT_UNIT)/SMOOTH << " " << unitName(DEFAULT_UNIT) << std::endl;
}
};
<|endoftext|>
|
<commit_before>#include "Array.h"
#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include "preprocessor/llvm_includes_end.h"
#include "RuntimeManager.h"
#include "Runtime.h"
#include "Utils.h"
#include <set> // DEBUG only
namespace dev
{
namespace eth
{
namespace jit
{
static const auto c_reallocStep = 1;
static const auto c_reallocMultipier = 2;
llvm::Value* LazyFunction::call(llvm::IRBuilder<>& _builder, std::initializer_list<llvm::Value*> const& _args, llvm::Twine const& _name)
{
if (!m_func)
m_func = m_creator();
return _builder.CreateCall(m_func, {_args.begin(), _args.size()}, _name);
}
llvm::Function* Array::createArrayPushFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.push", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto value = arrayPtr->getNextNode();
value->setName("value");
InsertPointGuard guard{m_builder};
auto entryBB = llvm::BasicBlock::Create(m_builder.getContext(), "Entry", func);
auto reallocBB = llvm::BasicBlock::Create(m_builder.getContext(), "Realloc", func);
auto pushBB = llvm::BasicBlock::Create(m_builder.getContext(), "Push", func);
m_builder.SetInsertPoint(entryBB);
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto cap = m_builder.CreateLoad(capPtr, "cap");
auto reallocReq = m_builder.CreateICmpEQ(cap, size, "reallocReq");
m_builder.CreateCondBr(reallocReq, reallocBB, pushBB);
m_builder.SetInsertPoint(reallocBB);
auto newCap = m_builder.CreateNUWAdd(cap, m_builder.getInt64(c_reallocStep), "newCap");
//newCap = m_builder.CreateNUWMul(newCap, m_builder.getInt64(c_reallocMultipier));
auto reallocSize = m_builder.CreateShl(newCap, 5, "reallocSize"); // size in bytes: newCap * 32
auto bytes = m_builder.CreateBitCast(data, Type::BytePtr, "bytes");
auto newBytes = m_reallocFunc.call(m_builder, {bytes, reallocSize}, "newBytes");
auto newData = m_builder.CreateBitCast(newBytes, Type::WordPtr, "newData");
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateStore(newCap, capPtr);
m_builder.CreateBr(pushBB);
m_builder.SetInsertPoint(pushBB);
auto dataPhi = m_builder.CreatePHI(Type::WordPtr, 2, "dataPhi");
dataPhi->addIncoming(data, entryBB);
dataPhi->addIncoming(newData, reallocBB);
auto newElemPtr = m_builder.CreateGEP(dataPhi, size, "newElemPtr");
m_builder.CreateStore(value, newElemPtr);
auto newSize = m_builder.CreateNUWAdd(size, m_builder.getInt64(1), "newSize");
m_builder.CreateStore(newSize, sizePtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::createArraySetFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size, Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.set", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
auto value = index->getNextNode();
value->setName("value");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
m_builder.CreateStore(value, valuePtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::createArrayGetFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Word, argTypes, false), llvm::Function::PrivateLinkage, "array.get", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
auto value = m_builder.CreateLoad(valuePtr, "value");
m_builder.CreateRet(value);
return func;
}
llvm::Function* Array::createGetPtrFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::WordPtr, argTypes, false), llvm::Function::PrivateLinkage, "array.getPtr", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto bytePtr = m_builder.CreateGEP(data, index, "bytePtr");
auto wordPtr = m_builder.CreateBitCast(bytePtr, Type::WordPtr, "wordPtr");
m_builder.CreateRet(wordPtr);
return func;
}
llvm::Function* Array::createFreeFunc()
{
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, m_array->getType(), false), llvm::Function::PrivateLinkage, "array.free", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto freeFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::BytePtr, false), llvm::Function::ExternalLinkage, "ext_free", getModule());
freeFunc->setDoesNotThrow();
freeFunc->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto mem = m_builder.CreateBitCast(data, Type::BytePtr, "mem");
m_builder.CreateCall(freeFunc, mem);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::getReallocFunc()
{
if (auto func = getModule()->getFunction("ext_realloc"))
return func;
llvm::Type* reallocArgTypes[] = {Type::BytePtr, Type::Size};
auto reallocFunc = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, reallocArgTypes, false), llvm::Function::ExternalLinkage, "ext_realloc", getModule());
reallocFunc->setDoesNotThrow();
reallocFunc->setDoesNotAlias(0);
reallocFunc->setDoesNotCapture(1);
return reallocFunc;
}
llvm::Function* Array::createExtendFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.extend", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto newSize = arrayPtr->getNextNode();
newSize->setName("newSize");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");// TODO: Use byte* in Array
auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto extSize = m_builder.CreateNUWSub(newSize, size, "extSize");
auto newData = m_reallocFunc.call(m_builder, {data, newSize}, "newData"); // TODO: Check realloc result for null
auto extPtr = m_builder.CreateGEP(newData, size, "extPtr");
m_builder.CreateMemSet(extPtr, m_builder.getInt8(0), extSize, 16);
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateStore(newSize, sizePtr);
m_builder.CreateStore(newSize, capPtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Type* Array::getType()
{
llvm::Type* elementTys[] = {Type::WordPtr, Type::Size, Type::Size};
static auto arrayTy = llvm::StructType::create(elementTys, "Array");
return arrayTy;
}
Array::Array(llvm::IRBuilder<>& _builder, char const* _name) :
CompilerHelper(_builder),
m_pushFunc([this](){ return createArrayPushFunc(); }),
m_setFunc([this](){ return createArraySetFunc(); }),
m_getFunc([this](){ return createArrayGetFunc(); }),
m_freeFunc([this](){ return createFreeFunc(); })
{
m_array = m_builder.CreateAlloca(getType(), nullptr, _name);
m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}
Array::Array(llvm::IRBuilder<>& _builder, llvm::Value* _array) :
CompilerHelper(_builder),
m_array(_array),
m_pushFunc([this](){ return createArrayPushFunc(); }),
m_setFunc([this](){ return createArraySetFunc(); }),
m_getFunc([this](){ return createArrayGetFunc(); }),
m_freeFunc([this](){ return createFreeFunc(); })
{
m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}
void Array::pop(llvm::Value* _count)
{
auto sizePtr = m_builder.CreateStructGEP(m_array, 1, "sizePtr");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto newSize = m_builder.CreateNUWSub(size, _count, "newSize");
m_builder.CreateStore(newSize, sizePtr);
}
llvm::Value* Array::size(llvm::Value* _array)
{
auto sizePtr = m_builder.CreateStructGEP(_array ? _array : m_array, 1, "sizePtr");
return m_builder.CreateLoad(sizePtr, "array.size");
}
void Array::extend(llvm::Value* _arrayPtr, llvm::Value* _size)
{
assert(_arrayPtr->getType() == m_array->getType());
assert(_size->getType() == Type::Size);
m_extendFunc.call(m_builder, {_arrayPtr, _size});
}
}
}
}
namespace
{
struct AllocatedMemoryWatchdog
{
std::set<void*> allocatedMemory;
~AllocatedMemoryWatchdog()
{
if (!allocatedMemory.empty())
{
DLOG(mem) << allocatedMemory.size() << " MEM LEAKS!\n";
for (auto&& leak : allocatedMemory)
DLOG(mem) << "\t" << leak << "\n";
}
}
};
AllocatedMemoryWatchdog watchdog;
}
extern "C"
{
using namespace dev::eth::jit;
EXPORT void* ext_realloc(void* _data, size_t _size) noexcept
{
//std::cerr << "REALLOC: " << _data << " [" << _size << "]" << std::endl;
auto newData = std::realloc(_data, _size);
if (_data != newData)
{
DLOG(mem) << "REALLOC: " << newData << " <- " << _data << " [" << _size << "]\n";
watchdog.allocatedMemory.erase(_data);
watchdog.allocatedMemory.insert(newData);
}
return newData;
}
EXPORT void ext_free(void* _data) noexcept
{
std::free(_data);
if (_data)
{
DLOG(mem) << "FREE : " << _data << "\n";
watchdog.allocatedMemory.erase(_data);
}
}
} // extern "C"
<commit_msg>Remove memory leak detector. Is it not thread-safe.<commit_after>#include "Array.h"
#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include "preprocessor/llvm_includes_end.h"
#include "RuntimeManager.h"
#include "Runtime.h"
#include "Utils.h"
namespace dev
{
namespace eth
{
namespace jit
{
static const auto c_reallocStep = 1;
static const auto c_reallocMultipier = 2;
llvm::Value* LazyFunction::call(llvm::IRBuilder<>& _builder, std::initializer_list<llvm::Value*> const& _args, llvm::Twine const& _name)
{
if (!m_func)
m_func = m_creator();
return _builder.CreateCall(m_func, {_args.begin(), _args.size()}, _name);
}
llvm::Function* Array::createArrayPushFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.push", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto value = arrayPtr->getNextNode();
value->setName("value");
InsertPointGuard guard{m_builder};
auto entryBB = llvm::BasicBlock::Create(m_builder.getContext(), "Entry", func);
auto reallocBB = llvm::BasicBlock::Create(m_builder.getContext(), "Realloc", func);
auto pushBB = llvm::BasicBlock::Create(m_builder.getContext(), "Push", func);
m_builder.SetInsertPoint(entryBB);
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto cap = m_builder.CreateLoad(capPtr, "cap");
auto reallocReq = m_builder.CreateICmpEQ(cap, size, "reallocReq");
m_builder.CreateCondBr(reallocReq, reallocBB, pushBB);
m_builder.SetInsertPoint(reallocBB);
auto newCap = m_builder.CreateNUWAdd(cap, m_builder.getInt64(c_reallocStep), "newCap");
//newCap = m_builder.CreateNUWMul(newCap, m_builder.getInt64(c_reallocMultipier));
auto reallocSize = m_builder.CreateShl(newCap, 5, "reallocSize"); // size in bytes: newCap * 32
auto bytes = m_builder.CreateBitCast(data, Type::BytePtr, "bytes");
auto newBytes = m_reallocFunc.call(m_builder, {bytes, reallocSize}, "newBytes");
auto newData = m_builder.CreateBitCast(newBytes, Type::WordPtr, "newData");
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateStore(newCap, capPtr);
m_builder.CreateBr(pushBB);
m_builder.SetInsertPoint(pushBB);
auto dataPhi = m_builder.CreatePHI(Type::WordPtr, 2, "dataPhi");
dataPhi->addIncoming(data, entryBB);
dataPhi->addIncoming(newData, reallocBB);
auto newElemPtr = m_builder.CreateGEP(dataPhi, size, "newElemPtr");
m_builder.CreateStore(value, newElemPtr);
auto newSize = m_builder.CreateNUWAdd(size, m_builder.getInt64(1), "newSize");
m_builder.CreateStore(newSize, sizePtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::createArraySetFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size, Type::Word};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.set", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
auto value = index->getNextNode();
value->setName("value");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
m_builder.CreateStore(value, valuePtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::createArrayGetFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Word, argTypes, false), llvm::Function::PrivateLinkage, "array.get", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto valuePtr = m_builder.CreateGEP(data, index, "valuePtr");
auto value = m_builder.CreateLoad(valuePtr, "value");
m_builder.CreateRet(value);
return func;
}
llvm::Function* Array::createGetPtrFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::WordPtr, argTypes, false), llvm::Function::PrivateLinkage, "array.getPtr", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto index = arrayPtr->getNextNode();
index->setName("index");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto bytePtr = m_builder.CreateGEP(data, index, "bytePtr");
auto wordPtr = m_builder.CreateBitCast(bytePtr, Type::WordPtr, "wordPtr");
m_builder.CreateRet(wordPtr);
return func;
}
llvm::Function* Array::createFreeFunc()
{
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, m_array->getType(), false), llvm::Function::PrivateLinkage, "array.free", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto freeFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::BytePtr, false), llvm::Function::ExternalLinkage, "ext_free", getModule());
freeFunc->setDoesNotThrow();
freeFunc->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateStructGEP(arrayPtr, 0, "dataPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto mem = m_builder.CreateBitCast(data, Type::BytePtr, "mem");
m_builder.CreateCall(freeFunc, mem);
m_builder.CreateRetVoid();
return func;
}
llvm::Function* Array::getReallocFunc()
{
if (auto func = getModule()->getFunction("ext_realloc"))
return func;
llvm::Type* reallocArgTypes[] = {Type::BytePtr, Type::Size};
auto reallocFunc = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, reallocArgTypes, false), llvm::Function::ExternalLinkage, "ext_realloc", getModule());
reallocFunc->setDoesNotThrow();
reallocFunc->setDoesNotAlias(0);
reallocFunc->setDoesNotCapture(1);
return reallocFunc;
}
llvm::Function* Array::createExtendFunc()
{
llvm::Type* argTypes[] = {m_array->getType(), Type::Size};
auto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "array.extend", getModule());
func->setDoesNotThrow();
func->setDoesNotCapture(1);
auto arrayPtr = &func->getArgumentList().front();
arrayPtr->setName("arrayPtr");
auto newSize = arrayPtr->getNextNode();
newSize->setName("newSize");
InsertPointGuard guard{m_builder};
m_builder.SetInsertPoint(llvm::BasicBlock::Create(m_builder.getContext(), {}, func));
auto dataPtr = m_builder.CreateBitCast(arrayPtr, Type::BytePtr->getPointerTo(), "dataPtr");// TODO: Use byte* in Array
auto sizePtr = m_builder.CreateStructGEP(arrayPtr, 1, "sizePtr");
auto capPtr = m_builder.CreateStructGEP(arrayPtr, 2, "capPtr");
auto data = m_builder.CreateLoad(dataPtr, "data");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto extSize = m_builder.CreateNUWSub(newSize, size, "extSize");
auto newData = m_reallocFunc.call(m_builder, {data, newSize}, "newData"); // TODO: Check realloc result for null
auto extPtr = m_builder.CreateGEP(newData, size, "extPtr");
m_builder.CreateMemSet(extPtr, m_builder.getInt8(0), extSize, 16);
m_builder.CreateStore(newData, dataPtr);
m_builder.CreateStore(newSize, sizePtr);
m_builder.CreateStore(newSize, capPtr);
m_builder.CreateRetVoid();
return func;
}
llvm::Type* Array::getType()
{
llvm::Type* elementTys[] = {Type::WordPtr, Type::Size, Type::Size};
static auto arrayTy = llvm::StructType::create(elementTys, "Array");
return arrayTy;
}
Array::Array(llvm::IRBuilder<>& _builder, char const* _name) :
CompilerHelper(_builder),
m_pushFunc([this](){ return createArrayPushFunc(); }),
m_setFunc([this](){ return createArraySetFunc(); }),
m_getFunc([this](){ return createArrayGetFunc(); }),
m_freeFunc([this](){ return createFreeFunc(); })
{
m_array = m_builder.CreateAlloca(getType(), nullptr, _name);
m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}
Array::Array(llvm::IRBuilder<>& _builder, llvm::Value* _array) :
CompilerHelper(_builder),
m_array(_array),
m_pushFunc([this](){ return createArrayPushFunc(); }),
m_setFunc([this](){ return createArraySetFunc(); }),
m_getFunc([this](){ return createArrayGetFunc(); }),
m_freeFunc([this](){ return createFreeFunc(); })
{
m_builder.CreateStore(llvm::ConstantAggregateZero::get(getType()), m_array);
}
void Array::pop(llvm::Value* _count)
{
auto sizePtr = m_builder.CreateStructGEP(m_array, 1, "sizePtr");
auto size = m_builder.CreateLoad(sizePtr, "size");
auto newSize = m_builder.CreateNUWSub(size, _count, "newSize");
m_builder.CreateStore(newSize, sizePtr);
}
llvm::Value* Array::size(llvm::Value* _array)
{
auto sizePtr = m_builder.CreateStructGEP(_array ? _array : m_array, 1, "sizePtr");
return m_builder.CreateLoad(sizePtr, "array.size");
}
void Array::extend(llvm::Value* _arrayPtr, llvm::Value* _size)
{
assert(_arrayPtr->getType() == m_array->getType());
assert(_size->getType() == Type::Size);
m_extendFunc.call(m_builder, {_arrayPtr, _size});
}
}
}
}
extern "C"
{
EXPORT void* ext_realloc(void* _data, size_t _size) noexcept
{
return std::realloc(_data, _size);
}
EXPORT void ext_free(void* _data) noexcept
{
std::free(_data);
}
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2016 Luxon Jean-Pierre
* gumichan01.olympe.in
*
* This library is under the MIT license
*
* Luxon Jean-Pierre (Gumichan01)
* luxon.jean.pierre@gmail.com
*
*/
#ifndef UTF8_STRING_HPP_INCLUDED
#define UTF8_STRING_HPP_INCLUDED
#include <string>
#include <iostream>
class UTF8iterator;
class UTF8string
{
std::string utf8data;
size_t utf8length;
bool utf8_is_valid_() const;
size_t utf8_length_() const;
size_t utf8_codepoint_len_(size_t j) const;
size_t utf8_bpos_at_(const size_t cpos) const;
UTF8iterator utf8_iterator_() const noexcept;
UTF8string utf8_reverse_aux_(UTF8iterator& it,
const UTF8iterator& end, UTF8string& res);
public:
const static size_t npos = std::string::npos;
UTF8string();
UTF8string(const std::string &str);
UTF8string(const UTF8string &u8str);
const UTF8string& operator =(const char * str);
const UTF8string& operator =(const std::string &str);
const UTF8string& operator =(const UTF8string &u8str);
const UTF8string& operator +=(const UTF8string &u8str);
const UTF8string& operator +=(const std::string &str);
const UTF8string& operator +=(const char * str);
void utf8_clear();
bool utf8_empty() const;
std::string utf8_at(const size_t index) const;
void utf8_pop();
UTF8string utf8_substr(size_t pos = 0, size_t len = npos) const;
size_t utf8_find(const UTF8string& str, size_t pos = 0) const;
UTF8string& utf8_reverse();
size_t utf8_size() const;
size_t utf8_length() const;
const char * utf8_str() const;
UTF8iterator utf8_begin() const noexcept;
UTF8iterator utf8_end() const noexcept;
~UTF8string() = default;
};
bool operator ==(const UTF8string &str1, const UTF8string &str2);
bool operator !=(const UTF8string &str1, const UTF8string &str2);
bool operator <=(const UTF8string &str1, const UTF8string &str2);
bool operator >=(const UTF8string &str1, const UTF8string &str2);
bool operator <(const UTF8string &str1, const UTF8string &str2);
bool operator >(const UTF8string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const std::string &str2);
UTF8string operator +(const std::string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const char * str2);
UTF8string operator +(const char * str1, const UTF8string &str2);
std::ostream & operator <<(std::ostream &os, const UTF8string &str);
std::istream & operator >>(std::istream &is, UTF8string &str);
#include "utf8_iterator.hpp"
#endif // UTF8_STRING_HPP_INCLUDED
<commit_msg>Documented the class<commit_after>/*
*
* Copyright (C) 2016 Luxon Jean-Pierre
* gumichan01.olympe.in
*
* This library is under the MIT license
*
* Luxon Jean-Pierre (Gumichan01)
* luxon.jean.pierre@gmail.com
*
*/
#ifndef UTF8_STRING_HPP_INCLUDED
#define UTF8_STRING_HPP_INCLUDED
/**
* @file utf8_string.hpp
* This is a UTF-8 string library header
*/
#include <string>
#include <iostream>
class UTF8iterator;
/**
* @class UTF8string
* @brief UTF-8 string class
*
* This class defines a UTF-8 string
*/
class UTF8string
{
std::string utf8data;
size_t utf8length;
bool utf8_is_valid_() const;
size_t utf8_length_() const;
size_t utf8_codepoint_len_(size_t j) const;
size_t utf8_bpos_at_(const size_t cpos) const;
UTF8iterator utf8_iterator_() const noexcept;
UTF8string utf8_reverse_aux_(UTF8iterator& it,
const UTF8iterator& end, UTF8string& res);
public:
const static size_t npos = std::string::npos;
/**
* @fn UTF8string()
*/
UTF8string();
/**
* @fn UTF8string(const std::string &str)
* @param str The string to convert from
* @exception std::invalid_argument If the string is not valid
*/
UTF8string(const std::string &str);
/**
* @fn UTF8string(const UTF8string &u8str)
* @param u8str The string to convert from
* @exception std::invalid_argument If the string is not valid
*/
UTF8string(const UTF8string &u8str);
/**
* @fn const UTF8string& operator =(const char * str)
* @param str C-string that will be converted
* @return A reference to the new utf-8 string
* @exception std::invalid_argument If the string is not valid
*/
const UTF8string& operator =(const char * str);
/**
* @fn const UTF8string& operator =(const std::string &str)
* @param str The string that will be converted and checked
* @return A reference to the new utf-8 string
* @exception std::invalid_argument If the string is not valid
*/
const UTF8string& operator =(const std::string &str);
/**
* @fn const UTF8string& operator =(const UTF8string &u8str)
* @param u8str The utf-8 string
* @return A reference to the new utf-8 string
* @exception std::invalid_argument If the string is not valid
*/
const UTF8string& operator =(const UTF8string &u8str);
/**
* @fn const UTF8string& operator +=(const UTF8string &u8str)
*
* Append a utf-8 string
*
* @param u8str The string to convert from
* @return The reference to the concatenated utf-8 string
*/
const UTF8string& operator +=(const UTF8string &u8str);
/**
* @fn const UTF8string& operator +=(const std::string &str)
*
* Append a string
*
* @param str The string to convert from
* @return The reference to the concatenated utf-8 string
* @exception std::invalid_argument If the string is not valid
*/
const UTF8string& operator +=(const std::string &str);
/**
* @fn const UTF8string& operator +=(const char * str)
*
* Append a C-string
*
* @param str The string to convert from
* @return The reference to the concatenated utf-8 string
* @exception std::invalid_argument If the string is not valid
*/
const UTF8string& operator +=(const char * str);
/**
* @fn void utf8_clear()
* Clear the content of the object
*/
void utf8_clear();
/**
* @fn bool utf8_empty() const
*
* Check if the content is empty
*
* @return TRUE If it is empty, FALSE otherwise
*/
bool utf8_empty() const;
/**
* @fn std::string utf8_at(const size_t index) const
*
* Get the codepoint at a specified position.
*
* @param index The index of the requested codepoint in the string
* @return The codepoint
* @exception std::out_of_range If the index if out of the string range
*/
std::string utf8_at(const size_t index) const;
/**
* @fn void utf8_pop()
*
* Remove the last codepoint.
*
* @exception std::length_error If the string is empty
*/
void utf8_pop();
/**
* @fn UTF8string utf8_substr(size_t pos = 0, size_t len = npos) const
*
* Generate a substring according to the position and the length requested.
*
* The substring is the portion of the object that starts at
* character position *pos* and spans *len* characters
* (or until the end of the string, whichever comes first).
*
* @param pos The beginning position of the substring (default value: 0)
* @param len The length of the substring (in number of codepoints, default value = npos)
* @return The substring
*/
UTF8string utf8_substr(size_t pos = 0, size_t len = npos) const;
/**
* @fn size_t utf8_find(const UTF8string& str, size_t pos = 0) const
*
* Search the utf8 string for the first occurrence of
* the sequence specified by its argument.
*
* When pos is specified, the search only includes characters
* at or after position pos, ignoring any possible occurrences
* that include characters before pos.
*
* @param str The string to look for
* @param pos The osition to start the search
* @return The position of the subtring if it was found
* (in number of codepoints), UTF8string::npos otherwise.
*/
size_t utf8_find(const UTF8string& str, size_t pos = 0) const;
/**
* @fn UTF8string& utf8_reverse()
* Reverse the current utf-8 string.
* @return The reversed string
*/
UTF8string& utf8_reverse();
/**
* @fn size_t utf8_size() const
* Get the memory size (in bytes) of the utf-8 string
* @return The memory size of the utf-8 string
*/
size_t utf8_size() const;
/**
* @fn size_t utf8_length() const
* Get the length of the utf-8 string
* @return The length of the utf-8 string (in number of codepoints)
*/
size_t utf8_length() const;
/**
* @fn const char * utf8_str() const
*
* Retunrs a pointer to an array that contains a null-terminated sequence
* of characters (C-string).
*
* This array include exactly the string plus the null character ('\0')
* at the end.
*
* @return A pointer to a C-string
*/
const char * utf8_str() const;
/**
* @fn UTF8iterator utf8_begin() const noexcept
*
* Returns an iterator that points to the first codepoint of the string
*
* @return An iterator to the beginnigng of the string
*/
UTF8iterator utf8_begin() const noexcept;
/**
* @fn UTF8iterator utf8_end() const noexcept
*
* Returns an iterator that points to the *past-the-end* codepoint of the string
*
* The past-the-end codepoint is a theoretical codepoint that would follow
* the last codepoint in the string. It shall not be dereferenced.
*
* @return An iterator to the past-the-end codepoint
*/
UTF8iterator utf8_end() const noexcept;
~UTF8string() = default;
};
bool operator ==(const UTF8string &str1, const UTF8string &str2);
bool operator !=(const UTF8string &str1, const UTF8string &str2);
bool operator <=(const UTF8string &str1, const UTF8string &str2);
bool operator >=(const UTF8string &str1, const UTF8string &str2);
bool operator <(const UTF8string &str1, const UTF8string &str2);
bool operator >(const UTF8string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const std::string &str2);
UTF8string operator +(const std::string &str1, const UTF8string &str2);
UTF8string operator +(const UTF8string &str1, const char * str2);
UTF8string operator +(const char * str1, const UTF8string &str2);
std::ostream & operator <<(std::ostream &os, const UTF8string &str);
std::istream & operator >>(std::istream &is, UTF8string &str);
#include "utf8_iterator.hpp"
#endif // UTF8_STRING_HPP_INCLUDED
<|endoftext|>
|
<commit_before>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"
#include <assert.h>
#include <string.h>
// This work is based on:
// TODO: references
namespace meshopt
{
const size_t kVertexBlockSize = 256;
static unsigned char* encodeVertexBlock(unsigned char* data, const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, const unsigned int* prediction)
{
(void)prediction;
assert(vertex_count > 0);
for (size_t k = 0; k < vertex_size; ++k)
{
*data++ = vertex_data[k];
}
for (size_t k = 0; k < vertex_size; ++k)
{
size_t vertex_offset = k;
for (size_t i = 1; i < vertex_count; ++i)
{
*data++ = vertex_data[vertex_offset + vertex_size] - vertex_data[vertex_offset];
vertex_offset += vertex_size;
}
}
return data;
}
typedef unsigned int VertexFifo[16];
typedef unsigned int EdgeFifo[16][3];
static void pushEdgeFifo(EdgeFifo fifo, unsigned int a, unsigned int b, unsigned int c, size_t& offset)
{
fifo[offset][0] = a;
fifo[offset][1] = b;
fifo[offset][2] = c;
offset = (offset + 1) & 15;
}
static void pushVertexFifo(VertexFifo fifo, unsigned int v, size_t& offset)
{
fifo[offset] = v;
offset = (offset + 1) & 15;
}
static unsigned int decodeVByte(const unsigned char*& data)
{
unsigned char lead = *data++;
// fast path: single byte
if (lead < 128)
return lead;
// slow path: up to 4 extra bytes
// note that this loop always terminates, which is important for malformed data
unsigned int result = lead & 127;
unsigned int shift = 7;
for (int i = 0; i < 4; ++i)
{
unsigned char group = *data++;
result |= (group & 127) << shift;
shift += 7;
if (group < 128)
break;
}
return result;
}
static unsigned int decodeIndex(const unsigned char*& data, unsigned int next, unsigned int last)
{
(void)next;
unsigned int v = decodeVByte(data);
unsigned int d = (v >> 1) ^ -int(v & 1);
return last + d;
}
struct DecodePredictionState
{
EdgeFifo edgefifo;
VertexFifo vertexfifo;
size_t edgefifooffset;
size_t vertexfifooffset;
unsigned int next;
unsigned int last;
size_t code_offset;
size_t data_offset;
size_t index_offset;
};
static size_t decodeVertexPrediction(DecodePredictionState& state, unsigned int* result, size_t result_size, size_t index_count, const unsigned char* buffer, size_t buffer_size)
{
assert(index_count % 3 == 0);
// the minimum valid encoding is 1 byte per triangle and a 16-byte codeaux table
// TODO: partial bounds check?..
if (buffer_size < index_count / 3 + 16)
return 0;
// since we store 16-byte codeaux table at the end, triangle data has to begin before data_safe_end
const unsigned char* code = buffer + state.code_offset;
const unsigned char* data = buffer + index_count / 3 + state.data_offset;
const unsigned char* data_safe_end = buffer + buffer_size - 16;
const unsigned char* codeaux_table = data_safe_end;
size_t result_offset = 0;
size_t i = state.index_offset;
for (; i < index_count; i += 3)
{
if (result_offset + 3 > result_size)
break;
// make sure we have enough data to read for a triangle
// each triangle reads at most 16 bytes of data: 1b for codeaux and 5b for each free index
// after this we can be sure we can read without extra bounds checks
if (data > data_safe_end)
return 0;
unsigned char codetri = *code++;
int fe = codetri >> 4;
if (fe < 15)
{
// fifo reads are wrapped around 16 entry buffer
unsigned int a = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][0];
unsigned int b = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][1];
unsigned int co = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][2];
int fec = codetri & 15;
unsigned int c = (fec == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - 1 - fec) & 15];
// note that we need to update the last index since free indices are delta-encoded
if (fec == 15)
state.last = c = decodeIndex(data, state.next, state.last);
// output prediction data
if (fec == 0)
{
unsigned int na = c - a;
unsigned int nb = c - b;
unsigned int nc = c - co;
unsigned int p =
(na < 256 && nb < 256 && nc < 256)
? (na << 16) | (nb << 8) | nc
: 0;
result[result_offset++] = p;
}
// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly
if (fec == 0 || fec == 15)
pushVertexFifo(state.vertexfifo, c, state.vertexfifooffset);
pushEdgeFifo(state.edgefifo, c, b, a, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, a, c, b, state.edgefifooffset);
}
else
{
// fast path: read codeaux from the table; we wrap table index so this access is memory-safe
unsigned char codeaux = codeaux_table[codetri & 15];
int fea = 0;
int feb = codeaux >> 4;
int fec = codeaux & 15;
// slow path: read a full byte for codeaux instead of using a table lookup
if ((codetri & 15) >= 14)
{
fea = (codetri & 15) == 14 ? 0 : 15;
codeaux = *data++;
feb = codeaux >> 4;
fec = codeaux & 15;
}
// fifo reads are wrapped around 16 entry buffer
// also note that we increment next for all three vertices before decoding indices - this matches encoder behavior
unsigned int a = (fea == 0) ? state.next++ : 0;
unsigned int b = (feb == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - feb) & 15];
unsigned int c = (fec == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - fec) & 15];
// note that we need to update the last index since free indices are delta-encoded
if (fea == 15)
state.last = a = decodeIndex(data, state.next, state.last);
if (feb == 15)
state.last = b = decodeIndex(data, state.next, state.last);
if (fec == 15)
state.last = c = decodeIndex(data, state.next, state.last);
// output prediction data
if (fea == 0)
result[result_offset++] = 0;
if (feb == 0)
result[result_offset++] = 0;
if (fec == 0)
result[result_offset++] = 0;
// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly
if (fea == 0 || fea == 15)
pushVertexFifo(state.vertexfifo, a, state.vertexfifooffset);
if (feb == 0 || feb == 15)
pushVertexFifo(state.vertexfifo, b, state.vertexfifooffset);
if (fec == 0 || fec == 15)
pushVertexFifo(state.vertexfifo, c, state.vertexfifooffset);
pushEdgeFifo(state.edgefifo, b, a, c, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, c, b, a, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, a, c, b, state.edgefifooffset);
}
}
// we should've read all data bytes and stopped at the boundary between data and codeaux table
// TODO!
// if (data != data_safe_end)
// return 0;
state.code_offset = code - buffer;
state.data_offset = data - buffer - index_count / 3;
state.index_offset = i;
return result_offset;
}
}
size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, size_t index_count, const unsigned char* index_buffer, size_t index_buffer_size)
{
using namespace meshopt;
assert(vertex_size > 0 && vertex_size <= 256);
assert(index_count % 3 == 0);
assert(index_buffer == 0 || index_buffer_size > 0);
(void)index_buffer;
(void)index_buffer_size;
const unsigned char* vertex_data = static_cast<const unsigned char*>(vertices);
unsigned char* data = buffer;
unsigned int prediction[kVertexBlockSize];
DecodePredictionState pstate = {};
size_t vertex_offset = 0;
if (index_buffer)
{
for (;;)
{
size_t psize = decodeVertexPrediction(pstate, prediction, sizeof(prediction) / sizeof(prediction[0]), index_count, index_buffer, index_buffer_size);
if (psize == 0)
break;
size_t block_size = psize;
if (vertex_offset + block_size > vertex_count)
break;
data = encodeVertexBlock(data, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, prediction);
vertex_offset += block_size;
}
}
while (vertex_offset < vertex_count)
{
size_t block_size = (vertex_offset + kVertexBlockSize < vertex_count) ? kVertexBlockSize : vertex_count - vertex_offset;
data = encodeVertexBlock(data, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, 0);
vertex_offset += block_size;
}
assert(size_t(data - buffer) <= buffer_size);
return data - buffer;
}
size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size)
{
return vertex_count * vertex_size * 2;
}
<commit_msg>vertexcodec: Store vertex block size before each block<commit_after>// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details
#include "meshoptimizer.h"
#include <assert.h>
#include <string.h>
// This work is based on:
// TODO: references
namespace meshopt
{
const size_t kVertexBlockSize = 256;
static unsigned char* encodeVertexBlock(unsigned char* data, const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, const unsigned int* prediction)
{
(void)prediction;
assert(vertex_count > 0 && vertex_count <= 256);
*data++ = static_cast<unsigned char>(vertex_count - 1);
for (size_t k = 0; k < vertex_size; ++k)
{
*data++ = vertex_data[k];
}
for (size_t k = 0; k < vertex_size; ++k)
{
size_t vertex_offset = k;
for (size_t i = 1; i < vertex_count; ++i)
{
*data++ = vertex_data[vertex_offset + vertex_size] - vertex_data[vertex_offset];
vertex_offset += vertex_size;
}
}
return data;
}
typedef unsigned int VertexFifo[16];
typedef unsigned int EdgeFifo[16][3];
static void pushEdgeFifo(EdgeFifo fifo, unsigned int a, unsigned int b, unsigned int c, size_t& offset)
{
fifo[offset][0] = a;
fifo[offset][1] = b;
fifo[offset][2] = c;
offset = (offset + 1) & 15;
}
static void pushVertexFifo(VertexFifo fifo, unsigned int v, size_t& offset)
{
fifo[offset] = v;
offset = (offset + 1) & 15;
}
static unsigned int decodeVByte(const unsigned char*& data)
{
unsigned char lead = *data++;
// fast path: single byte
if (lead < 128)
return lead;
// slow path: up to 4 extra bytes
// note that this loop always terminates, which is important for malformed data
unsigned int result = lead & 127;
unsigned int shift = 7;
for (int i = 0; i < 4; ++i)
{
unsigned char group = *data++;
result |= (group & 127) << shift;
shift += 7;
if (group < 128)
break;
}
return result;
}
static unsigned int decodeIndex(const unsigned char*& data, unsigned int next, unsigned int last)
{
(void)next;
unsigned int v = decodeVByte(data);
unsigned int d = (v >> 1) ^ -int(v & 1);
return last + d;
}
struct DecodePredictionState
{
EdgeFifo edgefifo;
VertexFifo vertexfifo;
size_t edgefifooffset;
size_t vertexfifooffset;
unsigned int next;
unsigned int last;
size_t code_offset;
size_t data_offset;
size_t index_offset;
};
static size_t decodeVertexPrediction(DecodePredictionState& state, unsigned int* result, size_t result_size, size_t index_count, const unsigned char* buffer, size_t buffer_size)
{
assert(index_count % 3 == 0);
// the minimum valid encoding is 1 byte per triangle and a 16-byte codeaux table
// TODO: partial bounds check?..
if (buffer_size < index_count / 3 + 16)
return 0;
// since we store 16-byte codeaux table at the end, triangle data has to begin before data_safe_end
const unsigned char* code = buffer + state.code_offset;
const unsigned char* data = buffer + index_count / 3 + state.data_offset;
const unsigned char* data_safe_end = buffer + buffer_size - 16;
const unsigned char* codeaux_table = data_safe_end;
size_t result_offset = 0;
size_t i = state.index_offset;
for (; i < index_count; i += 3)
{
if (result_offset + 3 > result_size)
break;
// make sure we have enough data to read for a triangle
// each triangle reads at most 16 bytes of data: 1b for codeaux and 5b for each free index
// after this we can be sure we can read without extra bounds checks
if (data > data_safe_end)
return 0;
unsigned char codetri = *code++;
int fe = codetri >> 4;
if (fe < 15)
{
// fifo reads are wrapped around 16 entry buffer
unsigned int a = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][0];
unsigned int b = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][1];
unsigned int co = state.edgefifo[(state.edgefifooffset - 1 - fe) & 15][2];
int fec = codetri & 15;
unsigned int c = (fec == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - 1 - fec) & 15];
// note that we need to update the last index since free indices are delta-encoded
if (fec == 15)
state.last = c = decodeIndex(data, state.next, state.last);
// output prediction data
if (fec == 0)
{
unsigned int na = c - a;
unsigned int nb = c - b;
unsigned int nc = c - co;
unsigned int p =
(na < 256 && nb < 256 && nc < 256)
? (na << 16) | (nb << 8) | nc
: 0;
result[result_offset++] = p;
}
// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly
if (fec == 0 || fec == 15)
pushVertexFifo(state.vertexfifo, c, state.vertexfifooffset);
pushEdgeFifo(state.edgefifo, c, b, a, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, a, c, b, state.edgefifooffset);
}
else
{
// fast path: read codeaux from the table; we wrap table index so this access is memory-safe
unsigned char codeaux = codeaux_table[codetri & 15];
int fea = 0;
int feb = codeaux >> 4;
int fec = codeaux & 15;
// slow path: read a full byte for codeaux instead of using a table lookup
if ((codetri & 15) >= 14)
{
fea = (codetri & 15) == 14 ? 0 : 15;
codeaux = *data++;
feb = codeaux >> 4;
fec = codeaux & 15;
}
// fifo reads are wrapped around 16 entry buffer
// also note that we increment next for all three vertices before decoding indices - this matches encoder behavior
unsigned int a = (fea == 0) ? state.next++ : 0;
unsigned int b = (feb == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - feb) & 15];
unsigned int c = (fec == 0) ? state.next++ : state.vertexfifo[(state.vertexfifooffset - fec) & 15];
// note that we need to update the last index since free indices are delta-encoded
if (fea == 15)
state.last = a = decodeIndex(data, state.next, state.last);
if (feb == 15)
state.last = b = decodeIndex(data, state.next, state.last);
if (fec == 15)
state.last = c = decodeIndex(data, state.next, state.last);
// output prediction data
if (fea == 0)
result[result_offset++] = 0;
if (feb == 0)
result[result_offset++] = 0;
if (fec == 0)
result[result_offset++] = 0;
// push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly
if (fea == 0 || fea == 15)
pushVertexFifo(state.vertexfifo, a, state.vertexfifooffset);
if (feb == 0 || feb == 15)
pushVertexFifo(state.vertexfifo, b, state.vertexfifooffset);
if (fec == 0 || fec == 15)
pushVertexFifo(state.vertexfifo, c, state.vertexfifooffset);
pushEdgeFifo(state.edgefifo, b, a, c, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, c, b, a, state.edgefifooffset);
pushEdgeFifo(state.edgefifo, a, c, b, state.edgefifooffset);
}
}
// we should've read all data bytes and stopped at the boundary between data and codeaux table
// TODO!
// if (data != data_safe_end)
// return 0;
state.code_offset = code - buffer;
state.data_offset = data - buffer - index_count / 3;
state.index_offset = i;
return result_offset;
}
}
size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, size_t index_count, const unsigned char* index_buffer, size_t index_buffer_size)
{
using namespace meshopt;
assert(vertex_size > 0 && vertex_size <= 256);
assert(index_count % 3 == 0);
assert(index_buffer == 0 || index_buffer_size > 0);
(void)index_buffer;
(void)index_buffer_size;
const unsigned char* vertex_data = static_cast<const unsigned char*>(vertices);
unsigned char* data = buffer;
unsigned int prediction[kVertexBlockSize];
DecodePredictionState pstate = {};
size_t vertex_offset = 0;
if (index_buffer)
{
for (;;)
{
size_t psize = decodeVertexPrediction(pstate, prediction, sizeof(prediction) / sizeof(prediction[0]), index_count, index_buffer, index_buffer_size);
if (psize == 0)
break;
size_t block_size = psize;
if (vertex_offset + block_size > vertex_count)
break;
data = encodeVertexBlock(data, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, prediction);
vertex_offset += block_size;
}
}
while (vertex_offset < vertex_count)
{
size_t block_size = (vertex_offset + kVertexBlockSize < vertex_count) ? kVertexBlockSize : vertex_count - vertex_offset;
data = encodeVertexBlock(data, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, 0);
vertex_offset += block_size;
}
assert(size_t(data - buffer) <= buffer_size);
return data - buffer;
}
size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size)
{
return vertex_count * vertex_size * 2;
}
<|endoftext|>
|
<commit_before>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include <iostream>
#include <fstream>
#include <chrono>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "Utility/Debug.h"
#include "Utility/Directory.h"
#include "PluginManager/PluginManager.h"
#include "Scene.h"
#include "Trade/AbstractImporter.h"
#include "MeshTools/Tipsify.h"
#include "configure.h"
using namespace std;
using namespace Corrade::PluginManager;
using namespace Corrade::Utility;
using namespace Magnum;
Scene* s;
shared_ptr<Object> o;
chrono::high_resolution_clock::time_point before;
bool wireframe, fps;
size_t frames;
double totalfps;
size_t totalmeasurecount;
Vector3 previousPosition;
/* Wrapper functions so GLUT can handle that */
void setViewport(int w, int h) {
s->setViewport(w, h);
}
void draw() {
if(fps) {
chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now();
double duration = chrono::duration<double>(now-before).count();
if(duration > 3.5) {
cout << frames << " frames in " << duration << " sec: "
<< frames/duration << " FPS \r";
cout.flush();
totalfps += frames/duration;
before = now;
frames = 0;
++totalmeasurecount;
}
}
s->draw();
glutSwapBuffers();
if(fps) {
++frames;
glutPostRedisplay();
}
}
void events(int key, int x, int y) {
switch(key) {
case GLUT_KEY_UP:
o->rotate(PI/18, -1, 0, 0);
break;
case GLUT_KEY_DOWN:
o->rotate(PI/18, 1, 0, 0);
break;
case GLUT_KEY_LEFT:
o->rotate(PI/18, 0, -1, 0, false);
break;
case GLUT_KEY_RIGHT:
o->rotate(PI/18, 0, 1, 0, false);
break;
case GLUT_KEY_PAGE_UP:
s->camera()->translate(0, 0, -0.5);
break;
case GLUT_KEY_PAGE_DOWN:
s->camera()->translate(0, 0, 0.5);
break;
case GLUT_KEY_HOME:
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE);
wireframe = !wireframe;
break;
case GLUT_KEY_END:
if(fps) cout << "Average FPS on " << s->camera()->viewport().x()
<< 'x' << s->camera()->viewport().y() << " from "
<< totalmeasurecount << " measures: "
<< totalfps/totalmeasurecount << " " << endl;
else before = chrono::high_resolution_clock::now();
fps = !fps;
frames = totalmeasurecount = 0;
totalfps = 0;
break;
}
glutPostRedisplay();
}
Vector3 positionOnSphere(int x, int y) {
Math::Vector2<unsigned int> viewport = s->camera()->viewport();
Vector2 position(x*2.0f/viewport.x() - 1.0f,
y*2.0f/viewport.y() - 1.0f);
GLfloat length = position.length();
Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length));
result.setY(-result.y());
return result.normalized();
}
void mouseEvents(int button, int state, int x, int y) {
switch(button) {
case GLUT_LEFT_BUTTON:
if(state == GLUT_DOWN) previousPosition = positionOnSphere(x, y);
else previousPosition = Vector3();
break;
case 3:
case 4:
if(state == GLUT_UP) return;
/* Distance between origin and near camera clipping plane */
GLfloat distance = s->camera()->transformation().at(3).z()-0-s->camera()->near();
/* Move 15% of the distance back or forward */
if(button == 3)
distance *= 1 - 1/0.85f;
else
distance *= 1 - 0.85f;
s->camera()->translate(0, 0, distance);
glutPostRedisplay();
break;
}
}
void dragEvents(int x, int y) {
Vector3 currentPosition = positionOnSphere(x, y);
Vector3 axis = Vector3::cross(previousPosition, currentPosition);
if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return;
GLfloat angle = acos(previousPosition*currentPosition);
o->rotate(angle, axis);
previousPosition = currentPosition;
glutPostRedisplay();
}
int main(int argc, char** argv) {
if(argc != 2) {
cout << "Usage: " << argv[0] << " file.dae" << endl;
return 0;
}
/* Instance ColladaImporter plugin */
PluginManager<Trade::AbstractImporter> manager(PLUGIN_IMPORTER_DIR);
if(manager.load("ColladaImporter") != AbstractPluginManager::LoadOk) {
Error() << "Could not load ColladaImporter plugin";
return 2;
}
unique_ptr<Trade::AbstractImporter> colladaImporter(manager.instance("ColladaImporter"));
if(!colladaImporter) {
Error() << "Could not instance ColladaImporter plugin";
return 3;
}
if(!(colladaImporter->features() & Trade::AbstractImporter::OpenFile)) {
Error() << "ColladaImporter cannot open files";
return 7;
}
/* Init GLUT */
glutInit(&argc, argv);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);
glutInitWindowSize(800, 600);
glutCreateWindow("Magnum viewer");
glutReshapeFunc(setViewport);
glutSpecialFunc(events);
glutMouseFunc(mouseEvents);
glutMotionFunc(dragEvents);
glutDisplayFunc(draw);
/* Init GLEW */
GLenum err = glewInit();
if(err != GLEW_OK) {
Error() << "GLEW error:" << glewGetErrorString(err);
return 1;
}
/* Initialize scene */
Scene scene;
s = &scene;
wireframe = false;
fps = false;
scene.setFeature(Scene::DepthTest, true);
/* Every scene needs a camera */
Camera* camera = new Camera(&scene);
camera->setPerspective(35.0f*PI/180, 0.001f, 100);
camera->translate(0, 0, 5);
scene.setCamera(camera);
/* Load file */
if(!colladaImporter->open(argv[1]))
return 4;
if(colladaImporter->objectCount() == 0)
return 5;
/* Optimize vertices */
shared_ptr<Trade::AbstractImporter::MeshData> meshData = colladaImporter->meshData(0);
if(meshData && meshData->indices() && meshData->vertices(0)) {
Debug() << "Optimizing mesh vertices using Tipsify algorithm (cache size 24)...";
MeshTools::tipsify(*meshData->indices(), meshData->vertices(0)->size(), 24);
}
o = colladaImporter->object(0);
if(!o) return 6;
o->setParent(&scene);
colladaImporter->close();
delete colladaImporter.release();
/* Main loop calls draw() periodically and setViewport() on window size change */
glutMainLoop();
return 0;
}
<commit_msg>Explicitly destroy imported object to prevent crash on exit.<commit_after>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include <iostream>
#include <fstream>
#include <chrono>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "Utility/Debug.h"
#include "Utility/Directory.h"
#include "PluginManager/PluginManager.h"
#include "Scene.h"
#include "Trade/AbstractImporter.h"
#include "MeshTools/Tipsify.h"
#include "configure.h"
using namespace std;
using namespace Corrade::PluginManager;
using namespace Corrade::Utility;
using namespace Magnum;
Scene* s;
shared_ptr<Object> o;
chrono::high_resolution_clock::time_point before;
bool wireframe, fps;
size_t frames;
double totalfps;
size_t totalmeasurecount;
Vector3 previousPosition;
/* Wrapper functions so GLUT can handle that */
void setViewport(int w, int h) {
s->setViewport(w, h);
}
void draw() {
if(fps) {
chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now();
double duration = chrono::duration<double>(now-before).count();
if(duration > 3.5) {
cout << frames << " frames in " << duration << " sec: "
<< frames/duration << " FPS \r";
cout.flush();
totalfps += frames/duration;
before = now;
frames = 0;
++totalmeasurecount;
}
}
s->draw();
glutSwapBuffers();
if(fps) {
++frames;
glutPostRedisplay();
}
}
void events(int key, int x, int y) {
switch(key) {
case GLUT_KEY_UP:
o->rotate(PI/18, -1, 0, 0);
break;
case GLUT_KEY_DOWN:
o->rotate(PI/18, 1, 0, 0);
break;
case GLUT_KEY_LEFT:
o->rotate(PI/18, 0, -1, 0, false);
break;
case GLUT_KEY_RIGHT:
o->rotate(PI/18, 0, 1, 0, false);
break;
case GLUT_KEY_PAGE_UP:
s->camera()->translate(0, 0, -0.5);
break;
case GLUT_KEY_PAGE_DOWN:
s->camera()->translate(0, 0, 0.5);
break;
case GLUT_KEY_HOME:
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE);
wireframe = !wireframe;
break;
case GLUT_KEY_END:
if(fps) cout << "Average FPS on " << s->camera()->viewport().x()
<< 'x' << s->camera()->viewport().y() << " from "
<< totalmeasurecount << " measures: "
<< totalfps/totalmeasurecount << " " << endl;
else before = chrono::high_resolution_clock::now();
fps = !fps;
frames = totalmeasurecount = 0;
totalfps = 0;
break;
}
glutPostRedisplay();
}
Vector3 positionOnSphere(int x, int y) {
Math::Vector2<unsigned int> viewport = s->camera()->viewport();
Vector2 position(x*2.0f/viewport.x() - 1.0f,
y*2.0f/viewport.y() - 1.0f);
GLfloat length = position.length();
Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length));
result.setY(-result.y());
return result.normalized();
}
void mouseEvents(int button, int state, int x, int y) {
switch(button) {
case GLUT_LEFT_BUTTON:
if(state == GLUT_DOWN) previousPosition = positionOnSphere(x, y);
else previousPosition = Vector3();
break;
case 3:
case 4:
if(state == GLUT_UP) return;
/* Distance between origin and near camera clipping plane */
GLfloat distance = s->camera()->transformation().at(3).z()-0-s->camera()->near();
/* Move 15% of the distance back or forward */
if(button == 3)
distance *= 1 - 1/0.85f;
else
distance *= 1 - 0.85f;
s->camera()->translate(0, 0, distance);
glutPostRedisplay();
break;
}
}
void dragEvents(int x, int y) {
Vector3 currentPosition = positionOnSphere(x, y);
Vector3 axis = Vector3::cross(previousPosition, currentPosition);
if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return;
GLfloat angle = acos(previousPosition*currentPosition);
o->rotate(angle, axis);
previousPosition = currentPosition;
glutPostRedisplay();
}
int main(int argc, char** argv) {
if(argc != 2) {
cout << "Usage: " << argv[0] << " file.dae" << endl;
return 0;
}
/* Instance ColladaImporter plugin */
PluginManager<Trade::AbstractImporter> manager(PLUGIN_IMPORTER_DIR);
if(manager.load("ColladaImporter") != AbstractPluginManager::LoadOk) {
Error() << "Could not load ColladaImporter plugin";
return 2;
}
unique_ptr<Trade::AbstractImporter> colladaImporter(manager.instance("ColladaImporter"));
if(!colladaImporter) {
Error() << "Could not instance ColladaImporter plugin";
return 3;
}
if(!(colladaImporter->features() & Trade::AbstractImporter::OpenFile)) {
Error() << "ColladaImporter cannot open files";
return 7;
}
/* Init GLUT */
glutInit(&argc, argv);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);
glutInitWindowSize(800, 600);
glutCreateWindow("Magnum viewer");
glutReshapeFunc(setViewport);
glutSpecialFunc(events);
glutMouseFunc(mouseEvents);
glutMotionFunc(dragEvents);
glutDisplayFunc(draw);
/* Init GLEW */
GLenum err = glewInit();
if(err != GLEW_OK) {
Error() << "GLEW error:" << glewGetErrorString(err);
return 1;
}
/* Initialize scene */
Scene scene;
s = &scene;
wireframe = false;
fps = false;
scene.setFeature(Scene::DepthTest, true);
/* Every scene needs a camera */
Camera* camera = new Camera(&scene);
camera->setPerspective(35.0f*PI/180, 0.001f, 100);
camera->translate(0, 0, 5);
scene.setCamera(camera);
/* Load file */
if(!colladaImporter->open(argv[1]))
return 4;
if(colladaImporter->objectCount() == 0)
return 5;
/* Optimize vertices */
shared_ptr<Trade::AbstractImporter::MeshData> meshData = colladaImporter->meshData(0);
if(meshData && meshData->indices() && meshData->vertices(0)) {
Debug() << "Optimizing mesh vertices using Tipsify algorithm (cache size 24)...";
MeshTools::tipsify(*meshData->indices(), meshData->vertices(0)->size(), 24);
}
o = colladaImporter->object(0);
if(!o) return 6;
o->setParent(&scene);
colladaImporter->close();
delete colladaImporter.release();
/* Main loop calls draw() periodically and setViewport() on window size change */
glutMainLoop();
o.reset();
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.
#include "benchmark/benchmark.h"
#include "arrow/compute/cast.h"
#include "arrow/compute/exec/expression.h"
#include "arrow/compute/exec/test_util.h"
#include "arrow/dataset/partition.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/type.h"
namespace arrow {
namespace compute {
std::shared_ptr<Scalar> ninety_nine_dict =
DictionaryScalar::Make(MakeScalar(0), ArrayFromJSON(int64(), "[99]"));
static void BindAndEvaluate(benchmark::State& state, Expression expr) {
ExecContext ctx;
auto struct_type = struct_({
field("int", int64()),
field("float", float64()),
});
auto dataset_schema = schema({
field("int_arr", int64()),
field("struct_arr", struct_type),
field("int_scalar", int64()),
field("struct_scalar", struct_type),
});
ExecBatch input(
{
Datum(ArrayFromJSON(int64(), "[0, 2, 4, 8]")),
Datum(ArrayFromJSON(struct_type,
"[[0, 2.0], [4, 8.0], [16, 32.0], [64, 128.0]]")),
Datum(ScalarFromJSON(int64(), "16")),
Datum(ScalarFromJSON(struct_type, "[32, 64.0]")),
},
/*length=*/4);
for (auto _ : state) {
ASSIGN_OR_ABORT(auto bound, expr.Bind(*dataset_schema));
ABORT_NOT_OK(ExecuteScalarExpression(bound, input, &ctx).status());
}
}
// A benchmark of SimplifyWithGuarantee using expressions arising from partitioning.
static void SimplifyFilterWithGuarantee(benchmark::State& state, Expression filter,
Expression guarantee) {
auto dataset_schema = schema({field("a", int64()), field("b", int64())});
ASSIGN_OR_ABORT(filter, filter.Bind(*dataset_schema));
for (auto _ : state) {
ABORT_NOT_OK(SimplifyWithGuarantee(filter, guarantee));
}
}
auto to_int64 = compute::CastOptions::Safe(int64());
// A fully simplified filter.
auto filter_simple_negative = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(98))));
auto filter_simple_positive = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(99))));
// A filter with casts inserted due to converting between the
// assumed-by-default type and the inferred partition schema.
auto filter_cast_negative =
and_(equal(call("cast", {field_ref("a")}, to_int64), literal(99)),
equal(call("cast", {field_ref("b")}, to_int64), literal(98)));
auto filter_cast_positive =
and_(equal(call("cast", {field_ref("a")}, to_int64), literal(99)),
equal(call("cast", {field_ref("b")}, to_int64), literal(99)));
// An unencoded partition expression for "a=99/b=99".
auto guarantee = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(99))));
// A partition expression for "a=99/b=99" that uses dictionaries (inferred by default).
auto guarantee_dictionary = and_(equal(field_ref("a"), literal(ninety_nine_dict)),
equal(field_ref("b"), literal(ninety_nine_dict)));
// Negative queries (partition expressions that fail the filter)
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_simple_guarantee_simple,
filter_simple_negative, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_cast_guarantee_simple,
filter_cast_negative, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee,
negative_filter_simple_guarantee_dictionary, filter_simple_negative,
guarantee_dictionary);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_cast_guarantee_dictionary,
filter_cast_negative, guarantee_dictionary);
// Positive queries (partition expressions that pass the filter)
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_simple_guarantee_simple,
filter_simple_positive, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_cast_guarantee_simple,
filter_cast_positive, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee,
positive_filter_simple_guarantee_dictionary, filter_simple_positive,
guarantee_dictionary);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_cast_guarantee_dictionary,
filter_cast_positive, guarantee_dictionary);
BENCHMARK_CAPTURE(BindAndEvaluate, simple_array, field_ref("int_arr"));
BENCHMARK_CAPTURE(BindAndEvaluate, simple_scalar, field_ref("int_scalar"));
BENCHMARK_CAPTURE(BindAndEvaluate, nested_array,
field_ref(FieldRef("struct_arr", "float")));
BENCHMARK_CAPTURE(BindAndEvaluate, nested_scalar,
field_ref(FieldRef("struct_scalar", "float")));
} // namespace compute
} // namespace arrow
<commit_msg>ARROW-16014: [C++] Create more benchmarks for measuring expression evaluation overhead<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "benchmark/benchmark.h"
#include "arrow/compute/cast.h"
#include "arrow/compute/exec/expression.h"
#include "arrow/compute/exec/test_util.h"
#include "arrow/dataset/partition.h"
#include "arrow/testing/generator.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/type.h"
namespace arrow {
namespace compute {
std::shared_ptr<Scalar> ninety_nine_dict =
DictionaryScalar::Make(MakeScalar(0), ArrayFromJSON(int64(), "[99]"));
static void BindAndEvaluate(benchmark::State& state, Expression expr) {
ExecContext ctx;
auto struct_type = struct_({
field("int", int64()),
field("float", float64()),
});
auto dataset_schema = schema({
field("int_arr", int64()),
field("struct_arr", struct_type),
field("int_scalar", int64()),
field("struct_scalar", struct_type),
});
ExecBatch input(
{
Datum(ArrayFromJSON(int64(), "[0, 2, 4, 8]")),
Datum(ArrayFromJSON(struct_type,
"[[0, 2.0], [4, 8.0], [16, 32.0], [64, 128.0]]")),
Datum(ScalarFromJSON(int64(), "16")),
Datum(ScalarFromJSON(struct_type, "[32, 64.0]")),
},
/*length=*/4);
for (auto _ : state) {
ASSIGN_OR_ABORT(auto bound, expr.Bind(*dataset_schema));
ABORT_NOT_OK(ExecuteScalarExpression(bound, input, &ctx).status());
}
}
// A benchmark of SimplifyWithGuarantee using expressions arising from partitioning.
static void SimplifyFilterWithGuarantee(benchmark::State& state, Expression filter,
Expression guarantee) {
auto dataset_schema = schema({field("a", int64()), field("b", int64())});
ASSIGN_OR_ABORT(filter, filter.Bind(*dataset_schema));
for (auto _ : state) {
ABORT_NOT_OK(SimplifyWithGuarantee(filter, guarantee));
}
}
static void ExecuteScalarExpressionOverhead(benchmark::State& state, Expression expr) {
const auto rows_per_batch = static_cast<int32_t>(state.range(0));
const auto num_batches = 1000000 / rows_per_batch;
ExecContext ctx;
auto dataset_schema = schema({
field("x", int64()),
});
ExecBatch input({Datum(ConstantArrayGenerator::Int64(rows_per_batch, 5))},
/*length=*/rows_per_batch);
ASSIGN_OR_ABORT(auto bound, expr.Bind(*dataset_schema));
for (auto _ : state) {
for (int it = 0; it < num_batches; ++it)
ABORT_NOT_OK(ExecuteScalarExpression(bound, input, &ctx).status());
}
state.counters["rows_per_second"] = benchmark::Counter(
static_cast<double>(state.iterations() * num_batches * rows_per_batch),
benchmark::Counter::kIsRate);
state.counters["batches_per_second"] = benchmark::Counter(
static_cast<double>(state.iterations() * num_batches), benchmark::Counter::kIsRate);
}
auto to_int64 = compute::CastOptions::Safe(int64());
// A fully simplified filter.
auto filter_simple_negative = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(98))));
auto filter_simple_positive = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(99))));
// A filter with casts inserted due to converting between the
// assumed-by-default type and the inferred partition schema.
auto filter_cast_negative =
and_(equal(call("cast", {field_ref("a")}, to_int64), literal(99)),
equal(call("cast", {field_ref("b")}, to_int64), literal(98)));
auto filter_cast_positive =
and_(equal(call("cast", {field_ref("a")}, to_int64), literal(99)),
equal(call("cast", {field_ref("b")}, to_int64), literal(99)));
// An unencoded partition expression for "a=99/b=99".
auto guarantee = and_(equal(field_ref("a"), literal(int64_t(99))),
equal(field_ref("b"), literal(int64_t(99))));
// A partition expression for "a=99/b=99" that uses dictionaries (inferred by default).
auto guarantee_dictionary = and_(equal(field_ref("a"), literal(ninety_nine_dict)),
equal(field_ref("b"), literal(ninety_nine_dict)));
auto complex_expression =
and_(less(field_ref("x"), literal(20)), greater(field_ref("x"), literal(0)));
auto simple_expression = call("negate", {field_ref("x")});
auto zero_copy_expression =
call("cast", {field_ref("x")}, compute::CastOptions::Safe(timestamp(TimeUnit::NANO)));
auto ref_only_expression = field_ref("x");
// Negative queries (partition expressions that fail the filter)
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_simple_guarantee_simple,
filter_simple_negative, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_cast_guarantee_simple,
filter_cast_negative, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee,
negative_filter_simple_guarantee_dictionary, filter_simple_negative,
guarantee_dictionary);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, negative_filter_cast_guarantee_dictionary,
filter_cast_negative, guarantee_dictionary);
// Positive queries (partition expressions that pass the filter)
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_simple_guarantee_simple,
filter_simple_positive, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_cast_guarantee_simple,
filter_cast_positive, guarantee);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee,
positive_filter_simple_guarantee_dictionary, filter_simple_positive,
guarantee_dictionary);
BENCHMARK_CAPTURE(SimplifyFilterWithGuarantee, positive_filter_cast_guarantee_dictionary,
filter_cast_positive, guarantee_dictionary);
BENCHMARK_CAPTURE(BindAndEvaluate, simple_array, field_ref("int_arr"));
BENCHMARK_CAPTURE(BindAndEvaluate, simple_scalar, field_ref("int_scalar"));
BENCHMARK_CAPTURE(BindAndEvaluate, nested_array,
field_ref(FieldRef("struct_arr", "float")));
BENCHMARK_CAPTURE(BindAndEvaluate, nested_scalar,
field_ref(FieldRef("struct_scalar", "float")));
BENCHMARK_CAPTURE(ExecuteScalarExpressionOverhead, complex_expression, complex_expression)
->ArgNames({"rows_per_batch"})
->RangeMultiplier(10)
->Range(1000, 1000000)
->DenseThreadRange(1, std::thread::hardware_concurrency(),
std::thread::hardware_concurrency())
->UseRealTime();
BENCHMARK_CAPTURE(ExecuteScalarExpressionOverhead, simple_expression, simple_expression)
->ArgNames({"rows_per_batch"})
->RangeMultiplier(10)
->Range(1000, 1000000)
->DenseThreadRange(1, std::thread::hardware_concurrency(),
std::thread::hardware_concurrency())
->UseRealTime();
BENCHMARK_CAPTURE(ExecuteScalarExpressionOverhead, zero_copy_expression,
zero_copy_expression)
->ArgNames({"rows_per_batch"})
->RangeMultiplier(10)
->Range(1000, 1000000)
->DenseThreadRange(1, std::thread::hardware_concurrency(),
std::thread::hardware_concurrency())
->UseRealTime();
BENCHMARK_CAPTURE(ExecuteScalarExpressionOverhead, ref_only_expression,
ref_only_expression)
->ArgNames({"rows_per_batch"})
->RangeMultiplier(10)
->Range(1000, 1000000)
->DenseThreadRange(1, std::thread::hardware_concurrency(),
std::thread::hardware_concurrency())
->UseRealTime();
} // namespace compute
} // namespace arrow
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* 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 <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
using namespace std;
namespace fs = filesystem;
namespace
{
///////////////////////////////////////////////////////////////////////////////////////////////////
string PROGRAM_NAME; ///< We set the program name on this global early on for use in Usage.
string_view VERSION = "1.0.0";
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Supported extensions for the files in the input directory.
// clang-format off
constexpr string_view SHADER_EXTENSIONS[] =
{
".vert",
".frag",
".def"
};
// clang-format on
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Function & variable to retrieve the size of the extension with the largest string size.
constexpr auto GetShaderExtensionMaxSize()
{
auto maxSize = 0u;
for(const auto& extension : SHADER_EXTENSIONS)
{
if(extension.size() > maxSize)
{
maxSize = extension.size();
}
}
return maxSize;
}
constexpr const int SHADER_MAX_EXTENSION_SIZE(GetShaderExtensionMaxSize());
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Prints out the Usage to standard output.
void Usage()
{
cout << "Usage: " << PROGRAM_NAME << " [OPTIONS] [IN_DIR] [OUT_DIR]" << endl;
cout << " IN_DIR: Input Directory which has all the shader files." << endl;
cout << " Supported extensions:";
string extensions;
for(const auto& extension : SHADER_EXTENSIONS)
{
extensions = extensions + " \"" + string(extension) + "\",";
}
extensions.pop_back(); // Remove the last comma.
cout << extensions << "." << endl;
cout << " OUT_DIR: Directory where the generated shader source code will be outputted to." << endl;
cout << " This directory will be created if it does not exist." << endl;
cout << " Any existing files of the same name in the directory will be overwritten." << endl;
cout << " Options: " << endl;
cout << " -s|--skip Skips the generation of the built-in header and source files" << endl;
cout << " -v|--version Prints out the version" << endl;
cout << " -h|--help Help" << endl;
cout << " NOTE: The options can be placed after the IN_DIR & OUT_DIR as well" << endl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Uses the filename to generate the shader variable name to use in source code.
/// @param[in] filename The filename of the shader (including the extension)
/// @return The shader variable name
string GetShaderVariableName(const string& filename)
{
string shaderVariableName("SHADER_" + filename);
for_each(
shaderVariableName.begin(),
shaderVariableName.end(),
[](char& character) {
switch(character)
{
case '-':
case '.':
{
character = '_';
break;
}
default:
{
character = ::toupper(character);
break;
}
}
});
return shaderVariableName;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Uses the ourDir & filename to generate the path of the output header file for the shader.
/// @param[in] outDir The directory where the readable shaders will be outputted to
/// @param[in] filename The filename of the shader (including the extension)
/// @return The path to the output file
fs::path GetShaderOutputFilePath(fs::path& outDir, const string& filename)
{
string outFilename(filename);
replace(outFilename.end() - SHADER_MAX_EXTENSION_SIZE, outFilename.end(), '.', '-');
outFilename = outDir.string() + "/" + outFilename + ".h";
return outFilename;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Generates the header file from the input shader file.
/// @param[in] shaderFile The full path of the input shader file
/// @param[in] shaderVariableName The variable name to use for the string_view
/// @param[in] outFilePath The full path to the output file
void GenerateHeaderFile(
ifstream& shaderFile,
const string& shaderVariableName,
const fs::path& outFilePath)
{
cout << " Generating \"" << shaderVariableName << "\" in " << outFilePath.filename();
ofstream outFile(outFilePath);
if(outFile.is_open())
{
outFile << "#pragma once" << endl
<< endl;
outFile << "const std::string_view " << shaderVariableName << endl;
outFile << "{" << endl;
string line;
while(getline(shaderFile, line))
{
outFile << "\"" << line << "\\n\"" << endl;
}
outFile << "};" << endl;
cout << " [OK]" << endl;
}
else
{
cout << " [FAIL]" << endl;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// If required, this accumulates data about all the shaders & generates the built-in cpp & header
class BuiltInFilesGenerator
{
public:
/// Constructor
/// @param[in] outDir The path to the output directory
BuiltInFilesGenerator(const fs::path& outDir)
: mHeaderFilePath(outDir.string() + "/../" + string(HEADER_FILE_NAME)),
mSourceFilePath(outDir.string() + "/" + string(SOURCE_FILE_NAME))
{
}
/// Default destructor
~BuiltInFilesGenerator() = default;
/// Adds the variable and the header file name to the appropriate vectors.
/// @param[in] variableName The string_view variable name used
/// @param[in] headerFileName The name of the header used
void Add(string&& variableName, const std::string& headerFilename)
{
mVariableNames.emplace_back(variableName);
mHeaderFileNames.emplace_back(headerFilename);
}
// Generates the built in files.
void Generate()
{
GenerateFile(
mVariableNames,
mHeaderFilePath,
"#pragma once\n\n#include <string_view>\n\n",
"extern const std::string_view ",
";");
GenerateFile(
mHeaderFileNames,
mSourceFilePath,
"#include \"../" + string(HEADER_FILE_NAME) + "\"\n\n",
"#include \"",
"\"");
}
private:
/// Generates the required file.
/// @param[in] strings A reference to the vector to parse
/// @param[in] filePath Outputs the data to this file
/// @param[in] header Puts this before parsing any of the vector
/// @param[in] before For each string, puts this string before it on every line
/// @param[in] after For each string, puts this string after it on every line
void GenerateFile(
vector<string>& strings,
const string& filePath,
const string_view header,
const string_view before,
const string_view after)
{
sort(strings.begin(), strings.end());
cout << " Generating \"" << filePath << "\"";
ofstream outFile(filePath);
if(outFile)
{
outFile << header;
for(auto& current : strings)
{
outFile << before << current << after << endl;
}
cout << " [OK]" << endl;
}
else
{
cout << " [FAIL]" << endl;
}
}
constexpr static string_view HEADER_FILE_NAME = "builtin-shader-extern-gen.h";
constexpr static string_view SOURCE_FILE_NAME = "builtin-shader-gen.cpp";
const string mHeaderFilePath; ///< Path to the header file to generate
const string mSourceFilePath; ///< Path to the source file to generate
vector<string> mVariableNames; ///< Holds all the variable names added through Add
vector<string> mHeaderFileNames; ///< Holds all the header file names added through Add
};
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Generates the header files from the shaders in the input directory & built-in files if reqruied.
///
/// @param[in] inDir The directory where all the input shader source is
/// @param[in] outDir The directory where the readable shaders will be outputted to
/// @param[in] generateBuiltInFiles If true, we generate the built-in files as well
/// @return 0 if successful, 1 if failure
int GenerateShaderSources(fs::path inDir, fs::path outDir, const bool generateBuiltInFiles)
{
if(!fs::is_directory(inDir))
{
cerr << "ERROR: " << inDir << " is not a valid directory" << endl;
Usage();
return 1;
}
try
{
fs::create_directories(outDir);
}
catch(...)
{
cerr << "ERROR: Unable to create directory " << outDir << endl;
return 1;
}
cout << "====================================================================" << endl;
cout << "Shader Input Directory: " << inDir << endl;
cout << "Shader Output Directory: " << outDir << endl;
cout << "====================================================================" << endl;
BuiltInFilesGenerator generator(outDir);
for(auto& file : fs::directory_iterator(inDir))
{
if(file.is_regular_file())
{
for(const auto& extension : SHADER_EXTENSIONS)
{
if(file.path().extension() == extension)
{
const fs::path& path(file.path());
const string filename(path.filename().string());
string shaderVariableName(GetShaderVariableName(filename));
ifstream shaderFile(path);
if(shaderFile.is_open())
{
fs::path outFilePath(GetShaderOutputFilePath(outDir, filename));
GenerateHeaderFile(shaderFile, shaderVariableName, outFilePath);
generator.Add(std::move(shaderVariableName), outFilePath.filename().string());
}
break;
}
}
}
}
if(generateBuiltInFiles)
{
generator.Generate();
}
cout << "====================================================================" << endl;
return 0;
}
} // unnamed namespace
///////////////////////////////////////////////////////////////////////////////////////////////////
/// MAIN.
int main(int argc, char* argv[])
{
PROGRAM_NAME = argv[0];
bool generateBuiltInFiles = true;
string inDir;
string outDir;
for(auto i = 1; i < argc; ++i)
{
string option(argv[i]);
if(option == "--skip" || option == "-s")
{
generateBuiltInFiles = false;
}
else if(option == "--help" || option == "-h")
{
cout << "DALi Shader Generator v" << VERSION << endl
<< endl;
Usage();
return 0;
}
else if(option == "--version" || option == "-v")
{
cout << VERSION << endl;
return 0;
}
else if(*option.begin() == '-')
{
cerr << "ERROR: " << option << " is not a supported option" << endl;
Usage();
return 1;
}
else if(inDir.empty())
{
inDir = option;
}
else if(outDir.empty())
{
outDir = option;
}
else if(inDir.size() && outDir.size())
{
cerr << "ERROR: Too many options" << endl;
Usage();
return 1;
}
}
if(inDir.empty() || outDir.empty())
{
cerr << "ERROR: Both IN_DIR & OUT_DIR not provided" << endl;
Usage();
return 1;
}
return GenerateShaderSources(inDir, outDir, generateBuiltInFiles);
}
<commit_msg>[Shader Generator] using Raw String Literal <commit_after>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* 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 <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
using namespace std;
namespace fs = filesystem;
namespace
{
///////////////////////////////////////////////////////////////////////////////////////////////////
string PROGRAM_NAME; ///< We set the program name on this global early on for use in Usage.
string_view VERSION = "1.0.0";
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Supported extensions for the files in the input directory.
// clang-format off
constexpr string_view SHADER_EXTENSIONS[] =
{
".vert",
".frag",
".def"
};
// clang-format on
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Function & variable to retrieve the size of the extension with the largest string size.
constexpr auto GetShaderExtensionMaxSize()
{
auto maxSize = 0u;
for(const auto& extension : SHADER_EXTENSIONS)
{
if(extension.size() > maxSize)
{
maxSize = extension.size();
}
}
return maxSize;
}
constexpr const int SHADER_MAX_EXTENSION_SIZE(GetShaderExtensionMaxSize());
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Prints out the Usage to standard output.
void Usage()
{
cout << "Usage: " << PROGRAM_NAME << " [OPTIONS] [IN_DIR] [OUT_DIR]" << endl;
cout << " IN_DIR: Input Directory which has all the shader files." << endl;
cout << " Supported extensions:";
string extensions;
for(const auto& extension : SHADER_EXTENSIONS)
{
extensions = extensions + " \"" + string(extension) + "\",";
}
extensions.pop_back(); // Remove the last comma.
cout << extensions << "." << endl;
cout << " OUT_DIR: Directory where the generated shader source code will be outputted to." << endl;
cout << " This directory will be created if it does not exist." << endl;
cout << " Any existing files of the same name in the directory will be overwritten." << endl;
cout << " Options: " << endl;
cout << " -s|--skip Skips the generation of the built-in header and source files" << endl;
cout << " -v|--version Prints out the version" << endl;
cout << " -h|--help Help" << endl;
cout << " NOTE: The options can be placed after the IN_DIR & OUT_DIR as well" << endl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Uses the filename to generate the shader variable name to use in source code.
/// @param[in] filename The filename of the shader (including the extension)
/// @return The shader variable name
string GetShaderVariableName(const string& filename)
{
string shaderVariableName("SHADER_" + filename);
for_each(
shaderVariableName.begin(),
shaderVariableName.end(),
[](char& character) {
switch(character)
{
case '-':
case '.':
{
character = '_';
break;
}
default:
{
character = ::toupper(character);
break;
}
}
});
return shaderVariableName;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Uses the ourDir & filename to generate the path of the output header file for the shader.
/// @param[in] outDir The directory where the readable shaders will be outputted to
/// @param[in] filename The filename of the shader (including the extension)
/// @return The path to the output file
fs::path GetShaderOutputFilePath(fs::path& outDir, const string& filename)
{
string outFilename(filename);
replace(outFilename.end() - SHADER_MAX_EXTENSION_SIZE, outFilename.end(), '.', '-');
outFilename = outDir.string() + "/" + outFilename + ".h";
return outFilename;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Generates the header file from the input shader file.
/// @param[in] shaderFile The full path of the input shader file
/// @param[in] shaderVariableName The variable name to use for the string_view
/// @param[in] outFilePath The full path to the output file
void GenerateHeaderFile(
ifstream& shaderFile,
const string& shaderVariableName,
const fs::path& outFilePath)
{
cout << " Generating \"" << shaderVariableName << "\" in " << outFilePath.filename();
ofstream outFile(outFilePath);
if(outFile.is_open())
{
outFile << "#pragma once" << endl
<< endl;
outFile << "const std::string_view " << shaderVariableName << endl;
outFile << "{" << endl;
outFile << "R\"(" << endl;
string line;
while(getline(shaderFile, line))
{
outFile << line << endl;
}
outFile << ")\"" << endl;
outFile << "};" << endl;
cout << " [OK]" << endl;
}
else
{
cout << " [FAIL]" << endl;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// If required, this accumulates data about all the shaders & generates the built-in cpp & header
class BuiltInFilesGenerator
{
public:
/// Constructor
/// @param[in] outDir The path to the output directory
BuiltInFilesGenerator(const fs::path& outDir)
: mHeaderFilePath(outDir.string() + "/../" + string(HEADER_FILE_NAME)),
mSourceFilePath(outDir.string() + "/" + string(SOURCE_FILE_NAME))
{
}
/// Default destructor
~BuiltInFilesGenerator() = default;
/// Adds the variable and the header file name to the appropriate vectors.
/// @param[in] variableName The string_view variable name used
/// @param[in] headerFileName The name of the header used
void Add(string&& variableName, const std::string& headerFilename)
{
mVariableNames.emplace_back(variableName);
mHeaderFileNames.emplace_back(headerFilename);
}
// Generates the built in files.
void Generate()
{
GenerateFile(
mVariableNames,
mHeaderFilePath,
"#pragma once\n\n#include <string_view>\n\n",
"extern const std::string_view ",
";");
GenerateFile(
mHeaderFileNames,
mSourceFilePath,
"#include \"../" + string(HEADER_FILE_NAME) + "\"\n\n",
"#include \"",
"\"");
}
private:
/// Generates the required file.
/// @param[in] strings A reference to the vector to parse
/// @param[in] filePath Outputs the data to this file
/// @param[in] header Puts this before parsing any of the vector
/// @param[in] before For each string, puts this string before it on every line
/// @param[in] after For each string, puts this string after it on every line
void GenerateFile(
vector<string>& strings,
const string& filePath,
const string_view header,
const string_view before,
const string_view after)
{
sort(strings.begin(), strings.end());
cout << " Generating \"" << filePath << "\"";
ofstream outFile(filePath);
if(outFile)
{
outFile << header;
for(auto& current : strings)
{
outFile << before << current << after << endl;
}
cout << " [OK]" << endl;
}
else
{
cout << " [FAIL]" << endl;
}
}
constexpr static string_view HEADER_FILE_NAME = "builtin-shader-extern-gen.h";
constexpr static string_view SOURCE_FILE_NAME = "builtin-shader-gen.cpp";
const string mHeaderFilePath; ///< Path to the header file to generate
const string mSourceFilePath; ///< Path to the source file to generate
vector<string> mVariableNames; ///< Holds all the variable names added through Add
vector<string> mHeaderFileNames; ///< Holds all the header file names added through Add
};
///////////////////////////////////////////////////////////////////////////////////////////////////
/// Generates the header files from the shaders in the input directory & built-in files if reqruied.
///
/// @param[in] inDir The directory where all the input shader source is
/// @param[in] outDir The directory where the readable shaders will be outputted to
/// @param[in] generateBuiltInFiles If true, we generate the built-in files as well
/// @return 0 if successful, 1 if failure
int GenerateShaderSources(fs::path inDir, fs::path outDir, const bool generateBuiltInFiles)
{
if(!fs::is_directory(inDir))
{
cerr << "ERROR: " << inDir << " is not a valid directory" << endl;
Usage();
return 1;
}
try
{
fs::create_directories(outDir);
}
catch(...)
{
cerr << "ERROR: Unable to create directory " << outDir << endl;
return 1;
}
cout << "====================================================================" << endl;
cout << "Shader Input Directory: " << inDir << endl;
cout << "Shader Output Directory: " << outDir << endl;
cout << "====================================================================" << endl;
BuiltInFilesGenerator generator(outDir);
for(auto& file : fs::directory_iterator(inDir))
{
if(file.is_regular_file())
{
for(const auto& extension : SHADER_EXTENSIONS)
{
if(file.path().extension() == extension)
{
const fs::path& path(file.path());
const string filename(path.filename().string());
string shaderVariableName(GetShaderVariableName(filename));
ifstream shaderFile(path);
if(shaderFile.is_open())
{
fs::path outFilePath(GetShaderOutputFilePath(outDir, filename));
GenerateHeaderFile(shaderFile, shaderVariableName, outFilePath);
generator.Add(std::move(shaderVariableName), outFilePath.filename().string());
}
break;
}
}
}
}
if(generateBuiltInFiles)
{
generator.Generate();
}
cout << "====================================================================" << endl;
return 0;
}
} // unnamed namespace
///////////////////////////////////////////////////////////////////////////////////////////////////
/// MAIN.
int main(int argc, char* argv[])
{
PROGRAM_NAME = argv[0];
bool generateBuiltInFiles = true;
string inDir;
string outDir;
for(auto i = 1; i < argc; ++i)
{
string option(argv[i]);
if(option == "--skip" || option == "-s")
{
generateBuiltInFiles = false;
}
else if(option == "--help" || option == "-h")
{
cout << "DALi Shader Generator v" << VERSION << endl
<< endl;
Usage();
return 0;
}
else if(option == "--version" || option == "-v")
{
cout << VERSION << endl;
return 0;
}
else if(*option.begin() == '-')
{
cerr << "ERROR: " << option << " is not a supported option" << endl;
Usage();
return 1;
}
else if(inDir.empty())
{
inDir = option;
}
else if(outDir.empty())
{
outDir = option;
}
else if(inDir.size() && outDir.size())
{
cerr << "ERROR: Too many options" << endl;
Usage();
return 1;
}
}
if(inDir.empty() || outDir.empty())
{
cerr << "ERROR: Both IN_DIR & OUT_DIR not provided" << endl;
Usage();
return 1;
}
return GenerateShaderSources(inDir, outDir, generateBuiltInFiles);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project 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 "pubchem.h"
#include <QtXml>
#include <QtNetwork>
#include "pubchemquery.h"
#include "downloadthread.h"
#include "pubchemquerythread.h"
#include <chemkit/molecule.h>
#include <chemkit/moleculefile.h>
namespace chemkit {
namespace web {
// === PubChemPrivate ====================================================== //
class PubChemPrivate
{
public:
QUrl url;
QString errorString;
};
// === PubChem ============================================================= //
/// \class PubChem pubchem.h chemkit/pubchem.h
/// \ingroup chemkit-web
/// \brief The PubChem class provides access to the %PubChem web
/// API.
// --- Construction and Destruction ---------------------------------------- //
/// Creates a new PubChem object.
PubChem::PubChem()
: d(new PubChemPrivate)
{
d->url = QUrl("http://pubchem.ncbi.nlm.nih.gov/");
}
/// Destroys the PubChem object.
PubChem::~PubChem()
{
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Sets the url to \p url.
void PubChem::setUrl(const QUrl &url)
{
d->url = url;
}
/// Returns the url.
QUrl PubChem::url() const
{
return d->url;
}
// --- Downloads ----------------------------------------------------------- //
/// Downloads and returns the molecule with the compound ID \p id.
/// If an error occurs \c 0 is returned.
///
/// The ownership of the returned molecule is passed to the caller.
Molecule* PubChem::downloadMolecule(const QString &id) const
{
QScopedPointer<MoleculeFile> file(downloadFile(id));
if(!file){
return 0;
}
Molecule *molecule = file->molecule();
file->removeMolecule(molecule);
return molecule;
}
/// Downloads and returns the file with the compound ID \p id. If an
/// error occurs \c 0 is returned.
///
/// The ownership of the returned file is passed to the caller.
MoleculeFile* PubChem::downloadFile(const QString &id) const
{
QByteArray data = downloadFileData(id, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file containing the compounds with ID's
/// in the list \p ids. If an error occurs \c 0 is returned.
///
/// The ownership of the file is passed to the caller.
///
/// For example, to download the file containing %PubChem Compounds
/// 1, 2, 3, 42 and 57:
/// \code
/// QStringList ids;
/// ids << "1" << "2" << "3" << "42" << "57";
/// MoleculeFile *file = pubchem.downloadFile(ids);
/// \endcode
MoleculeFile* PubChem::downloadFile(const QStringList &ids) const
{
QByteArray data = downloadFileData(ids, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file data for the compound with ID
/// \p id. If an error occurs an empty QByteArray is returned.
QByteArray PubChem::downloadFileData(const QString &id, const QString &format) const
{
Q_UNUSED(format);
QUrl url(QString("%1summary/summary.cgi?cid=%2&disopt=3DDisplaySDF").arg(d->url.toString())
.arg(id));
return DownloadThread::download(url);
}
/// Downloads and returns the file data for the compounds with ID's
/// in the list \p ids. If an error occurs an empty QByteArray is
/// returned.
QByteArray PubChem::downloadFileData(const QStringList &ids, const QString &format) const
{
PubChemQuery query = PubChemQuery::downloadQuery(ids, format);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
// the response contains a URL where the file can be downloaded
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Download-URL_url");
if(nodes.isEmpty()){
return QByteArray();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
QString url = element.text();
return DownloadThread::download(QUrl(url));
}
// --- Search -------------------------------------------------------------- //
/// Searches the %PubChem database for \p query and returns a list
/// of matching compound IDs. The returned list of ids can be passed
/// to PubChem::downloadFile() to download the molecules.
QStringList PubChem::search(const QString &query) const
{
QString url = "http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&term=%1";
QByteArray response = DownloadThread::download(QUrl(url.arg(query)));
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("Id");
QStringList ids;
for(int i = 0; i < nodes.size(); i++){
QDomNode node = nodes.item(i);
QDomElement element = node.toElement();
ids.append(element.text());
}
return ids;
}
// --- Standardization ----------------------------------------------------- //
/// Returns a string containing the standardized version of
/// \p formula in \p format. If an error occurs an empty QString is
/// returned.
///
/// For example, to standardize a SMILES formula:
/// \code
/// std::string formula = pubchem.standardizeFormula("c3cccc3", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &format) const
{
return standardizeFormula(formula, format, format);
}
/// Returns a string containing the standardized version of
/// \p formula from \p inputFormat in \p outputFormat. If an error
/// occurs an empty QString is returned.
///
/// For example, to convert an InChI string to standardized SMILES:
/// \code
/// std::string formula = pubchem.standardizeFormula("InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H", "inchi", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &inputFormat, const std::string &outputFormat) const
{
if(formula.empty()){
return std::string();
}
PubChemQuery query = PubChemQuery::standardizationQuery(formula, inputFormat, outputFormat);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Structure_structure_string");
if(nodes.isEmpty()){
return std::string();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
std::string standardizedFormula = element.text().toStdString();
return standardizedFormula;
}
/// Returns a string containing the standardized formula in \p format
/// for the \p molecule. If an error occurs an empty QString is
/// returned.
///
/// For example, to get the standardized InChI formula for a
/// molecule:
/// \code
/// std::string formula = pubchem.standardizeFormula(molecule, "inchi");
/// \endcode
std::string PubChem::standardizeFormula(const Molecule *molecule, const std::string &format) const
{
return standardizeFormula(molecule->formula("smiles"), "smiles", format);
}
// --- Error Handling ------------------------------------------------------ //
void PubChem::setErrorString(const QString &error)
{
d->errorString = error;
}
/// Returns a string describing the last error that occured.
QString PubChem::errorString() const
{
return d->errorString;
}
} // end web namespace
} // end chemkit namespace
<commit_msg>Fix documentation for PubChem::standardizeFormula()<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project 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 "pubchem.h"
#include <QtXml>
#include <QtNetwork>
#include "pubchemquery.h"
#include "downloadthread.h"
#include "pubchemquerythread.h"
#include <chemkit/molecule.h>
#include <chemkit/moleculefile.h>
namespace chemkit {
namespace web {
// === PubChemPrivate ====================================================== //
class PubChemPrivate
{
public:
QUrl url;
QString errorString;
};
// === PubChem ============================================================= //
/// \class PubChem pubchem.h chemkit/pubchem.h
/// \ingroup chemkit-web
/// \brief The PubChem class provides access to the %PubChem web
/// API.
// --- Construction and Destruction ---------------------------------------- //
/// Creates a new PubChem object.
PubChem::PubChem()
: d(new PubChemPrivate)
{
d->url = QUrl("http://pubchem.ncbi.nlm.nih.gov/");
}
/// Destroys the PubChem object.
PubChem::~PubChem()
{
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Sets the url to \p url.
void PubChem::setUrl(const QUrl &url)
{
d->url = url;
}
/// Returns the url.
QUrl PubChem::url() const
{
return d->url;
}
// --- Downloads ----------------------------------------------------------- //
/// Downloads and returns the molecule with the compound ID \p id.
/// If an error occurs \c 0 is returned.
///
/// The ownership of the returned molecule is passed to the caller.
Molecule* PubChem::downloadMolecule(const QString &id) const
{
QScopedPointer<MoleculeFile> file(downloadFile(id));
if(!file){
return 0;
}
Molecule *molecule = file->molecule();
file->removeMolecule(molecule);
return molecule;
}
/// Downloads and returns the file with the compound ID \p id. If an
/// error occurs \c 0 is returned.
///
/// The ownership of the returned file is passed to the caller.
MoleculeFile* PubChem::downloadFile(const QString &id) const
{
QByteArray data = downloadFileData(id, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file containing the compounds with ID's
/// in the list \p ids. If an error occurs \c 0 is returned.
///
/// The ownership of the file is passed to the caller.
///
/// For example, to download the file containing %PubChem Compounds
/// 1, 2, 3, 42 and 57:
/// \code
/// QStringList ids;
/// ids << "1" << "2" << "3" << "42" << "57";
/// MoleculeFile *file = pubchem.downloadFile(ids);
/// \endcode
MoleculeFile* PubChem::downloadFile(const QStringList &ids) const
{
QByteArray data = downloadFileData(ids, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file data for the compound with ID
/// \p id. If an error occurs an empty QByteArray is returned.
QByteArray PubChem::downloadFileData(const QString &id, const QString &format) const
{
Q_UNUSED(format);
QUrl url(QString("%1summary/summary.cgi?cid=%2&disopt=3DDisplaySDF").arg(d->url.toString())
.arg(id));
return DownloadThread::download(url);
}
/// Downloads and returns the file data for the compounds with ID's
/// in the list \p ids. If an error occurs an empty QByteArray is
/// returned.
QByteArray PubChem::downloadFileData(const QStringList &ids, const QString &format) const
{
PubChemQuery query = PubChemQuery::downloadQuery(ids, format);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
// the response contains a URL where the file can be downloaded
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Download-URL_url");
if(nodes.isEmpty()){
return QByteArray();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
QString url = element.text();
return DownloadThread::download(QUrl(url));
}
// --- Search -------------------------------------------------------------- //
/// Searches the %PubChem database for \p query and returns a list
/// of matching compound IDs. The returned list of ids can be passed
/// to PubChem::downloadFile() to download the molecules.
QStringList PubChem::search(const QString &query) const
{
QString url = "http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&term=%1";
QByteArray response = DownloadThread::download(QUrl(url.arg(query)));
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("Id");
QStringList ids;
for(int i = 0; i < nodes.size(); i++){
QDomNode node = nodes.item(i);
QDomElement element = node.toElement();
ids.append(element.text());
}
return ids;
}
// --- Standardization ----------------------------------------------------- //
/// Returns a string containing the standardized version of
/// \p formula in \p format. If an error occurs an empty string is
/// returned.
///
/// For example, to standardize a SMILES formula:
/// \code
/// std::string formula = pubchem.standardizeFormula("c3cccc3", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &format) const
{
return standardizeFormula(formula, format, format);
}
/// Returns a string containing the standardized version of
/// \p formula from \p inputFormat in \p outputFormat. If an error
/// occurs an empty string is returned.
///
/// For example, to convert an InChI string to standardized SMILES:
/// \code
/// std::string formula = pubchem.standardizeFormula("InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H", "inchi", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &inputFormat, const std::string &outputFormat) const
{
if(formula.empty()){
return std::string();
}
PubChemQuery query = PubChemQuery::standardizationQuery(formula, inputFormat, outputFormat);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Structure_structure_string");
if(nodes.isEmpty()){
return std::string();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
std::string standardizedFormula = element.text().toStdString();
return standardizedFormula;
}
/// Returns a string containing the standardized formula in \p format
/// for the \p molecule. If an error occurs an empty string is
/// returned.
///
/// For example, to get the standardized InChI formula for a
/// molecule:
/// \code
/// std::string formula = pubchem.standardizeFormula(molecule, "inchi");
/// \endcode
std::string PubChem::standardizeFormula(const Molecule *molecule, const std::string &format) const
{
return standardizeFormula(molecule->formula("smiles"), "smiles", format);
}
// --- Error Handling ------------------------------------------------------ //
void PubChem::setErrorString(const QString &error)
{
d->errorString = error;
}
/// Returns a string describing the last error that occured.
QString PubChem::errorString() const
{
return d->errorString;
}
} // end web namespace
} // end chemkit namespace
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// sqlite.cpp
//
// Identification: src/wire/sqlite.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <sys/un.h>
#include <string>
#include "common/logger.h"
#include "wire/sqlite.h"
#include <sqlite3.h>
namespace peloton {
namespace wire {
// used to synch sqlite accesses
std::mutex sqlite_mutex;
Sqlite::Sqlite() {
// filename is null for in memory db
auto rc = sqlite3_open_v2(
"sqlite.db", &sqlite_db_,
SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(sqlite_db_));
LOG_ERROR("Can't open database %s", sqlite3_errmsg(sqlite_db_));
exit(0);
} else {
fprintf(stderr, "\n");
}
}
Sqlite::~Sqlite() { sqlite3_close(sqlite_db_); }
/*
* PortalExec - Execute query string
*/
int Sqlite::PortalExec(const char *query, std::vector<ResType> &res,
std::vector<FieldInfoType> &info, int &rows_change,
std::string &err_msg) {
LOG_INFO("receive %s", query);
sqlite3_stmt *sql_stmt;
sqlite3_prepare_v2(sqlite_db_, query, -1, &sql_stmt, NULL);
GetRowDesc(sql_stmt, info);
return ExecPrepStmt(sql_stmt, true, res, rows_change, err_msg);
}
/*
* InitBindPrepStmt - Prepare and bind a query from a query string
*/
int Sqlite::PrepareStmt(const char *query, sqlite3_stmt **stmt,
std::string &err_msg) {
int rc = sqlite3_prepare_v2(sqlite_db_, query, -1, stmt, NULL);
if (rc != SQLITE_OK) {
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
return 0;
}
int Sqlite::BindStmt(std::vector<std::pair<int, std::string>> ¶meters,
sqlite3_stmt **stmt, std::string &err_msg) {
int paramno = 1;
for (auto ¶m : parameters) {
auto wire_type = param.first;
auto &wire_val = param.second;
int rc;
switch (wire_type) {
case WIRE_INTEGER: {
int int_val = std::stoi(wire_val);
rc = sqlite3_bind_int(*stmt, paramno, int_val);
} break;
case WIRE_FLOAT: {
double double_val = std::stod(wire_val);
rc = sqlite3_bind_double(*stmt, paramno, double_val);
} break;
case WIRE_TEXT: {
const char *str_val = wire_val.c_str();
size_t str_len = wire_val.size();
rc = sqlite3_bind_text(*stmt, paramno, str_val, (int)str_len,
SQLITE_TRANSIENT);
} break;
case WIRE_NULL: {
rc = sqlite3_bind_null(*stmt, paramno);
break;
}
default: { return 1; }
}
if (rc != SQLITE_OK) {
LOG_INFO("Error in binding: %s", sqlite3_errmsg(sqlite_db_));
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
paramno++;
}
return 0;
}
/*
* GetRowDesc - Get RowDescription of a query
*/
void Sqlite::GetRowDesc(void *stmt, std::vector<FieldInfoType> &info) {
auto sql_stmt = (sqlite3_stmt *)stmt;
auto col_num = sqlite3_column_count(sql_stmt);
for (int i = 0; i < col_num; i++) {
int t = sqlite3_column_type(sql_stmt, i);
const char *name = sqlite3_column_name(sql_stmt, i);
LOG_INFO("name: %s", name);
switch (t) {
case SQLITE_INTEGER: {
LOG_INFO("col int");
info.push_back(std::make_tuple(name, 23, 4));
break;
}
case SQLITE_FLOAT: {
LOG_INFO("col float");
info.push_back(std::make_tuple(name, 701, 8));
break;
}
case SQLITE_TEXT: {
LOG_INFO("col text");
info.push_back(std::make_tuple(name, 25, 255));
break;
}
default: {
// Workaround for empty results, should still return something
LOG_ERROR("Unrecognized column type: %d", t);
info.push_back(std::make_tuple(name, 25, 255));
break;
}
}
}
}
/*
* ExecPrepStmt - Execute a statement from a prepared and bound statement
*/
int Sqlite::ExecPrepStmt(void *stmt, bool unnamed, std::vector<ResType> &res,
int &rows_change, std::string &err_msg) {
LOG_INFO("Executing statement......................");
auto sql_stmt = (sqlite3_stmt *)stmt;
auto ret = sqlite3_step(sql_stmt);
LOG_INFO("ret: %d", ret);
auto col_num = sqlite3_column_count(sql_stmt);
LOG_INFO("column count: %d", col_num);
while (ret == SQLITE_ROW) {
for (int i = 0; i < col_num; i++) {
int t = sqlite3_column_type(sql_stmt, i);
const char *name = sqlite3_column_name(sql_stmt, i);
std::string value;
switch (t) {
case SQLITE_INTEGER: {
int v = sqlite3_column_int(sql_stmt, i);
value = std::to_string(v);
break;
}
case SQLITE_FLOAT: {
double v = (double)sqlite3_column_double(sql_stmt, i);
value = std::to_string(v);
break;
}
case SQLITE_TEXT: {
const char *v = (char *)sqlite3_column_text(sql_stmt, i);
value = std::string(v);
break;
}
default:
break;
}
// TODO: refactor this
res.push_back(ResType());
CopyFromTo(name, res.back().first);
CopyFromTo(value.c_str(), res.back().second);
}
ret = sqlite3_step(sql_stmt);
}
if (unnamed)
sqlite3_finalize(sql_stmt);
else
sqlite3_reset(sql_stmt);
sqlite3_db_release_memory(sqlite_db_);
// sql_stmt = nullptr;
if (ret != SQLITE_DONE) {
LOG_INFO("ret num %d, err is %s", ret, sqlite3_errmsg(sqlite_db_));
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
rows_change = sqlite3_changes(sqlite_db_);
return 0;
}
void Sqlite::Test() {
LOG_INFO("RUN TEST");
std::vector<ResType> res;
std::vector<FieldInfoType> info;
std::string err;
int rows;
// create table
PortalExec("DROP TABLE IF EXISTS AA", res, info, rows, err);
PortalExec("CREATE TABLE AA (id INT PRIMARY KEY, data TEXT);", res, info,
rows, err);
res.clear();
// test simple insert
PortalExec("INSERT INTO AA VALUES (1, 'abc'); ", res, info, rows, err);
std::vector<std::pair<int, std::string>> parameters;
parameters.push_back(std::make_pair(WIRE_TEXT, std::string("12")));
parameters.push_back(std::make_pair(WIRE_TEXT, std::string("abc")));
// test bind
sqlite3_stmt *s;
PrepareStmt("insert into AA (id, data) values ( ?, ? )", &s, err);
BindStmt(parameters, &s, err);
GetRowDesc(s, info);
ExecPrepStmt(s, false, res, rows, err);
BindStmt(parameters, &s, err);
GetRowDesc(s, info);
ExecPrepStmt(s, false, res, rows, err);
res.clear();
// select all
sqlite3_stmt *sql_stmt;
sqlite3_prepare_v2(sqlite_db_, "select * from AA;", -1, &sql_stmt, NULL);
res.clear();
info.clear();
GetRowDesc(s, info);
ExecPrepStmt(sql_stmt, false, res, rows, err);
// res.size() should be 4
// info.size() should be 2
LOG_INFO("col %ld, info %ld", res.size(), info.size());
res.clear();
}
void Sqlite::CopyFromTo(const char *src, std::vector<unsigned char> &dst) {
if (src == nullptr) {
return;
}
size_t len = strlen(src);
for (unsigned int i = 0; i < len; i++) {
dst.push_back((unsigned char)src[i]);
}
}
int Sqlite::ExecCallback(void *res, int argc, char **argv, char **azColName) {
auto output = (std::vector<ResType> *)res;
for (int i = 0; i < argc; i++) {
output->push_back(ResType());
if (argv[i] == NULL) {
LOG_INFO("value is null");
} else if (azColName[i] == NULL) {
LOG_INFO("name is null");
} else {
LOG_INFO("res %s %s", azColName[i], argv[i]);
}
CopyFromTo(azColName[i], output->at(i).first);
CopyFromTo(argv[i], output->at(i).second);
}
return 0;
}
int Sqlite::GetSize(const std::string &) { return 0; }
} // End wire namespace
} // End peloton namespace
<commit_msg>Disabled a sqlite function<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// sqlite.cpp
//
// Identification: src/wire/sqlite.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <sys/un.h>
#include <string>
#include "common/logger.h"
#include "wire/sqlite.h"
#include <sqlite3.h>
namespace peloton {
namespace wire {
// used to synch sqlite accesses
std::mutex sqlite_mutex;
Sqlite::Sqlite() {
// filename is null for in memory db
auto rc = sqlite3_open_v2(
"sqlite.db", &sqlite_db_,
SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(sqlite_db_));
LOG_ERROR("Can't open database %s", sqlite3_errmsg(sqlite_db_));
exit(0);
} else {
fprintf(stderr, "\n");
}
}
Sqlite::~Sqlite() { sqlite3_close(sqlite_db_); }
/*
* PortalExec - Execute query string
*/
int Sqlite::PortalExec(const char *query, std::vector<ResType> &res,
std::vector<FieldInfoType> &info, int &rows_change,
std::string &err_msg) {
LOG_INFO("receive %s", query);
sqlite3_stmt *sql_stmt;
sqlite3_prepare_v2(sqlite_db_, query, -1, &sql_stmt, NULL);
GetRowDesc(sql_stmt, info);
return ExecPrepStmt(sql_stmt, true, res, rows_change, err_msg);
}
/*
* InitBindPrepStmt - Prepare and bind a query from a query string
*/
int Sqlite::PrepareStmt(const char *query, sqlite3_stmt **stmt,
std::string &err_msg) {
int rc = sqlite3_prepare_v2(sqlite_db_, query, -1, stmt, NULL);
if (rc != SQLITE_OK) {
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
return 0;
}
int Sqlite::BindStmt(std::vector<std::pair<int, std::string>> ¶meters,
sqlite3_stmt **stmt, std::string &err_msg) {
int paramno = 1;
for (auto ¶m : parameters) {
auto wire_type = param.first;
auto &wire_val = param.second;
int rc;
switch (wire_type) {
case WIRE_INTEGER: {
int int_val = std::stoi(wire_val);
rc = sqlite3_bind_int(*stmt, paramno, int_val);
} break;
case WIRE_FLOAT: {
double double_val = std::stod(wire_val);
rc = sqlite3_bind_double(*stmt, paramno, double_val);
} break;
case WIRE_TEXT: {
const char *str_val = wire_val.c_str();
size_t str_len = wire_val.size();
rc = sqlite3_bind_text(*stmt, paramno, str_val, (int)str_len,
SQLITE_TRANSIENT);
} break;
case WIRE_NULL: {
rc = sqlite3_bind_null(*stmt, paramno);
break;
}
default: { return 1; }
}
if (rc != SQLITE_OK) {
LOG_INFO("Error in binding: %s", sqlite3_errmsg(sqlite_db_));
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
paramno++;
}
return 0;
}
/*
* GetRowDesc - Get RowDescription of a query
*/
void Sqlite::GetRowDesc(void *stmt, std::vector<FieldInfoType> &info) {
auto sql_stmt = (sqlite3_stmt *)stmt;
auto col_num = sqlite3_column_count(sql_stmt);
for (int i = 0; i < col_num; i++) {
int t = sqlite3_column_type(sql_stmt, i);
const char *name = sqlite3_column_name(sql_stmt, i);
LOG_INFO("name: %s", name);
switch (t) {
case SQLITE_INTEGER: {
LOG_INFO("col int");
info.push_back(std::make_tuple(name, 23, 4));
break;
}
case SQLITE_FLOAT: {
LOG_INFO("col float");
info.push_back(std::make_tuple(name, 701, 8));
break;
}
case SQLITE_TEXT: {
LOG_INFO("col text");
info.push_back(std::make_tuple(name, 25, 255));
break;
}
default: {
// Workaround for empty results, should still return something
LOG_ERROR("Unrecognized column type: %d", t);
info.push_back(std::make_tuple(name, 25, 255));
break;
}
}
}
}
/*
* ExecPrepStmt - Execute a statement from a prepared and bound statement
*/
int Sqlite::ExecPrepStmt(void *stmt, bool unnamed, std::vector<ResType> &res,
int &rows_change, std::string &err_msg) {
LOG_INFO("Executing statement......................");
auto sql_stmt = (sqlite3_stmt *)stmt;
auto ret = sqlite3_step(sql_stmt);
LOG_INFO("ret: %d", ret);
auto col_num = sqlite3_column_count(sql_stmt);
LOG_INFO("column count: %d", col_num);
while (ret == SQLITE_ROW) {
for (int i = 0; i < col_num; i++) {
int t = sqlite3_column_type(sql_stmt, i);
const char *name = sqlite3_column_name(sql_stmt, i);
std::string value;
switch (t) {
case SQLITE_INTEGER: {
int v = sqlite3_column_int(sql_stmt, i);
value = std::to_string(v);
break;
}
case SQLITE_FLOAT: {
double v = (double)sqlite3_column_double(sql_stmt, i);
value = std::to_string(v);
break;
}
case SQLITE_TEXT: {
const char *v = (char *)sqlite3_column_text(sql_stmt, i);
value = std::string(v);
break;
}
default:
break;
}
// TODO: refactor this
res.push_back(ResType());
CopyFromTo(name, res.back().first);
CopyFromTo(value.c_str(), res.back().second);
}
ret = sqlite3_step(sql_stmt);
}
if (unnamed)
sqlite3_finalize(sql_stmt);
else
sqlite3_reset(sql_stmt);
// TODO: Fix this
//sqlite3_db_release_memory(sqlite_db_);
// sql_stmt = nullptr;
if (ret != SQLITE_DONE) {
LOG_INFO("ret num %d, err is %s", ret, sqlite3_errmsg(sqlite_db_));
err_msg = std::string(sqlite3_errmsg(sqlite_db_));
return 1;
}
rows_change = sqlite3_changes(sqlite_db_);
return 0;
}
void Sqlite::Test() {
LOG_INFO("RUN TEST");
std::vector<ResType> res;
std::vector<FieldInfoType> info;
std::string err;
int rows;
// create table
PortalExec("DROP TABLE IF EXISTS AA", res, info, rows, err);
PortalExec("CREATE TABLE AA (id INT PRIMARY KEY, data TEXT);", res, info,
rows, err);
res.clear();
// test simple insert
PortalExec("INSERT INTO AA VALUES (1, 'abc'); ", res, info, rows, err);
std::vector<std::pair<int, std::string>> parameters;
parameters.push_back(std::make_pair(WIRE_TEXT, std::string("12")));
parameters.push_back(std::make_pair(WIRE_TEXT, std::string("abc")));
// test bind
sqlite3_stmt *s;
PrepareStmt("insert into AA (id, data) values ( ?, ? )", &s, err);
BindStmt(parameters, &s, err);
GetRowDesc(s, info);
ExecPrepStmt(s, false, res, rows, err);
BindStmt(parameters, &s, err);
GetRowDesc(s, info);
ExecPrepStmt(s, false, res, rows, err);
res.clear();
// select all
sqlite3_stmt *sql_stmt;
sqlite3_prepare_v2(sqlite_db_, "select * from AA;", -1, &sql_stmt, NULL);
res.clear();
info.clear();
GetRowDesc(s, info);
ExecPrepStmt(sql_stmt, false, res, rows, err);
// res.size() should be 4
// info.size() should be 2
LOG_INFO("col %ld, info %ld", res.size(), info.size());
res.clear();
}
void Sqlite::CopyFromTo(const char *src, std::vector<unsigned char> &dst) {
if (src == nullptr) {
return;
}
size_t len = strlen(src);
for (unsigned int i = 0; i < len; i++) {
dst.push_back((unsigned char)src[i]);
}
}
int Sqlite::ExecCallback(void *res, int argc, char **argv, char **azColName) {
auto output = (std::vector<ResType> *)res;
for (int i = 0; i < argc; i++) {
output->push_back(ResType());
if (argv[i] == NULL) {
LOG_INFO("value is null");
} else if (azColName[i] == NULL) {
LOG_INFO("name is null");
} else {
LOG_INFO("res %s %s", azColName[i], argv[i]);
}
CopyFromTo(azColName[i], output->at(i).first);
CopyFromTo(argv[i], output->at(i).second);
}
return 0;
}
int Sqlite::GetSize(const std::string &) { return 0; }
} // End wire namespace
} // End peloton namespace
<|endoftext|>
|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "inverted_index_storage.hpp"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using std::istringstream;
using std::make_pair;
using std::ostringstream;
using std::pair;
using std::sort;
using std::sqrt;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace storage {
inverted_index_storage::inverted_index_storage() {
}
inverted_index_storage::~inverted_index_storage() {
}
void inverted_index_storage::set(
const std::string& row,
const std::string& column,
float val) {
uint64_t column_id = column2id_.get_id_const(column);
if (column_id == common::key_manager::NOTFOUND) {
column_id = column2id_.get_id(column);
} else {
float cur_val = get(row, column);
column2norm_diff_[column_id] -= cur_val * cur_val;
}
inv_diff_[row][column_id] = val;
column2norm_diff_[column_id] += val * val;
}
float inverted_index_storage::get(
const string& row,
const string& column) const {
uint64_t column_id = column2id_.get_id_const(column);
if (column_id == common::key_manager::NOTFOUND) {
return 0.f;
}
{
bool exist = false;
float ret = get_from_tbl(row, column_id, inv_diff_, exist);
if (exist) {
return ret;
}
}
{
bool exist = false;
float ret = get_from_tbl(row, column_id, inv_, exist);
if (exist) {
return ret;
}
}
return 0.0;
}
float inverted_index_storage::get_from_tbl(
const std::string& row,
uint64_t column_id,
const tbl_t& tbl,
bool& exist) const {
exist = false;
if (column_id == common::key_manager::NOTFOUND) {
return 0.f;
}
tbl_t::const_iterator it = tbl.find(row);
if (it == inv_.end()) {
return 0.f;
} else {
row_t::const_iterator it_row = it->second.find(column_id);
if (it_row == it->second.end()) {
return 0.f;
} else {
exist = true;
return it_row->second;
}
}
}
void inverted_index_storage::remove(
const std::string& row,
const std::string& column) {
set(row, column, 0.f);
}
void inverted_index_storage::clear() {
tbl_t().swap(inv_);
tbl_t().swap(inv_diff_);
imap_float_t().swap(column2norm_);
imap_float_t().swap(column2norm_diff_);
common::key_manager().swap(column2id_);
}
void inverted_index_storage::get_all_column_ids(
std::vector<std::string>& ids) const {
ids.clear();
for (imap_float_t::const_iterator it = column2norm_.begin();
it != column2norm_.end(); ++it) {
ids.push_back(column2id_.get_key(it->first));
}
for (imap_float_t::const_iterator it = column2norm_diff_.begin();
it != column2norm_diff_.end(); ++it) {
if (column2norm_.find(it->first) == column2norm_.end()) {
ids.push_back(column2id_.get_key(it->first));
}
}
}
void inverted_index_storage::get_diff(diff_type& diff) const {
for (tbl_t::const_iterator it = inv_diff_.begin(); it != inv_diff_.end();
++it) {
vector<pair<string, float> > columns;
for (row_t::const_iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
columns.push_back(make_pair(column2id_.get_key(it2->first), it2->second));
}
diff.inv.set_row(it->first, columns);
}
for (imap_float_t::const_iterator it = column2norm_diff_.begin();
it != column2norm_diff_.end(); ++it) {
diff.column2norm[column2id_.get_key(it->first)] = it->second;
}
}
void inverted_index_storage::set_mixed_and_clear_diff(
const diff_type& mixed_diff) {
// istringstream is(mixed_diff_str);
// sparse_matrix_storage mixed_inv;
// map_float_t mixed_column2norm;
// revert_diff(mixed_diff_str, mixed_inv, mixed_column2norm);
vector<string> ids;
mixed_diff.inv.get_all_row_ids(ids);
for (size_t i = 0; i < ids.size(); ++i) {
const string& row = ids[i];
row_t& v = inv_[row];
vector<pair<string, float> > columns;
mixed_diff.inv.get_row(row, columns);
for (size_t j = 0; j < columns.size(); ++j) {
size_t id = column2id_.get_id(columns[j].first);
if (columns[j].second == 0.f) {
v.erase(id);
} else {
v[id] = columns[j].second;
}
}
}
inv_diff_.clear();
for (map_float_t::const_iterator it = mixed_diff.column2norm.begin();
it != mixed_diff.column2norm.end(); ++it) {
uint64_t column_index = column2id_.get_id(it->first);
column2norm_[column_index] += it->second;
if (column2norm_[column_index] == 0.f) {
column2norm_.erase(column_index);
}
}
column2norm_diff_.clear();
}
void inverted_index_storage::mix(const diff_type& lhs, diff_type& rhs) const {
// sparse_matrix_storage lhs_inv_diff, rhs_inv_diff;
// map_float_t lhs_column2norm_diff, rhs_column2norm_diff;
// revert_diff(lhs, lhs_inv_diff, lhs_column2norm_diff);
// revert_diff(rhs, rhs_inv_diff, rhs_column2norm_diff);
// merge inv diffs
vector<string> ids;
lhs.inv.get_all_row_ids(ids);
for (size_t i = 0; i < ids.size(); ++i) {
const string& row = ids[i];
vector<pair<string, float> > columns;
lhs.inv.get_row(row, columns);
rhs.inv.set_row(row, columns);
}
// merge norm diffs
for (map_float_t::const_iterator it = lhs.column2norm.begin();
it != lhs.column2norm.end(); ++it) {
rhs.column2norm[it->first] += it->second;
}
}
bool inverted_index_storage::save(std::ostream& os) {
pfi::data::serialization::binary_oarchive oa(os);
oa << *this;
return true;
}
bool inverted_index_storage::load(std::istream& is) {
pfi::data::serialization::binary_iarchive ia(is);
ia >> *this;
return true;
}
void inverted_index_storage::calc_scores(
const common::sfv_t& query,
vector<pair<string, float> >& scores,
size_t ret_num) const {
float query_norm = calc_l2norm(query);
if (query_norm == 0.f) {
return;
}
pfi::data::unordered_map<uint64_t, float> i_scores;
for (size_t i = 0; i < query.size(); ++i) {
const string& fid = query[i].first;
float val = query[i].second;
add_inp_scores(fid, val, i_scores);
}
vector<pair<float, uint64_t> > sorted_scores;
for (pfi::data::unordered_map<uint64_t, float>::const_iterator it = i_scores
.begin(); it != i_scores.end(); ++it) {
float norm = calc_columnl2norm(it->first);
float normed_score = (norm != 0.f) ? it->second / norm / query_norm : 0.f;
sorted_scores.push_back(make_pair(normed_score, it->first));
}
sort(sorted_scores.rbegin(), sorted_scores.rend());
for (size_t i = 0; i < sorted_scores.size() && i < ret_num; ++i) {
scores.push_back(
make_pair(column2id_.get_key(sorted_scores[i].second),
sorted_scores[i].first));
}
}
float inverted_index_storage::calc_l2norm(const common::sfv_t& sfv) {
float ret = 0.f;
for (size_t i = 0; i < sfv.size(); ++i) {
ret += sfv[i].second * sfv[i].second;
}
return sqrt(ret);
}
float inverted_index_storage::calc_columnl2norm(uint64_t column_id) const {
float ret = 0.f;
imap_float_t::const_iterator it_diff = column2norm_diff_.find(column_id);
if (it_diff != column2norm_diff_.end()) {
ret += it_diff->second;
}
imap_float_t::const_iterator it = column2norm_.find(column_id);
if (it != column2norm_.end()) {
ret += it->second;
}
return sqrt(ret);
}
void inverted_index_storage::add_inp_scores(
const std::string& row,
float val,
pfi::data::unordered_map<uint64_t, float>& scores) const {
tbl_t::const_iterator it_diff = inv_diff_.find(row);
if (it_diff != inv_diff_.end()) {
const row_t& row_v = it_diff->second;
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
scores[row_it->first] += row_it->second * val;
}
}
tbl_t::const_iterator it = inv_.find(row);
if (it != inv_.end()) {
const row_t& row_v = it->second;
if (it_diff == inv_diff_.end()) {
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
scores[row_it->first] += row_it->second * val;
}
} else {
const row_t& row_diff_v = it_diff->second;
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
if (row_diff_v.find(row_it->first) == row_diff_v.end()) {
scores[row_it->first] += row_it->second * val;
}
}
}
}
}
std::string inverted_index_storage::name() const {
return string("inverted_index_storage");
}
} // namespace storage
} // namespace core
} // namespace jubatus
<commit_msg>Remove old comments<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "inverted_index_storage.hpp"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using std::istringstream;
using std::make_pair;
using std::ostringstream;
using std::pair;
using std::sort;
using std::sqrt;
using std::string;
using std::vector;
namespace jubatus {
namespace core {
namespace storage {
inverted_index_storage::inverted_index_storage() {
}
inverted_index_storage::~inverted_index_storage() {
}
void inverted_index_storage::set(
const std::string& row,
const std::string& column,
float val) {
uint64_t column_id = column2id_.get_id_const(column);
if (column_id == common::key_manager::NOTFOUND) {
column_id = column2id_.get_id(column);
} else {
float cur_val = get(row, column);
column2norm_diff_[column_id] -= cur_val * cur_val;
}
inv_diff_[row][column_id] = val;
column2norm_diff_[column_id] += val * val;
}
float inverted_index_storage::get(
const string& row,
const string& column) const {
uint64_t column_id = column2id_.get_id_const(column);
if (column_id == common::key_manager::NOTFOUND) {
return 0.f;
}
{
bool exist = false;
float ret = get_from_tbl(row, column_id, inv_diff_, exist);
if (exist) {
return ret;
}
}
{
bool exist = false;
float ret = get_from_tbl(row, column_id, inv_, exist);
if (exist) {
return ret;
}
}
return 0.0;
}
float inverted_index_storage::get_from_tbl(
const std::string& row,
uint64_t column_id,
const tbl_t& tbl,
bool& exist) const {
exist = false;
if (column_id == common::key_manager::NOTFOUND) {
return 0.f;
}
tbl_t::const_iterator it = tbl.find(row);
if (it == inv_.end()) {
return 0.f;
} else {
row_t::const_iterator it_row = it->second.find(column_id);
if (it_row == it->second.end()) {
return 0.f;
} else {
exist = true;
return it_row->second;
}
}
}
void inverted_index_storage::remove(
const std::string& row,
const std::string& column) {
set(row, column, 0.f);
}
void inverted_index_storage::clear() {
tbl_t().swap(inv_);
tbl_t().swap(inv_diff_);
imap_float_t().swap(column2norm_);
imap_float_t().swap(column2norm_diff_);
common::key_manager().swap(column2id_);
}
void inverted_index_storage::get_all_column_ids(
std::vector<std::string>& ids) const {
ids.clear();
for (imap_float_t::const_iterator it = column2norm_.begin();
it != column2norm_.end(); ++it) {
ids.push_back(column2id_.get_key(it->first));
}
for (imap_float_t::const_iterator it = column2norm_diff_.begin();
it != column2norm_diff_.end(); ++it) {
if (column2norm_.find(it->first) == column2norm_.end()) {
ids.push_back(column2id_.get_key(it->first));
}
}
}
void inverted_index_storage::get_diff(diff_type& diff) const {
for (tbl_t::const_iterator it = inv_diff_.begin(); it != inv_diff_.end();
++it) {
vector<pair<string, float> > columns;
for (row_t::const_iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
columns.push_back(make_pair(column2id_.get_key(it2->first), it2->second));
}
diff.inv.set_row(it->first, columns);
}
for (imap_float_t::const_iterator it = column2norm_diff_.begin();
it != column2norm_diff_.end(); ++it) {
diff.column2norm[column2id_.get_key(it->first)] = it->second;
}
}
void inverted_index_storage::set_mixed_and_clear_diff(
const diff_type& mixed_diff) {
vector<string> ids;
mixed_diff.inv.get_all_row_ids(ids);
for (size_t i = 0; i < ids.size(); ++i) {
const string& row = ids[i];
row_t& v = inv_[row];
vector<pair<string, float> > columns;
mixed_diff.inv.get_row(row, columns);
for (size_t j = 0; j < columns.size(); ++j) {
size_t id = column2id_.get_id(columns[j].first);
if (columns[j].second == 0.f) {
v.erase(id);
} else {
v[id] = columns[j].second;
}
}
}
inv_diff_.clear();
for (map_float_t::const_iterator it = mixed_diff.column2norm.begin();
it != mixed_diff.column2norm.end(); ++it) {
uint64_t column_index = column2id_.get_id(it->first);
column2norm_[column_index] += it->second;
if (column2norm_[column_index] == 0.f) {
column2norm_.erase(column_index);
}
}
column2norm_diff_.clear();
}
void inverted_index_storage::mix(const diff_type& lhs, diff_type& rhs) const {
// merge inv diffs
vector<string> ids;
lhs.inv.get_all_row_ids(ids);
for (size_t i = 0; i < ids.size(); ++i) {
const string& row = ids[i];
vector<pair<string, float> > columns;
lhs.inv.get_row(row, columns);
rhs.inv.set_row(row, columns);
}
// merge norm diffs
for (map_float_t::const_iterator it = lhs.column2norm.begin();
it != lhs.column2norm.end(); ++it) {
rhs.column2norm[it->first] += it->second;
}
}
bool inverted_index_storage::save(std::ostream& os) {
pfi::data::serialization::binary_oarchive oa(os);
oa << *this;
return true;
}
bool inverted_index_storage::load(std::istream& is) {
pfi::data::serialization::binary_iarchive ia(is);
ia >> *this;
return true;
}
void inverted_index_storage::calc_scores(
const common::sfv_t& query,
vector<pair<string, float> >& scores,
size_t ret_num) const {
float query_norm = calc_l2norm(query);
if (query_norm == 0.f) {
return;
}
pfi::data::unordered_map<uint64_t, float> i_scores;
for (size_t i = 0; i < query.size(); ++i) {
const string& fid = query[i].first;
float val = query[i].second;
add_inp_scores(fid, val, i_scores);
}
vector<pair<float, uint64_t> > sorted_scores;
for (pfi::data::unordered_map<uint64_t, float>::const_iterator it = i_scores
.begin(); it != i_scores.end(); ++it) {
float norm = calc_columnl2norm(it->first);
float normed_score = (norm != 0.f) ? it->second / norm / query_norm : 0.f;
sorted_scores.push_back(make_pair(normed_score, it->first));
}
sort(sorted_scores.rbegin(), sorted_scores.rend());
for (size_t i = 0; i < sorted_scores.size() && i < ret_num; ++i) {
scores.push_back(
make_pair(column2id_.get_key(sorted_scores[i].second),
sorted_scores[i].first));
}
}
float inverted_index_storage::calc_l2norm(const common::sfv_t& sfv) {
float ret = 0.f;
for (size_t i = 0; i < sfv.size(); ++i) {
ret += sfv[i].second * sfv[i].second;
}
return sqrt(ret);
}
float inverted_index_storage::calc_columnl2norm(uint64_t column_id) const {
float ret = 0.f;
imap_float_t::const_iterator it_diff = column2norm_diff_.find(column_id);
if (it_diff != column2norm_diff_.end()) {
ret += it_diff->second;
}
imap_float_t::const_iterator it = column2norm_.find(column_id);
if (it != column2norm_.end()) {
ret += it->second;
}
return sqrt(ret);
}
void inverted_index_storage::add_inp_scores(
const std::string& row,
float val,
pfi::data::unordered_map<uint64_t, float>& scores) const {
tbl_t::const_iterator it_diff = inv_diff_.find(row);
if (it_diff != inv_diff_.end()) {
const row_t& row_v = it_diff->second;
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
scores[row_it->first] += row_it->second * val;
}
}
tbl_t::const_iterator it = inv_.find(row);
if (it != inv_.end()) {
const row_t& row_v = it->second;
if (it_diff == inv_diff_.end()) {
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
scores[row_it->first] += row_it->second * val;
}
} else {
const row_t& row_diff_v = it_diff->second;
for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end();
++row_it) {
if (row_diff_v.find(row_it->first) == row_diff_v.end()) {
scores[row_it->first] += row_it->second * val;
}
}
}
}
}
std::string inverted_index_storage::name() const {
return string("inverted_index_storage");
}
} // namespace storage
} // namespace core
} // namespace jubatus
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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.
*
*/
#ifndef PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#define PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#include "pcl/kdtree/kdtree_flann.h"
#include <pcl/console/print.h>
#include <flann/flann.hpp>
namespace pcl
{
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices)
{
cleanup (); // Perform an automatic cleanup of structures
if (!initParameters())
return;
input_ = cloud;
indices_ = indices;
if (input_ == NULL)
return;
m_lock_.lock ();
// Allocate enough data
if (!input_)
{
PCL_ERROR ("[pcl::KdTreeANN::setInputCloud] Invalid input!\n");
return;
}
if (indices != NULL)
convertCloudToArray (*input_, *indices_);
else
convertCloudToArray (*input_);
initData ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
KdTreeFLANN<PointT>::nearestKSearch (const PointT &point, int k,
std::vector<int> &k_indices,
std::vector<float> &k_distances)
{
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::nearestKSearch] Invalid query point given!" << point);
return (0);
}
std::vector<float> tmp (dim_);
point_representation_->vectorize ((PointT)point, tmp);
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k);
flann::Matrix<float> k_distances_mat (&k_distances[0], 1, k);
flann_index_->knnSearch (flann::Matrix<float>(&tmp[0], 1, dim_), k_indices_mat, k_distances_mat, k, flann::SearchParams (-1 ,epsilon_));
// Do mapping to original point cloud
if (!identity_mapping_) {
for (size_t i = 0; i < k_indices.size (); ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (k);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
int KdTreeFLANN<PointT>::radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_squared_distances, int max_nn) const
{
static flann::Matrix<int> indices_empty;
static flann::Matrix<float> dists_empty;
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::radiusSearch] Invalid query point given!" << point);
return 0;
}
std::vector<float> tmp(dim_);
point_representation_->vectorize ((PointT)point, tmp);
radius *= radius; // flann uses squared radius
size_t size;
if (indices_ == NULL) // no indices set, use full size of point cloud:
size = input_->points.size ();
else
size = indices_->size ();
int neighbors_in_radius = 0;
if (k_indices.size () == size && k_squared_distances.size () == size) // preallocated vectors
{
// if using preallocated vectors we ignore max_nn as we are sure to have enought space
// to store all neighbors found in radius
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
else // need to do search twice, first to find how many neighbors and allocate the vectors
{
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
indices_empty, dists_empty, radius, flann::SearchParams (-1, epsilon_, sorted_));
if (max_nn > 0)
{
neighbors_in_radius = std::min(neighbors_in_radius, max_nn);
}
k_indices.resize (neighbors_in_radius);
k_squared_distances.resize (neighbors_in_radius);
if (neighbors_in_radius == 0)
{
return (0);
}
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
// Do mapping to original point cloud
if (!identity_mapping_) {
for (int i = 0; i < neighbors_in_radius; ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (neighbors_in_radius);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::cleanup ()
{
delete flann_index_;
m_lock_.lock ();
// Data array cleanup
free (cloud_);
cloud_ = NULL;
index_mapping_.clear();
if (indices_)
indices_.reset ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
bool KdTreeFLANN<PointT>::initParameters ()
{
epsilon_ = 0.0; // default error bound value
dim_ = point_representation_->getNumberOfDimensions (); // Number of dimensions - default is 3 = xyz
// Create the kd_tree representation
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::initData ()
{
flann_index_ = new FLANNIndex(flann::Matrix<float>(cloud_, index_mapping_.size(), dim_),
flann::KDTreeSingleIndexParams(15)); // max 15 points/leaf
flann_index_->buildIndex();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = ros_cloud.points.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof(float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
{
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(cloud_index);
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud, const std::vector<int> &indices)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = indices.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = indices[indices_index];
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(indices_index); // If the returned index should be for the indices vector
//index_mapping_.push_back(cloud_index); // If the returned index should be for the ros cloud
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
} // end namespace
#define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
#endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
<commit_msg>Closing ticket #278<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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.
*
*/
#ifndef PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#define PCL_KDTREE_KDTREE_IMPL_FLANN_H_
#include "pcl/kdtree/kdtree_flann.h"
#include <pcl/console/print.h>
#include <flann/flann.hpp>
namespace pcl
{
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::setInputCloud (const PointCloudConstPtr &cloud, const IndicesConstPtr &indices)
{
cleanup (); // Perform an automatic cleanup of structures
if (!initParameters())
return;
input_ = cloud;
indices_ = indices;
if (input_ == NULL)
return;
m_lock_.lock ();
// Allocate enough data
if (!input_)
{
PCL_ERROR ("[pcl::KdTreeANN::setInputCloud] Invalid input!\n");
return;
}
if (indices != NULL)
convertCloudToArray (*input_, *indices_);
else
convertCloudToArray (*input_);
initData ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
KdTreeFLANN<PointT>::nearestKSearch (const PointT &point, int k,
std::vector<int> &k_indices,
std::vector<float> &k_distances)
{
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::nearestKSearch] Invalid query point given!" << point);
return (0);
}
if (k_indices.size() < (size_t)k) {
k_indices.resize(k);
}
if (k_distances.size() < (size_t)k) {
k_distances.resize(k);
}
std::vector<float> tmp (dim_);
point_representation_->vectorize ((PointT)point, tmp);
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k);
flann::Matrix<float> k_distances_mat (&k_distances[0], 1, k);
flann_index_->knnSearch (flann::Matrix<float>(&tmp[0], 1, dim_), k_indices_mat, k_distances_mat, k, flann::SearchParams (-1 ,epsilon_));
// Do mapping to original point cloud
if (!identity_mapping_) {
for (size_t i = 0; i < k_indices.size (); ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (k);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
int KdTreeFLANN<PointT>::radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
std::vector<float> &k_squared_distances, int max_nn) const
{
static flann::Matrix<int> indices_empty;
static flann::Matrix<float> dists_empty;
if (!point_representation_->isValid (point))
{
//PCL_ERROR_STREAM ("[pcl::KdTreeFLANN::radiusSearch] Invalid query point given!" << point);
return 0;
}
std::vector<float> tmp(dim_);
point_representation_->vectorize ((PointT)point, tmp);
radius *= radius; // flann uses squared radius
size_t size;
if (indices_ == NULL) // no indices set, use full size of point cloud:
size = input_->points.size ();
else
size = indices_->size ();
int neighbors_in_radius = 0;
if (k_indices.size () == size && k_squared_distances.size () == size) // preallocated vectors
{
// if using preallocated vectors we ignore max_nn as we are sure to have enought space
// to store all neighbors found in radius
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
else // need to do search twice, first to find how many neighbors and allocate the vectors
{
neighbors_in_radius = flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
indices_empty, dists_empty, radius, flann::SearchParams (-1, epsilon_, sorted_));
if (max_nn > 0)
{
neighbors_in_radius = std::min(neighbors_in_radius, max_nn);
}
k_indices.resize (neighbors_in_radius);
k_squared_distances.resize (neighbors_in_radius);
if (neighbors_in_radius == 0)
{
return (0);
}
flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k_indices.size());
flann::Matrix<float> k_distances_mat (&k_squared_distances[0], 1, k_squared_distances.size());
flann_index_->radiusSearch (flann::Matrix<float>(&tmp[0], 1, dim_),
k_indices_mat, k_distances_mat, radius, flann::SearchParams (-1, epsilon_, sorted_));
}
// Do mapping to original point cloud
if (!identity_mapping_) {
for (int i = 0; i < neighbors_in_radius; ++i)
{
int& neighbor_index = k_indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return (neighbors_in_radius);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::cleanup ()
{
delete flann_index_;
m_lock_.lock ();
// Data array cleanup
free (cloud_);
cloud_ = NULL;
index_mapping_.clear();
if (indices_)
indices_.reset ();
m_lock_.unlock ();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
bool KdTreeFLANN<PointT>::initParameters ()
{
epsilon_ = 0.0; // default error bound value
dim_ = point_representation_->getNumberOfDimensions (); // Number of dimensions - default is 3 = xyz
// Create the kd_tree representation
return (true);
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::initData ()
{
flann_index_ = new FLANNIndex(flann::Matrix<float>(cloud_, index_mapping_.size(), dim_),
flann::KDTreeSingleIndexParams(15)); // max 15 points/leaf
flann_index_->buildIndex();
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = ros_cloud.points.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof(float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
{
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(cloud_index);
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
void KdTreeFLANN<PointT>::convertCloudToArray (const PointCloud &ros_cloud, const std::vector<int> &indices)
{
// No point in doing anything if the array is empty
if (ros_cloud.points.empty ())
{
cloud_ = NULL;
return;
}
int original_no_of_points = indices.size();
cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = cloud_;
index_mapping_.reserve(original_no_of_points);
identity_mapping_ = true;
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = indices[indices_index];
const PointT point = ros_cloud.points[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid(point)) {
identity_mapping_ = false;
continue;
}
index_mapping_.push_back(indices_index); // If the returned index should be for the indices vector
//index_mapping_.push_back(cloud_index); // If the returned index should be for the ros cloud
point_representation_->vectorize(point, cloud_ptr);
cloud_ptr += dim_;
}
}
} // end namespace
#define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
#endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
<|endoftext|>
|
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <qcursor.h>
#include <qfile.h>
#include <qwidget.h>
#include <qdragobject.h>
#include <kapplication.h>
#include <kabc/vcardconverter.h>
#include <kaction.h>
#include <dcopref.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ktempfile.h>
#include <dcopclient.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/maillistdrag.h>
#include "core.h"
#include "summarywidget.h"
#include "korganizerplugin.h"
#include "korg_uniqueapp.h"
typedef KGenericFactory< KOrganizerPlugin, Kontact::Core > KOrganizerPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_korganizerplugin,
KOrganizerPluginFactory( "kontact_korganizerplugin" ) )
KOrganizerPlugin::KOrganizerPlugin( Kontact::Core *core, const char *, const QStringList& )
: Kontact::Plugin( core, core, "korganizer" ),
mIface( 0 )
{
setInstance( KOrganizerPluginFactory::instance() );
instance()->iconLoader()->addAppDir("kdepim");
insertNewAction( new KAction( i18n( "New Event..." ), "newappointment",
CTRL+SHIFT+Key_E, this, SLOT( slotNewEvent() ), actionCollection(),
"new_event" ) );
insertSyncAction( new KAction( i18n( "Synchronize Calendar" ), "reload",
0, this, SLOT( slotSyncEvents() ), actionCollection(),
"korganizer_sync" ) );
mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}
KOrganizerPlugin::~KOrganizerPlugin()
{
}
Kontact::Summary *KOrganizerPlugin::createSummaryWidget( QWidget *parent )
{
return new SummaryWidget( this, parent );
}
KParts::ReadOnlyPart *KOrganizerPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part )
return 0;
mIface = new KCalendarIface_stub( dcopClient(), "kontact", "CalendarIface" );
return part;
}
QString KOrganizerPlugin::tipFile() const
{
QString file = ::locate("data", "korganizer/tips");
return file;
}
QStringList KOrganizerPlugin::invisibleToolbarActions() const
{
QStringList invisible;
invisible += "new_event";
invisible += "new_todo";
invisible += "new_journal";
invisible += "view_todo";
invisible += "view_journal";
return invisible;
}
void KOrganizerPlugin::select()
{
interface()->showEventView();
}
KCalendarIface_stub *KOrganizerPlugin::interface()
{
if ( !mIface ) {
part();
}
Q_ASSERT( mIface );
return mIface;
}
void KOrganizerPlugin::slotNewEvent()
{
interface()->openEventEditor( "" );
}
void KOrganizerPlugin::slotSyncEvents()
{
DCOPRef ref( "kmail", "KMailICalIface" );
ref.send( "triggerSync", QString("Calendar") );
}
bool KOrganizerPlugin::createDCOPInterface( const QString& serviceType )
{
kdDebug(5602) << k_funcinfo << serviceType << endl;
if ( serviceType == "DCOP/Organizer" || serviceType == "DCOP/Calendar" ) {
if ( part() )
return true;
}
return false;
}
bool KOrganizerPlugin::isRunningStandalone()
{
return mUniqueAppWatcher->isRunningStandalone();
}
bool KOrganizerPlugin::canDecodeDrag( QMimeSource *mimeSource )
{
return QTextDrag::canDecode( mimeSource ) ||
KPIM::MailListDrag::canDecode( mimeSource );
}
void KOrganizerPlugin::processDropEvent( QDropEvent *event )
{
QString text;
KABC::VCardConverter converter;
if ( KVCardDrag::canDecode( event ) && KVCardDrag::decode( event, text ) ) {
KABC::Addressee::List contacts = converter.parseVCards( text );
KABC::Addressee::List::Iterator it;
QStringList attendees;
for ( it = contacts.begin(); it != contacts.end(); ++it ) {
QString email = (*it).fullEmail();
if ( email.isEmpty() )
attendees.append( (*it).realName() + "<>" );
else
attendees.append( email );
}
interface()->openEventEditor( i18n( "Meeting" ), QString::null, QString::null,
attendees );
return;
}
if ( QTextDrag::decode( event, text ) ) {
kdDebug(5602) << "DROP:" << text << endl;
interface()->openEventEditor( text );
return;
}
KPIM::MailList mails;
if ( KPIM::MailListDrag::decode( event, mails ) ) {
if ( mails.count() != 1 ) {
KMessageBox::sorry( core(),
i18n("Drops of multiple mails are not supported." ) );
} else {
KPIM::MailSummary mail = mails.first();
QString txt = i18n("From: %1\nTo: %2\nSubject: %3").arg( mail.from() )
.arg( mail.to() ).arg( mail.subject() );
KTempFile tf;
tf.setAutoDelete( true );
QString uri = QString::fromLatin1("kmail:") + QString::number( mail.serialNumber() );
tf.file()->writeBlock( event->encodedData( "message/rfc822" ) );
tf.close();
interface()->openEventEditor( i18n("Mail: %1").arg( mail.subject() ), txt,
uri, tf.name(), QStringList(), "message/rfc822" );
}
return;
}
KMessageBox::sorry( core(), i18n("Cannot handle drop events of type '%1'.")
.arg( event->format() ) );
}
void KOrganizerPlugin::loadProfile( const QString& directory )
{
DCOPRef ref( "korganizer", "KOrganizerIface" );
ref.send( "loadProfile", directory );
}
void KOrganizerPlugin::saveToProfile( const QString& directory ) const
{
DCOPRef ref( "korganizer", "KOrganizerIface" );
ref.send( "saveToProfile", directory );
}
#include "korganizerplugin.moc"
<commit_msg> -- kolab/issue2951 - handle drags from todo viewer.<commit_after>/*
This file is part of Kontact.
Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <qcursor.h>
#include <qfile.h>
#include <qwidget.h>
#include <qdragobject.h>
#include <kapplication.h>
#include <kabc/vcardconverter.h>
#include <kaction.h>
#include <dcopref.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ktempfile.h>
#include <dcopclient.h>
#include <libkdepim/kvcarddrag.h>
#include <libkdepim/maillistdrag.h>
#include <libkdepim/kpimprefs.h>
#include <libkcal/calendarlocal.h>
#include <libkcal/icaldrag.h>
#include "core.h"
#include "summarywidget.h"
#include "korganizerplugin.h"
#include "korg_uniqueapp.h"
typedef KGenericFactory< KOrganizerPlugin, Kontact::Core > KOrganizerPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_korganizerplugin,
KOrganizerPluginFactory( "kontact_korganizerplugin" ) )
KOrganizerPlugin::KOrganizerPlugin( Kontact::Core *core, const char *, const QStringList& )
: Kontact::Plugin( core, core, "korganizer" ),
mIface( 0 )
{
setInstance( KOrganizerPluginFactory::instance() );
instance()->iconLoader()->addAppDir("kdepim");
insertNewAction( new KAction( i18n( "New Event..." ), "newappointment",
CTRL+SHIFT+Key_E, this, SLOT( slotNewEvent() ), actionCollection(),
"new_event" ) );
insertSyncAction( new KAction( i18n( "Synchronize Calendar" ), "reload",
0, this, SLOT( slotSyncEvents() ), actionCollection(),
"korganizer_sync" ) );
mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );
}
KOrganizerPlugin::~KOrganizerPlugin()
{
}
Kontact::Summary *KOrganizerPlugin::createSummaryWidget( QWidget *parent )
{
return new SummaryWidget( this, parent );
}
KParts::ReadOnlyPart *KOrganizerPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part )
return 0;
mIface = new KCalendarIface_stub( dcopClient(), "kontact", "CalendarIface" );
return part;
}
QString KOrganizerPlugin::tipFile() const
{
QString file = ::locate("data", "korganizer/tips");
return file;
}
QStringList KOrganizerPlugin::invisibleToolbarActions() const
{
QStringList invisible;
invisible += "new_event";
invisible += "new_todo";
invisible += "new_journal";
invisible += "view_todo";
invisible += "view_journal";
return invisible;
}
void KOrganizerPlugin::select()
{
interface()->showEventView();
}
KCalendarIface_stub *KOrganizerPlugin::interface()
{
if ( !mIface ) {
part();
}
Q_ASSERT( mIface );
return mIface;
}
void KOrganizerPlugin::slotNewEvent()
{
interface()->openEventEditor( "" );
}
void KOrganizerPlugin::slotSyncEvents()
{
DCOPRef ref( "kmail", "KMailICalIface" );
ref.send( "triggerSync", QString("Calendar") );
}
bool KOrganizerPlugin::createDCOPInterface( const QString& serviceType )
{
kdDebug(5602) << k_funcinfo << serviceType << endl;
if ( serviceType == "DCOP/Organizer" || serviceType == "DCOP/Calendar" ) {
if ( part() )
return true;
}
return false;
}
bool KOrganizerPlugin::isRunningStandalone()
{
return mUniqueAppWatcher->isRunningStandalone();
}
bool KOrganizerPlugin::canDecodeDrag( QMimeSource *mimeSource )
{
return QTextDrag::canDecode( mimeSource ) ||
KPIM::MailListDrag::canDecode( mimeSource );
}
void KOrganizerPlugin::processDropEvent( QDropEvent *event )
{
QString text;
KABC::VCardConverter converter;
if ( KVCardDrag::canDecode( event ) && KVCardDrag::decode( event, text ) ) {
KABC::Addressee::List contacts = converter.parseVCards( text );
KABC::Addressee::List::Iterator it;
QStringList attendees;
for ( it = contacts.begin(); it != contacts.end(); ++it ) {
QString email = (*it).fullEmail();
if ( email.isEmpty() )
attendees.append( (*it).realName() + "<>" );
else
attendees.append( email );
}
interface()->openEventEditor( i18n( "Meeting" ), QString::null, QString::null,
attendees );
return;
}
if ( KCal::ICalDrag::canDecode( event) ) {
KCal::CalendarLocal cal( KPimPrefs::timezone() );
if ( KCal::ICalDrag::decode( event, &cal ) ) {
KCal::Incidence::List incidences = cal.incidences();
if ( !incidences.isEmpty() ) {
event->accept();
KCal::Incidence *i = incidences.first();
QString summary;
if ( dynamic_cast<KCal::Journal*>( i ) )
summary = i18n( "Note: %1" ).arg( i->summary() );
else
summary = i->summary();
interface()->openEventEditor( summary, i->description(), QString() );
return;
}
// else fall through to text decoding
}
}
if ( QTextDrag::decode( event, text ) ) {
kdDebug(5602) << "DROP:" << text << endl;
interface()->openEventEditor( text );
return;
}
KPIM::MailList mails;
if ( KPIM::MailListDrag::decode( event, mails ) ) {
if ( mails.count() != 1 ) {
KMessageBox::sorry( core(),
i18n("Drops of multiple mails are not supported." ) );
} else {
KPIM::MailSummary mail = mails.first();
QString txt = i18n("From: %1\nTo: %2\nSubject: %3").arg( mail.from() )
.arg( mail.to() ).arg( mail.subject() );
KTempFile tf;
tf.setAutoDelete( true );
QString uri = QString::fromLatin1("kmail:") + QString::number( mail.serialNumber() );
tf.file()->writeBlock( event->encodedData( "message/rfc822" ) );
tf.close();
interface()->openEventEditor( i18n("Mail: %1").arg( mail.subject() ), txt,
uri, tf.name(), QStringList(), "message/rfc822" );
}
return;
}
KMessageBox::sorry( core(), i18n("Cannot handle drop events of type '%1'.")
.arg( event->format() ) );
}
void KOrganizerPlugin::loadProfile( const QString& directory )
{
DCOPRef ref( "korganizer", "KOrganizerIface" );
ref.send( "loadProfile", directory );
}
void KOrganizerPlugin::saveToProfile( const QString& directory ) const
{
DCOPRef ref( "korganizer", "KOrganizerIface" );
ref.send( "saveToProfile", directory );
}
#include "korganizerplugin.moc"
<|endoftext|>
|
<commit_before>//===--- AMDGPUPropagateAttributes.cpp --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief This pass propagates attributes from kernels to the non-entry
/// functions. Most of the library functions were not compiled for specific ABI,
/// yet will be correctly compiled if proper attrbutes are propagated from the
/// caller.
///
/// The pass analyzes call graph and propagates ABI target features through the
/// call graph.
///
/// It can run in two modes: as a function or module pass. A function pass
/// simply propagates attributes. A module pass clones functions if there are
/// callers with different ABI. If a function is clonned all call sites will
/// be updated to use a correct clone.
///
/// A function pass is limited in functionality but can run early in the
/// pipeline. A module pass is more powerful but has to run late, so misses
/// library folding opportunities.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "amdgpu-propagate-attributes"
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <string>
using namespace llvm;
namespace llvm {
extern const SubtargetFeatureKV AMDGPUFeatureKV[AMDGPU::NumSubtargetFeatures-1];
}
namespace {
class AMDGPUPropagateAttributes {
const FeatureBitset TargetFeatures = {
AMDGPU::FeatureWavefrontSize16,
AMDGPU::FeatureWavefrontSize32,
AMDGPU::FeatureWavefrontSize64
};
class Clone{
public:
Clone(FeatureBitset FeatureMask, Function *OrigF, Function *NewF) :
FeatureMask(FeatureMask), OrigF(OrigF), NewF(NewF) {}
FeatureBitset FeatureMask;
Function *OrigF;
Function *NewF;
};
const TargetMachine *TM;
// Clone functions as needed or just set attributes.
bool AllowClone;
// Option propagation roots.
SmallSet<Function *, 32> Roots;
// Clones of functions with their attributes.
SmallVector<Clone, 32> Clones;
// Find a clone with required features.
Function *findFunction(const FeatureBitset &FeaturesNeeded,
Function *OrigF);
// Clone function F and set NewFeatures on the clone.
// Cole takes the name of original function.
Function *cloneWithFeatures(Function &F,
const FeatureBitset &NewFeatures);
// Set new function's features in place.
void setFeatures(Function &F, const FeatureBitset &NewFeatures);
std::string getFeatureString(const FeatureBitset &Features) const;
// Propagate attributes from Roots.
bool process();
public:
AMDGPUPropagateAttributes(const TargetMachine *TM, bool AllowClone) :
TM(TM), AllowClone(AllowClone) {}
// Use F as a root and propagate its attributes.
bool process(Function &F);
// Propagate attributes starting from kernel functions.
bool process(Module &M);
};
// Allows to propagate attributes early, but no clonning is allowed as it must
// be a function pass to run before any optimizations.
// TODO: We shall only need a one instance of module pass, but that needs to be
// in the linker pipeline which is currently not possible.
class AMDGPUPropagateAttributesEarly : public FunctionPass {
const TargetMachine *TM;
public:
static char ID; // Pass identification
AMDGPUPropagateAttributesEarly(const TargetMachine *TM = nullptr) :
FunctionPass(ID), TM(TM) {
initializeAMDGPUPropagateAttributesEarlyPass(
*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
// Allows to propagate attributes with clonning but does that late in the
// pipeline.
class AMDGPUPropagateAttributesLate : public ModulePass {
const TargetMachine *TM;
public:
static char ID; // Pass identification
AMDGPUPropagateAttributesLate(const TargetMachine *TM = nullptr) :
ModulePass(ID), TM(TM) {
initializeAMDGPUPropagateAttributesLatePass(
*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
} // end anonymous namespace.
char AMDGPUPropagateAttributesEarly::ID = 0;
char AMDGPUPropagateAttributesLate::ID = 0;
INITIALIZE_PASS(AMDGPUPropagateAttributesEarly,
"amdgpu-propagate-attributes-early",
"Early propagate attributes from kernels to functions",
false, false)
INITIALIZE_PASS(AMDGPUPropagateAttributesLate,
"amdgpu-propagate-attributes-late",
"Late propagate attributes from kernels to functions",
false, false)
Function *
AMDGPUPropagateAttributes::findFunction(const FeatureBitset &FeaturesNeeded,
Function *OrigF) {
// TODO: search for clone's clones.
for (Clone &C : Clones)
if (C.OrigF == OrigF && FeaturesNeeded == C.FeatureMask)
return C.NewF;
return nullptr;
}
bool AMDGPUPropagateAttributes::process(Module &M) {
for (auto &F : M.functions())
if (AMDGPU::isEntryFunctionCC(F.getCallingConv()))
Roots.insert(&F);
return process();
}
bool AMDGPUPropagateAttributes::process(Function &F) {
Roots.insert(&F);
return process();
}
bool AMDGPUPropagateAttributes::process() {
bool Changed = false;
SmallSet<Function *, 32> NewRoots;
SmallSet<Function *, 32> Replaced;
if (Roots.empty())
return false;
Module &M = *(*Roots.begin())->getParent();
do {
Roots.insert(NewRoots.begin(), NewRoots.end());
NewRoots.clear();
for (auto &F : M.functions()) {
if (F.isDeclaration() || Roots.count(&F) || Roots.count(&F))
continue;
const FeatureBitset &CalleeBits =
TM->getSubtargetImpl(F)->getFeatureBits();
SmallVector<std::pair<CallBase *, Function *>, 32> ToReplace;
for (User *U : F.users()) {
Instruction *I = dyn_cast<Instruction>(U);
if (!I)
continue;
CallBase *CI = dyn_cast<CallBase>(I);
if (!CI)
continue;
Function *Caller = CI->getCaller();
if (!Caller)
continue;
if (!Roots.count(Caller))
continue;
const FeatureBitset &CallerBits =
TM->getSubtargetImpl(*Caller)->getFeatureBits() & TargetFeatures;
if (CallerBits == (CalleeBits & TargetFeatures)) {
NewRoots.insert(&F);
continue;
}
Function *NewF = findFunction(CallerBits, &F);
if (!NewF) {
FeatureBitset NewFeatures((CalleeBits & ~TargetFeatures) |
CallerBits);
if (!AllowClone) {
// This may set different features on different iteartions if
// there is a contradiction in callers' attributes. In this case
// we rely on a second pass running on Module, which is allowed
// to clone.
setFeatures(F, NewFeatures);
NewRoots.insert(&F);
Changed = true;
break;
}
NewF = cloneWithFeatures(F, NewFeatures);
Clones.push_back(Clone(CallerBits, &F, NewF));
NewRoots.insert(NewF);
}
ToReplace.push_back(std::make_pair(CI, NewF));
Replaced.insert(&F);
Changed = true;
}
while (!ToReplace.empty()) {
auto R = ToReplace.pop_back_val();
R.first->setCalledFunction(R.second);
}
}
} while (!NewRoots.empty());
for (Function *F : Replaced) {
if (F->use_empty())
F->eraseFromParent();
}
return Changed;
}
Function *
AMDGPUPropagateAttributes::cloneWithFeatures(Function &F,
const FeatureBitset &NewFeatures) {
LLVM_DEBUG(dbgs() << "Cloning " << F.getName() << '\n');
ValueToValueMapTy dummy;
Function *NewF = CloneFunction(&F, dummy);
setFeatures(*NewF, NewFeatures);
// Swap names. If that is the only clone it will retain the name of now
// dead value.
if (F.hasName()) {
std::string NewName = NewF->getName();
NewF->takeName(&F);
F.setName(NewName);
// Name has changed, it does not need an external symbol.
F.setVisibility(GlobalValue::DefaultVisibility);
F.setLinkage(GlobalValue::InternalLinkage);
}
return NewF;
}
void AMDGPUPropagateAttributes::setFeatures(Function &F,
const FeatureBitset &NewFeatures) {
std::string NewFeatureStr = getFeatureString(NewFeatures);
LLVM_DEBUG(dbgs() << "Set features "
<< getFeatureString(NewFeatures & TargetFeatures)
<< " on " << F.getName() << '\n');
F.removeFnAttr("target-features");
F.addFnAttr("target-features", NewFeatureStr);
}
std::string
AMDGPUPropagateAttributes::getFeatureString(const FeatureBitset &Features) const
{
std::string Ret;
for (const SubtargetFeatureKV &KV : AMDGPUFeatureKV) {
if (Features[KV.Value])
Ret += (StringRef("+") + KV.Key + ",").str();
else if (TargetFeatures[KV.Value])
Ret += (StringRef("-") + KV.Key + ",").str();
}
Ret.pop_back(); // Remove last comma.
return Ret;
}
bool AMDGPUPropagateAttributesEarly::runOnFunction(Function &F) {
if (!TM || !AMDGPU::isEntryFunctionCC(F.getCallingConv()))
return false;
return AMDGPUPropagateAttributes(TM, false).process(F);
}
bool AMDGPUPropagateAttributesLate::runOnModule(Module &M) {
if (!TM)
return false;
return AMDGPUPropagateAttributes(TM, true).process(M);
}
FunctionPass
*llvm::createAMDGPUPropagateAttributesEarlyPass(const TargetMachine *TM) {
return new AMDGPUPropagateAttributesEarly(TM);
}
ModulePass
*llvm::createAMDGPUPropagateAttributesLatePass(const TargetMachine *TM) {
return new AMDGPUPropagateAttributesLate(TM);
}
<commit_msg>AMDGPU: Move DEBUG_TYPE definition below includes<commit_after>//===--- AMDGPUPropagateAttributes.cpp --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief This pass propagates attributes from kernels to the non-entry
/// functions. Most of the library functions were not compiled for specific ABI,
/// yet will be correctly compiled if proper attrbutes are propagated from the
/// caller.
///
/// The pass analyzes call graph and propagates ABI target features through the
/// call graph.
///
/// It can run in two modes: as a function or module pass. A function pass
/// simply propagates attributes. A module pass clones functions if there are
/// callers with different ABI. If a function is clonned all call sites will
/// be updated to use a correct clone.
///
/// A function pass is limited in functionality but can run early in the
/// pipeline. A module pass is more powerful but has to run late, so misses
/// library folding opportunities.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <string>
#define DEBUG_TYPE "amdgpu-propagate-attributes"
using namespace llvm;
namespace llvm {
extern const SubtargetFeatureKV AMDGPUFeatureKV[AMDGPU::NumSubtargetFeatures-1];
}
namespace {
class AMDGPUPropagateAttributes {
const FeatureBitset TargetFeatures = {
AMDGPU::FeatureWavefrontSize16,
AMDGPU::FeatureWavefrontSize32,
AMDGPU::FeatureWavefrontSize64
};
class Clone{
public:
Clone(FeatureBitset FeatureMask, Function *OrigF, Function *NewF) :
FeatureMask(FeatureMask), OrigF(OrigF), NewF(NewF) {}
FeatureBitset FeatureMask;
Function *OrigF;
Function *NewF;
};
const TargetMachine *TM;
// Clone functions as needed or just set attributes.
bool AllowClone;
// Option propagation roots.
SmallSet<Function *, 32> Roots;
// Clones of functions with their attributes.
SmallVector<Clone, 32> Clones;
// Find a clone with required features.
Function *findFunction(const FeatureBitset &FeaturesNeeded,
Function *OrigF);
// Clone function F and set NewFeatures on the clone.
// Cole takes the name of original function.
Function *cloneWithFeatures(Function &F,
const FeatureBitset &NewFeatures);
// Set new function's features in place.
void setFeatures(Function &F, const FeatureBitset &NewFeatures);
std::string getFeatureString(const FeatureBitset &Features) const;
// Propagate attributes from Roots.
bool process();
public:
AMDGPUPropagateAttributes(const TargetMachine *TM, bool AllowClone) :
TM(TM), AllowClone(AllowClone) {}
// Use F as a root and propagate its attributes.
bool process(Function &F);
// Propagate attributes starting from kernel functions.
bool process(Module &M);
};
// Allows to propagate attributes early, but no clonning is allowed as it must
// be a function pass to run before any optimizations.
// TODO: We shall only need a one instance of module pass, but that needs to be
// in the linker pipeline which is currently not possible.
class AMDGPUPropagateAttributesEarly : public FunctionPass {
const TargetMachine *TM;
public:
static char ID; // Pass identification
AMDGPUPropagateAttributesEarly(const TargetMachine *TM = nullptr) :
FunctionPass(ID), TM(TM) {
initializeAMDGPUPropagateAttributesEarlyPass(
*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
// Allows to propagate attributes with clonning but does that late in the
// pipeline.
class AMDGPUPropagateAttributesLate : public ModulePass {
const TargetMachine *TM;
public:
static char ID; // Pass identification
AMDGPUPropagateAttributesLate(const TargetMachine *TM = nullptr) :
ModulePass(ID), TM(TM) {
initializeAMDGPUPropagateAttributesLatePass(
*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
} // end anonymous namespace.
char AMDGPUPropagateAttributesEarly::ID = 0;
char AMDGPUPropagateAttributesLate::ID = 0;
INITIALIZE_PASS(AMDGPUPropagateAttributesEarly,
"amdgpu-propagate-attributes-early",
"Early propagate attributes from kernels to functions",
false, false)
INITIALIZE_PASS(AMDGPUPropagateAttributesLate,
"amdgpu-propagate-attributes-late",
"Late propagate attributes from kernels to functions",
false, false)
Function *
AMDGPUPropagateAttributes::findFunction(const FeatureBitset &FeaturesNeeded,
Function *OrigF) {
// TODO: search for clone's clones.
for (Clone &C : Clones)
if (C.OrigF == OrigF && FeaturesNeeded == C.FeatureMask)
return C.NewF;
return nullptr;
}
bool AMDGPUPropagateAttributes::process(Module &M) {
for (auto &F : M.functions())
if (AMDGPU::isEntryFunctionCC(F.getCallingConv()))
Roots.insert(&F);
return process();
}
bool AMDGPUPropagateAttributes::process(Function &F) {
Roots.insert(&F);
return process();
}
bool AMDGPUPropagateAttributes::process() {
bool Changed = false;
SmallSet<Function *, 32> NewRoots;
SmallSet<Function *, 32> Replaced;
if (Roots.empty())
return false;
Module &M = *(*Roots.begin())->getParent();
do {
Roots.insert(NewRoots.begin(), NewRoots.end());
NewRoots.clear();
for (auto &F : M.functions()) {
if (F.isDeclaration() || Roots.count(&F) || Roots.count(&F))
continue;
const FeatureBitset &CalleeBits =
TM->getSubtargetImpl(F)->getFeatureBits();
SmallVector<std::pair<CallBase *, Function *>, 32> ToReplace;
for (User *U : F.users()) {
Instruction *I = dyn_cast<Instruction>(U);
if (!I)
continue;
CallBase *CI = dyn_cast<CallBase>(I);
if (!CI)
continue;
Function *Caller = CI->getCaller();
if (!Caller)
continue;
if (!Roots.count(Caller))
continue;
const FeatureBitset &CallerBits =
TM->getSubtargetImpl(*Caller)->getFeatureBits() & TargetFeatures;
if (CallerBits == (CalleeBits & TargetFeatures)) {
NewRoots.insert(&F);
continue;
}
Function *NewF = findFunction(CallerBits, &F);
if (!NewF) {
FeatureBitset NewFeatures((CalleeBits & ~TargetFeatures) |
CallerBits);
if (!AllowClone) {
// This may set different features on different iteartions if
// there is a contradiction in callers' attributes. In this case
// we rely on a second pass running on Module, which is allowed
// to clone.
setFeatures(F, NewFeatures);
NewRoots.insert(&F);
Changed = true;
break;
}
NewF = cloneWithFeatures(F, NewFeatures);
Clones.push_back(Clone(CallerBits, &F, NewF));
NewRoots.insert(NewF);
}
ToReplace.push_back(std::make_pair(CI, NewF));
Replaced.insert(&F);
Changed = true;
}
while (!ToReplace.empty()) {
auto R = ToReplace.pop_back_val();
R.first->setCalledFunction(R.second);
}
}
} while (!NewRoots.empty());
for (Function *F : Replaced) {
if (F->use_empty())
F->eraseFromParent();
}
return Changed;
}
Function *
AMDGPUPropagateAttributes::cloneWithFeatures(Function &F,
const FeatureBitset &NewFeatures) {
LLVM_DEBUG(dbgs() << "Cloning " << F.getName() << '\n');
ValueToValueMapTy dummy;
Function *NewF = CloneFunction(&F, dummy);
setFeatures(*NewF, NewFeatures);
// Swap names. If that is the only clone it will retain the name of now
// dead value.
if (F.hasName()) {
std::string NewName = NewF->getName();
NewF->takeName(&F);
F.setName(NewName);
// Name has changed, it does not need an external symbol.
F.setVisibility(GlobalValue::DefaultVisibility);
F.setLinkage(GlobalValue::InternalLinkage);
}
return NewF;
}
void AMDGPUPropagateAttributes::setFeatures(Function &F,
const FeatureBitset &NewFeatures) {
std::string NewFeatureStr = getFeatureString(NewFeatures);
LLVM_DEBUG(dbgs() << "Set features "
<< getFeatureString(NewFeatures & TargetFeatures)
<< " on " << F.getName() << '\n');
F.removeFnAttr("target-features");
F.addFnAttr("target-features", NewFeatureStr);
}
std::string
AMDGPUPropagateAttributes::getFeatureString(const FeatureBitset &Features) const
{
std::string Ret;
for (const SubtargetFeatureKV &KV : AMDGPUFeatureKV) {
if (Features[KV.Value])
Ret += (StringRef("+") + KV.Key + ",").str();
else if (TargetFeatures[KV.Value])
Ret += (StringRef("-") + KV.Key + ",").str();
}
Ret.pop_back(); // Remove last comma.
return Ret;
}
bool AMDGPUPropagateAttributesEarly::runOnFunction(Function &F) {
if (!TM || !AMDGPU::isEntryFunctionCC(F.getCallingConv()))
return false;
return AMDGPUPropagateAttributes(TM, false).process(F);
}
bool AMDGPUPropagateAttributesLate::runOnModule(Module &M) {
if (!TM)
return false;
return AMDGPUPropagateAttributes(TM, true).process(M);
}
FunctionPass
*llvm::createAMDGPUPropagateAttributesEarlyPass(const TargetMachine *TM) {
return new AMDGPUPropagateAttributesEarly(TM);
}
ModulePass
*llvm::createAMDGPUPropagateAttributesLatePass(const TargetMachine *TM) {
return new AMDGPUPropagateAttributesLate(TM);
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Sean McKenna
//
// 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.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check our BVH for triangular faces, update hit info
bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());
// return hit info from intersecting rays in the BVH faces
return triang;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
bvh.Clear();
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
bvh.SetMesh(this,4);
return true;
}
private:
// add BVH for each triangular mesh
cyBVHTriMesh bvh;
// intersect a ray with a single triangle (Moller-Trumbore algorithm)
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
// select ray-triangle intersection algorithm
bool mt = true;
if(mt){
// grab vertex points
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
// compute edge vectors
Point e1 = b - a;
Point e2 = c - a;
// calculate first vector, P
Point P = r.dir ^ e2;
// calculate the determinant of the matrix equation
float determ = e1 % P;
// only continue for valid determinant ranges
if(abs(determ) > getBias()){
// calculate second vector, T
Point T = r.pos - a;
// calculate a barycentric component (u)
float u = T % P;
// only allow valid barycentric values
if(u > -getBias() && u < determ * (1.0 + getBias())){
// calculate a normal of the ray with an edge vector
Point Q = T ^ e1;
// calculate a barycentric component (v)
float v = r.dir % Q;
// only allow valid barycentric values
if(v > -getBias() && v + u < determ * (1.0 + getBias())){
// update barycentric coordinates
v /= determ;
u /= determ;
// compute the barycentric coordinates for interpolating values
Point bc = Point(1.0 - u - v, u, v);
// calculate the distance to hit the triangle
float t = (e2 % Q) / determ;
// only allow valid distances to hit
if(t > getBias() && t < h.z){
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(determ < 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
// normal ray tracing
}else{
// grab face vertices and compute face normal
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
Point n = (b - a) ^ (c - a);
// ignore rays nearly parallel to surface
if(r.dir % n > getBias() || r.dir % n < -getBias()){
// compute distance along ray direction to plane
float t = -((r.pos - a) % n) / (r.dir % n);
// only accept hits in front of ray (with some bias) & closer hits
if(t > getBias() && t < h.z){
// compute hit point
Point hit = r.pos + t * r.dir;
// simplify problem into 2D by removing the greatest normal component
Point2 a2;
Point2 b2;
Point2 c2;
Point2 hit2;
if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){
a2 = Point2(a.y, a.z);
b2 = Point2(b.y, b.z);
c2 = Point2(c.y, c.z);
hit2 = Point2(hit.y, hit.z);
}else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){
a2 = Point2(a.x, a.z);
b2 = Point2(b.x, b.z);
c2 = Point2(c.x, c.z);
hit2 = Point2(hit.x, hit.z);
}else{
a2 = Point2(a.x, a.y);
b2 = Point2(b.x, b.y);
c2 = Point2(c.x, c.y);
hit2 = Point2(hit.x, hit.y);
}
// compute the area of the triangular face (in 2D)
float area = (b2 - a2) ^ (c2 - a2);
// compute smaller areas of the face, in 2D
// aka, computation of the barycentric coordinates
float alpha = ((b2 - a2) ^ (hit2 - a2)) / area;
if(alpha > -getBias() && alpha < 1.0 + getBias()){
float beta = ((hit2 - a2) ^ (c2 - a2)) / area;
if(beta > -getBias() && alpha + beta < 1.0 + getBias()){
// interpolate the normal based on barycentric coordinates
Point bc = Point(1.0 - alpha - beta, beta, alpha);
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
}
}
// cast a ray into a BVH node, seeing which triangular faces may get hit
bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){
// grab node's bounding box
BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));
// does ray hit the node bounding box?
bool hit = b.intersectRay(r, h.z);
// recurse through child nodes if we hit node
if(hit){
// only recursively call function if not at a leaf node
if(!bvh.IsLeafNode(nodeID)){
// keep traversing the BVH hierarchy for hits
int c1 = bvh.GetFirstChildNode(nodeID);
int c2 = bvh.GetSecondChildNode(nodeID);
bool hit1 = traceBVHNode(r, h, face, c1);
bool hit2 = traceBVHNode(r, h, face, c2);
// if we get no hit
if(!hit1 && !hit2)
hit = false;
// for leaf nodes, trace ray into each triangular face
}else{
// get triangular faces of the hit BVH node
const unsigned int* faces = bvh.GetNodeElements(nodeID);
int size = bvh.GetNodeElementCount(nodeID);
// trace the ray into each triangular face, tracking hits
hit = false;
for(int i = 0; i < size; i++){
bool hit1 = intersectTriangle(r, h, face, faces[i]);
if(!hit && hit1)
hit = true;
}
}
}
// return if we hit a face within this node
return hit;
}
};
<commit_msg>remove slower ray-triangle intersection algorithm<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check our BVH for triangular faces, update hit info
bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());
// return hit info from intersecting rays in the BVH faces
return triang;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
bvh.Clear();
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
bvh.SetMesh(this,4);
return true;
}
private:
// add BVH for each triangular mesh
cyBVHTriMesh bvh;
// intersect a ray with a single triangle (Moller-Trumbore algorithm)
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
// grab vertex points
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
// compute edge vectors
Point e1 = b - a;
Point e2 = c - a;
// calculate first vector, P
Point P = r.dir ^ e2;
// calculate the determinant of the matrix equation
float determ = e1 % P;
// only continue for valid determinant ranges
if(abs(determ) > getBias()){
// calculate second vector, T
Point T = r.pos - a;
// calculate a barycentric component (u)
float u = T % P;
// only allow valid barycentric values
if(u > -getBias() && u < determ * (1.0 + getBias())){
// calculate a normal of the ray with an edge vector
Point Q = T ^ e1;
// calculate a barycentric component (v)
float v = r.dir % Q;
// only allow valid barycentric values
if(v > -getBias() && v + u < determ * (1.0 + getBias())){
// update barycentric coordinates
v /= determ;
u /= determ;
// compute the barycentric coordinates for interpolating values
Point bc = Point(1.0 - u - v, u, v);
// calculate the distance to hit the triangle
float t = (e2 % Q) / determ;
// only allow valid distances to hit
if(t > getBias() && t < h.z){
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(determ < 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
}
// cast a ray into a BVH node, seeing which triangular faces may get hit
bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){
// grab node's bounding box
BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));
// does ray hit the node bounding box?
bool hit = b.intersectRay(r, h.z);
// recurse through child nodes if we hit node
if(hit){
// only recursively call function if not at a leaf node
if(!bvh.IsLeafNode(nodeID)){
// keep traversing the BVH hierarchy for hits
int c1 = bvh.GetFirstChildNode(nodeID);
int c2 = bvh.GetSecondChildNode(nodeID);
bool hit1 = traceBVHNode(r, h, face, c1);
bool hit2 = traceBVHNode(r, h, face, c2);
// if we get no hit
if(!hit1 && !hit2)
hit = false;
// for leaf nodes, trace ray into each triangular face
}else{
// get triangular faces of the hit BVH node
const unsigned int* faces = bvh.GetNodeElements(nodeID);
int size = bvh.GetNodeElementCount(nodeID);
// trace the ray into each triangular face, tracking hits
hit = false;
for(int i = 0; i < size; i++){
bool hit1 = intersectTriangle(r, h, face, faces[i]);
if(!hit && hit1)
hit = true;
}
}
}
// return if we hit a face within this node
return hit;
}
};
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "runtime/runtime-state.h"
#include <iostream>
#include <jni.h>
#include <sstream>
#include <string>
#include "common/logging.h"
#include <boost/algorithm/string/join.hpp>
#include <gutil/strings/substitute.h>
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "common/status.h"
#include "exprs/expr.h"
#include "exprs/scalar-fn-call.h"
#include "runtime/buffered-block-mgr.h"
#include "runtime/bufferpool/reservation-tracker.h"
#include "runtime/data-stream-mgr.h"
#include "runtime/data-stream-recvr.h"
#include "runtime/descriptors.h"
#include "runtime/exec-env.h"
#include "runtime/mem-tracker.h"
#include "runtime/query-state.h"
#include "runtime/runtime-filter-bank.h"
#include "runtime/timestamp-value.h"
#include "util/auth-util.h" // for GetEffectiveUser()
#include "util/bitmap.h"
#include "util/cpu-info.h"
#include "util/debug-util.h"
#include "util/disk-info.h"
#include "util/error-util.h"
#include "util/jni-util.h"
#include "util/mem-info.h"
#include "util/pretty-printer.h"
#include "common/names.h"
using namespace llvm;
DECLARE_int32(max_errors);
// The fraction of the query mem limit that is used for the block mgr. Operators
// that accumulate memory all use the block mgr so the majority of the memory should
// be allocated to the block mgr. The remaining memory is used by the non-spilling
// operators and should be independent of data size.
static const float BLOCK_MGR_MEM_FRACTION = 0.8f;
// The minimum amount of memory that must be left after the block mgr reserves the
// BLOCK_MGR_MEM_FRACTION. The block limit is:
// min(query_limit * BLOCK_MGR_MEM_FRACTION, query_limit - BLOCK_MGR_MEM_MIN_REMAINING)
// TODO: this value was picked arbitrarily and the tests are written to rely on this
// for the minimum memory required to run the query. Revisit.
static const int64_t BLOCK_MGR_MEM_MIN_REMAINING = 100 * 1024 * 1024;
namespace impala {
RuntimeState::RuntimeState(QueryState* query_state, const TPlanFragmentCtx& fragment_ctx,
const TPlanFragmentInstanceCtx& instance_ctx, ExecEnv* exec_env)
: query_state_(query_state),
fragment_ctx_(&fragment_ctx),
instance_ctx_(&instance_ctx),
now_(new TimestampValue(TimestampValue::Parse(query_state->query_ctx().now_string))),
exec_env_(exec_env),
profile_(obj_pool(), "Fragment " + PrintId(instance_ctx.fragment_instance_id)),
instance_buffer_reservation_(nullptr),
is_cancelled_(false),
root_node_id_(-1) {
Init();
}
RuntimeState::RuntimeState(
const TQueryCtx& qctx, ExecEnv* exec_env, DescriptorTbl* desc_tbl)
: query_state_(new QueryState(qctx, "test-pool")),
fragment_ctx_(nullptr),
instance_ctx_(nullptr),
local_query_state_(query_state_),
now_(new TimestampValue(TimestampValue::Parse(qctx.now_string))),
exec_env_(exec_env),
profile_(obj_pool(), "<unnamed>"),
instance_buffer_reservation_(nullptr),
is_cancelled_(false),
root_node_id_(-1) {
if (query_ctx().request_pool.empty()) {
const_cast<TQueryCtx&>(query_ctx()).request_pool = "test-pool";
}
if (desc_tbl != nullptr) query_state_->desc_tbl_ = desc_tbl;
Init();
}
RuntimeState::~RuntimeState() {
DCHECK(instance_mem_tracker_ == nullptr) << "Must call ReleaseResources()";
}
void RuntimeState::Init() {
SCOPED_TIMER(profile_.total_time_counter());
// Register with the thread mgr
resource_pool_ = exec_env_->thread_mgr()->RegisterPool();
DCHECK(resource_pool_ != NULL);
total_thread_statistics_ = ADD_THREAD_COUNTERS(runtime_profile(), "TotalThreads");
total_storage_wait_timer_ = ADD_TIMER(runtime_profile(), "TotalStorageWaitTime");
total_network_send_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkSendTime");
total_network_receive_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkReceiveTime");
instance_mem_tracker_.reset(new MemTracker(
runtime_profile(), -1, runtime_profile()->name(), query_mem_tracker()));
if (query_state_ != nullptr && exec_env_->buffer_pool() != nullptr) {
instance_buffer_reservation_ = obj_pool()->Add(new ReservationTracker);
instance_buffer_reservation_->InitChildTracker(&profile_,
query_state_->buffer_reservation(), instance_mem_tracker_.get(),
numeric_limits<int64_t>::max());
}
}
void RuntimeState::InitFilterBank() {
filter_bank_.reset(new RuntimeFilterBank(query_ctx(), this));
}
Status RuntimeState::CreateBlockMgr() {
DCHECK(block_mgr_.get() == NULL);
// Compute the max memory the block mgr will use.
int64_t block_mgr_limit = query_mem_tracker()->lowest_limit();
if (block_mgr_limit < 0) block_mgr_limit = numeric_limits<int64_t>::max();
block_mgr_limit = min(static_cast<int64_t>(block_mgr_limit * BLOCK_MGR_MEM_FRACTION),
block_mgr_limit - BLOCK_MGR_MEM_MIN_REMAINING);
if (block_mgr_limit < 0) block_mgr_limit = 0;
if (query_options().__isset.max_block_mgr_memory &&
query_options().max_block_mgr_memory > 0) {
block_mgr_limit = query_options().max_block_mgr_memory;
LOG(WARNING) << "Block mgr mem limit: "
<< PrettyPrinter::Print(block_mgr_limit, TUnit::BYTES);
}
RETURN_IF_ERROR(BufferedBlockMgr::Create(this, query_mem_tracker(),
runtime_profile(), exec_env()->tmp_file_mgr(), block_mgr_limit,
io_mgr()->max_read_buffer_size(), &block_mgr_));
return Status::OK();
}
Status RuntimeState::CreateCodegen() {
if (codegen_.get() != NULL) return Status::OK();
// TODO: add the fragment ID to the codegen ID as well
RETURN_IF_ERROR(LlvmCodeGen::CreateImpalaCodegen(this,
instance_mem_tracker_.get(), PrintId(fragment_instance_id()), &codegen_));
codegen_->EnableOptimizations(true);
profile_.AddChild(codegen_->runtime_profile());
return Status::OK();
}
Status RuntimeState::CodegenScalarFns() {
for (ScalarFnCall* scalar_fn : scalar_fns_to_codegen_) {
Function* fn;
RETURN_IF_ERROR(scalar_fn->GetCodegendComputeFn(codegen_.get(), &fn));
}
return Status::OK();
}
string RuntimeState::ErrorLog() {
lock_guard<SpinLock> l(error_log_lock_);
return PrintErrorMapToString(error_log_);
}
void RuntimeState::GetErrors(ErrorLogMap* errors) {
lock_guard<SpinLock> l(error_log_lock_);
*errors = error_log_;
}
bool RuntimeState::LogError(const ErrorMsg& message, int vlog_level) {
lock_guard<SpinLock> l(error_log_lock_);
// All errors go to the log, unreported_error_count_ is counted independently of the
// size of the error_log to account for errors that were already reported to the
// coordinator
VLOG(vlog_level) << "Error from query " << query_id() << ": " << message.msg();
if (ErrorCount(error_log_) < query_options().max_errors) {
AppendError(&error_log_, message);
return true;
}
return false;
}
void RuntimeState::GetUnreportedErrors(ErrorLogMap* new_errors) {
lock_guard<SpinLock> l(error_log_lock_);
*new_errors = error_log_;
// Reset all messages, but keep all already reported keys so that we do not report the
// same errors multiple times.
ClearErrorMap(error_log_);
}
Status RuntimeState::LogOrReturnError(const ErrorMsg& message) {
DCHECK_NE(message.error(), TErrorCode::OK);
// If either abort_on_error=true or the error necessitates execution stops
// immediately, return an error status.
if (abort_on_error() ||
message.error() == TErrorCode::MEM_LIMIT_EXCEEDED ||
message.error() == TErrorCode::CANCELLED) {
return Status(message);
}
// Otherwise, add the error to the error log and continue.
LogError(message);
return Status::OK();
}
void RuntimeState::SetMemLimitExceeded(MemTracker* tracker,
int64_t failed_allocation_size, const ErrorMsg* msg) {
Status status = tracker->MemLimitExceeded(this, msg == nullptr ? "" : msg->msg(),
failed_allocation_size);
{
lock_guard<SpinLock> l(query_status_lock_);
if (query_status_.ok()) query_status_ = status;
}
LogError(status.msg());
// Add warning about missing stats except for compute stats child queries.
if (!query_ctx().__isset.parent_query_id &&
query_ctx().__isset.tables_missing_stats &&
!query_ctx().tables_missing_stats.empty()) {
LogError(ErrorMsg(TErrorCode::GENERAL,
GetTablesMissingStatsWarning(query_ctx().tables_missing_stats)));
}
DCHECK(query_status_.IsMemLimitExceeded());
}
Status RuntimeState::CheckQueryState() {
if (instance_mem_tracker_ != nullptr
&& UNLIKELY(instance_mem_tracker_->AnyLimitExceeded())) {
SetMemLimitExceeded(instance_mem_tracker_.get());
}
return GetQueryStatus();
}
void RuntimeState::AcquireReaderContext(DiskIoRequestContext* reader_context) {
boost::lock_guard<SpinLock> l(reader_contexts_lock_);
reader_contexts_.push_back(reader_context);
}
void RuntimeState::UnregisterReaderContexts() {
boost::lock_guard<SpinLock> l(reader_contexts_lock_);
for (DiskIoRequestContext* context : reader_contexts_) {
io_mgr()->UnregisterContext(context);
}
reader_contexts_.clear();
}
void RuntimeState::ReleaseResources() {
UnregisterReaderContexts();
if (filter_bank_ != nullptr) filter_bank_->Close();
if (resource_pool_ != nullptr) {
exec_env_->thread_mgr()->UnregisterPool(resource_pool_);
}
block_mgr_.reset(); // Release any block mgr memory, if this is the last reference.
codegen_.reset(); // Release any memory associated with codegen.
// Release the reservation, which should be unused at the point.
if (instance_buffer_reservation_ != nullptr) instance_buffer_reservation_->Close();
// 'query_mem_tracker()' must be valid as long as 'instance_mem_tracker_' is so
// delete 'instance_mem_tracker_' first.
// LogUsage() walks the MemTracker tree top-down when the memory limit is exceeded, so
// break the link between 'instance_mem_tracker_' and its parent before
// 'instance_mem_tracker_' and its children are destroyed.
instance_mem_tracker_->UnregisterFromParent();
if (instance_mem_tracker_->consumption() != 0) {
LOG(WARNING) << "Query " << query_id() << " may have leaked memory." << endl
<< instance_mem_tracker_->LogUsage();
}
instance_mem_tracker_.reset();
if (local_query_state_.get() != nullptr) {
// if we created this QueryState, we must call ReleaseResources()
local_query_state_->ReleaseResources();
}
}
const std::string& RuntimeState::GetEffectiveUser() const {
return impala::GetEffectiveUser(query_ctx().session);
}
ImpalaBackendClientCache* RuntimeState::impalad_client_cache() {
return exec_env_->impalad_client_cache();
}
CatalogServiceClientCache* RuntimeState::catalogd_client_cache() {
return exec_env_->catalogd_client_cache();
}
DiskIoMgr* RuntimeState::io_mgr() {
return exec_env_->disk_io_mgr();
}
DataStreamMgr* RuntimeState::stream_mgr() {
return exec_env_->stream_mgr();
}
HBaseTableFactory* RuntimeState::htable_factory() {
return exec_env_->htable_factory();
}
ObjectPool* RuntimeState::obj_pool() const {
DCHECK(query_state_ != nullptr);
return query_state_->obj_pool();
}
const TQueryCtx& RuntimeState::query_ctx() const {
DCHECK(query_state_ != nullptr);
return query_state_->query_ctx();
}
const DescriptorTbl& RuntimeState::desc_tbl() const {
DCHECK(query_state_ != nullptr);
return query_state_->desc_tbl();
}
const TQueryOptions& RuntimeState::query_options() const {
return query_ctx().client_request.query_options;
}
MemTracker* RuntimeState::query_mem_tracker() {
DCHECK(query_state_ != nullptr);
return query_state_->query_mem_tracker();
}
}
<commit_msg>IMPALA-5432: Remove invalid DCHECK from SetMemLimitExceeded<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "runtime/runtime-state.h"
#include <iostream>
#include <jni.h>
#include <sstream>
#include <string>
#include "common/logging.h"
#include <boost/algorithm/string/join.hpp>
#include <gutil/strings/substitute.h>
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "common/status.h"
#include "exprs/expr.h"
#include "exprs/scalar-fn-call.h"
#include "runtime/buffered-block-mgr.h"
#include "runtime/bufferpool/reservation-tracker.h"
#include "runtime/data-stream-mgr.h"
#include "runtime/data-stream-recvr.h"
#include "runtime/descriptors.h"
#include "runtime/exec-env.h"
#include "runtime/mem-tracker.h"
#include "runtime/query-state.h"
#include "runtime/runtime-filter-bank.h"
#include "runtime/timestamp-value.h"
#include "util/auth-util.h" // for GetEffectiveUser()
#include "util/bitmap.h"
#include "util/cpu-info.h"
#include "util/debug-util.h"
#include "util/disk-info.h"
#include "util/error-util.h"
#include "util/jni-util.h"
#include "util/mem-info.h"
#include "util/pretty-printer.h"
#include "common/names.h"
using namespace llvm;
DECLARE_int32(max_errors);
// The fraction of the query mem limit that is used for the block mgr. Operators
// that accumulate memory all use the block mgr so the majority of the memory should
// be allocated to the block mgr. The remaining memory is used by the non-spilling
// operators and should be independent of data size.
static const float BLOCK_MGR_MEM_FRACTION = 0.8f;
// The minimum amount of memory that must be left after the block mgr reserves the
// BLOCK_MGR_MEM_FRACTION. The block limit is:
// min(query_limit * BLOCK_MGR_MEM_FRACTION, query_limit - BLOCK_MGR_MEM_MIN_REMAINING)
// TODO: this value was picked arbitrarily and the tests are written to rely on this
// for the minimum memory required to run the query. Revisit.
static const int64_t BLOCK_MGR_MEM_MIN_REMAINING = 100 * 1024 * 1024;
namespace impala {
RuntimeState::RuntimeState(QueryState* query_state, const TPlanFragmentCtx& fragment_ctx,
const TPlanFragmentInstanceCtx& instance_ctx, ExecEnv* exec_env)
: query_state_(query_state),
fragment_ctx_(&fragment_ctx),
instance_ctx_(&instance_ctx),
now_(new TimestampValue(TimestampValue::Parse(query_state->query_ctx().now_string))),
exec_env_(exec_env),
profile_(obj_pool(), "Fragment " + PrintId(instance_ctx.fragment_instance_id)),
instance_buffer_reservation_(nullptr),
is_cancelled_(false),
root_node_id_(-1) {
Init();
}
RuntimeState::RuntimeState(
const TQueryCtx& qctx, ExecEnv* exec_env, DescriptorTbl* desc_tbl)
: query_state_(new QueryState(qctx, "test-pool")),
fragment_ctx_(nullptr),
instance_ctx_(nullptr),
local_query_state_(query_state_),
now_(new TimestampValue(TimestampValue::Parse(qctx.now_string))),
exec_env_(exec_env),
profile_(obj_pool(), "<unnamed>"),
instance_buffer_reservation_(nullptr),
is_cancelled_(false),
root_node_id_(-1) {
if (query_ctx().request_pool.empty()) {
const_cast<TQueryCtx&>(query_ctx()).request_pool = "test-pool";
}
if (desc_tbl != nullptr) query_state_->desc_tbl_ = desc_tbl;
Init();
}
RuntimeState::~RuntimeState() {
DCHECK(instance_mem_tracker_ == nullptr) << "Must call ReleaseResources()";
}
void RuntimeState::Init() {
SCOPED_TIMER(profile_.total_time_counter());
// Register with the thread mgr
resource_pool_ = exec_env_->thread_mgr()->RegisterPool();
DCHECK(resource_pool_ != NULL);
total_thread_statistics_ = ADD_THREAD_COUNTERS(runtime_profile(), "TotalThreads");
total_storage_wait_timer_ = ADD_TIMER(runtime_profile(), "TotalStorageWaitTime");
total_network_send_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkSendTime");
total_network_receive_timer_ = ADD_TIMER(runtime_profile(), "TotalNetworkReceiveTime");
instance_mem_tracker_.reset(new MemTracker(
runtime_profile(), -1, runtime_profile()->name(), query_mem_tracker()));
if (query_state_ != nullptr && exec_env_->buffer_pool() != nullptr) {
instance_buffer_reservation_ = obj_pool()->Add(new ReservationTracker);
instance_buffer_reservation_->InitChildTracker(&profile_,
query_state_->buffer_reservation(), instance_mem_tracker_.get(),
numeric_limits<int64_t>::max());
}
}
void RuntimeState::InitFilterBank() {
filter_bank_.reset(new RuntimeFilterBank(query_ctx(), this));
}
Status RuntimeState::CreateBlockMgr() {
DCHECK(block_mgr_.get() == NULL);
// Compute the max memory the block mgr will use.
int64_t block_mgr_limit = query_mem_tracker()->lowest_limit();
if (block_mgr_limit < 0) block_mgr_limit = numeric_limits<int64_t>::max();
block_mgr_limit = min(static_cast<int64_t>(block_mgr_limit * BLOCK_MGR_MEM_FRACTION),
block_mgr_limit - BLOCK_MGR_MEM_MIN_REMAINING);
if (block_mgr_limit < 0) block_mgr_limit = 0;
if (query_options().__isset.max_block_mgr_memory &&
query_options().max_block_mgr_memory > 0) {
block_mgr_limit = query_options().max_block_mgr_memory;
LOG(WARNING) << "Block mgr mem limit: "
<< PrettyPrinter::Print(block_mgr_limit, TUnit::BYTES);
}
RETURN_IF_ERROR(BufferedBlockMgr::Create(this, query_mem_tracker(),
runtime_profile(), exec_env()->tmp_file_mgr(), block_mgr_limit,
io_mgr()->max_read_buffer_size(), &block_mgr_));
return Status::OK();
}
Status RuntimeState::CreateCodegen() {
if (codegen_.get() != NULL) return Status::OK();
// TODO: add the fragment ID to the codegen ID as well
RETURN_IF_ERROR(LlvmCodeGen::CreateImpalaCodegen(this,
instance_mem_tracker_.get(), PrintId(fragment_instance_id()), &codegen_));
codegen_->EnableOptimizations(true);
profile_.AddChild(codegen_->runtime_profile());
return Status::OK();
}
Status RuntimeState::CodegenScalarFns() {
for (ScalarFnCall* scalar_fn : scalar_fns_to_codegen_) {
Function* fn;
RETURN_IF_ERROR(scalar_fn->GetCodegendComputeFn(codegen_.get(), &fn));
}
return Status::OK();
}
string RuntimeState::ErrorLog() {
lock_guard<SpinLock> l(error_log_lock_);
return PrintErrorMapToString(error_log_);
}
void RuntimeState::GetErrors(ErrorLogMap* errors) {
lock_guard<SpinLock> l(error_log_lock_);
*errors = error_log_;
}
bool RuntimeState::LogError(const ErrorMsg& message, int vlog_level) {
lock_guard<SpinLock> l(error_log_lock_);
// All errors go to the log, unreported_error_count_ is counted independently of the
// size of the error_log to account for errors that were already reported to the
// coordinator
VLOG(vlog_level) << "Error from query " << query_id() << ": " << message.msg();
if (ErrorCount(error_log_) < query_options().max_errors) {
AppendError(&error_log_, message);
return true;
}
return false;
}
void RuntimeState::GetUnreportedErrors(ErrorLogMap* new_errors) {
lock_guard<SpinLock> l(error_log_lock_);
*new_errors = error_log_;
// Reset all messages, but keep all already reported keys so that we do not report the
// same errors multiple times.
ClearErrorMap(error_log_);
}
Status RuntimeState::LogOrReturnError(const ErrorMsg& message) {
DCHECK_NE(message.error(), TErrorCode::OK);
// If either abort_on_error=true or the error necessitates execution stops
// immediately, return an error status.
if (abort_on_error() ||
message.error() == TErrorCode::MEM_LIMIT_EXCEEDED ||
message.error() == TErrorCode::CANCELLED) {
return Status(message);
}
// Otherwise, add the error to the error log and continue.
LogError(message);
return Status::OK();
}
void RuntimeState::SetMemLimitExceeded(MemTracker* tracker,
int64_t failed_allocation_size, const ErrorMsg* msg) {
Status status = tracker->MemLimitExceeded(this, msg == nullptr ? "" : msg->msg(),
failed_allocation_size);
{
lock_guard<SpinLock> l(query_status_lock_);
if (query_status_.ok()) query_status_ = status;
}
LogError(status.msg());
// Add warning about missing stats except for compute stats child queries.
if (!query_ctx().__isset.parent_query_id &&
query_ctx().__isset.tables_missing_stats &&
!query_ctx().tables_missing_stats.empty()) {
LogError(ErrorMsg(TErrorCode::GENERAL,
GetTablesMissingStatsWarning(query_ctx().tables_missing_stats)));
}
}
Status RuntimeState::CheckQueryState() {
if (instance_mem_tracker_ != nullptr
&& UNLIKELY(instance_mem_tracker_->AnyLimitExceeded())) {
SetMemLimitExceeded(instance_mem_tracker_.get());
}
return GetQueryStatus();
}
void RuntimeState::AcquireReaderContext(DiskIoRequestContext* reader_context) {
boost::lock_guard<SpinLock> l(reader_contexts_lock_);
reader_contexts_.push_back(reader_context);
}
void RuntimeState::UnregisterReaderContexts() {
boost::lock_guard<SpinLock> l(reader_contexts_lock_);
for (DiskIoRequestContext* context : reader_contexts_) {
io_mgr()->UnregisterContext(context);
}
reader_contexts_.clear();
}
void RuntimeState::ReleaseResources() {
UnregisterReaderContexts();
if (filter_bank_ != nullptr) filter_bank_->Close();
if (resource_pool_ != nullptr) {
exec_env_->thread_mgr()->UnregisterPool(resource_pool_);
}
block_mgr_.reset(); // Release any block mgr memory, if this is the last reference.
codegen_.reset(); // Release any memory associated with codegen.
// Release the reservation, which should be unused at the point.
if (instance_buffer_reservation_ != nullptr) instance_buffer_reservation_->Close();
// 'query_mem_tracker()' must be valid as long as 'instance_mem_tracker_' is so
// delete 'instance_mem_tracker_' first.
// LogUsage() walks the MemTracker tree top-down when the memory limit is exceeded, so
// break the link between 'instance_mem_tracker_' and its parent before
// 'instance_mem_tracker_' and its children are destroyed.
instance_mem_tracker_->UnregisterFromParent();
if (instance_mem_tracker_->consumption() != 0) {
LOG(WARNING) << "Query " << query_id() << " may have leaked memory." << endl
<< instance_mem_tracker_->LogUsage();
}
instance_mem_tracker_.reset();
if (local_query_state_.get() != nullptr) {
// if we created this QueryState, we must call ReleaseResources()
local_query_state_->ReleaseResources();
}
}
const std::string& RuntimeState::GetEffectiveUser() const {
return impala::GetEffectiveUser(query_ctx().session);
}
ImpalaBackendClientCache* RuntimeState::impalad_client_cache() {
return exec_env_->impalad_client_cache();
}
CatalogServiceClientCache* RuntimeState::catalogd_client_cache() {
return exec_env_->catalogd_client_cache();
}
DiskIoMgr* RuntimeState::io_mgr() {
return exec_env_->disk_io_mgr();
}
DataStreamMgr* RuntimeState::stream_mgr() {
return exec_env_->stream_mgr();
}
HBaseTableFactory* RuntimeState::htable_factory() {
return exec_env_->htable_factory();
}
ObjectPool* RuntimeState::obj_pool() const {
DCHECK(query_state_ != nullptr);
return query_state_->obj_pool();
}
const TQueryCtx& RuntimeState::query_ctx() const {
DCHECK(query_state_ != nullptr);
return query_state_->query_ctx();
}
const DescriptorTbl& RuntimeState::desc_tbl() const {
DCHECK(query_state_ != nullptr);
return query_state_->desc_tbl();
}
const TQueryOptions& RuntimeState::query_options() const {
return query_ctx().client_request.query_options;
}
MemTracker* RuntimeState::query_mem_tracker() {
DCHECK(query_state_ != nullptr);
return query_state_->query_mem_tracker();
}
}
<|endoftext|>
|
<commit_before>// This file is part of the "libxzero" project
// (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
// (c) 2014-2015 Paul Asmuth <https://github.com/paulasmuth>
//
// libxzero is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// 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 <xzero/Base64.h>
namespace xzero {
const char Base64::base64_[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
/* aaaack but it's fast and const should make it shared text page. */
const unsigned char Base64::pr2six_[256] = {
/* ASCII table */
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0..15
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 16..31
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 32..47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 48..63
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 64..95
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 80..95
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 96..111
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 112..127
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 128..143
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 144..150
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 160..175
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 176..191
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 192..207
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 208..223
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 224..239
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 240..255
};
int Base64::encodeLength(int sourceLength) {
return ((sourceLength + 2) / 3 * 4) + 1;
}
std::string Base64::encode(const std::string &text) {
return encode((const unsigned char *)text.data(), text.size());
}
std::string Base64::encode(const Buffer &buffer) {
return encode((const unsigned char *)buffer.data(), buffer.size());
}
std::string Base64::encode(const unsigned char *buffer, int ALength) {
const int len = ALength;
const unsigned char *string = buffer;
char *encoded = new char[encodeLength(ALength) + 1];
int i;
char *p = encoded;
for (i = 0; i < len - 2; i += 3) {
*p++ = base64_[(string[i] >> 2) & 0x3F];
*p++ = base64_[((string[i] & 0x3) << 4) |
((int)(string[i + 1] & 0xF0) >> 4)];
*p++ = base64_[((string[i + 1] & 0xF) << 2) |
((int)(string[i + 2] & 0xC0) >> 6)];
*p++ = base64_[string[i + 2] & 0x3F];
}
if (i < len) {
*p++ = base64_[(string[i] >> 2) & 0x3F];
if (i == (len - 1)) {
*p++ = base64_[((string[i] & 0x3) << 4)];
*p++ = '=';
} else {
*p++ = base64_[((string[i] & 0x3) << 4) |
((int)(string[i + 1] & 0xF0) >> 4)];
*p++ = base64_[((string[i + 1] & 0xF) << 2)];
}
*p++ = '=';
}
//*p++ = '\0';
int outlen = p - encoded;
return std::string(encoded, outlen);
}
int Base64::decodeLength(const std::string &buffer) {
return decodeLength(buffer.c_str());
}
int Base64::decodeLength(const char *buffer) {
const unsigned char *bufin = (const unsigned char *)buffer;
while (pr2six_[*(bufin++)] <= 63)
;
int nprbytes = (bufin - (const unsigned char *)buffer) - 1;
int nbytesdecoded = ((nprbytes + 3) / 4) * 3;
return nbytesdecoded + 1;
}
Buffer Base64::decode(const std::string& value) {
Buffer result;
result.reserve(decodeLength(value));
int len = decode(value.c_str(), (unsigned char *)result.data());
result.resize(len);
return result;
}
Buffer Base64::decode(const BufferRef &input) {
size_t decodeLen = decodeLength(input.str().c_str());
Buffer output;
output.reserve(1 + decodeLen);
output.resize(output.capacity());
size_t nbleft = 0;
for (auto i = input.cbegin(), e = input.cend();
i != e && pr2six_[static_cast<int>(*i)] != 64; ++i)
++nbleft;
const unsigned char *inp = (const unsigned char *)&input[0];
unsigned char *outp = (unsigned char *)&output[0];
while (nbleft > 4) {
*outp++ = (unsigned char)(pr2six_[inp[0]] << 2 | pr2six_[inp[1]] >> 4);
*outp++ = (unsigned char)(pr2six_[inp[1]] << 4 | pr2six_[inp[2]] >> 2);
*outp++ = (unsigned char)(pr2six_[inp[2]] << 6 | pr2six_[inp[3]]);
inp += 4;
nbleft -= 4;
}
if (nbleft > 1) {
*outp++ = (unsigned char)(pr2six_[inp[0]] << 2 | pr2six_[inp[1]] >> 4);
if (nbleft > 2) {
*outp++ = (unsigned char)(pr2six_[inp[1]] << 4 | pr2six_[inp[2]] >> 2);
if (nbleft > 3) {
*outp++ = (unsigned char)(pr2six_[inp[2]] << 6 | pr2six_[inp[3]]);
}
}
}
decodeLen -= (4 - nbleft) & 3;
output.resize(decodeLen - 1);
return std::move(output);
}
int Base64::decode(const char *input, unsigned char *output) {
const char *bufcoded = input;
unsigned char *bufplain = output;
const unsigned char *bufin;
unsigned char *bufout;
bufin = (const unsigned char *)bufcoded;
while (pr2six_[*(bufin++)] <= 63)
;
int nprbytes = (bufin - (const unsigned char *)bufcoded) - 1;
int nbytesdecoded = (((int)nprbytes + 3) / 4) * 3;
bufout = (unsigned char *)bufplain;
bufin = (const unsigned char *)bufcoded;
while (nprbytes > 4) {
*(bufout++) =
(unsigned char)(pr2six_[*bufin] << 2 | pr2six_[bufin[1]] >> 4);
*(bufout++) =
(unsigned char)(pr2six_[bufin[1]] << 4 | pr2six_[bufin[2]] >> 2);
*(bufout++) = (unsigned char)(pr2six_[bufin[2]] << 6 | pr2six_[bufin[3]]);
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
*(bufout++) =
(unsigned char)(pr2six_[*bufin] << 2 | pr2six_[bufin[1]] >> 4);
if (nprbytes > 2) {
*(bufout++) =
(unsigned char)(pr2six_[bufin[1]] << 4 | pr2six_[bufin[2]] >> 2);
if (nprbytes > 3) {
*(bufout++) =
(unsigned char)(pr2six_[bufin[2]] << 6 | pr2six_[bufin[3]]);
}
}
}
nbytesdecoded -= (4 - (int)nprbytes) & 3;
return nbytesdecoded;
}
} // namespace xzero
<commit_msg>dead file cleanup<commit_after><|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File SharedArray.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Scientific Computing and Imaging Institute,
// University of Utah (USA) and Department of Aeronautics, Imperial
// College London (UK).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
// This is a copy of boost::shared_array with minor modifications.
#include <boost/config.hpp> // for broken compiler workarounds
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/detail/shared_count.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/bind.hpp>
#include <cstddef> // for std::ptrdiff_t
#include <algorithm> // for std::swap
#include <functional> // for std::less
#include <LibUtilities/BasicUtils/mojo.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/assert.hpp>
namespace Nektar
{
/// \brief Wraps a reference counted T* and deletes it when it is no longer referenced.
///
/// SharedArray is a replacement for boost::shared_array. It addresses the following
/// problem with boost::shared_array
///
/// A "const boost::shared_array<T>" still allows you to modify the internal data
/// held by the array. In other words, it is possible to do the following:
///
/// const boost::shared_array<double>& foo();
///
/// const boost::shared_array<double>& a = foo();
/// a[0] = 1.0;
///
/// With SharedArrays, a "const SharedArray" will not allow you to modify the
/// underlying data.
///
/// An additional feature of a SharedArray is the ability to create a new shared array
/// with an offset:
///
/// SharedArray<double> coeffs = MemoryManager::AllocateSharedArray<double>(10);
/// SharedArray<double> offset = coefffs+5; // offset[5] = coeffs[0]
///
/// coeffs and offset point to the same underlying array, so if coeffs goes out of scope the array
/// is not deleted until offset goes out of scope.
///
template<class T>
class SharedArrayBase
{
protected:
// Borland 5.5.1 specific workarounds
typedef boost::checked_array_deleter<T> deleter;
typedef SharedArrayBase<T> this_type;
public:
template<typename U> friend class SharedArrayBase;
template<typename U> friend class SharedArray;
SharedArrayBase() :
px(0),
pn((T*)0, deleter()),
m_offset(0),
m_size(0)
{
}
explicit SharedArrayBase(unsigned int s) :
px(new T[s]),
pn(px, deleter()),
m_offset(0),
m_size(0)
{
}
SharedArrayBase(T* p, unsigned int s) :
px(p),
pn(p, deleter()),
m_offset(0),
m_size(s)
{
}
SharedArrayBase(const SharedArrayBase<T>& rhs, unsigned int offset) :
px(rhs.px),
pn(rhs.pn),
m_offset(offset),
m_size(rhs.m_size)
{
}
SharedArrayBase(const SharedArrayBase<T>& rhs) :
px(rhs.px),
pn(rhs.pn),
m_offset(rhs.m_offset),
m_size(rhs.m_size)
{
}
SharedArrayBase(T* rhs_px, const boost::detail::shared_count& rhs_pn,
unsigned int rhs_offset, unsigned int rhs_size) :
px(rhs_px),
pn(rhs_pn),
m_offset(rhs_offset),
m_size(rhs_size)
{
}
//
// Requirements: D's copy constructor must not throw
//
// shared_array will release p by calling d(p)
//
template<class D>
SharedArrayBase(T* p, unsigned int s, D d) :
px(p),
pn(p, d),
m_offset(0),
m_size(s)
{
}
SharedArrayBase<T>& operator=(const SharedArrayBase<T>& rhs)
{
px = rhs.px;
pn = rhs.pn;
m_offset = rhs.m_offset;
m_size = rhs.m_size;
return *this;
}
SharedArrayBase<T>& operator+=(unsigned int incr)
{
m_offset += incr;
return *this;
}
void reset()
{
this_type().swap(*this);
}
void reset(T* p, unsigned int size)
{
BOOST_ASSERT(p == 0 || p != px);
this_type(p, size).swap(*this);
}
template <class D> void reset(T * p, unsigned int size, D d)
{
this_type(p, size, d).swap(*this);
}
T& operator[] (std::ptrdiff_t i) // never throws
{
BOOST_ASSERT(px != 0);
BOOST_ASSERT(i >= 0);
return px[i + m_offset];
}
const T& operator[] (std::ptrdiff_t i) const // never throws
{
BOOST_ASSERT(px != 0);
BOOST_ASSERT(i >= 0);
return px[i + m_offset];
}
T* get() // never throws
{
return px + m_offset;
}
const T* get() const
{
return px + m_offset;
}
unsigned int GetSize() const { return m_size; }
// implicit conversion to "bool"
#if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const
{
return px != 0;
}
#elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::get;
}
#else
typedef T * this_type::*unspecified_bool_type;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::px;
}
#endif
bool operator! () const // never throws
{
return px == 0;
}
bool unique() const // never throws
{
return pn.unique();
}
long use_count() const // never throws
{
return pn.use_count();
}
void swap(SharedArrayBase<T>& other) // never throws
{
std::swap(px, other.px);
pn.swap(other.pn);
std::swap(m_offset, other.m_offset);
std::swap(m_size, other.m_size);
}
typedef T* iterator;
typedef const T* const_iterator;
iterator begin() { return px + m_offset; }
iterator end() { return px + m_size; }
const_iterator begin() const { return px + m_offset; }
const_iterator end() const { return px + m_size; }
protected:
T* px;
boost::detail::shared_count pn;
unsigned int m_offset;
unsigned int m_size;
};
template<class T>
class SharedArray : public SharedArrayBase<T>, public MojoEnabled<SharedArray<T> >
{
public:
SharedArray() :
SharedArrayBase<T>()
{
}
explicit SharedArray(unsigned int s) :
SharedArrayBase<T>(s)
{
}
SharedArray(T* p, unsigned int s) :
SharedArrayBase<T>(p, s)
{
}
template<class D>
SharedArray(T* p, unsigned int s, D d) :
SharedArrayBase<T>(p, s, d)
{
}
SharedArray(SharedArray<T>& rhs, unsigned int offset) :
SharedArrayBase<T>(rhs, offset)
{
}
SharedArray(SharedArray<T>& rhs) :
SharedArrayBase<T>(rhs)
{
}
SharedArray(Temporary<SharedArray<T> > rhs) :
SharedArrayBase<T>(rhs.GetValue().px, rhs.GetValue().pn, rhs.GetValue().m_offset, rhs.GetValue().m_size)
{
}
SharedArray<T>& operator=(SharedArray<T>& rhs)
{
SharedArrayBase<T>::operator=(rhs);
return *this;
}
SharedArray<T>& operator=(Temporary<SharedArray<T> > rhs)
{
this->px = rhs.GetValue().px;
this->pn = rhs.GetValue().pn;
this->m_offset = rhs.GetValue().m_offset;
this->m_size = rhs.GetValue().m_size;
return *this;
}
private:
};
template<class T>
class SharedArray<const T> : public SharedArrayBase<const T>
{
public:
friend class SharedArray<T>;
SharedArray() :
SharedArrayBase<const T>()
{
}
explicit SharedArray(unsigned int s) :
SharedArrayBase<const T>(s)
{
}
SharedArray(const T* p, unsigned int s) :
SharedArrayBase<const T>(p, s)
{
}
SharedArray(SharedArray<const T>& rhs, unsigned int offset) :
SharedArrayBase<const T>(rhs, offset)
{
}
template<class D>
SharedArray(const T* p, unsigned int s, D d) :
SharedArrayBase<const T>(p, s, d)
{
}
SharedArray(const SharedArray<const T>& rhs) :
SharedArrayBase<const T>(rhs)
{
}
SharedArray(const SharedArray<T>& rhs) :
SharedArrayBase<const T>(rhs.px, rhs.pn, rhs.m_offset, rhs.m_size)
{
}
SharedArray<const T>& operator=(const SharedArray<const T>& rhs)
{
SharedArrayBase<const T>::operator=(rhs);
return *this;
}
SharedArray<const T>& operator=(const SharedArray<T>& rhs)
{
this->px = rhs.px;
this->pn = rhs.pn;
this->m_offset = rhs.m_offset;
this->m_size = rhs.m_size;
return *this;
}
};
template<class T> inline bool operator==(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return a.get() == b.get();
}
template<class T> inline bool operator!=(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return a.get() != b.get();
}
template<class T> inline bool operator<(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return std::less<T*>()(a.get(), b.get());
}
template<class T> void swap(SharedArray<T> & a, SharedArray<T> & b) // never throws
{
a.swap(b);
}
template<typename T>
SharedArray<T> operator+(SharedArray<T>& lhs, unsigned int offset)
{
return SharedArray<T>(lhs, offset);
}
template<typename T>
SharedArray<T> operator+(unsigned int offset, SharedArray<T>& rhs)
{
return SharedArray<T>(rhs, offset);
}
}
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
<commit_msg>Fixed an initialization problem where the size was not being set in the constructor.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File SharedArray.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Scientific Computing and Imaging Institute,
// University of Utah (USA) and Department of Aeronautics, Imperial
// College London (UK).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
// This is a copy of boost::shared_array with minor modifications.
#include <boost/config.hpp> // for broken compiler workarounds
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/detail/shared_count.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/bind.hpp>
#include <cstddef> // for std::ptrdiff_t
#include <algorithm> // for std::swap
#include <functional> // for std::less
#include <LibUtilities/BasicUtils/mojo.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/assert.hpp>
namespace Nektar
{
/// \brief Wraps a reference counted T* and deletes it when it is no longer referenced.
///
/// SharedArray is a replacement for boost::shared_array. It addresses the following
/// problem with boost::shared_array
///
/// A "const boost::shared_array<T>" still allows you to modify the internal data
/// held by the array. In other words, it is possible to do the following:
///
/// const boost::shared_array<double>& foo();
///
/// const boost::shared_array<double>& a = foo();
/// a[0] = 1.0;
///
/// With SharedArrays, a "const SharedArray" will not allow you to modify the
/// underlying data.
///
/// An additional feature of a SharedArray is the ability to create a new shared array
/// with an offset:
///
/// SharedArray<double> coeffs = MemoryManager::AllocateSharedArray<double>(10);
/// SharedArray<double> offset = coefffs+5; // offset[5] = coeffs[0]
///
/// coeffs and offset point to the same underlying array, so if coeffs goes out of scope the array
/// is not deleted until offset goes out of scope.
///
template<class T>
class SharedArrayBase
{
protected:
// Borland 5.5.1 specific workarounds
typedef boost::checked_array_deleter<T> deleter;
typedef SharedArrayBase<T> this_type;
public:
template<typename U> friend class SharedArrayBase;
template<typename U> friend class SharedArray;
SharedArrayBase() :
px(0),
pn((T*)0, deleter()),
m_offset(0),
m_size(0)
{
}
explicit SharedArrayBase(unsigned int s) :
px(new T[s]),
pn(px, deleter()),
m_offset(0),
m_size(s)
{
}
SharedArrayBase(T* p, unsigned int s) :
px(p),
pn(p, deleter()),
m_offset(0),
m_size(s)
{
}
SharedArrayBase(const SharedArrayBase<T>& rhs, unsigned int offset) :
px(rhs.px),
pn(rhs.pn),
m_offset(offset),
m_size(rhs.m_size)
{
}
SharedArrayBase(const SharedArrayBase<T>& rhs) :
px(rhs.px),
pn(rhs.pn),
m_offset(rhs.m_offset),
m_size(rhs.m_size)
{
}
SharedArrayBase(T* rhs_px, const boost::detail::shared_count& rhs_pn,
unsigned int rhs_offset, unsigned int rhs_size) :
px(rhs_px),
pn(rhs_pn),
m_offset(rhs_offset),
m_size(rhs_size)
{
}
//
// Requirements: D's copy constructor must not throw
//
// shared_array will release p by calling d(p)
//
template<class D>
SharedArrayBase(T* p, unsigned int s, D d) :
px(p),
pn(p, d),
m_offset(0),
m_size(s)
{
}
SharedArrayBase<T>& operator=(const SharedArrayBase<T>& rhs)
{
px = rhs.px;
pn = rhs.pn;
m_offset = rhs.m_offset;
m_size = rhs.m_size;
return *this;
}
SharedArrayBase<T>& operator+=(unsigned int incr)
{
m_offset += incr;
return *this;
}
void reset()
{
this_type().swap(*this);
}
void reset(T* p, unsigned int size)
{
BOOST_ASSERT(p == 0 || p != px);
this_type(p, size).swap(*this);
}
template <class D> void reset(T * p, unsigned int size, D d)
{
this_type(p, size, d).swap(*this);
}
T& operator[] (std::ptrdiff_t i) // never throws
{
BOOST_ASSERT(px != 0);
BOOST_ASSERT(i >= 0);
return px[i + m_offset];
}
const T& operator[] (std::ptrdiff_t i) const // never throws
{
BOOST_ASSERT(px != 0);
BOOST_ASSERT(i >= 0);
return px[i + m_offset];
}
T* get() // never throws
{
return px + m_offset;
}
const T* get() const
{
return px + m_offset;
}
unsigned int GetSize() const { return m_size; }
// implicit conversion to "bool"
#if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const
{
return px != 0;
}
#elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::get;
}
#else
typedef T * this_type::*unspecified_bool_type;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::px;
}
#endif
bool operator! () const // never throws
{
return px == 0;
}
bool unique() const // never throws
{
return pn.unique();
}
long use_count() const // never throws
{
return pn.use_count();
}
void swap(SharedArrayBase<T>& other) // never throws
{
std::swap(px, other.px);
pn.swap(other.pn);
std::swap(m_offset, other.m_offset);
std::swap(m_size, other.m_size);
}
typedef T* iterator;
typedef const T* const_iterator;
iterator begin() { return px + m_offset; }
iterator end() { return px + m_size; }
const_iterator begin() const { return px + m_offset; }
const_iterator end() const { return px + m_size; }
protected:
T* px;
boost::detail::shared_count pn;
unsigned int m_offset;
unsigned int m_size;
};
template<class T>
class SharedArray : public SharedArrayBase<T>, public MojoEnabled<SharedArray<T> >
{
public:
SharedArray() :
SharedArrayBase<T>()
{
}
explicit SharedArray(unsigned int s) :
SharedArrayBase<T>(s)
{
}
SharedArray(T* p, unsigned int s) :
SharedArrayBase<T>(p, s)
{
}
template<class D>
SharedArray(T* p, unsigned int s, D d) :
SharedArrayBase<T>(p, s, d)
{
}
SharedArray(SharedArray<T>& rhs, unsigned int offset) :
SharedArrayBase<T>(rhs, offset)
{
}
SharedArray(SharedArray<T>& rhs) :
SharedArrayBase<T>(rhs)
{
}
SharedArray(Temporary<SharedArray<T> > rhs) :
SharedArrayBase<T>(rhs.GetValue().px, rhs.GetValue().pn, rhs.GetValue().m_offset, rhs.GetValue().m_size)
{
}
SharedArray<T>& operator=(SharedArray<T>& rhs)
{
SharedArrayBase<T>::operator=(rhs);
return *this;
}
SharedArray<T>& operator=(Temporary<SharedArray<T> > rhs)
{
this->px = rhs.GetValue().px;
this->pn = rhs.GetValue().pn;
this->m_offset = rhs.GetValue().m_offset;
this->m_size = rhs.GetValue().m_size;
return *this;
}
private:
};
template<class T>
class SharedArray<const T> : public SharedArrayBase<const T>
{
public:
friend class SharedArray<T>;
SharedArray() :
SharedArrayBase<const T>()
{
}
explicit SharedArray(unsigned int s) :
SharedArrayBase<const T>(s)
{
}
SharedArray(const T* p, unsigned int s) :
SharedArrayBase<const T>(p, s)
{
}
SharedArray(SharedArray<const T>& rhs, unsigned int offset) :
SharedArrayBase<const T>(rhs, offset)
{
}
template<class D>
SharedArray(const T* p, unsigned int s, D d) :
SharedArrayBase<const T>(p, s, d)
{
}
SharedArray(const SharedArray<const T>& rhs) :
SharedArrayBase<const T>(rhs)
{
}
SharedArray(const SharedArray<T>& rhs) :
SharedArrayBase<const T>(rhs.px, rhs.pn, rhs.m_offset, rhs.m_size)
{
}
SharedArray<const T>& operator=(const SharedArray<const T>& rhs)
{
SharedArrayBase<const T>::operator=(rhs);
return *this;
}
SharedArray<const T>& operator=(const SharedArray<T>& rhs)
{
this->px = rhs.px;
this->pn = rhs.pn;
this->m_offset = rhs.m_offset;
this->m_size = rhs.m_size;
return *this;
}
};
template<class T> inline bool operator==(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return a.get() == b.get();
}
template<class T> inline bool operator!=(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return a.get() != b.get();
}
template<class T> inline bool operator<(SharedArray<T> const & a, SharedArray<T> const & b) // never throws
{
return std::less<T*>()(a.get(), b.get());
}
template<class T> void swap(SharedArray<T> & a, SharedArray<T> & b) // never throws
{
a.swap(b);
}
template<typename T>
SharedArray<T> operator+(SharedArray<T>& lhs, unsigned int offset)
{
return SharedArray<T>(lhs, offset);
}
template<typename T>
SharedArray<T> operator+(unsigned int offset, SharedArray<T>& rhs)
{
return SharedArray<T>(rhs, offset);
}
}
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHARED_ARRAY_HPP
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id: Value.cpp 48537 2013-02-11 17:30:03Z vvassilev $
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Value.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/AST/Type.h"
#include "clang/AST/CanonicalType.h"
namespace cling {
Value::Value():
m_ClangType(),
m_LLVMType()
{
assert(sizeof(llvm::GenericValue()) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue();
}
Value::Value(const Value& other):
m_ClangType(other.m_ClangType),
m_LLVMType(other.m_LLVMType)
{
assert(sizeof(llvm::GenericValue()) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(other.getGV());
}
Value::Value(const llvm::GenericValue& v, clang::QualType t)
: m_ClangType(t.getAsOpaquePtr()), m_LLVMType(0)
{
assert(sizeof(llvm::GenericValue()) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(v);
}
Value::Value(const llvm::GenericValue& v, clang::QualType clangTy,
const llvm::Type* llvmTy)
: m_ClangType(clangTy.getAsOpaquePtr()), m_LLVMType(llvmTy)
{
assert(sizeof(llvm::GenericValue()) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(v);
}
Value& Value::operator =(const Value& other) {
m_ClangType = other.m_ClangType;
m_LLVMType = other.m_LLVMType;
setGV(other.getGV());
return *this;
}
llvm::GenericValue Value::getGV() const {
return reinterpret_cast<const llvm::GenericValue&>(m_GV);
}
void Value::setGV(llvm::GenericValue GV) {
assert(sizeof(llvm::GenericValue()) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
reinterpret_cast<llvm::GenericValue&>(m_GV) = GV;
}
clang::QualType Value::getClangType() const {
return clang::QualType::getFromOpaquePtr(m_ClangType);
}
bool Value::isValid() const { return !getClangType().isNull(); }
bool Value::isVoid(const clang::ASTContext& ASTContext) const {
return isValid()
&& getClangType().getDesugaredType(ASTContext)->isVoidType();
}
Value::EStorageType Value::getStorageType() const {
const clang::Type* desugCanon = getClangType()->getUnqualifiedDesugaredType();
desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr()
->getUnqualifiedDesugaredType();
if (desugCanon->isSignedIntegerOrEnumerationType())
return kSignedIntegerOrEnumerationType;
else if (desugCanon->isUnsignedIntegerOrEnumerationType())
return kUnsignedIntegerOrEnumerationType;
else if (desugCanon->isRealFloatingType()) {
const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>();
if (BT->getKind() == clang::BuiltinType::Double)
return kDoubleType;
else if (BT->getKind() == clang::BuiltinType::Float)
return kFloatType;
else if (BT->getKind() == clang::BuiltinType::LongDouble)
return kLongDoubleType;
} else if (desugCanon->isPointerType() || desugCanon->isObjectType())
return kPointerType;
return kUnsupportedType;
}
void* Value::getAs(void**) const { return getGV().PointerVal; }
double Value::getAs(double*) const { return getGV().DoubleVal; }
long double Value::getAs(long double*) const {
return getAs((double*)0);
}
float Value::getAs(float*) const { return getGV().FloatVal; }
bool Value::getAs(bool*) const { return getGV().IntVal.getBoolValue(); }
signed char Value::getAs(signed char*) const {
return (signed char) getAs((signed long long*)0);
}
unsigned char Value::getAs(unsigned char*) const {
return (unsigned char) getAs((unsigned long long*)0);
}
signed short Value::getAs(signed short*) const {
return (signed short) getAs((signed long long*)0);
}
unsigned short Value::getAs(unsigned short*) const {
return (unsigned short) getAs((unsigned long long*)0);
}
signed int Value::getAs(signed int*) const {
return (signed int) getAs((signed long long*)0);
}
unsigned int Value::getAs(unsigned int*) const {
return (unsigned int) getAs((unsigned long long*)0);
}
signed long Value::getAs(signed long*) const {
return (long) getAs((signed long long*)0);
}
unsigned long Value::getAs(unsigned long*) const {
return (signed long) getAs((unsigned long long*)0);
}
signed long long Value::getAs(signed long long*) const {
return getGV().IntVal.getSExtValue();
}
unsigned long long Value::getAs(unsigned long long*) const {
return getGV().IntVal.getZExtValue();
}
} // namespace cling
<commit_msg>Don't test the sizeof(c'tor) but the sizeof(type)...<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id: Value.cpp 48537 2013-02-11 17:30:03Z vvassilev $
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Value.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/AST/Type.h"
#include "clang/AST/CanonicalType.h"
namespace cling {
Value::Value():
m_ClangType(),
m_LLVMType()
{
assert(sizeof(llvm::GenericValue) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue();
}
Value::Value(const Value& other):
m_ClangType(other.m_ClangType),
m_LLVMType(other.m_LLVMType)
{
assert(sizeof(llvm::GenericValue) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(other.getGV());
}
Value::Value(const llvm::GenericValue& v, clang::QualType t)
: m_ClangType(t.getAsOpaquePtr()), m_LLVMType(0)
{
assert(sizeof(llvm::GenericValue) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(v);
}
Value::Value(const llvm::GenericValue& v, clang::QualType clangTy,
const llvm::Type* llvmTy)
: m_ClangType(clangTy.getAsOpaquePtr()), m_LLVMType(llvmTy)
{
assert(sizeof(llvm::GenericValue) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
new (m_GV) llvm::GenericValue(v);
}
Value& Value::operator =(const Value& other) {
m_ClangType = other.m_ClangType;
m_LLVMType = other.m_LLVMType;
setGV(other.getGV());
return *this;
}
llvm::GenericValue Value::getGV() const {
return reinterpret_cast<const llvm::GenericValue&>(m_GV);
}
void Value::setGV(llvm::GenericValue GV) {
assert(sizeof(llvm::GenericValue) <= sizeof(m_GV)
&& "GlobalValue buffer too small");
reinterpret_cast<llvm::GenericValue&>(m_GV) = GV;
}
clang::QualType Value::getClangType() const {
return clang::QualType::getFromOpaquePtr(m_ClangType);
}
bool Value::isValid() const { return !getClangType().isNull(); }
bool Value::isVoid(const clang::ASTContext& ASTContext) const {
return isValid()
&& getClangType().getDesugaredType(ASTContext)->isVoidType();
}
Value::EStorageType Value::getStorageType() const {
const clang::Type* desugCanon = getClangType()->getUnqualifiedDesugaredType();
desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr()
->getUnqualifiedDesugaredType();
if (desugCanon->isSignedIntegerOrEnumerationType())
return kSignedIntegerOrEnumerationType;
else if (desugCanon->isUnsignedIntegerOrEnumerationType())
return kUnsignedIntegerOrEnumerationType;
else if (desugCanon->isRealFloatingType()) {
const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>();
if (BT->getKind() == clang::BuiltinType::Double)
return kDoubleType;
else if (BT->getKind() == clang::BuiltinType::Float)
return kFloatType;
else if (BT->getKind() == clang::BuiltinType::LongDouble)
return kLongDoubleType;
} else if (desugCanon->isPointerType() || desugCanon->isObjectType())
return kPointerType;
return kUnsupportedType;
}
void* Value::getAs(void**) const { return getGV().PointerVal; }
double Value::getAs(double*) const { return getGV().DoubleVal; }
long double Value::getAs(long double*) const {
return getAs((double*)0);
}
float Value::getAs(float*) const { return getGV().FloatVal; }
bool Value::getAs(bool*) const { return getGV().IntVal.getBoolValue(); }
signed char Value::getAs(signed char*) const {
return (signed char) getAs((signed long long*)0);
}
unsigned char Value::getAs(unsigned char*) const {
return (unsigned char) getAs((unsigned long long*)0);
}
signed short Value::getAs(signed short*) const {
return (signed short) getAs((signed long long*)0);
}
unsigned short Value::getAs(unsigned short*) const {
return (unsigned short) getAs((unsigned long long*)0);
}
signed int Value::getAs(signed int*) const {
return (signed int) getAs((signed long long*)0);
}
unsigned int Value::getAs(unsigned int*) const {
return (unsigned int) getAs((unsigned long long*)0);
}
signed long Value::getAs(signed long*) const {
return (long) getAs((signed long long*)0);
}
unsigned long Value::getAs(unsigned long*) const {
return (signed long) getAs((unsigned long long*)0);
}
signed long long Value::getAs(signed long long*) const {
return getGV().IntVal.getSExtValue();
}
unsigned long long Value::getAs(unsigned long long*) const {
return getGV().IntVal.getZExtValue();
}
} // namespace cling
<|endoftext|>
|
<commit_before>//===-- TargetData.cpp - Data size & alignment routines --------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target properties related to datatype size/offset/alignment
// information.
//
// This structure should be created once, filled in if the defaults are not
// correct and then passed around by const&. None of the members functions
// require modification to the object.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetData.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
using namespace llvm;
// Handle the Pass registration stuff necessary to use TargetData's.
namespace {
// Register the default SparcV9 implementation...
RegisterPass<TargetData> X("targetdata", "Target Data Layout");
}
static inline void getTypeInfo(const Type *Ty, const TargetData *TD,
uint64_t &Size, unsigned char &Alignment);
//===----------------------------------------------------------------------===//
// Support for StructLayout
//===----------------------------------------------------------------------===//
StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
StructAlignment = 0;
StructSize = 0;
// Loop over each of the elements, placing them in memory...
for (StructType::element_iterator TI = ST->element_begin(),
TE = ST->element_end(); TI != TE; ++TI) {
const Type *Ty = *TI;
unsigned char A;
unsigned TyAlign;
uint64_t TySize;
getTypeInfo(Ty, &TD, TySize, A);
TyAlign = A;
// Add padding if necessary to make the data element aligned properly...
if (StructSize % TyAlign != 0)
StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding...
// Keep track of maximum alignment constraint
StructAlignment = std::max(TyAlign, StructAlignment);
MemberOffsets.push_back(StructSize);
StructSize += TySize; // Consume space for this data item
}
// Empty structures have alignment of 1 byte.
if (StructAlignment == 0) StructAlignment = 1;
// Add padding to the end of the struct so that it could be put in an array
// and all array elements would be aligned correctly.
if (StructSize % StructAlignment != 0)
StructSize = (StructSize/StructAlignment + 1) * StructAlignment;
}
//===----------------------------------------------------------------------===//
// TargetData Class Implementation
//===----------------------------------------------------------------------===//
TargetData::TargetData(const std::string &TargetName,
bool isLittleEndian, unsigned char PtrSize,
unsigned char PtrAl, unsigned char DoubleAl,
unsigned char FloatAl, unsigned char LongAl,
unsigned char IntAl, unsigned char ShortAl,
unsigned char ByteAl) {
// If this assert triggers, a pass "required" TargetData information, but the
// top level tool did not provide one for it. We do not want to default
// construct, or else we might end up using a bad endianness or pointer size!
//
assert(!TargetName.empty() &&
"ERROR: Tool did not specify a target data to use!");
LittleEndian = isLittleEndian;
PointerSize = PtrSize;
PointerAlignment = PtrAl;
DoubleAlignment = DoubleAl;
assert(DoubleAlignment == PtrAl &&
"Double alignment and pointer alignment agree for now!");
FloatAlignment = FloatAl;
LongAlignment = LongAl;
IntAlignment = IntAl;
ShortAlignment = ShortAl;
ByteAlignment = ByteAl;
}
TargetData::TargetData(const std::string &ToolName, const Module *M) {
LittleEndian = M->getEndianness() != Module::BigEndian;
PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;
PointerAlignment = PointerSize;
DoubleAlignment = PointerSize;
FloatAlignment = 4;
LongAlignment = 8;
IntAlignment = 4;
ShortAlignment = 2;
ByteAlignment = 1;
}
static std::map<std::pair<const TargetData*,const StructType*>,
StructLayout> *Layouts = 0;
TargetData::~TargetData() {
if (Layouts) {
// Remove any layouts for this TD.
std::map<std::pair<const TargetData*,
const StructType*>, StructLayout>::iterator
I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));
while (I != Layouts->end() && I->first.first == this)
Layouts->erase(I++);
if (Layouts->empty()) {
delete Layouts;
Layouts = 0;
}
}
}
const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
if (Layouts == 0)
Layouts = new std::map<std::pair<const TargetData*,const StructType*>,
StructLayout>();
std::map<std::pair<const TargetData*,const StructType*>,
StructLayout>::iterator
I = Layouts->lower_bound(std::make_pair(this, Ty));
if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)
return &I->second;
else {
return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),
StructLayout(Ty, *this)))->second;
}
}
static inline void getTypeInfo(const Type *Ty, const TargetData *TD,
uint64_t &Size, unsigned char &Alignment) {
assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
switch (Ty->getTypeID()) {
case Type::VoidTyID:
case Type::BoolTyID:
case Type::UByteTyID:
case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;
case Type::UShortTyID:
case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;
case Type::UIntTyID:
case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;
case Type::ULongTyID:
case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;
case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;
case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;
case Type::LabelTyID:
case Type::PointerTyID:
Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();
return;
case Type::ArrayTyID: {
const ArrayType *ATy = (const ArrayType *)Ty;
getTypeInfo(ATy->getElementType(), TD, Size, Alignment);
Size *= ATy->getNumElements();
return;
}
case Type::StructTyID: {
// Get the layout annotation... which is lazily created on demand.
const StructLayout *Layout = TD->getStructLayout((const StructType*)Ty);
Size = Layout->StructSize; Alignment = Layout->StructAlignment;
return;
}
case Type::TypeTyID:
default:
assert(0 && "Bad type for getTypeInfo!!!");
return;
}
}
uint64_t TargetData::getTypeSize(const Type *Ty) const {
uint64_t Size;
unsigned char Align;
getTypeInfo(Ty, this, Size, Align);
return Size;
}
unsigned char TargetData::getTypeAlignment(const Type *Ty) const {
uint64_t Size;
unsigned char Align;
getTypeInfo(Ty, this, Size, Align);
return Align;
}
/// getIntPtrType - Return an unsigned integer type that is the same size or
/// greater to the host pointer size.
const Type *TargetData::getIntPtrType() const {
switch (getPointerSize()) {
default: assert(0 && "Unknown pointer size!");
case 2: return Type::UShortTy;
case 4: return Type::UIntTy;
case 8: return Type::ULongTy;
}
}
uint64_t TargetData::getIndexedOffset(const Type *ptrTy,
const std::vector<Value*> &Idx) const {
const Type *Ty = ptrTy;
assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
uint64_t Result = 0;
generic_gep_type_iterator<std::vector<Value*>::const_iterator>
TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());
for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {
if (const StructType *STy = dyn_cast<StructType>(*TI)) {
assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx");
unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();
// Get structure layout information...
const StructLayout *Layout = getStructLayout(STy);
// Add in the offset, as calculated by the structure layout info...
assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!");
Result += Layout->MemberOffsets[FieldNo];
// Update Ty to refer to current element
Ty = STy->getElementType(FieldNo);
} else {
// Update Ty to refer to current element
Ty = cast<SequentialType>(Ty)->getElementType();
// Get the array index and the size of each array element.
int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue();
Result += arrayIdx * (int64_t)getTypeSize(Ty);
}
}
return Result;
}
<commit_msg>Handle targets where alignment can be bigger than the size of the data. Contributed by Vladimir Prus!<commit_after>//===-- TargetData.cpp - Data size & alignment routines --------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target properties related to datatype size/offset/alignment
// information.
//
// This structure should be created once, filled in if the defaults are not
// correct and then passed around by const&. None of the members functions
// require modification to the object.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetData.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
using namespace llvm;
// Handle the Pass registration stuff necessary to use TargetData's.
namespace {
// Register the default SparcV9 implementation...
RegisterPass<TargetData> X("targetdata", "Target Data Layout");
}
static inline void getTypeInfo(const Type *Ty, const TargetData *TD,
uint64_t &Size, unsigned char &Alignment);
//===----------------------------------------------------------------------===//
// Support for StructLayout
//===----------------------------------------------------------------------===//
StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
StructAlignment = 0;
StructSize = 0;
// Loop over each of the elements, placing them in memory...
for (StructType::element_iterator TI = ST->element_begin(),
TE = ST->element_end(); TI != TE; ++TI) {
const Type *Ty = *TI;
unsigned char A;
unsigned TyAlign;
uint64_t TySize;
getTypeInfo(Ty, &TD, TySize, A);
TyAlign = A;
// Add padding if necessary to make the data element aligned properly...
if (StructSize % TyAlign != 0)
StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding...
// Keep track of maximum alignment constraint
StructAlignment = std::max(TyAlign, StructAlignment);
MemberOffsets.push_back(StructSize);
StructSize += TySize; // Consume space for this data item
}
// Empty structures have alignment of 1 byte.
if (StructAlignment == 0) StructAlignment = 1;
// Add padding to the end of the struct so that it could be put in an array
// and all array elements would be aligned correctly.
if (StructSize % StructAlignment != 0)
StructSize = (StructSize/StructAlignment + 1) * StructAlignment;
}
//===----------------------------------------------------------------------===//
// TargetData Class Implementation
//===----------------------------------------------------------------------===//
TargetData::TargetData(const std::string &TargetName,
bool isLittleEndian, unsigned char PtrSize,
unsigned char PtrAl, unsigned char DoubleAl,
unsigned char FloatAl, unsigned char LongAl,
unsigned char IntAl, unsigned char ShortAl,
unsigned char ByteAl) {
// If this assert triggers, a pass "required" TargetData information, but the
// top level tool did not provide one for it. We do not want to default
// construct, or else we might end up using a bad endianness or pointer size!
//
assert(!TargetName.empty() &&
"ERROR: Tool did not specify a target data to use!");
LittleEndian = isLittleEndian;
PointerSize = PtrSize;
PointerAlignment = PtrAl;
DoubleAlignment = DoubleAl;
assert(DoubleAlignment == PtrAl &&
"Double alignment and pointer alignment agree for now!");
FloatAlignment = FloatAl;
LongAlignment = LongAl;
IntAlignment = IntAl;
ShortAlignment = ShortAl;
ByteAlignment = ByteAl;
}
TargetData::TargetData(const std::string &ToolName, const Module *M) {
LittleEndian = M->getEndianness() != Module::BigEndian;
PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;
PointerAlignment = PointerSize;
DoubleAlignment = PointerSize;
FloatAlignment = 4;
LongAlignment = 8;
IntAlignment = 4;
ShortAlignment = 2;
ByteAlignment = 1;
}
static std::map<std::pair<const TargetData*,const StructType*>,
StructLayout> *Layouts = 0;
TargetData::~TargetData() {
if (Layouts) {
// Remove any layouts for this TD.
std::map<std::pair<const TargetData*,
const StructType*>, StructLayout>::iterator
I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));
while (I != Layouts->end() && I->first.first == this)
Layouts->erase(I++);
if (Layouts->empty()) {
delete Layouts;
Layouts = 0;
}
}
}
const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
if (Layouts == 0)
Layouts = new std::map<std::pair<const TargetData*,const StructType*>,
StructLayout>();
std::map<std::pair<const TargetData*,const StructType*>,
StructLayout>::iterator
I = Layouts->lower_bound(std::make_pair(this, Ty));
if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)
return &I->second;
else {
return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),
StructLayout(Ty, *this)))->second;
}
}
static inline void getTypeInfo(const Type *Ty, const TargetData *TD,
uint64_t &Size, unsigned char &Alignment) {
assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
switch (Ty->getTypeID()) {
case Type::VoidTyID:
case Type::BoolTyID:
case Type::UByteTyID:
case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;
case Type::UShortTyID:
case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;
case Type::UIntTyID:
case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;
case Type::ULongTyID:
case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;
case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;
case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;
case Type::LabelTyID:
case Type::PointerTyID:
Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();
return;
case Type::ArrayTyID: {
const ArrayType *ATy = cast<ArrayType>(Ty);
unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
getTypeInfo(ATy->getElementType(), TD, Size, Alignment);
Size = AlignedSize*ATy->getNumElements();
return;
}
case Type::StructTyID: {
// Get the layout annotation... which is lazily created on demand.
const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
Size = Layout->StructSize; Alignment = Layout->StructAlignment;
return;
}
default:
assert(0 && "Bad type for getTypeInfo!!!");
return;
}
}
uint64_t TargetData::getTypeSize(const Type *Ty) const {
uint64_t Size;
unsigned char Align;
getTypeInfo(Ty, this, Size, Align);
return Size;
}
unsigned char TargetData::getTypeAlignment(const Type *Ty) const {
uint64_t Size;
unsigned char Align;
getTypeInfo(Ty, this, Size, Align);
return Align;
}
/// getIntPtrType - Return an unsigned integer type that is the same size or
/// greater to the host pointer size.
const Type *TargetData::getIntPtrType() const {
switch (getPointerSize()) {
default: assert(0 && "Unknown pointer size!");
case 2: return Type::UShortTy;
case 4: return Type::UIntTy;
case 8: return Type::ULongTy;
}
}
uint64_t TargetData::getIndexedOffset(const Type *ptrTy,
const std::vector<Value*> &Idx) const {
const Type *Ty = ptrTy;
assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
uint64_t Result = 0;
generic_gep_type_iterator<std::vector<Value*>::const_iterator>
TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());
for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {
if (const StructType *STy = dyn_cast<StructType>(*TI)) {
assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx");
unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();
// Get structure layout information...
const StructLayout *Layout = getStructLayout(STy);
// Add in the offset, as calculated by the structure layout info...
assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!");
Result += Layout->MemberOffsets[FieldNo];
// Update Ty to refer to current element
Ty = STy->getElementType(FieldNo);
} else {
// Update Ty to refer to current element
Ty = cast<SequentialType>(Ty)->getElementType();
// Get the array index and the size of each array element.
int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue();
Result += arrayIdx * (int64_t)getTypeSize(Ty);
}
}
return Result;
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Toggl Desktop developers.
#include <QApplication>
#include <QMetaType>
#include <QDebug>
#include <QVector>
#include <stdint.h>
#include <stdbool.h>
#include "qtsingleapplication.h" // NOLINT
#include <QCommandLineParser>
#include "./autocompleteview.h"
#include "./bugsnag.h"
#include "./genericview.h"
#include "./mainwindowcontroller.h"
#include "./toggl.h"
class TogglApplication : public QtSingleApplication {
public:
TogglApplication(int &argc, char **argv) // NOLINT
: QtSingleApplication(argc, argv) {}
virtual bool notify(QObject *receiver, QEvent *event) {
try {
return QtSingleApplication::notify(receiver, event);
} catch(std::exception e) {
TogglApi::notifyBugsnag("std::exception", e.what(),
receiver->objectName());
} catch(...) {
TogglApi::notifyBugsnag("unspecified", "exception",
receiver->objectName());
}
return true;
}
};
int main(int argc, char *argv[]) try {
Bugsnag::apiKey = "2a46aa1157256f759053289f2d687c2f";
qRegisterMetaType<uint64_t>("uint64_t");
qRegisterMetaType<int64_t>("int64_t");
qRegisterMetaType<_Bool>("_Bool");
qRegisterMetaType<QVector<TimeEntryView*> >("QVector<TimeEntryView*>");
qRegisterMetaType<QVector<AutocompleteView*> >("QVector<AutocompleteView*");
qRegisterMetaType<QVector<GenericView*> >("QVector<GenericView*");
TogglApplication a(argc, argv);
if (a.sendMessage(("Wake up!"))) {
qDebug() << "An instance of TogglDesktop is already running. "
"This instance will now quit.";
return 0;
}
a.setApplicationName("Toggl Desktop");
a.setApplicationVersion(APP_VERSION);
Bugsnag::app.version = APP_VERSION;
QCommandLineParser parser;
parser.setApplicationDescription("Toggl Desktop");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption logPathOption(
QStringList() << "log-path",
"<path> of the app log file",
"path");
parser.addOption(logPathOption);
QCommandLineOption dbPathOption(
QStringList() << "db-path",
"<path> of the app DB file",
"path");
parser.addOption(dbPathOption);
QCommandLineOption scriptPathOption(
QStringList() << "script-path",
"<path> of a Lua script to run",
"path");
parser.addOption(scriptPathOption);
parser.process(a);
MainWindowController w;
w.show();
return a.exec();
} catch (std::exception &e) { // NOLINT
TogglApi::notifyBugsnag("std::exception", e.what(), "main");
return 1;
} catch (...) { // NOLINT
TogglApi::notifyBugsnag("unspecified", "exception", "main");
return 1;
}
<commit_msg>Fix lint issue<commit_after>// Copyright 2014 Toggl Desktop developers.
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QMetaType>
#include <QVector>
#include <stdint.h>
#include <stdbool.h>
#include "qtsingleapplication.h" // NOLINT
#include "./autocompleteview.h"
#include "./bugsnag.h"
#include "./genericview.h"
#include "./mainwindowcontroller.h"
#include "./toggl.h"
class TogglApplication : public QtSingleApplication {
public:
TogglApplication(int &argc, char **argv) // NOLINT
: QtSingleApplication(argc, argv) {}
virtual bool notify(QObject *receiver, QEvent *event) {
try {
return QtSingleApplication::notify(receiver, event);
} catch(std::exception e) {
TogglApi::notifyBugsnag("std::exception", e.what(),
receiver->objectName());
} catch(...) {
TogglApi::notifyBugsnag("unspecified", "exception",
receiver->objectName());
}
return true;
}
};
int main(int argc, char *argv[]) try {
Bugsnag::apiKey = "2a46aa1157256f759053289f2d687c2f";
qRegisterMetaType<uint64_t>("uint64_t");
qRegisterMetaType<int64_t>("int64_t");
qRegisterMetaType<_Bool>("_Bool");
qRegisterMetaType<QVector<TimeEntryView*> >("QVector<TimeEntryView*>");
qRegisterMetaType<QVector<AutocompleteView*> >("QVector<AutocompleteView*");
qRegisterMetaType<QVector<GenericView*> >("QVector<GenericView*");
TogglApplication a(argc, argv);
if (a.sendMessage(("Wake up!"))) {
qDebug() << "An instance of TogglDesktop is already running. "
"This instance will now quit.";
return 0;
}
a.setApplicationName("Toggl Desktop");
a.setApplicationVersion(APP_VERSION);
Bugsnag::app.version = APP_VERSION;
QCommandLineParser parser;
parser.setApplicationDescription("Toggl Desktop");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption logPathOption(
QStringList() << "log-path",
"<path> of the app log file",
"path");
parser.addOption(logPathOption);
QCommandLineOption dbPathOption(
QStringList() << "db-path",
"<path> of the app DB file",
"path");
parser.addOption(dbPathOption);
QCommandLineOption scriptPathOption(
QStringList() << "script-path",
"<path> of a Lua script to run",
"path");
parser.addOption(scriptPathOption);
parser.process(a);
MainWindowController w;
w.show();
return a.exec();
} catch (std::exception &e) { // NOLINT
TogglApi::notifyBugsnag("std::exception", e.what(), "main");
return 1;
} catch (...) { // NOLINT
TogglApi::notifyBugsnag("unspecified", "exception", "main");
return 1;
}
<|endoftext|>
|
<commit_before>
/*!
* \file cuda_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/cuda_utilities.h"
#include "../global/global.h"
/*
PCM : n_ghost = 2
PLMP : n_ghost = 2
PLMC : n_ghost = 3
PPMP : n_ghost = 4
PPMC : n_ghost = 4
*/
// =============================================================================
// Local helper functions
namespace
{
struct TestParams
{
std::vector<int> n_ghost {2, 2, 3, 4};
std::vector<int> nx {1, 2048, 2048, 2048};
std::vector<int> ny {1, 2048, 2048, 2048};
std::vector<int> nz {1, 4096, 4096, 4096};
std::vector<std::string> names{"Single-cell 3D PCM/PLMP case", "Large 3D PCM/PLMP case", "Large PLMC case", "Large PPMP/PPMC case"};
};
}
TEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<std::vector<int>> fiducial_indices {{1, 2, 3, 4, 5, 6},
{4, 5, 6, 7, 8, 9},
{7, 8, 9, 4, 5, 6},
{7, 8, 9, 4, 5, 6}};
for (size_t i = 0; i < parameters.names.size(); i++)
{
int is;
int ie;
int js;
int je;
int ks;
int ke;
cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);
std::vector<int> test_indices {is, ie, js, je, ks, ke};
for (int j = 0; j < test_indices.size(); j++)
{
testingUtilities::checkResults(fiducial_indices[i], test_indices[i][j], parameters.names[i]);
}
}
}<commit_msg>add test for real index utility function<commit_after>
/*!
* \file cuda_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/cuda_utilities.h"
#include "../global/global.h"
/*
PCM : n_ghost = 2
PLMP : n_ghost = 2
PLMC : n_ghost = 3
PPMP : n_ghost = 4
PPMC : n_ghost = 4
*/
// =============================================================================
// Local helper functions
namespace
{
struct TestParams
{
std::vector<int> n_ghost {2, 2, 3, 4};
std::vector<int> nx {1, 2048, 2048, 2048};
std::vector<int> ny {1, 2048, 2048, 2048};
std::vector<int> nz {1, 4096, 4096, 4096};
std::vector<std::string> names{"Single-cell 3D PCM/PLMP case", "Large 3D PCM/PLMP case", "Large PLMC case", "Large PPMP/PPMC case"};
};
}
TEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<std::vector<int>> fiducial_indices {{1, 2, 3, 4, 5, 6},
{4, 5, 6, 7, 8, 9},
{7, 8, 9, 4, 5, 6},
{7, 8, 9, 4, 5, 6}};
for (size_t i = 0; i < parameters.names.size(); i++)
{
int is;
int ie;
int js;
int je;
int ks;
int ke;
cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);
std::vector<int> test_indices {is, ie, js, je, ks, ke};
for (int j = 0; j < test_indices.size(); j++)
{
testingUtilities::checkResults(fiducial_indices[i][j], test_indices[i], parameters.names[i]);
}
}
}<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, PAL Robotics, S.L.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/*
* Author: Bence Magyar
*/
#include <controller_interface/controller.h>
#include <hardware_interface/joint_command_interface.h>
#include <pluginlib/class_list_macros.h>
#include <nav_msgs/Odometry.h>
#include <tf/tfMessage.h>
#include <tf/transform_datatypes.h>
#include <urdf_parser/urdf_parser.h>
#include <realtime_tools/realtime_buffer.h>
#include <realtime_tools/realtime_publisher.h>
#include <boost/assign.hpp>
#include <diff_drive_controller/odometry.h>
namespace diff_drive_controller{
class DiffDriveController : public controller_interface::Controller<hardware_interface::VelocityJointInterface>
{
public:
bool init(hardware_interface::VelocityJointInterface* hw,
ros::NodeHandle& root_nh,
ros::NodeHandle &controller_nh)
{
const std::string complete_ns = controller_nh.getNamespace();
std::size_t id = complete_ns.find_last_of("/");
name_ = complete_ns.substr(id + 1);
// get joint names from the parameter server
std::string left_wheel_name, right_wheel_name;
bool res = controller_nh.hasParam("left_wheel");
if(!res || !controller_nh.getParam("left_wheel", left_wheel_name))
{
ROS_ERROR_NAMED(name_, "Couldn't retrieve left wheel name from param server.");
return false;
}
res = controller_nh.hasParam("right_wheel");
if(!res || !controller_nh.getParam("right_wheel", right_wheel_name))
{
ROS_ERROR_NAMED(name_, "Couldn't retrieve right wheel name from param server.");
return false;
}
double publish_rate;
controller_nh.param("publish_rate", publish_rate, 50.0);
ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at "
<< publish_rate << "Hz.");
publish_period_ = ros::Duration(1.0 / publish_rate);
// parse robot description
const std::string model_param_name = "/robot_description";
res = root_nh.hasParam(model_param_name);
std::string robot_model_str="";
if(!res || !root_nh.getParam(model_param_name,robot_model_str))
{
ROS_ERROR_NAMED(name_, "Robot descripion couldn't be retrieved from param server.");
return false;
}
boost::shared_ptr<urdf::ModelInterface> model_ptr(urdf::parseURDF(robot_model_str));
boost::shared_ptr<const urdf::Joint> wheelJointPtr(model_ptr->getJoint(left_wheel_name));
if(!wheelJointPtr.get())
{
ROS_ERROR_STREAM_NAMED(name_, left_wheel_name
<< " couldn't be retrieved from model description");
return false;
}
wheel_radius_ = fabs(wheelJointPtr->parent_to_joint_origin_transform.position.z);
wheel_separation_ = 2.0 * fabs(wheelJointPtr->parent_to_joint_origin_transform.position.y);
odometry_.setWheelParams(wheel_separation_, wheel_radius_);
ROS_DEBUG_STREAM_NAMED(name_,
"Odometry params : wheel separation " << wheel_separation_
<< ", wheel radius " << wheel_radius_);
// get the joint object to use in the realtime loop
ROS_DEBUG_STREAM_NAMED(name_,
"Adding left wheel with joint name: " << left_wheel_name
<< " and right wheel with joint name: " << right_wheel_name);
left_wheel_joint_ = hw->getHandle(left_wheel_name); // throws on failure
right_wheel_joint_ = hw->getHandle(right_wheel_name); // throws on failure
// setup odometry realtime publisher + odom message constant fields
odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
odom_pub_->msg_.header.frame_id = "odom";
odom_pub_->msg_.pose.pose.position.z = 0;
odom_pub_->msg_.pose.covariance = boost::assign::list_of
(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
odom_pub_->msg_.twist.twist.linear.y = 0;
odom_pub_->msg_.twist.twist.linear.z = 0;
odom_pub_->msg_.twist.twist.angular.x = 0;
odom_pub_->msg_.twist.twist.angular.y = 0;
odom_pub_->msg_.twist.covariance = boost::assign::list_of
(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(controller_nh, "/tf", 100));
odom_frame.transform.translation.z = 0.0;
odom_frame.child_frame_id = "base_footprint";
odom_frame.header.frame_id = "odom";
sub_command_ = controller_nh.subscribe("cmd_vel", 1, &DiffDriveController::cmdVelCallback, this);
return true;
}
void update(const ros::Time& time, const ros::Duration& period)
{
// MOVE ROBOT
// command the wheels according to the messages from the cmd_vel topic
const Commands curr_cmd = *(command_.readFromRT());
const double vel_right =
(curr_cmd.lin + curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_;
const double vel_left =
(curr_cmd.lin - curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_;
left_wheel_joint_.setCommand(vel_left);
right_wheel_joint_.setCommand(vel_right);
// COMPUTE AND PUBLISH ODOMETRY
// estimate linear and angular velocity using joint information
//----------------------------
if(!odometry_.update(left_wheel_joint_.getPosition(), right_wheel_joint_.getPosition(), time))
{
ROS_WARN_NAMED(name_,
"Dropped odom: period too small to integrate or no change.");
return;
}
// publish odometry message
if(last_state_publish_time_ + publish_period_ < time)
{
last_state_publish_time_ += publish_period_;
// compute and store orientation info
const geometry_msgs::Quaternion orientation(
tf::createQuaternionMsgFromYaw(odometry_.getHeading()));
// populate odom message and publish
if(odom_pub_->trylock())
{
odom_pub_->msg_.header.stamp = time;
odom_pub_->msg_.pose.pose.position.x = odometry_.getPos().x;
odom_pub_->msg_.pose.pose.position.y = odometry_.getPos().y;
odom_pub_->msg_.pose.pose.orientation = orientation;
odom_pub_->msg_.twist.twist.linear.x = odometry_.getLinearEstimated();
odom_pub_->msg_.twist.twist.angular.z = odometry_.getAngularEstimated();
odom_pub_->unlockAndPublish();
}
// publish tf /odom frame
if(tf_odom_pub_->trylock())
{
odom_frame.header.stamp = time;
odom_frame.transform.translation.x = odometry_.getPos().x;
odom_frame.transform.translation.y = odometry_.getPos().y;
odom_frame.transform.rotation = orientation;
tf_odom_pub_->msg_.transforms.clear();
tf_odom_pub_->msg_.transforms.push_back(odom_frame);
tf_odom_pub_->unlockAndPublish();
}
}
}
void starting(const ros::Time& time)
{
// set velocity to 0
const double vel = 0.0;
left_wheel_joint_.setCommand(vel);
right_wheel_joint_.setCommand(vel);
// register starting time used to keep fixed rate
last_state_publish_time_ = time;
}
void stopping(const ros::Time& time)
{
// set velocity to 0
const double vel = 0.0;
left_wheel_joint_.setCommand(vel);
right_wheel_joint_.setCommand(vel);
}
private:
std::string name_;
// publish rate related
ros::Duration publish_period_;
ros::Time last_state_publish_time_;
// hardware handles
hardware_interface::JointHandle left_wheel_joint_;
hardware_interface::JointHandle right_wheel_joint_;
// cmd_vel related
struct Commands
{
double lin;
double ang;
};
realtime_tools::RealtimeBuffer<Commands> command_;
Commands command_struct_;
ros::Subscriber sub_command_;
// odometry related
boost::shared_ptr<realtime_tools::RealtimePublisher<nav_msgs::Odometry> > odom_pub_;
boost::shared_ptr<realtime_tools::RealtimePublisher<tf::tfMessage> > tf_odom_pub_;
Odometry odometry_;
double wheel_separation_;
double wheel_radius_;
geometry_msgs::TransformStamped odom_frame;
private:
void cmdVelCallback(const geometry_msgs::Twist& command)
{
if(isRunning())
{
command_struct_.ang = command.angular.z;
command_struct_.lin = command.linear.x;
command_.writeFromNonRT (command_struct_);
ROS_DEBUG_STREAM_NAMED(name_,
"Added values to command. Ang: " << command_struct_.ang
<< ", Lin: " << command_struct_.lin);
}
else
{
ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running.");
}
}
};
PLUGINLIB_DECLARE_CLASS(diff_drive_controller, DiffDriveController, diff_drive_controller::DiffDriveController, controller_interface::ControllerBase);
}//namespace
<commit_msg>Added parsing of covariance params.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, PAL Robotics, S.L.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/*
* Author: Bence Magyar
*/
#include <controller_interface/controller.h>
#include <hardware_interface/joint_command_interface.h>
#include <pluginlib/class_list_macros.h>
#include <nav_msgs/Odometry.h>
#include <tf/tfMessage.h>
#include <tf/transform_datatypes.h>
#include <urdf_parser/urdf_parser.h>
#include <realtime_tools/realtime_buffer.h>
#include <realtime_tools/realtime_publisher.h>
#include <boost/assign.hpp>
#include <diff_drive_controller/odometry.h>
namespace diff_drive_controller{
class DiffDriveController : public controller_interface::Controller<hardware_interface::VelocityJointInterface>
{
public:
bool init(hardware_interface::VelocityJointInterface* hw,
ros::NodeHandle& root_nh,
ros::NodeHandle &controller_nh)
{
const std::string complete_ns = controller_nh.getNamespace();
std::size_t id = complete_ns.find_last_of("/");
name_ = complete_ns.substr(id + 1);
// get joint names from the parameter server
std::string left_wheel_name, right_wheel_name;
bool res = controller_nh.hasParam("left_wheel");
if(!res || !controller_nh.getParam("left_wheel", left_wheel_name))
{
ROS_ERROR_NAMED(name_, "Couldn't retrieve left wheel name from param server.");
return false;
}
res = controller_nh.hasParam("right_wheel");
if(!res || !controller_nh.getParam("right_wheel", right_wheel_name))
{
ROS_ERROR_NAMED(name_, "Couldn't retrieve right wheel name from param server.");
return false;
}
double publish_rate;
controller_nh.param("publish_rate", publish_rate, 50.0);
ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at "
<< publish_rate << "Hz.");
publish_period_ = ros::Duration(1.0 / publish_rate);
// parse robot description
const std::string model_param_name = "/robot_description";
res = root_nh.hasParam(model_param_name);
std::string robot_model_str="";
if(!res || !root_nh.getParam(model_param_name,robot_model_str))
{
ROS_ERROR_NAMED(name_, "Robot descripion couldn't be retrieved from param server.");
return false;
}
boost::shared_ptr<urdf::ModelInterface> model_ptr(urdf::parseURDF(robot_model_str));
boost::shared_ptr<const urdf::Joint> wheelJointPtr(model_ptr->getJoint(left_wheel_name));
if(!wheelJointPtr.get())
{
ROS_ERROR_STREAM_NAMED(name_, left_wheel_name
<< " couldn't be retrieved from model description");
return false;
}
wheel_radius_ = fabs(wheelJointPtr->parent_to_joint_origin_transform.position.z);
wheel_separation_ = 2.0 * fabs(wheelJointPtr->parent_to_joint_origin_transform.position.y);
odometry_.setWheelParams(wheel_separation_, wheel_radius_);
ROS_DEBUG_STREAM_NAMED(name_,
"Odometry params : wheel separation " << wheel_separation_
<< ", wheel radius " << wheel_radius_);
// get and check params for covariances
XmlRpc::XmlRpcValue pose_cov_list;
controller_nh.getParam("pose_covariance_diagonal", pose_cov_list);
ROS_ASSERT(pose_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
ROS_ASSERT(pose_cov_list.size() == 6);
for (int i = 0; i < pose_cov_list.size(); ++i)
ROS_ASSERT(pose_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);
XmlRpc::XmlRpcValue twist_cov_list;
controller_nh.getParam("twist_covariance_diagonal", twist_cov_list);
ROS_ASSERT(twist_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
ROS_ASSERT(twist_cov_list.size() == 6);
for (int i = 0; i < twist_cov_list.size(); ++i)
ROS_ASSERT(twist_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);
// setup odometry realtime publisher + odom message constant fields
odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
odom_pub_->msg_.header.frame_id = "odom";
odom_pub_->msg_.pose.pose.position.z = 0;
odom_pub_->msg_.pose.covariance = boost::assign::list_of
(static_cast<double>(pose_cov_list[0])) (0) (0) (0) (0) (0)
(0) (static_cast<double>(pose_cov_list[1])) (0) (0) (0) (0)
(0) (0) (static_cast<double>(pose_cov_list[2])) (0) (0) (0)
(0) (0) (0) (static_cast<double>(pose_cov_list[3])) (0) (0)
(0) (0) (0) (0) (static_cast<double>(pose_cov_list[4])) (0)
(0) (0) (0) (0) (0) (static_cast<double>(pose_cov_list[5]));
odom_pub_->msg_.twist.twist.linear.y = 0;
odom_pub_->msg_.twist.twist.linear.z = 0;
odom_pub_->msg_.twist.twist.angular.x = 0;
odom_pub_->msg_.twist.twist.angular.y = 0;
odom_pub_->msg_.twist.covariance = boost::assign::list_of
(static_cast<double>(twist_cov_list[0])) (0) (0) (0) (0) (0)
(0) (static_cast<double>(twist_cov_list[1])) (0) (0) (0) (0)
(0) (0) (static_cast<double>(twist_cov_list[2])) (0) (0) (0)
(0) (0) (0) (static_cast<double>(twist_cov_list[3])) (0) (0)
(0) (0) (0) (0) (static_cast<double>(twist_cov_list[4])) (0)
(0) (0) (0) (0) (0) (static_cast<double>(twist_cov_list[5]));
tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(controller_nh, "/tf", 100));
odom_frame.transform.translation.z = 0.0;
odom_frame.child_frame_id = "base_footprint";
odom_frame.header.frame_id = "odom";
// get the joint object to use in the realtime loop
ROS_DEBUG_STREAM_NAMED(name_,
"Adding left wheel with joint name: " << left_wheel_name
<< " and right wheel with joint name: " << right_wheel_name);
left_wheel_joint_ = hw->getHandle(left_wheel_name); // throws on failure
right_wheel_joint_ = hw->getHandle(right_wheel_name); // throws on failure
sub_command_ = controller_nh.subscribe("cmd_vel", 1, &DiffDriveController::cmdVelCallback, this);
return true;
}
void update(const ros::Time& time, const ros::Duration& period)
{
// MOVE ROBOT
// command the wheels according to the messages from the cmd_vel topic
const Commands curr_cmd = *(command_.readFromRT());
const double vel_right =
(curr_cmd.lin + curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_;
const double vel_left =
(curr_cmd.lin - curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_;
left_wheel_joint_.setCommand(vel_left);
right_wheel_joint_.setCommand(vel_right);
// COMPUTE AND PUBLISH ODOMETRY
// estimate linear and angular velocity using joint information
//----------------------------
if(!odometry_.update(left_wheel_joint_.getPosition(), right_wheel_joint_.getPosition(), time))
{
ROS_WARN_NAMED(name_,
"Dropped odom: period too small to integrate or no change.");
return;
}
// publish odometry message
if(last_state_publish_time_ + publish_period_ < time)
{
last_state_publish_time_ += publish_period_;
// compute and store orientation info
const geometry_msgs::Quaternion orientation(
tf::createQuaternionMsgFromYaw(odometry_.getHeading()));
// populate odom message and publish
if(odom_pub_->trylock())
{
odom_pub_->msg_.header.stamp = time;
odom_pub_->msg_.pose.pose.position.x = odometry_.getPos().x;
odom_pub_->msg_.pose.pose.position.y = odometry_.getPos().y;
odom_pub_->msg_.pose.pose.orientation = orientation;
odom_pub_->msg_.twist.twist.linear.x = odometry_.getLinearEstimated();
odom_pub_->msg_.twist.twist.angular.z = odometry_.getAngularEstimated();
odom_pub_->unlockAndPublish();
}
// publish tf /odom frame
if(tf_odom_pub_->trylock())
{
odom_frame.header.stamp = time;
odom_frame.transform.translation.x = odometry_.getPos().x;
odom_frame.transform.translation.y = odometry_.getPos().y;
odom_frame.transform.rotation = orientation;
tf_odom_pub_->msg_.transforms.clear();
tf_odom_pub_->msg_.transforms.push_back(odom_frame);
tf_odom_pub_->unlockAndPublish();
}
}
}
void starting(const ros::Time& time)
{
// set velocity to 0
const double vel = 0.0;
left_wheel_joint_.setCommand(vel);
right_wheel_joint_.setCommand(vel);
// register starting time used to keep fixed rate
last_state_publish_time_ = time;
}
void stopping(const ros::Time& time)
{
// set velocity to 0
const double vel = 0.0;
left_wheel_joint_.setCommand(vel);
right_wheel_joint_.setCommand(vel);
}
private:
std::string name_;
// publish rate related
ros::Duration publish_period_;
ros::Time last_state_publish_time_;
// hardware handles
hardware_interface::JointHandle left_wheel_joint_;
hardware_interface::JointHandle right_wheel_joint_;
// cmd_vel related
struct Commands
{
double lin;
double ang;
};
realtime_tools::RealtimeBuffer<Commands> command_;
Commands command_struct_;
ros::Subscriber sub_command_;
// odometry related
boost::shared_ptr<realtime_tools::RealtimePublisher<nav_msgs::Odometry> > odom_pub_;
boost::shared_ptr<realtime_tools::RealtimePublisher<tf::tfMessage> > tf_odom_pub_;
Odometry odometry_;
double wheel_separation_;
double wheel_radius_;
geometry_msgs::TransformStamped odom_frame;
private:
void cmdVelCallback(const geometry_msgs::Twist& command)
{
if(isRunning())
{
command_struct_.ang = command.angular.z;
command_struct_.lin = command.linear.x;
command_.writeFromNonRT (command_struct_);
ROS_DEBUG_STREAM_NAMED(name_,
"Added values to command. Ang: " << command_struct_.ang
<< ", Lin: " << command_struct_.lin);
}
else
{
ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running.");
}
}
};
PLUGINLIB_DECLARE_CLASS(diff_drive_controller, DiffDriveController, diff_drive_controller::DiffDriveController, controller_interface::ControllerBase);
}//namespace
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2004 by *
* Jason Kivlighn (jkivlighn@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. *
***************************************************************************/
#include "prepmethodlistview.h"
#include <kmessagebox.h>
#include <kconfig.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kpopupmenu.h>
#include "backends/recipedb.h"
#include "dialogs/createelementdialog.h"
#include "dialogs/dependanciesdialog.h"
PrepMethodListView::PrepMethodListView( QWidget *parent, RecipeDB *db ) : DBListViewBase( parent,db,db->prepMethodCount())
{
connect( database, SIGNAL( prepMethodCreated( const Element & ) ), SLOT( checkCreatePrepMethod( const Element & ) ) );
connect( database, SIGNAL( prepMethodRemoved( int ) ), SLOT( removePrepMethod( int ) ) );
setAllColumnsShowFocus( true );
setDefaultRenameAction( QListView::Reject );
}
void PrepMethodListView::load( int limit, int offset )
{
ElementList prepMethodList;
database->loadPrepMethods( &prepMethodList, limit, offset );
for ( ElementList::const_iterator ing_it = prepMethodList.begin(); ing_it != prepMethodList.end(); ++ing_it )
createPrepMethod( *ing_it );
}
void PrepMethodListView::checkCreatePrepMethod( const Element &el )
{
if ( handleElement(el.name) ) { //only create this prep method if the base class okays it
createPrepMethod(el);
}
}
StdPrepMethodListView::StdPrepMethodListView( QWidget *parent, RecipeDB *db, bool editable ) : PrepMethodListView( parent, db )
{
addColumn( i18n( "Preparation Method" ) );
KConfig * config = KGlobal::config();
config->setGroup( "Advanced" );
bool show_id = config->readBoolEntry( "ShowID", false );
addColumn( i18n( "Id" ), show_id ? -1 : 0 );
if ( editable ) {
setRenameable( 0, true );
KIconLoader *il = new KIconLoader;
kpop = new KPopupMenu( this );
kpop->insertItem( il->loadIcon( "filenew", KIcon::NoGroup, 16 ), i18n( "&Create" ), this, SLOT( createNew() ), CTRL + Key_C );
kpop->insertItem( il->loadIcon( "editdelete", KIcon::NoGroup, 16 ), i18n( "&Delete" ), this, SLOT( remove
() ), Key_Delete );
kpop->insertItem( il->loadIcon( "edit", KIcon::NoGroup, 16 ), i18n( "&Rename" ), this, SLOT( rename() ), CTRL + Key_R );
kpop->polish();
delete il;
connect( this, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ), SLOT( showPopup( KListView *, QListViewItem *, const QPoint & ) ) );
connect( this, SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( modPrepMethod( QListViewItem* ) ) );
connect( this, SIGNAL( itemRenamed( QListViewItem* ) ), this, SLOT( savePrepMethod( QListViewItem* ) ) );
}
}
void StdPrepMethodListView::showPopup( KListView * /*l*/, QListViewItem *i, const QPoint &p )
{
if ( i )
kpop->exec( p );
}
void StdPrepMethodListView::createNew()
{
CreateElementDialog * elementDialog = new CreateElementDialog( this, i18n( "New Preparation Method" ) );
if ( elementDialog->exec() == QDialog::Accepted ) {
QString result = elementDialog->newElementName();
//check bounds first
if ( checkBounds( result ) )
database->createNewPrepMethod( result ); // Create the new prepMethod in the database
}
}
void StdPrepMethodListView::remove
()
{
QListViewItem * item = currentItem();
if ( item ) {
ElementList dependingRecipes;
int prepMethodID = item->text( 1 ).toInt();
database->findPrepMethodDependancies( prepMethodID, &dependingRecipes );
if ( dependingRecipes.isEmpty() )
database->removePrepMethod( prepMethodID );
else // Need Warning!
{
DependanciesDialog *warnDialog = new DependanciesDialog( this, &dependingRecipes );
if ( warnDialog->exec() == QDialog::Accepted )
database->removePrepMethod( prepMethodID );
delete warnDialog;
}
}
}
void StdPrepMethodListView::rename()
{
QListViewItem * item = currentItem();
if ( item )
PrepMethodListView::rename( item, 0 );
}
void StdPrepMethodListView::createPrepMethod( const Element &ing )
{
createElement(new QListViewItem( this, ing.name, QString::number( ing.id ) ));
}
void StdPrepMethodListView::removePrepMethod( int id )
{
QListViewItem * item = findItem( QString::number( id ), 1 );
removeElement(item);
}
void StdPrepMethodListView::modPrepMethod( QListViewItem* i )
{
if ( i )
PrepMethodListView::rename( i, 0 );
}
void StdPrepMethodListView::savePrepMethod( QListViewItem* i )
{
if ( !checkBounds( i->text( 0 ) ) ) {
reload(); //reset the changed text
return ;
}
int existing_id = database->findExistingPrepByName( i->text( 0 ) );
int prep_id = i->text( 1 ).toInt();
if ( existing_id != -1 && existing_id != prep_id ) //category already exists with this label... merge the two
{
switch ( KMessageBox::warningContinueCancel( this, i18n( "This preparation method already exists. Continuing will merge these two into one. Are you sure?" ) ) )
{
case KMessageBox::Continue: {
database->mergePrepMethods( existing_id, prep_id );
break;
}
default:
reload();
break;
}
}
else {
database->modPrepMethod( ( i->text( 1 ) ).toInt(), i->text( 0 ) );
}
}
bool StdPrepMethodListView::checkBounds( const QString &name )
{
if ( name.length() > database->maxPrepMethodNameLength() ) {
KMessageBox::error( this, QString( i18n( "Preparation method cannot be longer than %1 characters." ) ).arg( database->maxPrepMethodNameLength() ) );
return false;
}
return true;
}
#include "prepmethodlistview.moc"
<commit_msg>Make the progress bar when loading prep methods give a percent<commit_after>/***************************************************************************
* Copyright (C) 2004 by *
* Jason Kivlighn (jkivlighn@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. *
***************************************************************************/
#include "prepmethodlistview.h"
#include <kmessagebox.h>
#include <kconfig.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kpopupmenu.h>
#include "backends/recipedb.h"
#include "dialogs/createelementdialog.h"
#include "dialogs/dependanciesdialog.h"
PrepMethodListView::PrepMethodListView( QWidget *parent, RecipeDB *db ) : DBListViewBase( parent,db,db->prepMethodCount())
{
connect( database, SIGNAL( prepMethodCreated( const Element & ) ), SLOT( checkCreatePrepMethod( const Element & ) ) );
connect( database, SIGNAL( prepMethodRemoved( int ) ), SLOT( removePrepMethod( int ) ) );
setAllColumnsShowFocus( true );
setDefaultRenameAction( QListView::Reject );
}
void PrepMethodListView::load( int limit, int offset )
{
ElementList prepMethodList;
database->loadPrepMethods( &prepMethodList, limit, offset );
setTotalItems(prepMethodList.count());
for ( ElementList::const_iterator ing_it = prepMethodList.begin(); ing_it != prepMethodList.end(); ++ing_it )
createPrepMethod( *ing_it );
}
void PrepMethodListView::checkCreatePrepMethod( const Element &el )
{
if ( handleElement(el.name) ) { //only create this prep method if the base class okays it
createPrepMethod(el);
}
}
StdPrepMethodListView::StdPrepMethodListView( QWidget *parent, RecipeDB *db, bool editable ) : PrepMethodListView( parent, db )
{
addColumn( i18n( "Preparation Method" ) );
KConfig * config = KGlobal::config();
config->setGroup( "Advanced" );
bool show_id = config->readBoolEntry( "ShowID", false );
addColumn( i18n( "Id" ), show_id ? -1 : 0 );
if ( editable ) {
setRenameable( 0, true );
KIconLoader *il = new KIconLoader;
kpop = new KPopupMenu( this );
kpop->insertItem( il->loadIcon( "filenew", KIcon::NoGroup, 16 ), i18n( "&Create" ), this, SLOT( createNew() ), CTRL + Key_C );
kpop->insertItem( il->loadIcon( "editdelete", KIcon::NoGroup, 16 ), i18n( "&Delete" ), this, SLOT( remove
() ), Key_Delete );
kpop->insertItem( il->loadIcon( "edit", KIcon::NoGroup, 16 ), i18n( "&Rename" ), this, SLOT( rename() ), CTRL + Key_R );
kpop->polish();
delete il;
connect( this, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ), SLOT( showPopup( KListView *, QListViewItem *, const QPoint & ) ) );
connect( this, SIGNAL( doubleClicked( QListViewItem* ) ), this, SLOT( modPrepMethod( QListViewItem* ) ) );
connect( this, SIGNAL( itemRenamed( QListViewItem* ) ), this, SLOT( savePrepMethod( QListViewItem* ) ) );
}
}
void StdPrepMethodListView::showPopup( KListView * /*l*/, QListViewItem *i, const QPoint &p )
{
if ( i )
kpop->exec( p );
}
void StdPrepMethodListView::createNew()
{
CreateElementDialog * elementDialog = new CreateElementDialog( this, i18n( "New Preparation Method" ) );
if ( elementDialog->exec() == QDialog::Accepted ) {
QString result = elementDialog->newElementName();
//check bounds first
if ( checkBounds( result ) )
database->createNewPrepMethod( result ); // Create the new prepMethod in the database
}
}
void StdPrepMethodListView::remove
()
{
QListViewItem * item = currentItem();
if ( item ) {
ElementList dependingRecipes;
int prepMethodID = item->text( 1 ).toInt();
database->findPrepMethodDependancies( prepMethodID, &dependingRecipes );
if ( dependingRecipes.isEmpty() )
database->removePrepMethod( prepMethodID );
else // Need Warning!
{
DependanciesDialog *warnDialog = new DependanciesDialog( this, &dependingRecipes );
if ( warnDialog->exec() == QDialog::Accepted )
database->removePrepMethod( prepMethodID );
delete warnDialog;
}
}
}
void StdPrepMethodListView::rename()
{
QListViewItem * item = currentItem();
if ( item )
PrepMethodListView::rename( item, 0 );
}
void StdPrepMethodListView::createPrepMethod( const Element &ing )
{
createElement(new QListViewItem( this, ing.name, QString::number( ing.id ) ));
}
void StdPrepMethodListView::removePrepMethod( int id )
{
QListViewItem * item = findItem( QString::number( id ), 1 );
removeElement(item);
}
void StdPrepMethodListView::modPrepMethod( QListViewItem* i )
{
if ( i )
PrepMethodListView::rename( i, 0 );
}
void StdPrepMethodListView::savePrepMethod( QListViewItem* i )
{
if ( !checkBounds( i->text( 0 ) ) ) {
reload(); //reset the changed text
return ;
}
int existing_id = database->findExistingPrepByName( i->text( 0 ) );
int prep_id = i->text( 1 ).toInt();
if ( existing_id != -1 && existing_id != prep_id ) //category already exists with this label... merge the two
{
switch ( KMessageBox::warningContinueCancel( this, i18n( "This preparation method already exists. Continuing will merge these two into one. Are you sure?" ) ) )
{
case KMessageBox::Continue: {
database->mergePrepMethods( existing_id, prep_id );
break;
}
default:
reload();
break;
}
}
else {
database->modPrepMethod( ( i->text( 1 ) ).toInt(), i->text( 0 ) );
}
}
bool StdPrepMethodListView::checkBounds( const QString &name )
{
if ( name.length() > database->maxPrepMethodNameLength() ) {
KMessageBox::error( this, QString( i18n( "Preparation method cannot be longer than %1 characters." ) ).arg( database->maxPrepMethodNameLength() ) );
return false;
}
return true;
}
#include "prepmethodlistview.moc"
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <aws/core/Aws.h>
#include <aws/core/config/AWSProfileConfigLoader.h>
#include <aws/core/utils/Outcome.h>
#include <aws/kinesis/KinesisClient.h>
#include <aws/kinesis/model/DescribeStreamRequest.h>
#include <aws/kinesis/model/GetRecordsRequest.h>
#include <aws/kinesis/model/GetShardIteratorRequest.h>
#include <aws/kinesis/model/PutRecordsRequest.h>
#include <aws/kinesis/model/ShardIteratorType.h>
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/platform/s3/aws_crypto.h"
namespace tensorflow {
namespace {
Aws::Client::ClientConfiguration* InitializeDefaultClientConfig() {
static Aws::Client::ClientConfiguration config;
const char* endpoint = getenv("KINESIS_ENDPOINT");
if (endpoint) {
config.endpointOverride = Aws::String(endpoint);
}
const char* region = getenv("AWS_REGION");
if (region) {
config.region = Aws::String(region);
} else {
// Load config file (e.g., ~/.aws/config) only if AWS_SDK_LOAD_CONFIG
// is set with a truthy value.
const char* load_config_env = getenv("AWS_SDK_LOAD_CONFIG");
string load_config =
load_config_env ? str_util::Lowercase(load_config_env) : "";
if (load_config == "true" || load_config == "1") {
Aws::String config_file;
// If AWS_CONFIG_FILE is set then use it, otherwise use ~/.aws/config.
const char* config_file_env = getenv("AWS_CONFIG_FILE");
if (config_file_env) {
config_file = config_file_env;
} else {
const char* home_env = getenv("HOME");
if (home_env) {
config_file = home_env;
config_file += "/.aws/config";
}
}
Aws::Config::AWSConfigFileProfileConfigLoader loader(config_file);
// Load the configuration. If successful, get the region.
// If the load is not successful, then generate a warning.
if (loader.Load()) {
auto profiles = loader.GetProfiles();
if (!profiles["default"].GetRegion().empty()) {
config.region = profiles["default"].GetRegion();
}
} else {
LOG(WARNING) << "Failed to load the profile in " << config_file << ".";
}
}
}
const char* use_https = getenv("KINESIS_USE_HTTPS");
if (use_https) {
if (use_https[0] == '0') {
config.scheme = Aws::Http::Scheme::HTTP;
} else {
config.scheme = Aws::Http::Scheme::HTTPS;
}
}
const char* verify_ssl = getenv("KINESIS_VERIFY_SSL");
if (verify_ssl) {
if (verify_ssl[0] == '0') {
config.verifySSL = false;
} else {
config.verifySSL = true;
}
}
const char* connect_timeout = getenv("KINESIS_CONNECT_TIMEOUT_MSEC");
if (connect_timeout) {
int64 timeout;
if (strings::safe_strto64(connect_timeout, &timeout)) {
config.connectTimeoutMs = timeout;
}
}
const char* request_timeout = getenv("KINESIS_REQUEST_TIMEOUT_MSEC");
if (request_timeout) {
int64 timeout;
if (strings::safe_strto64(request_timeout, &timeout)) {
config.requestTimeoutMs = timeout;
}
}
return &config;
}
Aws::Client::ClientConfiguration& GetDefaultClientConfig() {
static Aws::Client::ClientConfiguration* config =
InitializeDefaultClientConfig();
return *config;
}
static mutex mu(LINKER_INITIALIZED);
static unsigned count(0);
void AwsInitAPI() {
mutex_lock lock(mu);
count++;
if (count == 1) {
Aws::SDKOptions options;
options.cryptoOptions.sha256Factory_create_fn = []() {
return Aws::MakeShared<AWSSHA256Factory>(AWSCryptoAllocationTag);
};
options.cryptoOptions.sha256HMACFactory_create_fn = []() {
return Aws::MakeShared<AWSSHA256HmacFactory>(AWSCryptoAllocationTag);
};
Aws::InitAPI(options);
}
}
void AwsShutdownAPI() {
mutex_lock lock(mu);
count--;
if (count == 0) {
Aws::SDKOptions options;
Aws::ShutdownAPI(options);
}
}
void ShutdownClient(Aws::Kinesis::KinesisClient* client) {
if (client != nullptr) {
delete client;
AwsShutdownAPI();
}
}
}
class KinesisDatasetOp : public DatasetOpKernel {
public:
using DatasetOpKernel::DatasetOpKernel;
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
std::string stream = "";
OP_REQUIRES_OK(ctx,
ParseScalarArgument<std::string>(ctx, "stream", &stream));
std::string shard = "";
OP_REQUIRES_OK(ctx, ParseScalarArgument<std::string>(ctx, "shard", &shard));
bool read_indefinitely = true;
OP_REQUIRES_OK(ctx, ParseScalarArgument<bool>(ctx, "read_indefinitely",
&read_indefinitely));
int64 interval = -1;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, "interval", &interval));
OP_REQUIRES(ctx, (interval > 0),
errors::InvalidArgument(
"Interval value should be large than 0, got ", interval));
*output = new Dataset(ctx, stream, shard, read_indefinitely, interval);
}
private:
class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const string& stream, const string& shard,
const bool read_indefinitely, const int64 interval)
: DatasetBase(DatasetContext(ctx)),
stream_(stream),
shard_(shard),
read_indefinitely_(read_indefinitely),
interval_(interval) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, strings::StrCat(prefix, "::Kinesis")}));
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override { return "KinesisDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* stream = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(stream_, &stream));
Node* shard = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(shard_, &shard));
Node* read_indefinitely = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(read_indefinitely_, &read_indefinitely));
Node* interval = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(interval_, &interval));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {stream, shard, read_indefinitely, interval}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
client_(nullptr, ShutdownClient) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (iterator_ == "") {
TF_RETURN_IF_ERROR(SetupStreamsLocked());
}
do {
Aws::Kinesis::Model::GetRecordsRequest request;
auto outcome = client_->GetRecords(
request.WithShardIterator(iterator_).WithLimit(1));
if (!outcome.IsSuccess()) {
return errors::Unknown(outcome.GetError().GetExceptionName(), ": ",
outcome.GetError().GetMessage());
}
if (outcome.GetResult().GetRecords().size() == 0) {
// If no records were returned then nothing is available at the
// moment.
if (!dataset()->read_indefinitely_) {
*end_of_sequence = true;
return Status::OK();
}
// Continue the loop after a period of time.
ctx->env()->SleepForMicroseconds(dataset()->interval_);
continue;
}
if (outcome.GetResult().GetRecords().size() != 1) {
return errors::Unknown("invalid number of records ",
outcome.GetResult().GetRecords().size(),
" returned");
}
iterator_ = outcome.GetResult().GetNextShardIterator();
const auto& data = outcome.GetResult().GetRecords()[0].GetData();
StringPiece value(
reinterpret_cast<const char*>(data.GetUnderlyingData()),
data.GetLength());
Tensor value_tensor(ctx->allocator({}), DT_STRING, {});
value_tensor.scalar<std::string>()() = std::string(value);
out_tensors->emplace_back(std::move(value_tensor));
*end_of_sequence = false;
return Status::OK();
} while (true);
}
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
return errors::Unimplemented("SaveInternal is currently not supported");
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
return errors::Unimplemented(
"RestoreInternal is currently not supported");
}
private:
// Sets up Kinesis streams to read from.
Status SetupStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
AwsInitAPI();
client_.reset(
new Aws::Kinesis::KinesisClient(GetDefaultClientConfig()));
Aws::Kinesis::Model::DescribeStreamRequest request;
auto outcome = client_->DescribeStream(
request.WithStreamName(dataset()->stream_.c_str()));
if (!outcome.IsSuccess()) {
return errors::Unknown(outcome.GetError().GetExceptionName(), ": ",
outcome.GetError().GetMessage());
}
Aws::String shard;
Aws::String sequence;
if (dataset()->shard_ == "") {
if (outcome.GetResult().GetStreamDescription().GetShards().size() !=
1) {
return errors::InvalidArgument(
"shard has to be provided unless the stream only have one "
"shard, there are ",
outcome.GetResult().GetStreamDescription().GetShards().size(),
" shards in stream ", dataset()->stream_);
}
shard = outcome.GetResult()
.GetStreamDescription()
.GetShards()[0]
.GetShardId();
sequence = outcome.GetResult()
.GetStreamDescription()
.GetShards()[0]
.GetSequenceNumberRange()
.GetStartingSequenceNumber();
} else {
for (const auto& entry :
outcome.GetResult().GetStreamDescription().GetShards()) {
if (entry.GetShardId() == dataset()->shard_.c_str()) {
shard = entry.GetShardId();
sequence =
entry.GetSequenceNumberRange().GetStartingSequenceNumber();
break;
}
}
if (shard == "") {
return errors::InvalidArgument("no shard ", dataset()->shard_,
" in stream ", dataset()->stream_);
}
}
Aws::Kinesis::Model::GetShardIteratorRequest iterator_request;
auto iterator_outcome = client_->GetShardIterator(
iterator_request.WithStreamName(dataset()->stream_.c_str())
.WithShardId(shard)
.WithShardIteratorType(
Aws::Kinesis::Model::ShardIteratorType::AT_SEQUENCE_NUMBER)
.WithStartingSequenceNumber(sequence));
if (!iterator_outcome.IsSuccess()) {
return errors::Unknown(iterator_outcome.GetError().GetExceptionName(),
": ",
iterator_outcome.GetError().GetMessage());
}
iterator_ = iterator_outcome.GetResult().GetShardIterator();
return Status::OK();
}
mutex mu_;
Aws::String iterator_ GUARDED_BY(mu_);
std::unique_ptr<Aws::Kinesis::KinesisClient, decltype(&ShutdownClient)>
client_ GUARDED_BY(mu_);
};
const std::string stream_;
const std::string shard_;
const bool read_indefinitely_;
const int64 interval_;
};
};
REGISTER_KERNEL_BUILDER(Name("KinesisDataset").Device(DEVICE_CPU),
KinesisDatasetOp);
} // namespace tensorflow
<commit_msg>Rework on AWS crypto<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <aws/core/Aws.h>
#include <aws/core/config/AWSProfileConfigLoader.h>
#include <aws/core/utils/crypto/Factories.h>
#include <aws/core/utils/crypto/HMAC.h>
#include <aws/core/utils/crypto/Hash.h>
#include <aws/core/utils/crypto/HashResult.h>
#include <aws/core/utils/Outcome.h>
#include <aws/kinesis/KinesisClient.h>
#include <aws/kinesis/model/DescribeStreamRequest.h>
#include <aws/kinesis/model/GetRecordsRequest.h>
#include <aws/kinesis/model/GetShardIteratorRequest.h>
#include <aws/kinesis/model/PutRecordsRequest.h>
#include <aws/kinesis/model/ShardIteratorType.h>
#include "tensorflow/core/framework/dataset.h"
namespace tensorflow {
namespace {
static const char* AWSCryptoAllocationTag = "AWSCryptoAllocation";
class AWSSHA256Factory : public Aws::Utils::Crypto::HashFactory {
public:
std::shared_ptr<Aws::Utils::Crypto::Hash> CreateImplementation()
const override;
};
class AWSSHA256HmacFactory : public Aws::Utils::Crypto::HMACFactory {
public:
std::shared_ptr<Aws::Utils::Crypto::HMAC> CreateImplementation()
const override;
};
class AWSSha256HMACOpenSSLImpl : public Aws::Utils::Crypto::HMAC {
public:
AWSSha256HMACOpenSSLImpl() {}
virtual ~AWSSha256HMACOpenSSLImpl() = default;
virtual Aws::Utils::Crypto::HashResult Calculate(
const Aws::Utils::ByteBuffer& toSign,
const Aws::Utils::ByteBuffer& secret) override {
unsigned int length = SHA256_DIGEST_LENGTH;
Aws::Utils::ByteBuffer digest(length);
memset(digest.GetUnderlyingData(), 0, length);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, secret.GetUnderlyingData(),
static_cast<int>(secret.GetLength()), EVP_sha256(), NULL);
HMAC_Update(&ctx, toSign.GetUnderlyingData(), toSign.GetLength());
HMAC_Final(&ctx, digest.GetUnderlyingData(), &length);
HMAC_CTX_cleanup(&ctx);
return Aws::Utils::Crypto::HashResult(std::move(digest));
}
};
class AWSSha256OpenSSLImpl : public Aws::Utils::Crypto::Hash {
public:
AWSSha256OpenSSLImpl() {}
virtual ~AWSSha256OpenSSLImpl() = default;
virtual Aws::Utils::Crypto::HashResult Calculate(
const Aws::String& str) override {
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.data(), str.size());
Aws::Utils::ByteBuffer hash(SHA256_DIGEST_LENGTH);
SHA256_Final(hash.GetUnderlyingData(), &sha256);
return Aws::Utils::Crypto::HashResult(std::move(hash));
}
virtual Aws::Utils::Crypto::HashResult Calculate(
Aws::IStream& stream) override {
SHA256_CTX sha256;
SHA256_Init(&sha256);
auto currentPos = stream.tellg();
if (currentPos == std::streampos(std::streamoff(-1))) {
currentPos = 0;
stream.clear();
}
stream.seekg(0, stream.beg);
char streamBuffer
[Aws::Utils::Crypto::Hash::INTERNAL_HASH_STREAM_BUFFER_SIZE];
while (stream.good()) {
stream.read(streamBuffer,
Aws::Utils::Crypto::Hash::INTERNAL_HASH_STREAM_BUFFER_SIZE);
auto bytesRead = stream.gcount();
if (bytesRead > 0) {
SHA256_Update(&sha256, streamBuffer, static_cast<size_t>(bytesRead));
}
}
stream.clear();
stream.seekg(currentPos, stream.beg);
Aws::Utils::ByteBuffer hash(SHA256_DIGEST_LENGTH);
SHA256_Final(hash.GetUnderlyingData(), &sha256);
return Aws::Utils::Crypto::HashResult(std::move(hash));
}
};
std::shared_ptr<Aws::Utils::Crypto::Hash>
AWSSHA256Factory::CreateImplementation() const {
return Aws::MakeShared<AWSSha256OpenSSLImpl>(AWSCryptoAllocationTag);
}
std::shared_ptr<Aws::Utils::Crypto::HMAC>
AWSSHA256HmacFactory::CreateImplementation() const {
return Aws::MakeShared<AWSSha256HMACOpenSSLImpl>(AWSCryptoAllocationTag);
}
Aws::Client::ClientConfiguration* InitializeDefaultClientConfig() {
static Aws::Client::ClientConfiguration config;
const char* endpoint = getenv("KINESIS_ENDPOINT");
if (endpoint) {
config.endpointOverride = Aws::String(endpoint);
}
const char* region = getenv("AWS_REGION");
if (region) {
config.region = Aws::String(region);
} else {
// Load config file (e.g., ~/.aws/config) only if AWS_SDK_LOAD_CONFIG
// is set with a truthy value.
const char* load_config_env = getenv("AWS_SDK_LOAD_CONFIG");
string load_config =
load_config_env ? str_util::Lowercase(load_config_env) : "";
if (load_config == "true" || load_config == "1") {
Aws::String config_file;
// If AWS_CONFIG_FILE is set then use it, otherwise use ~/.aws/config.
const char* config_file_env = getenv("AWS_CONFIG_FILE");
if (config_file_env) {
config_file = config_file_env;
} else {
const char* home_env = getenv("HOME");
if (home_env) {
config_file = home_env;
config_file += "/.aws/config";
}
}
Aws::Config::AWSConfigFileProfileConfigLoader loader(config_file);
// Load the configuration. If successful, get the region.
// If the load is not successful, then generate a warning.
if (loader.Load()) {
auto profiles = loader.GetProfiles();
if (!profiles["default"].GetRegion().empty()) {
config.region = profiles["default"].GetRegion();
}
} else {
LOG(WARNING) << "Failed to load the profile in " << config_file << ".";
}
}
}
const char* use_https = getenv("KINESIS_USE_HTTPS");
if (use_https) {
if (use_https[0] == '0') {
config.scheme = Aws::Http::Scheme::HTTP;
} else {
config.scheme = Aws::Http::Scheme::HTTPS;
}
}
const char* verify_ssl = getenv("KINESIS_VERIFY_SSL");
if (verify_ssl) {
if (verify_ssl[0] == '0') {
config.verifySSL = false;
} else {
config.verifySSL = true;
}
}
const char* connect_timeout = getenv("KINESIS_CONNECT_TIMEOUT_MSEC");
if (connect_timeout) {
int64 timeout;
if (strings::safe_strto64(connect_timeout, &timeout)) {
config.connectTimeoutMs = timeout;
}
}
const char* request_timeout = getenv("KINESIS_REQUEST_TIMEOUT_MSEC");
if (request_timeout) {
int64 timeout;
if (strings::safe_strto64(request_timeout, &timeout)) {
config.requestTimeoutMs = timeout;
}
}
return &config;
}
Aws::Client::ClientConfiguration& GetDefaultClientConfig() {
static Aws::Client::ClientConfiguration* config =
InitializeDefaultClientConfig();
return *config;
}
static mutex mu(LINKER_INITIALIZED);
static unsigned count(0);
void AwsInitAPI() {
mutex_lock lock(mu);
count++;
if (count == 1) {
Aws::SDKOptions options;
options.cryptoOptions.sha256Factory_create_fn = []() {
return Aws::MakeShared<AWSSHA256Factory>(AWSCryptoAllocationTag);
};
options.cryptoOptions.sha256HMACFactory_create_fn = []() {
return Aws::MakeShared<AWSSHA256HmacFactory>(AWSCryptoAllocationTag);
};
Aws::InitAPI(options);
}
}
void AwsShutdownAPI() {
mutex_lock lock(mu);
count--;
if (count == 0) {
Aws::SDKOptions options;
Aws::ShutdownAPI(options);
}
}
void ShutdownClient(Aws::Kinesis::KinesisClient* client) {
if (client != nullptr) {
delete client;
AwsShutdownAPI();
}
}
}
class KinesisDatasetOp : public DatasetOpKernel {
public:
using DatasetOpKernel::DatasetOpKernel;
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
std::string stream = "";
OP_REQUIRES_OK(ctx,
ParseScalarArgument<std::string>(ctx, "stream", &stream));
std::string shard = "";
OP_REQUIRES_OK(ctx, ParseScalarArgument<std::string>(ctx, "shard", &shard));
bool read_indefinitely = true;
OP_REQUIRES_OK(ctx, ParseScalarArgument<bool>(ctx, "read_indefinitely",
&read_indefinitely));
int64 interval = -1;
OP_REQUIRES_OK(ctx, ParseScalarArgument<int64>(ctx, "interval", &interval));
OP_REQUIRES(ctx, (interval > 0),
errors::InvalidArgument(
"Interval value should be large than 0, got ", interval));
*output = new Dataset(ctx, stream, shard, read_indefinitely, interval);
}
private:
class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const string& stream, const string& shard,
const bool read_indefinitely, const int64 interval)
: DatasetBase(DatasetContext(ctx)),
stream_(stream),
shard_(shard),
read_indefinitely_(read_indefinitely),
interval_(interval) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(
new Iterator({this, strings::StrCat(prefix, "::Kinesis")}));
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override { return "KinesisDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* stream = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(stream_, &stream));
Node* shard = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(shard_, &shard));
Node* read_indefinitely = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(read_indefinitely_, &read_indefinitely));
Node* interval = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(interval_, &interval));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {stream, shard, read_indefinitely, interval}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
client_(nullptr, ShutdownClient) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (iterator_ == "") {
TF_RETURN_IF_ERROR(SetupStreamsLocked());
}
do {
Aws::Kinesis::Model::GetRecordsRequest request;
auto outcome = client_->GetRecords(
request.WithShardIterator(iterator_).WithLimit(1));
if (!outcome.IsSuccess()) {
return errors::Unknown(outcome.GetError().GetExceptionName(), ": ",
outcome.GetError().GetMessage());
}
if (outcome.GetResult().GetRecords().size() == 0) {
// If no records were returned then nothing is available at the
// moment.
if (!dataset()->read_indefinitely_) {
*end_of_sequence = true;
return Status::OK();
}
// Continue the loop after a period of time.
ctx->env()->SleepForMicroseconds(dataset()->interval_);
continue;
}
if (outcome.GetResult().GetRecords().size() != 1) {
return errors::Unknown("invalid number of records ",
outcome.GetResult().GetRecords().size(),
" returned");
}
iterator_ = outcome.GetResult().GetNextShardIterator();
const auto& data = outcome.GetResult().GetRecords()[0].GetData();
StringPiece value(
reinterpret_cast<const char*>(data.GetUnderlyingData()),
data.GetLength());
Tensor value_tensor(ctx->allocator({}), DT_STRING, {});
value_tensor.scalar<std::string>()() = std::string(value);
out_tensors->emplace_back(std::move(value_tensor));
*end_of_sequence = false;
return Status::OK();
} while (true);
}
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
return errors::Unimplemented("SaveInternal is currently not supported");
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
return errors::Unimplemented(
"RestoreInternal is currently not supported");
}
private:
// Sets up Kinesis streams to read from.
Status SetupStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
AwsInitAPI();
client_.reset(
new Aws::Kinesis::KinesisClient(GetDefaultClientConfig()));
Aws::Kinesis::Model::DescribeStreamRequest request;
auto outcome = client_->DescribeStream(
request.WithStreamName(dataset()->stream_.c_str()));
if (!outcome.IsSuccess()) {
return errors::Unknown(outcome.GetError().GetExceptionName(), ": ",
outcome.GetError().GetMessage());
}
Aws::String shard;
Aws::String sequence;
if (dataset()->shard_ == "") {
if (outcome.GetResult().GetStreamDescription().GetShards().size() !=
1) {
return errors::InvalidArgument(
"shard has to be provided unless the stream only have one "
"shard, there are ",
outcome.GetResult().GetStreamDescription().GetShards().size(),
" shards in stream ", dataset()->stream_);
}
shard = outcome.GetResult()
.GetStreamDescription()
.GetShards()[0]
.GetShardId();
sequence = outcome.GetResult()
.GetStreamDescription()
.GetShards()[0]
.GetSequenceNumberRange()
.GetStartingSequenceNumber();
} else {
for (const auto& entry :
outcome.GetResult().GetStreamDescription().GetShards()) {
if (entry.GetShardId() == dataset()->shard_.c_str()) {
shard = entry.GetShardId();
sequence =
entry.GetSequenceNumberRange().GetStartingSequenceNumber();
break;
}
}
if (shard == "") {
return errors::InvalidArgument("no shard ", dataset()->shard_,
" in stream ", dataset()->stream_);
}
}
Aws::Kinesis::Model::GetShardIteratorRequest iterator_request;
auto iterator_outcome = client_->GetShardIterator(
iterator_request.WithStreamName(dataset()->stream_.c_str())
.WithShardId(shard)
.WithShardIteratorType(
Aws::Kinesis::Model::ShardIteratorType::AT_SEQUENCE_NUMBER)
.WithStartingSequenceNumber(sequence));
if (!iterator_outcome.IsSuccess()) {
return errors::Unknown(iterator_outcome.GetError().GetExceptionName(),
": ",
iterator_outcome.GetError().GetMessage());
}
iterator_ = iterator_outcome.GetResult().GetShardIterator();
return Status::OK();
}
mutex mu_;
Aws::String iterator_ GUARDED_BY(mu_);
std::unique_ptr<Aws::Kinesis::KinesisClient, decltype(&ShutdownClient)>
client_ GUARDED_BY(mu_);
};
const std::string stream_;
const std::string shard_;
const bool read_indefinitely_;
const int64 interval_;
};
};
REGISTER_KERNEL_BUILDER(Name("KinesisDataset").Device(DEVICE_CPU),
KinesisDatasetOp);
} // namespace tensorflow
<|endoftext|>
|
<commit_before><commit_msg>sal_Bool -> bool in address.cxx<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optutil.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2006-08-04 12:12: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_sc.hxx"
#include <vcl/svapp.hxx>
#include "optutil.hxx"
#include "global.hxx" // for pSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
//------------------------------------------------------------------
// static
BOOL ScOptionsUtil::IsMetricSystem()
{
//! which language should be used here - system language or installed office language?
// MeasurementSystem eSys = Application::GetAppInternational().GetMeasurementSystem();
MeasurementSystem eSys = ScGlobal::pLocaleData->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
//------------------------------------------------------------------
ScLinkConfigItem::ScLinkConfigItem( const rtl::OUString rSubTree ) :
ConfigItem( rSubTree )
{
}
ScLinkConfigItem::ScLinkConfigItem( const rtl::OUString rSubTree, sal_Int16 nMode ) :
ConfigItem( rSubTree, nMode )
{
}
void ScLinkConfigItem::SetCommitLink( const Link& rLink )
{
aCommitLink = rLink;
}
void ScLinkConfigItem::Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames )
{
//! not implemented yet...
}
void ScLinkConfigItem::Commit()
{
aCommitLink.Call( this );
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.7.88); FILE MERGED 2006/11/28 13:24:48 nn 1.7.88.1: #i69284# warning-free: core, wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optutil.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:17:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <vcl/svapp.hxx>
#include "optutil.hxx"
#include "global.hxx" // for pSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
//------------------------------------------------------------------
// static
BOOL ScOptionsUtil::IsMetricSystem()
{
//! which language should be used here - system language or installed office language?
// MeasurementSystem eSys = Application::GetAppInternational().GetMeasurementSystem();
MeasurementSystem eSys = ScGlobal::pLocaleData->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
//------------------------------------------------------------------
ScLinkConfigItem::ScLinkConfigItem( const rtl::OUString rSubTree ) :
ConfigItem( rSubTree )
{
}
ScLinkConfigItem::ScLinkConfigItem( const rtl::OUString rSubTree, sal_Int16 nMode ) :
ConfigItem( rSubTree, nMode )
{
}
void ScLinkConfigItem::SetCommitLink( const Link& rLink )
{
aCommitLink = rLink;
}
void ScLinkConfigItem::Notify( const com::sun::star::uno::Sequence<rtl::OUString>& /* aPropertyNames */ )
{
//! not implemented yet...
}
void ScLinkConfigItem::Commit()
{
aCommitLink.Call( this );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xelink.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-11-05 13:40:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XELINK_HXX
#define SC_XELINK_HXX
#ifndef SC_MARKDATA_HXX
#include "markdata.hxx"
#endif
#ifndef SC_XLLINK_HXX
#include "xllink.hxx"
#endif
#ifndef SC_XEHELPER_HXX
#include "xehelper.hxx"
#endif
#ifndef SC_XERECORD_HXX
#include "xerecord.hxx"
#endif
class ScRange;
struct SingleRefData;
/* ============================================================================
Classes for export of different kinds of internal/external references.
- 3D cell and cell range links
- External cell and cell range links
- Internal and external defined names
- Add-in functions
- DDE links
- OLE object links
============================================================================ */
// Excel sheet indexes ========================================================
typedef ::std::vector< ::std::pair< sal_uInt16, sal_uInt16 > > XclExpRefLogVec;
/** Stores the correct Excel sheet index for each Calc sheet.
@descr The class knows all sheets which will not exported
(i.e. external link sheets, scenario sheets). */
class XclExpTabIdBuffer
{
public:
/** Initializes the complete buffer from the passed document. */
explicit XclExpTabIdBuffer( ScDocument& rDoc );
/** Returns true, if the specified Calc sheet is used to store external cell contents. */
bool IsExternal( sal_uInt16 nScTab ) const;
/** Returns true, if the specified Calc sheet has to be exported. */
bool IsExportTable( sal_uInt16 nScTab ) const;
/** Returns the Excel sheet index for a given Calc sheet. */
sal_uInt16 GetXclTab( sal_uInt16 nScTab ) const;
/** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. */
sal_uInt16 GetRealScTab( sal_uInt16 nSortedTab ) const;
/** Returns the index of the passed Calc sheet in the sorted sheet names list. */
sal_uInt16 GetSortedScTab( sal_uInt16 nScTab ) const;
/** Returns the number of Calc sheets. */
inline sal_uInt16 GetScTabCount() const { return mnScCnt; }
/** Returns the number of Excel sheets to be exported. */
inline sal_uInt16 GetXclTabCount() const { return mnXclCnt; }
/** Returns the number of external linked sheets (in Calc). */
inline sal_uInt16 GetExternTabCount() const { return mnExtCnt; }
/** Returns the number of codepages (VBA modules). */
inline sal_uInt16 GetCodenameCount() const { return mnCodeCnt; }
/** Returns the maximum number of Calc sheets and codepages. */
inline sal_uInt16 GetMaxScTabCount() const { return ::std::max( mnScCnt, mnCodeCnt ); }
// *** for change tracking ***
/** Enables logging of Excel sheet indexes in each 3D-reference. */
void StartRefLog();
/** Appends sheet index pair (called by formula compiler). */
void AppendTabRef( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );
/** Disables logging of Excel sheet indexes. */
const XclExpRefLogVec& EndRefLog();
private:
/** Searches for sheets not to be exported. */
void CalcXclIndexes();
/** Sorts the names of all tables and stores the indexes of the sorted indexes. */
void CalcSortedIndexes( ScDocument& rDoc );
private:
typedef ::std::vector< ::std::pair< sal_uInt16, sal_uInt8 > > IndexEntryVec;
IndexEntryVec maIndexVec; /// Array of sheet index information.
sal_uInt16 mnScCnt; /// Count of Calc sheets.
sal_uInt16 mnXclCnt; /// Count of Excel sheets to be exported.
sal_uInt16 mnExtCnt; /// Count of external link sheets (in Calc).
sal_uInt16 mnCodeCnt; /// Count of codepages.
ScfUInt16Vec maFromSortedVec; /// Sorted index -> real index.
ScfUInt16Vec maToSortedVec; /// Real index -> sorted index.
XclExpRefLogVec maRefLog; /// A log for each requested Excel sheet index.
bool mbEnableLog; /// true = log all sheet indexes (for formula compiler).
};
// Export link manager ========================================================
class XclExpLinkManager_Impl;
/** Stores all EXTERNSHEET and SUPBOOK record data.
@descr This is the central class for export of all external references.
File contents in BIFF8:
- Record SUPBOOK: Contains the name of an external workbook and the names of its sheets.
This record is followed by EXTERNNAME, XCT and CRN records.
- Record XCT: Contains the sheet index of the following CRN records.
- Record CRN: Contains addresses (row and column) and values of external referenced cells.
- Record NAME: Contains defined names of the own workbook. This record follows the
EXTERNSHEET record.
- Record EXTERNNAME: Contains external defined names or DDE links or OLE object links.
- Record EXTERNSHEET: Contains indexes to URLs of external documents (SUPBOOKs)
and sheet indexes for each external reference used anywhere in the workbook.
This record follows a list of SUPBOOK records.
*/
class XclExpLinkManager : public XclExpRecordBase
{
public:
explicit XclExpLinkManager( const XclExpRoot& rRoot );
virtual ~XclExpLinkManager();
/** Searches for XTI structure with the given Excel sheet range. Adds new XTI if not found.
@return The list index of the XTI structure. */
sal_uInt16 FindXti( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );
/** Returns the external document URL of the specified Excel sheet. */
const XclExpString* GetUrl( sal_uInt16 nXclTab ) const;
/** Returns the external sheet name of the specified Excel sheet. */
const XclExpString* GetTableName( sal_uInt16 nXclTab ) const;
/** Stores the cell with the given address in a CRN record list. */
void StoreCellCont( const SingleRefData& rRef );
/** Stores all cells in the given range in a CRN record list. */
void StoreCellRange( const SingleRefData& rRef1, const SingleRefData& rRef2 );
/** Finds or inserts an EXTERNNAME record for an add-in function name.
@param rnXti Returns the index of the XTI structure which contains the add-in function name.
@param rnExtName Returns the 1-based EXTERNNAME record index. */
void InsertAddIn(
sal_uInt16& rnXti, sal_uInt16& rnExtName,
const String& rName );
/** Finds or inserts an EXTERNNAME record for DDE links.
@param rnXti Returns the index of the XTI structure which contains the DDE link.
@param rnExtName Returns the 1-based EXTERNNAME record index. */
bool InsertDde(
sal_uInt16& rnXti, sal_uInt16& rnExtName,
const String& rApplic, const String& rTopic, const String& rItem );
/** Writes the entire Link table. */
virtual void Save( XclExpStream& rStrm );
private:
typedef ::std::auto_ptr< XclExpLinkManager_Impl > XclExpLinkManager_ImplPtr;
XclExpLinkManager_ImplPtr mpImpl;
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS calc18 (1.4.112); FILE MERGED 2003/11/18 10:30:18 dr 1.4.112.3: #113975# type correctness for Excel/Calc cell address components 2003/11/07 09:17:07 dr 1.4.112.2: RESYNC: (1.4-1.5); FILE MERGED 2003/11/05 08:47:33 dr 1.4.112.1: #112908# visible/selected sheet handling; ScExtDocOptions to XclRoot<commit_after>/*************************************************************************
*
* $RCSfile: xelink.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-03-02 09:43:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XELINK_HXX
#define SC_XELINK_HXX
#ifndef SC_MARKDATA_HXX
#include "markdata.hxx"
#endif
#ifndef SC_XLLINK_HXX
#include "xllink.hxx"
#endif
#ifndef SC_XEHELPER_HXX
#include "xehelper.hxx"
#endif
#ifndef SC_XERECORD_HXX
#include "xerecord.hxx"
#endif
class ScRange;
struct SingleRefData;
/* ============================================================================
Classes for export of different kinds of internal/external references.
- 3D cell and cell range links
- External cell and cell range links
- Internal and external defined names
- Add-in functions
- DDE links
- OLE object links
============================================================================ */
// Excel sheet indexes ========================================================
typedef ::std::pair< sal_uInt16, sal_uInt16 > XclExpRefLogEntry;
typedef ::std::vector< XclExpRefLogEntry > XclExpRefLogVec;
/** Stores the correct Excel sheet index for each Calc sheet.
@descr The class knows all sheets which will not exported
(i.e. external link sheets, scenario sheets). */
class XclExpTabInfo
{
public:
/** Initializes the complete buffer from the current exported document. */
explicit XclExpTabInfo( const XclExpRoot& rRoot );
/** Returns true, if the specified Calc sheet will be exported. */
bool IsExportTab( USHORT nScTab ) const;
/** Returns true, if the specified Calc sheet is used to store external cell contents. */
bool IsExternalTab( USHORT nScTab ) const;
/** Returns true, if the specified Calc sheet is visible and will be exported. */
bool IsVisibleTab( USHORT nScTab ) const;
/** Returns true, if the specified Calc sheet is selected and will be exported. */
bool IsSelectedTab( USHORT nScTab ) const;
/** Returns true, if the specified Calc sheet is the active displayed sheet. */
bool IsActiveTab( USHORT nScTab ) const;
/** Returns the Excel sheet index for a given Calc sheet. */
sal_uInt16 GetXclTab( USHORT nScTab ) const;
/** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. */
USHORT GetRealScTab( USHORT nSortedTab ) const;
/** Returns the index of the passed Calc sheet in the sorted sheet names list. */
USHORT GetSortedScTab( USHORT nScTab ) const;
/** Returns the number of Calc sheets. */
inline USHORT GetScTabCount() const { return mnScCnt; }
/** Returns the number of Excel sheets to be exported. */
inline sal_uInt16 GetXclTabCount() const { return mnXclCnt; }
/** Returns the number of external linked sheets. */
inline sal_uInt16 GetXclExtTabCount() const { return mnXclExtCnt; }
/** Returns the number of codepages (VBA modules). */
inline sal_uInt16 GetXclCodenameCount() const { return mnXclCodeCnt; }
/** Returns the number of exported selected sheets. */
inline sal_uInt16 GetXclSelectedCount() const { return mnXclSelected; }
/** Returns the Excel index of the active, displayed sheet. */
inline sal_uInt16 GetXclActiveTab() const { return mnXclActive; }
/** Returns the Excel index of the first visible sheet. */
inline sal_uInt16 GetXclFirstVisTab() const { return mnXclFirstVis; }
// *** for change tracking ***
/** Enables logging of Excel sheet indexes in each 3D-reference. */
void StartRefLog();
/** Appends sheet index pair (called by formula compiler). */
void AppendTabRef( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );
/** Disables logging of Excel sheet indexes. */
const XclExpRefLogVec& EndRefLog();
private:
/** Returns true, if any of the passed flags is set for the specified Calc sheet. */
bool GetFlag( USHORT nScTab, sal_uInt8 nFlags ) const;
/** Sets or clears (depending on bSet) all passed flags for the specified Calc sheet. */
void SetFlag( USHORT nScTab, sal_uInt8 nFlags, bool bSet = true );
/** Searches for sheets not to be exported. */
void CalcXclIndexes();
/** Sorts the names of all tables and stores the indexes of the sorted indexes. */
void CalcSortedIndexes( ScDocument& rDoc );
private:
typedef ::std::pair< sal_uInt16, sal_uInt8 > ScTabInfoEntry;
typedef ::std::vector< ScTabInfoEntry > ScTabInfoVec;
ScTabInfoVec maTabInfoVec; /// Array of Calc sheet index information.
USHORT mnScCnt; /// Count of Calc sheets.
sal_uInt16 mnXclCnt; /// Count of Excel sheets to be exported.
sal_uInt16 mnXclExtCnt; /// Count of external link sheets.
sal_uInt16 mnXclCodeCnt; /// Count of codepages.
sal_uInt16 mnXclSelected; /// Count of selected and exported sheets.
sal_uInt16 mnXclActive; /// Active (selected) sheet.
sal_uInt16 mnXclFirstVis; /// First visible sheet.
ScfUInt16Vec maFromSortedVec; /// Sorted index -> real index.
ScfUInt16Vec maToSortedVec; /// Real index -> sorted index.
XclExpRefLogVec maRefLog; /// A log for each requested Excel sheet index.
bool mbEnableLog; /// true = log all sheet indexes (for formula compiler).
};
// Export link manager ========================================================
class XclExpLinkManager_Impl;
/** Stores all data for internal/external references (the link table).
@descr Contents in BIFF8:
- Record SUPBOOK: Contains the name of an external workbook and the names of its sheets.
This record is followed by EXTERNNAME, XCT and CRN records.
- Record XCT: Contains the sheet index of the following CRN records.
- Record CRN: Contains addresses (row and column) and values of external referenced cells.
- Record NAME: Contains defined names of the own workbook. This record follows the
EXTERNSHEET record.
- Record EXTERNNAME: Contains external defined names or DDE links or OLE object links.
- Record EXTERNSHEET: Contains indexes to URLs of external documents (SUPBOOKs)
and sheet indexes for each external reference used anywhere in the workbook.
This record follows a list of SUPBOOK records (it is the last record of the link table).
*/
class XclExpLinkManager : public XclExpRecordBase
{
public:
explicit XclExpLinkManager( const XclExpRoot& rRoot );
virtual ~XclExpLinkManager();
/** Searches for XTI structure with the given Excel sheet range. Adds new XTI if not found.
@return The list index of the XTI structure. */
sal_uInt16 FindXti( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );
/** Returns the external document URL of the specified Excel sheet. */
const XclExpString* GetUrl( sal_uInt16 nXclTab ) const;
/** Returns the external sheet name of the specified Excel sheet. */
const XclExpString* GetTabName( sal_uInt16 nXclTab ) const;
/** Stores the cell with the given address in a CRN record list. */
void StoreCell( const SingleRefData& rRef );
/** Stores all cells in the given range in a CRN record list. */
void StoreCellRange( const SingleRefData& rRef1, const SingleRefData& rRef2 );
/** Finds or inserts an EXTERNNAME record for an add-in function name.
@param rnXti Returns the index of the XTI structure which contains the add-in function name.
@param rnExtName Returns the 1-based EXTERNNAME record index. */
void InsertAddIn(
sal_uInt16& rnXti, sal_uInt16& rnExtName,
const String& rName );
/** Finds or inserts an EXTERNNAME record for DDE links.
@param rnXti Returns the index of the XTI structure which contains the DDE link.
@param rnExtName Returns the 1-based EXTERNNAME record index. */
bool InsertDde(
sal_uInt16& rnXti, sal_uInt16& rnExtName,
const String& rApplic, const String& rTopic, const String& rItem );
/** Writes the entire Link table. */
virtual void Save( XclExpStream& rStrm );
private:
typedef ::std::auto_ptr< XclExpLinkManager_Impl > XclExpLinkManager_ImplPtr;
XclExpLinkManager_ImplPtr mpImpl;
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2003-08-07 15:30:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
// Global data ================================================================
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpTabIdBuffer;
class XclExpLinkManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ::std::auto_ptr< XclExpSst > XclExpSstPtr;
typedef ::std::auto_ptr< XclExpPalette > XclExpPalettePtr;
typedef ::std::auto_ptr< XclExpFontBuffer > XclExpFontBufferPtr;
typedef ::std::auto_ptr< XclExpNumFmtBuffer > XclExpNumFmtBufferPtr;
typedef ::std::auto_ptr< XclExpXFBuffer > XclExpXFBufferPtr;
typedef ::std::auto_ptr< XclExpTabIdBuffer > XclExpTabIdBufferPtr;
typedef ::std::auto_ptr< XclExpLinkManager > XclExpLinkManagerPtr;
XclExpSstPtr mpSst; /// The shared string table.
XclExpPalettePtr mpPalette; /// The color buffer.
XclExpFontBufferPtr mpFontBuffer; /// All fonts in the file.
XclExpNumFmtBufferPtr mpNumFmtBuffer; /// All number formats in the file.
XclExpXFBufferPtr mpXFBuffer; /// All XF records in the file.
XclExpTabIdBufferPtr mpTabIdBuffer; /// Calc->Excel sheet index conversion.
XclExpLinkManagerPtr mpLinkManager; /// Manager for internal/external links.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData(
XclBiff eBiff,
ScDocument& rDocument,
const String& rDocUrl,
CharSet eCharSet,
bool bRelUrl );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
public:
XclExpRoot( const XclExpRoot& rRoot );
XclExpRoot& operator=( const XclExpRoot& rRoot );
/** Returns this root instance - for code readability in derived classes. */
inline const XclExpRoot& GetRoot() const { return *this; }
/** Returns true, if URLs should be stored relative to the document location. */
inline bool IsRelUrl() const { return mrExpData.mbRelUrl; }
/** Returns the shared string table. */
XclExpSst& GetSst() const;
/** Returns the color buffer. */
XclExpPalette& GetPalette() const;
/** Returns the font buffer. */
XclExpFontBuffer& GetFontBuffer() const;
/** Returns the number format buffer. */
XclExpNumFmtBuffer& GetNumFmtBuffer() const;
/** Returns the cell formatting attributes buffer. */
XclExpXFBuffer& GetXFBuffer() const;
/** Returns the buffer for Calc->Excel sheet index conversion. */
XclExpTabIdBuffer& GetTabIdBuffer() const;
/** Returns the link manager. */
XclExpLinkManager& GetLinkManager() const;
/** Returns the Excel add-in function name for a Calc function name. */
String GetXclAddInName( const String& rScName ) const;
/** Checks if the passed cell address is a valid Excel cell position.
@descr See XclRoot::CheckCellAddress for details. */
bool CheckCellAddress( const ScAddress& rPos ) const;
/** Checks and eventually crops the cell range to valid Excel dimensions.
@descr See XclRoot::CheckCellRange for details. */
bool CheckCellRange( ScRange& rRange ) const;
/** Checks and eventually crops the cell ranges to valid Excel dimensions.
@descr See XclRoot::CheckCellRangeList for details. */
void CheckCellRangeList( ScRangeList& rRanges ) const;
protected:
explicit XclExpRoot( XclExpRootData& rExpRootData );
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS calc17 (1.6.4); FILE MERGED 2003/10/02 13:06:12 dr 1.6.4.1: #101529# new NAME import, update of imp/exp link managers<commit_after>/*************************************************************************
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2003-11-05 13:40:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
// Global data ================================================================
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpTabIdBuffer;
class XclExpLinkManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ::std::auto_ptr< XclExpSst > XclExpSstPtr;
typedef ::std::auto_ptr< XclExpPalette > XclExpPalettePtr;
typedef ::std::auto_ptr< XclExpFontBuffer > XclExpFontBufferPtr;
typedef ::std::auto_ptr< XclExpNumFmtBuffer > XclExpNumFmtBufferPtr;
typedef ::std::auto_ptr< XclExpXFBuffer > XclExpXFBufferPtr;
typedef ::std::auto_ptr< XclExpTabIdBuffer > XclExpTabIdBufferPtr;
typedef ::std::auto_ptr< XclExpLinkManager > XclExpLinkManagerPtr;
XclExpSstPtr mpSst; /// The shared string table.
XclExpPalettePtr mpPalette; /// The color buffer.
XclExpFontBufferPtr mpFontBuffer; /// All fonts in the file.
XclExpNumFmtBufferPtr mpNumFmtBuffer; /// All number formats in the file.
XclExpXFBufferPtr mpXFBuffer; /// All XF records in the file.
XclExpTabIdBufferPtr mpTabIdBuffer; /// Calc->Excel sheet index conversion.
XclExpLinkManagerPtr mpLinkManager; /// Manager for internal/external links.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData(
XclBiff eBiff,
ScDocument& rDocument,
const String& rDocUrl,
CharSet eCharSet,
bool bRelUrl );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
public:
/** Returns this root instance - for code readability in derived classes. */
inline const XclExpRoot& GetRoot() const { return *this; }
/** Returns true, if URLs should be stored relative to the document location. */
inline bool IsRelUrl() const { return mrExpData.mbRelUrl; }
/** Returns the shared string table. */
XclExpSst& GetSst() const;
/** Returns the color buffer. */
XclExpPalette& GetPalette() const;
/** Returns the font buffer. */
XclExpFontBuffer& GetFontBuffer() const;
/** Returns the number format buffer. */
XclExpNumFmtBuffer& GetNumFmtBuffer() const;
/** Returns the cell formatting attributes buffer. */
XclExpXFBuffer& GetXFBuffer() const;
/** Returns the buffer for Calc->Excel sheet index conversion. */
XclExpTabIdBuffer& GetTabIdBuffer() const;
/** Returns the link manager. */
XclExpLinkManager& GetLinkManager() const;
/** Returns the Excel add-in function name for a Calc function name. */
String GetXclAddInName( const String& rScName ) const;
/** Checks if the passed cell address is a valid Excel cell position.
@descr See XclRoot::CheckCellAddress for details. */
bool CheckCellAddress( const ScAddress& rPos ) const;
/** Checks and eventually crops the cell range to valid Excel dimensions.
@descr See XclRoot::CheckCellRange for details. */
bool CheckCellRange( ScRange& rRange ) const;
/** Checks and eventually crops the cell ranges to valid Excel dimensions.
@descr See XclRoot::CheckCellRangeList for details. */
void CheckCellRangeList( ScRangeList& rRanges ) const;
protected:
explicit XclExpRoot( XclExpRootData& rExpRootData );
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: vg $ $Date: 2005-02-21 13:43:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
#ifndef SC_XERECORD_HXX
#include "xerecord.hxx"
#endif
// Forward declarations of objects in public use ==============================
class XclExpStream;
class XclExpString;
class XclExpTokenArray;
typedef ScfRef< XclExpString > XclExpStringRef;
typedef ScfRef< XclExpTokenArray > XclExpTokenArrayRef;
// Global data ================================================================
class XclExpTabInfo;
class XclExpAddressConverter;
class XclExpFormulaCompiler;
class XclExpProgressBar;
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpLinkManager;
class XclExpNameManager;
class XclExpFilterManager;
class XclExpPivotTableManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ScfRef< XclExpTabInfo > XclExpTabInfoRef;
typedef ScfRef< XclExpAddressConverter > XclExpAddrConvRef;
typedef ScfRef< XclExpFormulaCompiler > XclExpFmlaCompRef;
typedef ScfRef< XclExpProgressBar > XclExpProgressRef;
typedef ScfRef< XclExpSst > XclExpSstRef;
typedef ScfRef< XclExpPalette > XclExpPaletteRef;
typedef ScfRef< XclExpFontBuffer > XclExpFontBfrRef;
typedef ScfRef< XclExpNumFmtBuffer > XclExpNumFmtBfrRef;
typedef ScfRef< XclExpXFBuffer > XclExpXFBfrRef;
typedef ScfRef< XclExpNameManager > XclExpNameMgrRef;
typedef ScfRef< XclExpLinkManager > XclExpLinkMgrRef;
typedef ScfRef< XclExpFilterManager > XclExpFilterMgrRef;
typedef ScfRef< XclExpPivotTableManager > XclExpPTableMgrRef;
XclExpTabInfoRef mxTabInfo; /// Calc->Excel sheet index conversion.
XclExpAddrConvRef mxAddrConv; /// The address converter.
XclExpFmlaCompRef mxFmlaComp; /// The formula compiler.
XclExpProgressRef mxProgress; /// The export progress bar.
XclExpSstRef mxSst; /// The shared string table.
XclExpPaletteRef mxPalette; /// The color buffer.
XclExpFontBfrRef mxFontBfr; /// All fonts in the file.
XclExpNumFmtBfrRef mxNumFmtBfr; /// All number formats in the file.
XclExpXFBfrRef mxXFBfr; /// All XF records in the file.
XclExpNameMgrRef mxNameMgr; /// Internal defined names.
XclExpLinkMgrRef mxGlobLinkMgr; /// Global link manager for defined names.
XclExpLinkMgrRef mxLocLinkMgr; /// Local link manager for a sheet.
XclExpFilterMgrRef mxFilterMgr; /// Manager for filtered areas in all sheets.
XclExpPTableMgrRef mxPTableMgr; /// All pivot tables and pivot caches.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, SvStream& rBookStrm,
ScDocument& rDoc, CharSet eCharSet );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
public:
explicit XclExpRoot( XclExpRootData& rExpRootData );
/** Returns this root instance - for code readability in derived classes. */
inline const XclExpRoot& GetRoot() const { return *this; }
/** Returns true, if URLs should be stored relative to the document location. */
inline bool IsRelUrl() const { return mrExpData.mbRelUrl; }
/** Returns the buffer for Calc->Excel sheet index conversion. */
XclExpTabInfo& GetTabInfo() const;
/** Returns the address converter. */
XclExpAddressConverter& GetAddressConverter() const;
/** Returns the formula compiler to produce formula token arrays. */
XclExpFormulaCompiler& GetFormulaCompiler() const;
/** Returns the export progress bar. */
XclExpProgressBar& GetProgressBar() const;
/** Returns the shared string table. */
XclExpSst& GetSst() const;
/** Returns the color buffer. */
XclExpPalette& GetPalette() const;
/** Returns the font buffer. */
XclExpFontBuffer& GetFontBuffer() const;
/** Returns the number format buffer. */
XclExpNumFmtBuffer& GetNumFmtBuffer() const;
/** Returns the cell formatting attributes buffer. */
XclExpXFBuffer& GetXFBuffer() const;
/** Returns the global link manager for defined names. */
XclExpLinkManager& GetGlobalLinkManager() const;
/** Returns the local link manager for the current sheet. */
XclExpLinkManager& GetLocalLinkManager() const;
/** Returns the buffer that contains internal defined names. */
XclExpNameManager& GetNameManager() const;
/** Returns the filter manager. */
XclExpFilterManager& GetFilterManager() const;
/** Returns the pivot table manager. */
XclExpPivotTableManager& GetPivotTableManager() const;
/** Is called when export filter starts to create the Excel document (all BIFF versions). */
void InitializeConvert();
/** Is called when export filter starts to create the workbook global data (>=BIFF5). */
void InitializeGlobals();
/** Is called when export filter starts to create data for a single sheet (all BIFF versions). */
void InitializeTable( SCTAB nScTab );
/** Is called before export filter starts to write the records to the stream. */
void InitializeSave();
/** Returns the reference to a record (or record list) representing a root object.
@param nRecId Identifier that specifies which record is returned. */
XclExpRecordRef CreateRecord( sal_uInt16 nRecId ) const;
private:
/** Returns the local or global link manager, depending on current context. */
XclExpRootData::XclExpLinkMgrRef GetLocalLinkMgrRef() const;
private:
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS dr34 (1.14.46); FILE MERGED 2005/02/24 20:11:47 dr 1.14.46.3: RESYNC: (1.14-1.15); FILE MERGED 2005/02/11 14:52:17 dr 1.14.46.2: removed xerecord.hxx <-> xeroot.hxx dependency 2005/02/11 09:32:58 dr 1.14.46.1: removed xerecord.hxx <-> xeroot.hxx dependency<commit_after>/*************************************************************************
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-03-29 13:45:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
// Forward declarations of objects in public use ==============================
class XclExpStream;
class XclExpRecordBase;
class XclExpString;
class XclExpTokenArray;
typedef ScfRef< XclExpRecordBase > XclExpRecordRef;
typedef ScfRef< XclExpString > XclExpStringRef;
typedef ScfRef< XclExpTokenArray > XclExpTokenArrayRef;
// Global data ================================================================
class XclExpTabInfo;
class XclExpAddressConverter;
class XclExpFormulaCompiler;
class XclExpProgressBar;
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpLinkManager;
class XclExpNameManager;
class XclExpFilterManager;
class XclExpPivotTableManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ScfRef< XclExpTabInfo > XclExpTabInfoRef;
typedef ScfRef< XclExpAddressConverter > XclExpAddrConvRef;
typedef ScfRef< XclExpFormulaCompiler > XclExpFmlaCompRef;
typedef ScfRef< XclExpProgressBar > XclExpProgressRef;
typedef ScfRef< XclExpSst > XclExpSstRef;
typedef ScfRef< XclExpPalette > XclExpPaletteRef;
typedef ScfRef< XclExpFontBuffer > XclExpFontBfrRef;
typedef ScfRef< XclExpNumFmtBuffer > XclExpNumFmtBfrRef;
typedef ScfRef< XclExpXFBuffer > XclExpXFBfrRef;
typedef ScfRef< XclExpNameManager > XclExpNameMgrRef;
typedef ScfRef< XclExpLinkManager > XclExpLinkMgrRef;
typedef ScfRef< XclExpFilterManager > XclExpFilterMgrRef;
typedef ScfRef< XclExpPivotTableManager > XclExpPTableMgrRef;
XclExpTabInfoRef mxTabInfo; /// Calc->Excel sheet index conversion.
XclExpAddrConvRef mxAddrConv; /// The address converter.
XclExpFmlaCompRef mxFmlaComp; /// The formula compiler.
XclExpProgressRef mxProgress; /// The export progress bar.
XclExpSstRef mxSst; /// The shared string table.
XclExpPaletteRef mxPalette; /// The color buffer.
XclExpFontBfrRef mxFontBfr; /// All fonts in the file.
XclExpNumFmtBfrRef mxNumFmtBfr; /// All number formats in the file.
XclExpXFBfrRef mxXFBfr; /// All XF records in the file.
XclExpNameMgrRef mxNameMgr; /// Internal defined names.
XclExpLinkMgrRef mxGlobLinkMgr; /// Global link manager for defined names.
XclExpLinkMgrRef mxLocLinkMgr; /// Local link manager for a sheet.
XclExpFilterMgrRef mxFilterMgr; /// Manager for filtered areas in all sheets.
XclExpPTableMgrRef mxPTableMgr; /// All pivot tables and pivot caches.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, SvStream& rBookStrm,
ScDocument& rDoc, CharSet eCharSet );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
public:
explicit XclExpRoot( XclExpRootData& rExpRootData );
/** Returns this root instance - for code readability in derived classes. */
inline const XclExpRoot& GetRoot() const { return *this; }
/** Returns true, if URLs should be stored relative to the document location. */
inline bool IsRelUrl() const { return mrExpData.mbRelUrl; }
/** Returns the buffer for Calc->Excel sheet index conversion. */
XclExpTabInfo& GetTabInfo() const;
/** Returns the address converter. */
XclExpAddressConverter& GetAddressConverter() const;
/** Returns the formula compiler to produce formula token arrays. */
XclExpFormulaCompiler& GetFormulaCompiler() const;
/** Returns the export progress bar. */
XclExpProgressBar& GetProgressBar() const;
/** Returns the shared string table. */
XclExpSst& GetSst() const;
/** Returns the color buffer. */
XclExpPalette& GetPalette() const;
/** Returns the font buffer. */
XclExpFontBuffer& GetFontBuffer() const;
/** Returns the number format buffer. */
XclExpNumFmtBuffer& GetNumFmtBuffer() const;
/** Returns the cell formatting attributes buffer. */
XclExpXFBuffer& GetXFBuffer() const;
/** Returns the global link manager for defined names. */
XclExpLinkManager& GetGlobalLinkManager() const;
/** Returns the local link manager for the current sheet. */
XclExpLinkManager& GetLocalLinkManager() const;
/** Returns the buffer that contains internal defined names. */
XclExpNameManager& GetNameManager() const;
/** Returns the filter manager. */
XclExpFilterManager& GetFilterManager() const;
/** Returns the pivot table manager. */
XclExpPivotTableManager& GetPivotTableManager() const;
/** Is called when export filter starts to create the Excel document (all BIFF versions). */
void InitializeConvert();
/** Is called when export filter starts to create the workbook global data (>=BIFF5). */
void InitializeGlobals();
/** Is called when export filter starts to create data for a single sheet (all BIFF versions). */
void InitializeTable( SCTAB nScTab );
/** Is called before export filter starts to write the records to the stream. */
void InitializeSave();
/** Returns the reference to a record (or record list) representing a root object.
@param nRecId Identifier that specifies which record is returned. */
XclExpRecordRef CreateRecord( sal_uInt16 nRecId ) const;
private:
/** Returns the local or global link manager, depending on current context. */
XclExpRootData::XclExpLinkMgrRef GetLocalLinkMgrRef() const;
private:
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before><commit_msg>(multiplayer-basic) Cleanup of a few code comments.<commit_after><|endoftext|>
|
<commit_before>#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/solar_system.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "geometry/epoch.hpp"
#include "geometry/named_quantities.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Minute;
using quantities::si::Metre;
using quantities::si::Milli;
namespace physics {
class EclipseTest : public testing::Test {
protected:
EclipseTest() {
solar_system_1950_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_jd_2433282_500000000.proto.txt");
}
SolarSystem<ICRFJ2000Equator> solar_system_1950_;
};
TEST_F(EclipseTest, Dummy) {
auto ephemeris = solar_system_1950_.MakeEphemeris(McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(),
45 * Minute,
5 * Milli(Metre));
ephemeris->Prolong(JulianDate(2433374.5)); // Prolong until date of eclipse (Eclipse was 1950-04-02 but JD is 1950-04-03:00:00:00)
// pass body to Ephemeris.trajectory
auto earth = ephemeris->bodies()[solar_system_1950_.index("Earth")];
auto sun = ephemeris->bodies()[solar_system_1950_.index("Sun")];
auto moon = ephemeris->bodies()[solar_system_1950_.index("Moon")];
// check body angles at target times: P1, U1, U2, U3, U4, P4. (Us might be unavailable for some eclipses)
// Future: 2048-01-01
};
} // physics
} // principia
<commit_msg>blocking out future<commit_after>#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/solar_system.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "geometry/epoch.hpp"
#include "geometry/named_quantities.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Minute;
using quantities::si::Metre;
using quantities::si::Milli;
namespace physics {
class EclipseTest : public testing::Test {
protected:
EclipseTest() {
solar_system_1950_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_jd_2433282_500000000.proto.txt");
}
SolarSystem<ICRFJ2000Equator> solar_system_1950_;
};
TEST_F(EclipseTest, Dummy) {
auto ephemeris = solar_system_1950_.MakeEphemeris(McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(),
45 * Minute,
5 * Milli(Metre));
ephemeris->Prolong(JulianDate(2433374.5)); // Prolong until date of eclipse (Eclipse was 1950-04-02 but JD is 1950-04-03:00:00:00)
// pass body to Ephemeris.trajectory
auto sun = ephemeris->bodies()[solar_system_1950_.index("Sun")];
auto earth = ephemeris->bodies()[solar_system_1950_.index("Earth")];
auto moon = ephemeris->bodies()[solar_system_1950_.index("Moon")];
// Get positions/trajectories/ephemeres for bodies
// Dates will have to be for U1, etc. (and all will have to be generated)
auto some_instant = JulianDate(2433374.5);
ephemeris->trajectory(sun)->EvaluatePosition(some_instant, nullptr);
ephemeris->trajectory(earth)->EvaluatePosition(some_instant, nullptr);
ephemeris->trajectory(moon)->EvaluatePosition(some_instant, nullptr);
// check body angles at target times
// Future: check 2048-01-01 Lunar eclipse
};
} // physics
} // principia
<|endoftext|>
|
<commit_before>
#include "drake/examples/kuka_iiwa_arm/iiwa_simulation.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_status.h"
#include "drake/Path.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "lcmtypes/drake/lcmt_iiwa_status.hpp"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
// This class exists to keep the LCM messages which are passing
// through BotVisualizer from being sent back out via LCM again.
template <template <typename> class Vector>
class SinkSystem {
public:
template <typename ScalarType>
using StateVector = Drake::NullVector<ScalarType>;
template <typename ScalarType>
using InputVector = Vector<ScalarType>;
template <typename ScalarType>
using OutputVector = Drake::NullVector<ScalarType>;
SinkSystem() {}
template <typename ScalarType>
StateVector<ScalarType> dynamics(const double &t,
const StateVector<ScalarType> &x,
const InputVector<ScalarType> &u) const {
return StateVector<ScalarType>();
}
template <typename ScalarType>
OutputVector<ScalarType> output(const double &t,
const StateVector<ScalarType> &x,
const InputVector<ScalarType> &u) const {
return OutputVector<ScalarType>();
}
bool isTimeVarying() const { return false; }
};
int do_main(int argc, const char* argv[]) {
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
const std::shared_ptr<RigidBodyTree>& tree =
CreateKukaIiwaSystem()->getRigidBodyTree();
auto visualizer =
std::make_shared<Drake::BotVisualizer<IiwaStatus>>(lcm, tree);
auto sink = std::make_shared<SinkSystem<IiwaStatus>>();
auto sys = Drake::cascade(visualizer, sink);
Drake::runLCM(sys, lcm, 0, 1e9);
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, const char* argv[]) {
return drake::examples::kuka_iiwa_arm::do_main(argc, argv);
}
<commit_msg>Made the shared pointer a real shared pointer.<commit_after>
#include "drake/examples/kuka_iiwa_arm/iiwa_simulation.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_status.h"
#include "drake/Path.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include "lcmtypes/drake/lcmt_iiwa_status.hpp"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
// This class exists to keep the LCM messages which are passing
// through BotVisualizer from being sent back out via LCM again.
template <template <typename> class Vector>
class SinkSystem {
public:
template <typename ScalarType>
using StateVector = Drake::NullVector<ScalarType>;
template <typename ScalarType>
using InputVector = Vector<ScalarType>;
template <typename ScalarType>
using OutputVector = Drake::NullVector<ScalarType>;
SinkSystem() {}
template <typename ScalarType>
StateVector<ScalarType> dynamics(const double &t,
const StateVector<ScalarType> &x,
const InputVector<ScalarType> &u) const {
return StateVector<ScalarType>();
}
template <typename ScalarType>
OutputVector<ScalarType> output(const double &t,
const StateVector<ScalarType> &x,
const InputVector<ScalarType> &u) const {
return OutputVector<ScalarType>();
}
bool isTimeVarying() const { return false; }
};
int do_main(int argc, const char* argv[]) {
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
const std::shared_ptr<RigidBodyTree> tree =
CreateKukaIiwaSystem()->getRigidBodyTree();
auto visualizer =
std::make_shared<Drake::BotVisualizer<IiwaStatus>>(lcm, tree);
auto sink = std::make_shared<SinkSystem<IiwaStatus>>();
auto sys = Drake::cascade(visualizer, sink);
Drake::runLCM(sys, lcm, 0, 1e9);
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, const char* argv[]) {
return drake::examples::kuka_iiwa_arm::do_main(argc, argv);
}
<|endoftext|>
|
<commit_before>#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/solar_system.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "geometry/epoch.hpp"
#include "geometry/named_quantities.hpp"
#include "quantities/elementary_functions.hpp"
#include "geometry/grassmann.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Minute;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Kilo;
namespace physics {
class EclipseTest : public testing::Test {
protected:
EclipseTest() {
solar_system_1950_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_jd_2433282_500000000.proto.txt");
}
SolarSystem<ICRFJ2000Equator> solar_system_1950_;
};
TEST_F(EclipseTest, Dummy) {
auto ephemeris = solar_system_1950_.MakeEphemeris(McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(),
45 * Minute,
5 * Milli(Metre));
ephemeris->Prolong(JulianDate(2433374.5)); // Prolong until date of eclipse (Eclipse was 1950-04-02 but JD is 1950-04-03:00:00:00)
// pass body to Ephemeris.trajectory
auto sun = ephemeris->bodies()[solar_system_1950_.index("Sun")];
auto earth = ephemeris->bodies()[solar_system_1950_.index("Earth")];
auto moon = ephemeris->bodies()[solar_system_1950_.index("Moon")];
// Get positions/trajectories/ephemeres for bodies
// Dates will have to be for U1, etc. (and all will have to be generated)
auto some_instant = JulianDate(2433374.5);
auto q_sun = ephemeris->trajectory(sun)->EvaluatePosition(some_instant, nullptr);
auto q_moon = ephemeris->trajectory(moon)->EvaluatePosition(some_instant, nullptr);
auto q_earth = ephemeris->trajectory(earth)->EvaluatePosition(some_instant, nullptr);
// Massive_body eventually needs radius information. Or non-hardcoded data pulled from https://github.com/mockingbirdnest/Principia/blob/master/astronomy/gravity_model.proto.txt
auto r_sun = 696000.0 * Kilo(Metre);
auto r_moon = 6378.1363 * Kilo(Metre);
auto r_earth = 1738.0 * Kilo(Metre);
// check body angles at target times
// Lunar eclipse
// Earth/Sun lineup
auto alpha = ArcSin((r_sun - r_earth)/(q_sun - q_earth).Norm());
auto q_U23 = q_earth + (q_sun - q_earth)/(q_sun - q_earth).Norm() * (r_earth - r_moon) / Sin(alpha);
auto q_U13 = q_earth + (q_sun - q_earth)/(q_sun - q_earth).Norm() * (r_earth + r_moon) / Sin(alpha);
// Earth/Moon lineup
// auto beta = ArcCos(InnerProduct(q_moon, q_earth) / (q_moon - q_earth).Norm()); // Does not work because InnerProduct doesn't seem to actually be used. Also wrong inputs, and does not work in principle since we'd need another vector
// Where we would compare angles if they were calculable
// U14 have the same angle, also expressible 2 different ways:
// ArcSin((r_sun + r_moon)/(q_moon - q_sun).Norm());
// ArcSin((r_earth + r_moon)/(q_moon - q_earth).Norm());
// Or as egg suggests, finding the distance with an angle. But these need to have error ranges instead of exact value...
// (r_sun - r_moon) / Sin(alpha) == (q_moon - q_sun).Norm();
// (r_earth - r_moon) / Sin(alpha) == (q_moon - q_earth).Norm();
// U23
// ArcSin((r_sun - r_moon)/(q_moon - q_sun).Norm());
// ArcSin((r_earth - r_moon)/(q_moon - q_earth).Norm());
// (r_sun + r_moon) / Sin(alpha) == (q_moon - q_sun).Norm();
// (r_earth + r_moon) / Sin(alpha) == (q_moon - q_earth).Norm();
// LOG(ERROR) << ArcTan(1.0);
// Future: check 2048-01-01 Lunar eclipse
};
} // physics
} // principia
<commit_msg>Angular.cpp<commit_after>#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/solar_system.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "geometry/epoch.hpp"
#include "geometry/named_quantities.hpp"
#include "quantities/elementary_functions.hpp"
#include "geometry/grassmann.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::JulianDate;
using integrators::McLachlanAtela1992Order5Optimal;
using quantities::si::Minute;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Kilo;
using quantities::ArcCos; // This feels very cargocultish, especially since I don't need it for ArcSin.
namespace physics {
class EclipseTest : public testing::Test {
protected:
EclipseTest() {
solar_system_1950_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_jd_2433282_500000000.proto.txt");
}
SolarSystem<ICRFJ2000Equator> solar_system_1950_;
};
TEST_F(EclipseTest, Dummy) {
auto ephemeris = solar_system_1950_.MakeEphemeris(McLachlanAtela1992Order5Optimal<Position<ICRFJ2000Equator>>(),
45 * Minute,
5 * Milli(Metre));
ephemeris->Prolong(JulianDate(2433374.5)); // Prolong until date of eclipse (Eclipse was 1950-04-02 but JD is 1950-04-03:00:00:00)
// pass body to Ephemeris.trajectory
auto sun = ephemeris->bodies()[solar_system_1950_.index("Sun")];
auto earth = ephemeris->bodies()[solar_system_1950_.index("Earth")];
auto moon = ephemeris->bodies()[solar_system_1950_.index("Moon")];
// Get positions/trajectories/ephemeres for bodies
// Dates will have to be for U1, etc. (and all will have to be generated)
auto some_instant = JulianDate(2433374.5);
auto q_sun = ephemeris->trajectory(sun)->EvaluatePosition(some_instant, nullptr);
auto q_moon = ephemeris->trajectory(moon)->EvaluatePosition(some_instant, nullptr);
auto q_earth = ephemeris->trajectory(earth)->EvaluatePosition(some_instant, nullptr);
// Massive_body eventually needs radius information. Or non-hardcoded data pulled from https://github.com/mockingbirdnest/Principia/blob/master/astronomy/gravity_model.proto.txt
auto r_sun = 696000.0 * Kilo(Metre);
auto r_moon = 6378.1363 * Kilo(Metre);
auto r_earth = 1738.0 * Kilo(Metre);
// check body angles at target times
// Lunar eclipse
// Earth/Sun lineup
auto alpha = ArcSin((r_sun - r_earth)/(q_sun - q_earth).Norm());
auto q_U23 = q_earth + Normalize(q_sun - q_earth) * (r_earth - r_moon) / Sin(alpha);
auto q_U14 = q_earth + Normalize(q_sun - q_earth) * (r_earth + r_moon) / Sin(alpha);
// Earth/Moon lineup
auto beta = ArcCos(InnerProduct(q_U23 - q_earth, q_U23 - q_moon) / ((q_U23 - q_moon).Norm() * (q_U23 - q_earth).Norm()));
auto gamma = ArcCos(InnerProduct(q_U14 - q_earth, q_U14 - q_moon) / ((q_U14 - q_moon).Norm() * (q_U14 - q_earth).Norm()));
// Still need to compare angles
// U14 have the same angle, also expressible 2 different ways:
// ArcSin((r_sun + r_moon)/(q_moon - q_sun).Norm());
// ArcSin((r_earth + r_moon)/(q_moon - q_earth).Norm());
// Or as egg suggests, finding the distance with an angle. But these need to have error ranges instead of exact value...
// (r_sun - r_moon) / Sin(alpha) == (q_moon - q_sun).Norm();
// (r_earth - r_moon) / Sin(alpha) == (q_moon - q_earth).Norm();
// U23
// ArcSin((r_sun - r_moon)/(q_moon - q_sun).Norm());
// ArcSin((r_earth - r_moon)/(q_moon - q_earth).Norm());
// (r_sun + r_moon) / Sin(alpha) == (q_moon - q_sun).Norm();
// (r_earth + r_moon) / Sin(alpha) == (q_moon - q_earth).Norm();
// LOG(ERROR) << ArcTan(1.0);
// Future: check 2048-01-01 Lunar eclipse
};
} // physics
} // principia
<|endoftext|>
|
<commit_before>/** @file
*
* @ingroup dspWindowFunctionLib
*
* @brief Generalized Window Function Wrapper for Jamoma DSP
*
* @details
*
* @authors Tim Place, Nathan Wolek, Trond Lossius,
*
* @copyright Copyright © 2010 by Timothy Place @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTWindowFunction.h"
#define thisTTClass WindowFunction
#define thisTTClassName "WindowFunction"
#define thisTTClassTags "dspWindowFunctionLib, audio, processor"
TT_AUDIO_CONSTRUCTOR,
mFunctionObject(NULL),
mNumPoints(8192),
mPadding(0)
{
addAttributeWithSetter(Function, kTypeSymbol);
addAttributeWithSetter(NumPoints, kTypeUInt32);
addAttributeWithSetter(Mode, kTypeSymbol);
addAttributeWithSetter(Padding, kTypeUInt32);
addMessageWithArguments(getFunctions);
addMessageWithArguments(setParameter);
setAttributeValue(TT("function"), TT("rectangular"));
setAttributeValue(TT("mode"), TT("lookup"));
}
WindowFunction::~WindowFunction()
{
delete mFunctionObject;
}
TTErr WindowFunction::setFunction(const TTValue& function)
{
TTErr err;
mFunction = function;
err = TTObjectBaseInstantiate(mFunction, &mFunctionObject, mMaxNumChannels);
if (!err)
err = fill();
return err;
}
TTErr WindowFunction::setParameter(const TTValue& aParameterValueForTheFunction, TTValue&)
{
TTErr err;
if (aParameterValueForTheFunction.size() < 2)
err = kTTErrWrongNumValues;
else {
TTSymbol parameterName = aParameterValueForTheFunction;
TTValue v;
v.copyFrom(aParameterValueForTheFunction, 1);
err = mFunctionObject->setAttributeValue(parameterName, v);
if (!err)
fill();
}
return err;
}
TTErr WindowFunction::fill()
{
mLookupTable.assign(mNumPoints, 0.0);
if (mFunctionObject) {
TTInt32 numPoints = mNumPoints-(mPadding*2);
TTLimitMin<TTInt32>(numPoints, 0);
for (TTInt32 i=0; i<numPoints; i++)
mFunctionObject->calculate(i/TTFloat64(numPoints-1), mLookupTable[i+mPadding]);
}
else
mLookupTable.assign(mNumPoints, 0.0);
return kTTErrNone;
}
TTErr WindowFunction::setNumPoints(const TTValue& numPoints)
{
return doSetNumPoints(numPoints);
}
TTErr WindowFunction::doSetNumPoints(const TTUInt32 numPoints)
{
mNumPoints = numPoints;
mLookupTable.resize(mNumPoints);
return fill();
}
TTErr WindowFunction::setPadding(const TTValue& padding)
{
mPadding = padding;
return fill();
}
TTErr WindowFunction::setMode(const TTValue& mode)
{
mMode = mode;
if (mMode == TT("apply")) {
setProcessMethod(processApply);
setCalculateMethod(lookupValue);
}
else if (mMode == TT("generate")) {
setProcessMethod(processGenerate);
setCalculateMethod(calculateValue);
}
else {
setProcessMethod(processLookup);
setCalculateMethod(lookupValue);
}
return kTTErrNone;
}
TTErr WindowFunction::getFunctions(const TTValue&, TTValue& listOfWindowTypesToReturn)
{
return TTGetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("window"));
}
#if 0
#pragma mark -
#pragma mark Process Routines
#endif
inline TTErr WindowFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
return mFunctionObject->calculate(x, y);
}
inline TTErr WindowFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
return kTTErrNone;
}
TTErr WindowFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
return mFunctionObject->process(inputs, outputs);
}
TTErr WindowFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TT_WRAP_CALCULATE_METHOD(lookupValue)
}
TTErr WindowFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs = in.getVectorSizeAsInt();
TTSampleValuePtr inSample;
TTSampleValuePtr outSample;
TTUInt16 numChannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// In 'apply' mode we automatically update the lookup table size to the vector size
// This is slow, but hopefully only happens once (if ever)
if (vs != mNumPoints)
doSetNumPoints(vs);
for (channel=0; channel<numChannels; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel];
for (TTUInt32 i=0; i<vs; i++)
*outSample++ = (*inSample++) * mLookupTable[i];
}
return kTTErrNone;
}
<commit_msg>replacing deprecated TTGetRegisteredClassNamesForTags with static TTObject method. see #238<commit_after>/** @file
*
* @ingroup dspWindowFunctionLib
*
* @brief Generalized Window Function Wrapper for Jamoma DSP
*
* @details
*
* @authors Tim Place, Nathan Wolek, Trond Lossius,
*
* @copyright Copyright © 2010 by Timothy Place @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTWindowFunction.h"
#define thisTTClass WindowFunction
#define thisTTClassName "WindowFunction"
#define thisTTClassTags "dspWindowFunctionLib, audio, processor"
TT_AUDIO_CONSTRUCTOR,
mFunctionObject(NULL),
mNumPoints(8192),
mPadding(0)
{
addAttributeWithSetter(Function, kTypeSymbol);
addAttributeWithSetter(NumPoints, kTypeUInt32);
addAttributeWithSetter(Mode, kTypeSymbol);
addAttributeWithSetter(Padding, kTypeUInt32);
addMessageWithArguments(getFunctions);
addMessageWithArguments(setParameter);
setAttributeValue(TT("function"), TT("rectangular"));
setAttributeValue(TT("mode"), TT("lookup"));
}
WindowFunction::~WindowFunction()
{
delete mFunctionObject;
}
TTErr WindowFunction::setFunction(const TTValue& function)
{
TTErr err;
mFunction = function;
err = TTObjectBaseInstantiate(mFunction, &mFunctionObject, mMaxNumChannels);
if (!err)
err = fill();
return err;
}
TTErr WindowFunction::setParameter(const TTValue& aParameterValueForTheFunction, TTValue&)
{
TTErr err;
if (aParameterValueForTheFunction.size() < 2)
err = kTTErrWrongNumValues;
else {
TTSymbol parameterName = aParameterValueForTheFunction;
TTValue v;
v.copyFrom(aParameterValueForTheFunction, 1);
err = mFunctionObject->setAttributeValue(parameterName, v);
if (!err)
fill();
}
return err;
}
TTErr WindowFunction::fill()
{
mLookupTable.assign(mNumPoints, 0.0);
if (mFunctionObject) {
TTInt32 numPoints = mNumPoints-(mPadding*2);
TTLimitMin<TTInt32>(numPoints, 0);
for (TTInt32 i=0; i<numPoints; i++)
mFunctionObject->calculate(i/TTFloat64(numPoints-1), mLookupTable[i+mPadding]);
}
else
mLookupTable.assign(mNumPoints, 0.0);
return kTTErrNone;
}
TTErr WindowFunction::setNumPoints(const TTValue& numPoints)
{
return doSetNumPoints(numPoints);
}
TTErr WindowFunction::doSetNumPoints(const TTUInt32 numPoints)
{
mNumPoints = numPoints;
mLookupTable.resize(mNumPoints);
return fill();
}
TTErr WindowFunction::setPadding(const TTValue& padding)
{
mPadding = padding;
return fill();
}
TTErr WindowFunction::setMode(const TTValue& mode)
{
mMode = mode;
if (mMode == TT("apply")) {
setProcessMethod(processApply);
setCalculateMethod(lookupValue);
}
else if (mMode == TT("generate")) {
setProcessMethod(processGenerate);
setCalculateMethod(calculateValue);
}
else {
setProcessMethod(processLookup);
setCalculateMethod(lookupValue);
}
return kTTErrNone;
}
TTErr WindowFunction::getFunctions(const TTValue&, TTValue& listOfWindowTypesToReturn)
{
return TTObject::GetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("window"));
}
#if 0
#pragma mark -
#pragma mark Process Routines
#endif
inline TTErr WindowFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
return mFunctionObject->calculate(x, y);
}
inline TTErr WindowFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
return kTTErrNone;
}
TTErr WindowFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
return mFunctionObject->process(inputs, outputs);
}
TTErr WindowFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TT_WRAP_CALCULATE_METHOD(lookupValue)
}
TTErr WindowFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs = in.getVectorSizeAsInt();
TTSampleValuePtr inSample;
TTSampleValuePtr outSample;
TTUInt16 numChannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// In 'apply' mode we automatically update the lookup table size to the vector size
// This is slow, but hopefully only happens once (if ever)
if (vs != mNumPoints)
doSetNumPoints(vs);
for (channel=0; channel<numChannels; channel++) {
inSample = in.mSampleVectors[channel];
outSample = out.mSampleVectors[channel];
for (TTUInt32 i=0; i<vs; i++)
*outSample++ = (*inSample++) * mLookupTable[i];
}
return kTTErrNone;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2002 by Jorrit Tyberghein, Daniel Duhprey
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <cssysdef.h>
#include <cssys/sysfunc.h>
#include <csver.h>
#include <csutil/csobject.h>
#include <csutil/cmdhelp.h>
#include <csutil/cspmeter.h>
#include <csutil/cscolor.h>
#include <cstool/initapp.h>
#include <cstool/csview.h>
#include <iutil/objreg.h>
#include <iutil/vfs.h>
#include <iutil/virtclk.h>
#include <iutil/csinput.h>
#include <iutil/eventq.h>
#include <iutil/event.h>
#include <iutil/plugin.h>
#include <iutil/cfgmgr.h>
#include <iengine/engine.h>
#include <iengine/sector.h>
#include <iengine/camera.h>
#include <iengine/campos.h>
#include <iengine/mesh.h>
#include <iengine/material.h>
#include <iengine/light.h>
#include <iengine/statlght.h>
#include <imesh/object.h>
#include <imesh/thing/thing.h>
#include <imesh/thing/polygon.h>
#include <imesh/ball.h>
#include <ivideo/graph3d.h>
#include <ivideo/graph2d.h>
#include <ivideo/txtmgr.h>
#include <ivideo/fontserv.h>
#include <igraphic/imageio.h>
#include <isound/loader.h>
#include <isound/handle.h>
#include <isound/source.h>
#include <isound/listener.h>
#include <isound/wrapper.h>
#include <isound/renderer.h>
#include <ivaria/reporter.h>
#include <ivaria/stdrep.h>
#include <ivaria/conout.h>
#include <ivaria/perfstat.h>
#include <ivaria/dynamics.h>
#include <imap/parser.h>
#include <imesh/terrbig.h>
#include "tbtut.h"
CS_IMPLEMENT_APPLICATION
TerrBigTut *Sys = NULL;
TerrBigTut::TerrBigTut (iObjectRegistry* o)
{
object_reg = o;
}
TerrBigTut::~TerrBigTut ()
{
}
void TerrBigTut::Report (int s, const char *m)
{
csReport (object_reg, s, "TerrBigTut", m);
}
bool TerrBigTut::Initialize ()
{
if (!csInitializer::RequestPlugins (object_reg,
CS_REQUEST_VFS,
CS_REQUEST_SOFTWARE3D,
CS_REQUEST_ENGINE,
CS_REQUEST_FONTSERVER,
CS_REQUEST_IMAGELOADER,
CS_REQUEST_LEVELLOADER,
CS_REQUEST_REPORTER,
CS_REQUEST_REPORTERLISTENER,
CS_REQUEST_END))
{
Report (CS_REPORTER_SEVERITY_ERROR,
"Failed to initialize plugins");
return false;
}
if (!csInitializer::SetupEventHandler (object_reg, SimpleEventHandler)) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to create event handler");
return false;
}
if (csCommandLineHelper::CheckHelp (object_reg)) {
csCommandLineHelper::Help (object_reg);
return false;
}
if ((vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize virtual clock");
return false;
}
if ((engine = CS_QUERY_REGISTRY (object_reg, iEngine)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize engine");
return false;
}
if ((loader = CS_QUERY_REGISTRY (object_reg, iLoader)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize map loader");
return false;
}
if ((g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize graphics");
return false;
}
if ((kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize keyboard");
return false;
}
if (!csInitializer::OpenApplication (object_reg)) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to start the application");
return false;
}
engine->SetLightingCacheMode (0);
if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif")) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Error loading 'stone4' texture!\n");
return false;
}
iMaterialWrapper *tm = engine->GetMaterialList()->FindByName ("stone");
room = engine->CreateSector ("room");
csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
csRef<iThingState> walls_state (
SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState));
iPolygon3D* p;
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 0, 128));
p->CreateVertex (csVector3 (128, 0, 128));
p->CreateVertex (csVector3 (128, 0, -128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (-128, 100, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, 128));
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (128, 0, 128));
p->CreateVertex (csVector3 (-128, 0, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (128, 0, -128));
p->CreateVertex (csVector3 (128, 0, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (-128, 100, 128));
p->CreateVertex (csVector3 (-128, 0, 128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->CreateVertex (csVector3 (128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
csRef<iMeshFactoryWrapper> factory;
factory = engine->CreateMeshFactory ("crystalspace.mesh.object.terrbig",
"terrain_factory");
if (!factory) {
Report (CS_REPORTER_SEVERITY_ERROR, "Can't create terrbig mesh factory!");
return false;
}
csRef<iMeshWrapper> mesh;
mesh = engine->CreateMeshWrapper (factory, "terrain", room, csVector3 (0,0,0));
csRef<iTerrBigState> terrbigstate;
terrbigstate = SCF_QUERY_INTERFACE (mesh->GetMeshObject(), iTerrBigState);
if (!loader->LoadTexture ("heightmap", "/lev/terrain/heightmap.png")) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Error loading 'wood' texture!\n");
return false;
}
iMaterialWrapper *mat = engine->GetMaterialList()->FindByName ("heightmap");
terrbigstate->SetMaterialsList (&mat, 1);
terrbigstate->LoadHeightMapFile ("./data/terrain/test.map");
mesh->SetRenderPriority (engine->GetRenderPriority ("object"));
mesh->SetZBufMode (CS_ZBUF_USE);
mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
csRef<iStatLight> light;
iLightList* ll = room->GetLights ();
light = engine->CreateLight (NULL, csVector3 (-3, 5, 0), 10,
csColor (1, 0, 0), false);
ll->Add (light->QueryLight ());
light = engine->CreateLight (NULL, csVector3 (3, 5, 0), 10,
csColor (0, 0, 1), false);
ll->Add (light->QueryLight ());
light = engine->CreateLight (NULL, csVector3 (0, 5, -3), 10,
csColor (0, 1, 0), false);
ll->Add (light->QueryLight ());
engine->Prepare ();
view = csPtr<iView> (new csView (engine, g3d));
view->GetCamera ()->SetSector (room);
view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
iGraphics2D* g2d = g3d->GetDriver2D ();
view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());
view->GetCamera()->Move (csVector3 (0, 20, 0));
iTextureManager* txtmgr = g3d->GetTextureManager ();
txtmgr->SetPalette ();
return true;
}
void TerrBigTut::MainLoop ()
{
csDefaultRunLoop (object_reg);
}
bool TerrBigTut::SimpleEventHandler (iEvent &e)
{
return Sys->HandleEvent (e);
}
bool TerrBigTut::HandleEvent (iEvent &e)
{
if (e.Type == csevBroadcast && e.Command.Code == cscmdProcess) {
SetupFrame ();
return true;
}
if (e.Type == csevBroadcast && e.Command.Code == cscmdFinalProcess) {
FinishFrame ();
return true;
}
if (e.Type == csevKeyDown && e.Key.Code == CSKEY_ESC) {
csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
return true;
};
return false;
}
void TerrBigTut::SetupFrame ()
{
float elapsed_time = ((float)vc->GetElapsedTicks ())/1000.0;
float speed = elapsed_time * 0.6;
iCamera *c = view->GetCamera ();
if (kbd->GetKeyState (CSKEY_RIGHT))
c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
if (kbd->GetKeyState (CSKEY_LEFT))
c->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);
if (kbd->GetKeyState (CSKEY_PGUP))
c->GetTransform ().RotateThis (CS_VEC_TILT_UP, speed);
if (kbd->GetKeyState (CSKEY_PGDN))
c->GetTransform ().RotateThis (CS_VEC_TILT_DOWN, speed);
if (kbd->GetKeyState (CSKEY_UP))
c->Move (CS_VEC_FORWARD * 10 * speed);
if (kbd->GetKeyState (CSKEY_DOWN))
c->Move (CS_VEC_FORWARD * -10 * speed);
if (g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS)) {
view->Draw ();
}
}
void TerrBigTut::FinishFrame ()
{
g3d->FinishDraw ();
g3d->Print (NULL);
}
int main (int argc, char *argv[])
{
iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);
Sys = new TerrBigTut(object_reg);
if (Sys->Initialize ()) {
Sys->MainLoop ();
}
delete Sys;
csInitializer::DestroyApplication (object_reg);
return 0;
}
<commit_msg>Updated to reflect the changes to TerrBigState<commit_after>/*
Copyright (C) 2002 by Jorrit Tyberghein, Daniel Duhprey
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <cssysdef.h>
#include <cssys/sysfunc.h>
#include <csver.h>
#include <csutil/csobject.h>
#include <csutil/cmdhelp.h>
#include <csutil/cspmeter.h>
#include <csutil/cscolor.h>
#include <cstool/initapp.h>
#include <cstool/csview.h>
#include <iutil/objreg.h>
#include <iutil/vfs.h>
#include <iutil/virtclk.h>
#include <iutil/csinput.h>
#include <iutil/eventq.h>
#include <iutil/event.h>
#include <iutil/plugin.h>
#include <iutil/cfgmgr.h>
#include <iengine/engine.h>
#include <iengine/sector.h>
#include <iengine/camera.h>
#include <iengine/campos.h>
#include <iengine/mesh.h>
#include <iengine/material.h>
#include <iengine/light.h>
#include <iengine/statlght.h>
#include <imesh/object.h>
#include <imesh/thing/thing.h>
#include <imesh/thing/polygon.h>
#include <imesh/ball.h>
#include <ivideo/graph3d.h>
#include <ivideo/graph2d.h>
#include <ivideo/txtmgr.h>
#include <ivideo/fontserv.h>
#include <igraphic/imageio.h>
#include <isound/loader.h>
#include <isound/handle.h>
#include <isound/source.h>
#include <isound/listener.h>
#include <isound/wrapper.h>
#include <isound/renderer.h>
#include <ivaria/reporter.h>
#include <ivaria/stdrep.h>
#include <ivaria/conout.h>
#include <ivaria/perfstat.h>
#include <ivaria/dynamics.h>
#include <imap/parser.h>
#include <imesh/terrbig.h>
#include "tbtut.h"
CS_IMPLEMENT_APPLICATION
TerrBigTut *Sys = NULL;
TerrBigTut::TerrBigTut (iObjectRegistry* o)
{
object_reg = o;
}
TerrBigTut::~TerrBigTut ()
{
}
void TerrBigTut::Report (int s, const char *m)
{
csReport (object_reg, s, "TerrBigTut", m);
}
bool TerrBigTut::Initialize ()
{
if (!csInitializer::RequestPlugins (object_reg,
CS_REQUEST_VFS,
CS_REQUEST_SOFTWARE3D,
CS_REQUEST_ENGINE,
CS_REQUEST_FONTSERVER,
CS_REQUEST_IMAGELOADER,
CS_REQUEST_LEVELLOADER,
CS_REQUEST_REPORTER,
CS_REQUEST_REPORTERLISTENER,
CS_REQUEST_END))
{
Report (CS_REPORTER_SEVERITY_ERROR,
"Failed to initialize plugins");
return false;
}
if (!csInitializer::SetupEventHandler (object_reg, SimpleEventHandler)) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to create event handler");
return false;
}
if (csCommandLineHelper::CheckHelp (object_reg)) {
csCommandLineHelper::Help (object_reg);
return false;
}
if ((vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize virtual clock");
return false;
}
if ((engine = CS_QUERY_REGISTRY (object_reg, iEngine)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize engine");
return false;
}
if ((loader = CS_QUERY_REGISTRY (object_reg, iLoader)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize map loader");
return false;
}
if ((g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize graphics");
return false;
}
if ((kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver)) == NULL) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to initialize keyboard");
return false;
}
if (!csInitializer::OpenApplication (object_reg)) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Unable to start the application");
return false;
}
engine->SetLightingCacheMode (0);
if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif")) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Error loading 'stone4' texture!\n");
return false;
}
iMaterialWrapper *tm = engine->GetMaterialList()->FindByName ("stone");
room = engine->CreateSector ("room");
csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
csRef<iThingState> walls_state (
SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState));
iPolygon3D* p;
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 0, 128));
p->CreateVertex (csVector3 (128, 0, 128));
p->CreateVertex (csVector3 (128, 0, -128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (-128, 100, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, 128));
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (128, 0, 128));
p->CreateVertex (csVector3 (-128, 0, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (128, 100, 128));
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (128, 0, -128));
p->CreateVertex (csVector3 (128, 0, 128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (-128, 100, 128));
p->CreateVertex (csVector3 (-128, 0, 128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls_state->CreatePolygon ();
p->SetMaterial (tm);
p->CreateVertex (csVector3 (128, 100, -128));
p->CreateVertex (csVector3 (-128, 100, -128));
p->CreateVertex (csVector3 (-128, 0, -128));
p->CreateVertex (csVector3 (128, 0, -128));
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
csRef<iMeshFactoryWrapper> factory;
factory = engine->CreateMeshFactory ("crystalspace.mesh.object.terrbig",
"terrain_factory");
if (!factory) {
Report (CS_REPORTER_SEVERITY_ERROR, "Can't create terrbig mesh factory!");
return false;
}
csRef<iMeshWrapper> mesh;
mesh = engine->CreateMeshWrapper (factory, "terrain", room, csVector3 (0,0,0));
csRef<iTerrBigState> terrbigstate;
terrbigstate = SCF_QUERY_INTERFACE (mesh->GetMeshObject(), iTerrBigState);
if (!loader->LoadTexture ("heightmap", "/lev/terrain/heightmap.png")) {
Report (CS_REPORTER_SEVERITY_ERROR,
"Error loading 'wood' texture!\n");
return false;
}
iMaterialWrapper *mat = engine->GetMaterialList()->FindByName ("heightmap");
terrbigstate->SetMaterialsList (&mat, 1);
terrbigstate->LoadHeightMapFile ("./data/terrain/test.map");
terrbigstate->SetScaleFactor (csVector3 (1.0, 10, 1.0));
mesh->SetRenderPriority (engine->GetRenderPriority ("object"));
mesh->SetZBufMode (CS_ZBUF_USE);
mesh->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
csRef<iStatLight> light;
iLightList* ll = room->GetLights ();
light = engine->CreateLight (NULL, csVector3 (-50, 20, 0), 10,
csColor (1, 0, 0), false);
ll->Add (light->QueryLight ());
light = engine->CreateLight (NULL, csVector3 (50, 20, 0), 10,
csColor (0, 0, 1), false);
ll->Add (light->QueryLight ());
light = engine->CreateLight (NULL, csVector3 (0, 20, -50), 10,
csColor (0, 1, 0), false);
ll->Add (light->QueryLight ());
engine->Prepare ();
view = csPtr<iView> (new csView (engine, g3d));
view->GetCamera ()->SetSector (room);
iGraphics2D* g2d = g3d->GetDriver2D ();
view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());
view->GetCamera()->Move (csVector3 (0, 20, 0));
iTextureManager* txtmgr = g3d->GetTextureManager ();
txtmgr->SetPalette ();
return true;
}
void TerrBigTut::MainLoop ()
{
csDefaultRunLoop (object_reg);
}
bool TerrBigTut::SimpleEventHandler (iEvent &e)
{
return Sys->HandleEvent (e);
}
bool TerrBigTut::HandleEvent (iEvent &e)
{
if (e.Type == csevBroadcast && e.Command.Code == cscmdProcess) {
SetupFrame ();
return true;
}
if (e.Type == csevBroadcast && e.Command.Code == cscmdFinalProcess) {
FinishFrame ();
return true;
}
if (e.Type == csevKeyDown && e.Key.Code == CSKEY_ESC) {
csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
return true;
};
return false;
}
void TerrBigTut::SetupFrame ()
{
float elapsed_time = ((float)vc->GetElapsedTicks ())/1000.0;
float speed = elapsed_time * 0.6;
iCamera *c = view->GetCamera ();
if (kbd->GetKeyState (CSKEY_RIGHT))
c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
if (kbd->GetKeyState (CSKEY_LEFT))
c->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);
if (kbd->GetKeyState (CSKEY_PGUP))
c->GetTransform ().RotateThis (CS_VEC_TILT_UP, speed);
if (kbd->GetKeyState (CSKEY_PGDN))
c->GetTransform ().RotateThis (CS_VEC_TILT_DOWN, speed);
if (kbd->GetKeyState (CSKEY_UP))
c->Move (CS_VEC_FORWARD * 10 * speed);
if (kbd->GetKeyState (CSKEY_DOWN))
c->Move (CS_VEC_FORWARD * -10 * speed);
if (g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS)) {
view->Draw ();
}
}
void TerrBigTut::FinishFrame ()
{
g3d->FinishDraw ();
g3d->Print (NULL);
}
int main (int argc, char *argv[])
{
iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);
Sys = new TerrBigTut(object_reg);
if (Sys->Initialize ()) {
Sys->MainLoop ();
}
delete Sys;
csInitializer::DestroyApplication (object_reg);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#1226487 Dereference null return value<commit_after><|endoftext|>
|
<commit_before>/// \file ROOT/RError.h
/// \ingroup Base ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2019-12-11
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RError
#define ROOT7_RError
#include <ROOT/RConfig.hxx> // for R__[un]likely
#include <ROOT/RLogger.hxx> // for R__LOG_PRETTY_FUNCTION
#include <cstddef>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// The RResult<T> class and their related classes are used for call chains that can throw exceptions,
// such as I/O code paths. Throwing of the exception is deferred to allow for `if (result)` style error
// checking where it makes sense.
//
// A function returning an RResult might look like this:
//
// RResult<int> MyIOFunc()
// {
// int rv = syscall(...);
// if (rv == -1)
// R__FAIL("user-facing error message");
// if (rv == kShortcut)
// return 42;
// R__FORWARD_RESULT(FuncThatReturnsRResultOfInt());
// }
//
// Code using MyIOFunc might look like this:
//
// auto result = MyIOOperation();
// if (!result) {
// /* custom error handling or result.Throw() */
// }
// switch (result.Get()) {
// ...
// }
//
// Note that RResult<void> can be used for a function without return value, like this
//
// RResult<void> DoSomething()
// {
// if (failure)
// R__FAIL("user-facing error messge");
// R__SUCCESS
// }
namespace ROOT {
namespace Experimental {
// clang-format off
/**
\class ROOT::Experimental::RError
\ingroup Base
\brief Captures diagnostics related to a ROOT runtime error
*/
// clang-format on
class RError {
public:
struct RLocation {
RLocation() = default;
RLocation(const std::string &func, const std::string &file, int line)
: fFunction(func), fSourceFile(file), fSourceLine(line) {}
// TODO(jblomer) use std::source_location once available
std::string fFunction;
std::string fSourceFile;
int fSourceLine;
};
private:
/// User-facing error message
std::string fMessage;
/// The location of the error related to fMessage plus upper frames if the error is forwarded through the call stack
std::vector<RLocation> fStackTrace;
public:
/// Used by R__FAIL
RError(const std::string &message, RLocation &&sourceLocation);
/// Used by R__FORWARD_RESULT
void AddFrame(RLocation &&sourceLocation);
/// Add more information to the diagnostics
void AppendToMessage(const std::string &info) { fMessage += info; }
/// Format a dignostics report, e.g. for an exception message
std::string GetReport() const;
const std::vector<RLocation> &GetStackTrace() const { return fStackTrace; }
};
// clang-format off
/**
\class ROOT::Experimental::RException
\ingroup Base
\brief Base class for all ROOT issued exceptions
*/
// clang-format on
class RException : public std::runtime_error {
RError fError;
public:
explicit RException(const RError &error) : std::runtime_error(error.GetReport()), fError(error) {}
const RError &GetError() const { return fError; }
};
/// Wrapper class that generates a data member of type T in RResult<T> for all Ts except T == void
namespace Internal {
template <typename T>
struct RResultType {
RResultType() = default;
explicit RResultType(const T &value) : fValue(value) {}
T fValue;
};
template <>
struct RResultType<void> {};
} // namespace Internal
// clang-format off
/**
\class ROOT::Experimental::RResult
\ingroup Base
\brief The class is used as a return type for operations that can fail; wraps a value of type T or an RError
The RResult enforces checking whether it contains a valid value or an error state. If the RResult leaves the scope
unchecked, it will throw an exception. RResult should only be allocated on the stack, which is helped by deleting the
new operator. RResult is movable but not copyable to avoid throwing exceptions multiple times.
*/
// clang-format on
template <typename T>
class RResult : public Internal::RResultType<T> {
private:
/// This is the nullptr for an RResult representing success
std::unique_ptr<RError> fError;
/// This is safe because checking an RResult is not a multi-threaded operation
mutable bool fIsChecked{false};
public:
/// Constructor is _not_ explicit in order to allow for `return T();` for functions returning RResult<T>
/// Only available if T is not void
template <typename Dummy = T, typename = typename std::enable_if_t<!std::is_void<T>::value, Dummy>>
RResult(const Dummy &value) : Internal::RResultType<T>(value) {}
/// Constructor is _not_ explicit such that the RError returned by R__FAIL can be converted into an RResult<T>
/// for any T
RResult(const RError &error) : fError(std::make_unique<RError>(error)) {}
/// RResult<void> has a default contructor that creates an object representing success
template <typename Dummy = T, typename = typename std::enable_if_t<std::is_void<T>::value, Dummy>>
RResult() {}
RResult(const RResult &other) = delete;
RResult(RResult &&other) = default;
RResult &operator =(const RResult &other) = delete;
RResult &operator =(RResult &&other) = default;
~RResult() noexcept(false)
{
if (R__unlikely(fError && !fIsChecked)) {
// Prevent from throwing if the object is deconstructed in the course of stack unwinding for another exception
#if __cplusplus >= 201703L
if (std::uncaught_exceptions() == 0)
#else
if (!std::uncaught_exception())
#endif
{
throw RException(*fError);
}
}
}
/// Only available if T is not void
template <typename Dummy = T>
typename std::enable_if_t<!std::is_void<T>::value, const Dummy &>
Get()
{
if (R__unlikely(fError)) {
fError->AppendToMessage(" (invalid access)");
throw RException(*fError);
}
return Internal::RResultType<T>::fValue;
}
explicit operator bool() const
{
fIsChecked = true;
return !fError;
}
RError *GetError() { return fError.get(); }
void Throw() { throw RException(*fError); }
// Help to prevent heap construction of RResult objects. Unchecked RResult objects in failure state should throw
// an exception close to the error location. For stack allocated RResult objects, an exception is thrown
// the latest when leaving the scope. Heap allocated ill RResult objects can live much longer making it difficult
// to trace back the original failure.
void *operator new(std::size_t size) = delete;
void *operator new(std::size_t, void *) = delete;
void *operator new[](std::size_t) = delete;
void *operator new[](std::size_t, void *) = delete;
};
/// Short-hand to return an RResult<void> indicating success
#define R__SUCCESS return ROOT::Experimental::RResult<void>();
/// Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult<T>
#define R__FAIL(msg) return ROOT::Experimental::RError(msg, {R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__})
/// Short-hand to return an RResult<T> value from a subroutine to the calling stack frame
#define R__FORWARD_RESULT(res) if (res.GetError()) \
{ res.GetError()->AddFrame({R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}); } \
return res
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>[v7, excpetions] code comment improvements<commit_after>/// \file ROOT/RError.h
/// \ingroup Base ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2019-12-11
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RError
#define ROOT7_RError
#include <ROOT/RConfig.hxx> // for R__[un]likely
#include <ROOT/RLogger.hxx> // for R__LOG_PRETTY_FUNCTION
#include <cstddef>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// The RResult<T> class and their related classes are used for call chains that can throw exceptions,
// such as I/O code paths. Throwing of the exception is deferred to allow for `if (result)` style error
// checking where it makes sense.
//
// A function returning an RResult might look like this:
//
// RResult<int> MyIOFunc()
// {
// int rv = syscall(...);
// if (rv == -1)
// R__FAIL("user-facing error message");
// if (rv == kShortcut)
// return 42;
// R__FORWARD_RESULT(FuncThatReturnsRResultOfInt());
// }
//
// Code using MyIOFunc might look like this:
//
// auto result = MyIOOperation();
// if (!result) {
// /* custom error handling or result.Throw() */
// }
// switch (result.Get()) {
// ...
// }
//
// Note that RResult<void> can be used for a function without return value, like this
//
// RResult<void> DoSomething()
// {
// if (failure)
// R__FAIL("user-facing error messge");
// R__SUCCESS
// }
namespace ROOT {
namespace Experimental {
// clang-format off
/**
\class ROOT::Experimental::RError
\ingroup Base
\brief Captures diagnostics related to a ROOT runtime error
*/
// clang-format on
class RError {
public:
struct RLocation {
RLocation() = default;
RLocation(const std::string &func, const std::string &file, int line)
: fFunction(func), fSourceFile(file), fSourceLine(line) {}
// TODO(jblomer) use std::source_location once available
std::string fFunction;
std::string fSourceFile;
int fSourceLine;
};
private:
/// User-facing error message
std::string fMessage;
/// The location of the error related to fMessage plus upper frames if the error is forwarded through the call stack
std::vector<RLocation> fStackTrace;
public:
/// Used by R__FAIL
RError(const std::string &message, RLocation &&sourceLocation);
/// Used by R__FORWARD_RESULT
void AddFrame(RLocation &&sourceLocation);
/// Add more information to the diagnostics
void AppendToMessage(const std::string &info) { fMessage += info; }
/// Format a dignostics report, e.g. for an exception message
std::string GetReport() const;
const std::vector<RLocation> &GetStackTrace() const { return fStackTrace; }
};
// clang-format off
/**
\class ROOT::Experimental::RException
\ingroup Base
\brief Base class for all ROOT issued exceptions
*/
// clang-format on
class RException : public std::runtime_error {
RError fError;
public:
explicit RException(const RError &error) : std::runtime_error(error.GetReport()), fError(error) {}
const RError &GetError() const { return fError; }
};
/// Wrapper class that generates a data member of type T in RResult<T> for all Ts except T == void
namespace Internal {
template <typename T>
struct RResultType {
RResultType() = default;
explicit RResultType(const T &value) : fValue(value) {}
T fValue;
};
template <>
struct RResultType<void> {};
} // namespace Internal
// clang-format off
/**
\class ROOT::Experimental::RResult
\ingroup Base
\brief The class is used as a return type for operations that can fail; wraps a value of type T or an RError
RResult enforces checking whether it contains a valid value or an error state. If the RResult leaves the scope
unchecked, it will throw an exception. RResult should only be allocated on the stack, which is helped by deleting the
new operator. RResult is movable but not copyable to avoid throwing multiple exceptions about the same failure.
*/
// clang-format on
template <typename T>
class RResult : public Internal::RResultType<T> {
private:
/// This is the nullptr for an RResult representing success
std::unique_ptr<RError> fError;
/// This is safe because checking an RResult is not a multi-threaded operation
mutable bool fIsChecked{false};
public:
/// Constructor is _not_ explicit in order to allow for `return T();` for functions returning RResult<T>
/// Only available if T is not void
template <typename Dummy = T, typename = typename std::enable_if_t<!std::is_void<T>::value, Dummy>>
RResult(const Dummy &value) : Internal::RResultType<T>(value) {}
/// Constructor is _not_ explicit such that the RError returned by R__FAIL can be converted into an RResult<T>
/// for any T
RResult(const RError &error) : fError(std::make_unique<RError>(error)) {}
/// RResult<void> has a default contructor that creates an object representing success
template <typename Dummy = T, typename = typename std::enable_if_t<std::is_void<T>::value, Dummy>>
RResult() {}
RResult(const RResult &other) = delete;
RResult(RResult &&other) = default;
RResult &operator =(const RResult &other) = delete;
RResult &operator =(RResult &&other) = default;
~RResult() noexcept(false)
{
if (R__unlikely(fError && !fIsChecked)) {
// Prevent from throwing if the object is deconstructed in the course of stack unwinding for another exception
#if __cplusplus >= 201703L
if (std::uncaught_exceptions() == 0)
#else
if (!std::uncaught_exception())
#endif
{
throw RException(*fError);
}
}
}
/// Only available if T is not void
template <typename Dummy = T>
typename std::enable_if_t<!std::is_void<T>::value, const Dummy &>
Get()
{
if (R__unlikely(fError)) {
fError->AppendToMessage(" (invalid access)");
throw RException(*fError);
}
return Internal::RResultType<T>::fValue;
}
explicit operator bool() const
{
fIsChecked = true;
return !fError;
}
RError *GetError() { return fError.get(); }
void Throw() { throw RException(*fError); }
// Help to prevent heap construction of RResult objects. Unchecked RResult objects in failure state should throw
// an exception close to the error location. For stack allocated RResult objects, an exception is thrown
// the latest when leaving the scope. Heap allocated ill RResult objects can live much longer making it difficult
// to trace back the original failure.
void *operator new(std::size_t size) = delete;
void *operator new(std::size_t, void *) = delete;
void *operator new[](std::size_t) = delete;
void *operator new[](std::size_t, void *) = delete;
};
/// Short-hand to return an RResult<void> indicating success
#define R__SUCCESS return ROOT::Experimental::RResult<void>();
/// Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult<T>
#define R__FAIL(msg) return ROOT::Experimental::RError(msg, {R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__})
/// Short-hand to return an RResult<T> value from a subroutine to the calling stack frame
#define R__FORWARD_RESULT(res) if (res.GetError()) \
{ res.GetError()->AddFrame({R__LOG_PRETTY_FUNCTION, __FILE__, __LINE__}); } \
return res
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|>
|
<commit_before>// ==========================================================================
// samcat
// ==========================================================================
// Copyright (c) 2006-2014, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/bam_io.h>
#include <seqan/arg_parse.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace seqan;
// ==========================================================================
// Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class AppOptions
// --------------------------------------------------------------------------
// This struct stores the options from the command line.
//
// You might want to rename this to reflect the name of your app.
struct AppOptions
{
StringSet<CharString> inFiles;
CharString outFile;
bool bamFormat;
bool verbose;
};
// ==========================================================================
// Functions
// ==========================================================================
// --------------------------------------------------------------------------
// Function mergeBamFiles()
// --------------------------------------------------------------------------
template <typename TWriter>
void catBamFiles(TWriter &writer, StringSet<CharString> &inFiles, AppOptions const &options)
{
String<BamFileIn *> readerPtr;
resize(readerPtr, length(inFiles));
// Step 1: Merge all headers (if available)
BamHeader header;
for (unsigned i = 0; i < length(inFiles); ++i)
{
readerPtr[i] = new BamFileIn(writer);
bool success;
if (inFiles[i] != "-")
success = open(*readerPtr[i], toCString(inFiles[i]));
else
// read from stdin (autodetect format from stream)
success = open(*readerPtr[i], std::cin);
if (!success)
{
std::cerr << "Couldn't open " << toCString(inFiles[i]) << " for reading." << std::endl;
close(*readerPtr[i]);
delete readerPtr[i];
readerPtr[i] = NULL;
continue;
}
readRecord(header, *(readerPtr[i]));
}
// Step 2: Remove duplicate header entries and write merged header
removeDuplicates(header);
writeRecord(writer, header);
// Step 3: Read and output alignment records
BamAlignmentRecord record;
String<BamAlignmentRecord> records;
__uint64 numRecords = 0;
double start = sysTime();
for (unsigned i = 0; i != length(inFiles); ++i)
{
if (readerPtr[i] == NULL)
continue;
BamFileIn &reader = *readerPtr[i];
// copy all alignment records
if (isEqual(format(writer), Sam()))
{
// For Sam parallel batch processing is faster
while (!atEnd(reader))
{
unsigned size = readBatch(records, reader, 100000);
writeRecords(writer, prefix(records, size));
numRecords += size;
}
}
else
{
while (!atEnd(reader))
{
readRecord(record, reader);
writeRecord(writer, record);
++numRecords;
}
}
close(reader);
delete readerPtr[i];
}
double stop = sysTime();
if (options.verbose)
{
std::cerr << "Number of alignments: " << numRecords << std::endl;
std::cerr << "Elapsed time: " << stop - start << " seconds" << std::endl;
}
}
// --------------------------------------------------------------------------
// Function parseCommandLine()
// --------------------------------------------------------------------------
ArgumentParser::ParseResult
parseCommandLine(AppOptions & options, int argc, char const ** argv)
{
// Setup ArgumentParser.
ArgumentParser parser("samcat");
// Set short description, version, and date.
setCategory(parser, "Utilities");
setVersion(parser, "0.1");
setDate(parser, "May 2014");
// Define usage line and long description.
addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIINFILE\\fP> [<\\fIINFILE\\fP> ...] [-o <\\fIOUTFILE\\fP>]");
#if SEQAN_HAS_ZLIB
setShortDescription(parser, "SAM/BAM file concatenation and conversion");
addDescription(parser, "This tool reads a set of input files in SAM or BAM format "
#else
setShortDescription(parser, "SAM file concatenation and conversion");
addDescription(parser, "This tool reads a set of input files in SAM format "
#endif
"and outputs the concatenation of them. "
"If the output file name is ommitted the result is written to stdout.");
addDescription(parser, "(c) Copyright in 2014 by David Weese.");
addOption(parser, ArgParseOption("o", "output", "Output file name.", ArgParseOption::OUTPUTFILE));
setValidValues(parser, "output", BamFileOut::getFileFormatExtensions());
// We require one argument.
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "INFILE", true));
setValidValues(parser, 0, BamFileIn::getFileFormatExtensions());
#if SEQAN_HAS_ZLIB
setHelpText(parser, 0, "Input SAM or BAM file (or - for stdin).");
addOption(parser, ArgParseOption("b", "bam", "Use BAM format for standard output. Default: SAM."));
#else
setHelpText(parser, 0, "Input SAM file (or - for stdin).");
#endif
addOption(parser, ArgParseOption("v", "verbose", "Print some stats."));
// Add Examples Section.
addTextSection(parser, "Examples");
addListItem(parser, "\\fBsamcat\\fP \\fBmapped1.sam\\fP \\fBmapped2.sam\\fP \\fB-o\\fP \\fBmerged.sam\\fP",
"Merge two SAM files.");
#if SEQAN_HAS_ZLIB
addListItem(parser, "\\fBsamcat\\fP \\fBinput.sam\\fP \\fB-o\\fP \\fBouput.bam\\fP",
"Convert a SAM file into BAM format.");
#endif
// Parse command line.
ArgumentParser::ParseResult res = parse(parser, argc, argv);
// Only extract options if the program will continue after parseCommandLine()
if (res != ArgumentParser::PARSE_OK)
return res;
options.inFiles = getArgumentValues(parser, 0);
getOptionValue(options.outFile, parser, "output");
#if SEQAN_HAS_ZLIB
getOptionValue(options.bamFormat, parser, "bam");
#endif
getOptionValue(options.verbose, parser, "verbose");
return ArgumentParser::PARSE_OK;
}
// --------------------------------------------------------------------------
// Function main()
// --------------------------------------------------------------------------
// Program entry point.
int main(int argc, char const ** argv)
{
// Parse the command line.
AppOptions options;
ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv);
// If there was an error parsing or built-in argument parser functionality
// was triggered then we exit the program. The return code is 1 if there
// were errors and 0 if there were none.
if (res != ArgumentParser::PARSE_OK)
return res == ArgumentParser::PARSE_ERROR;
bool success;
BamFileOut writer;
if (!empty(options.outFile))
success = open(writer, toCString(options.outFile));
else
{
// write to stdout
#if SEQAN_HAS_ZLIB
if (options.bamFormat)
success = open(writer, std::cout, Bam());
else
#endif
success = open(writer, std::cout, Sam());
}
if (!success)
{
std::cerr << "Couldn't open " << options.outFile << " for writing." << std::endl;
return 1;
}
catBamFiles(writer, options.inFiles, options);
return 0;
}
<commit_msg>[FIX] no header reordering if input is a single file<commit_after>// ==========================================================================
// samcat
// ==========================================================================
// Copyright (c) 2006-2014, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/bam_io.h>
#include <seqan/arg_parse.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace seqan;
// ==========================================================================
// Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class AppOptions
// --------------------------------------------------------------------------
// This struct stores the options from the command line.
//
// You might want to rename this to reflect the name of your app.
struct AppOptions
{
StringSet<CharString> inFiles;
CharString outFile;
bool bamFormat;
bool verbose;
};
// ==========================================================================
// Functions
// ==========================================================================
// --------------------------------------------------------------------------
// Function mergeBamFiles()
// --------------------------------------------------------------------------
template <typename TWriter>
void catBamFiles(TWriter &writer, StringSet<CharString> &inFiles, AppOptions const &options)
{
String<BamFileIn *> readerPtr;
resize(readerPtr, length(inFiles));
// Step 1: Merge all headers (if available)
BamHeader header;
for (unsigned i = 0; i < length(inFiles); ++i)
{
readerPtr[i] = new BamFileIn(writer);
bool success;
if (inFiles[i] != "-")
success = open(*readerPtr[i], toCString(inFiles[i]));
else
// read from stdin (autodetect format from stream)
success = open(*readerPtr[i], std::cin);
if (!success)
{
std::cerr << "Couldn't open " << toCString(inFiles[i]) << " for reading." << std::endl;
close(*readerPtr[i]);
delete readerPtr[i];
readerPtr[i] = NULL;
continue;
}
readRecord(header, *(readerPtr[i]));
}
// Step 2: Remove duplicate header entries and write merged header
if (length(inFiles) > 1)
removeDuplicates(header);
writeRecord(writer, header);
// Step 3: Read and output alignment records
BamAlignmentRecord record;
String<BamAlignmentRecord> records;
__uint64 numRecords = 0;
double start = sysTime();
for (unsigned i = 0; i != length(inFiles); ++i)
{
if (readerPtr[i] == NULL)
continue;
BamFileIn &reader = *readerPtr[i];
// copy all alignment records
if (isEqual(format(writer), Sam()))
{
// For Sam parallel batch processing is faster
while (!atEnd(reader))
{
unsigned size = readBatch(records, reader, 100000);
writeRecords(writer, prefix(records, size));
numRecords += size;
}
}
else
{
while (!atEnd(reader))
{
readRecord(record, reader);
writeRecord(writer, record);
++numRecords;
}
}
close(reader);
delete readerPtr[i];
}
double stop = sysTime();
if (options.verbose)
{
std::cerr << "Number of alignments: " << numRecords << std::endl;
std::cerr << "Elapsed time: " << stop - start << " seconds" << std::endl;
}
}
// --------------------------------------------------------------------------
// Function parseCommandLine()
// --------------------------------------------------------------------------
ArgumentParser::ParseResult
parseCommandLine(AppOptions & options, int argc, char const ** argv)
{
// Setup ArgumentParser.
ArgumentParser parser("samcat");
// Set short description, version, and date.
setCategory(parser, "Utilities");
setVersion(parser, "0.1");
setDate(parser, "May 2014");
// Define usage line and long description.
addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIINFILE\\fP> [<\\fIINFILE\\fP> ...] [-o <\\fIOUTFILE\\fP>]");
#if SEQAN_HAS_ZLIB
setShortDescription(parser, "SAM/BAM file concatenation and conversion");
addDescription(parser, "This tool reads a set of input files in SAM or BAM format "
#else
setShortDescription(parser, "SAM file concatenation and conversion");
addDescription(parser, "This tool reads a set of input files in SAM format "
#endif
"and outputs the concatenation of them. "
"If the output file name is ommitted the result is written to stdout.");
addDescription(parser, "(c) Copyright in 2014 by David Weese.");
addOption(parser, ArgParseOption("o", "output", "Output file name.", ArgParseOption::OUTPUTFILE));
setValidValues(parser, "output", BamFileOut::getFileFormatExtensions());
// We require one argument.
addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "INFILE", true));
setValidValues(parser, 0, BamFileIn::getFileFormatExtensions());
#if SEQAN_HAS_ZLIB
setHelpText(parser, 0, "Input SAM or BAM file (or - for stdin).");
addOption(parser, ArgParseOption("b", "bam", "Use BAM format for standard output. Default: SAM."));
#else
setHelpText(parser, 0, "Input SAM file (or - for stdin).");
#endif
addOption(parser, ArgParseOption("v", "verbose", "Print some stats."));
// Add Examples Section.
addTextSection(parser, "Examples");
addListItem(parser, "\\fBsamcat\\fP \\fBmapped1.sam\\fP \\fBmapped2.sam\\fP \\fB-o\\fP \\fBmerged.sam\\fP",
"Merge two SAM files.");
#if SEQAN_HAS_ZLIB
addListItem(parser, "\\fBsamcat\\fP \\fBinput.sam\\fP \\fB-o\\fP \\fBouput.bam\\fP",
"Convert a SAM file into BAM format.");
#endif
// Parse command line.
ArgumentParser::ParseResult res = parse(parser, argc, argv);
// Only extract options if the program will continue after parseCommandLine()
if (res != ArgumentParser::PARSE_OK)
return res;
options.inFiles = getArgumentValues(parser, 0);
getOptionValue(options.outFile, parser, "output");
#if SEQAN_HAS_ZLIB
getOptionValue(options.bamFormat, parser, "bam");
#endif
getOptionValue(options.verbose, parser, "verbose");
return ArgumentParser::PARSE_OK;
}
// --------------------------------------------------------------------------
// Function main()
// --------------------------------------------------------------------------
// Program entry point.
int main(int argc, char const ** argv)
{
// Parse the command line.
AppOptions options;
ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv);
// If there was an error parsing or built-in argument parser functionality
// was triggered then we exit the program. The return code is 1 if there
// were errors and 0 if there were none.
if (res != ArgumentParser::PARSE_OK)
return res == ArgumentParser::PARSE_ERROR;
bool success;
BamFileOut writer;
if (!empty(options.outFile))
success = open(writer, toCString(options.outFile));
else
// write to stdout
#if SEQAN_HAS_ZLIB
if (options.bamFormat)
success = open(writer, std::cout, Bam());
else
#endif
success = open(writer, std::cout, Sam());
if (!success)
{
std::cerr << "Couldn't open " << options.outFile << " for writing." << std::endl;
return 1;
}
catBamFiles(writer, options.inFiles, options);
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2007 by Robert Zwerus <arzie@dds.nl> *
* *
* 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 Library 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 "akappend.h"
#include "libs/imapparser_p.h"
#include "imapstreamparser.h"
#include "append.h"
#include "response.h"
#include "handlerhelper.h"
#include "akonadi.h"
#include "connection.h"
#include "preprocessormanager.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "storage/transaction.h"
#include "storage/parttypehelper.h"
#include "storage/dbconfig.h"
#include "storage/partstreamer.h"
#include "storage/parthelper.h"
#include "libs/protocol_p.h"
#include <QtCore/QDebug>
using namespace Akonadi;
using namespace Akonadi::Server;
AkAppend::AkAppend()
: Handler()
{
}
AkAppend::~AkAppend()
{
}
QByteArray AkAppend::parseFlag( const QByteArray &flag ) const
{
const int pos1 = flag.indexOf( '[' );
const int pos2 = flag.lastIndexOf( ']' );
return flag.mid( pos1 + 1, pos2 - pos1 - 1 );
}
bool AkAppend::buildPimItem( PimItem &item, Collection &col,
ChangedAttributes &itemFlags,
ChangedAttributes &itemTagsRID,
ChangedAttributes &itemTagsGID )
{
// Arguments: mailbox name
// OPTIONAL flag parenthesized list
// OPTIONAL date/time string
// (partname literal)+
//
// Syntax:
// x-akappend = "X-AKAPPEND" SP mailbox SP size [SP flag-list] [SP date-time] SP (partname SP literal)+
const QByteArray mailbox = m_streamParser->readString();
const qint64 size = m_streamParser->readNumber();
// parse optional flag parenthesized list
// Syntax:
// flag-list = "(" [flag *(SP flag)] ")"
// flag = "\ANSWERED" / "\FLAGGED" / "\DELETED" / "\SEEN" /
// "\DRAFT" / flag-keyword / flag-extension
// ; Does not include "\Recent"
// flag-extension = "\" atom
// flag-keyword = atom
QList<QByteArray> flags;
if ( m_streamParser->hasList() ) {
flags = m_streamParser->readParenthesizedList();
}
// parse optional date/time string
QDateTime dateTime;
if ( m_streamParser->hasDateTime() ) {
dateTime = m_streamParser->readDateTime().toUTC();
// FIXME Should we return an error if m_dateTime is invalid?
} else {
// if date/time is not given then it will be set to the current date/time
// converted to UTC.
dateTime = QDateTime::currentDateTime().toUTC();
}
Response response;
col = HandlerHelper::collectionFromIdOrName( mailbox );
if ( !col.isValid() ) {
throw HandlerException( QByteArray( "Unknown collection for '" ) + mailbox + QByteArray( "'." ) );
}
if ( col.isVirtual() ) {
throw HandlerException( "Cannot append item into virtual collection" );
}
QByteArray mt;
QString remote_id;
QString remote_revision;
QString gid;
Q_FOREACH ( const QByteArray &flag, flags ) {
if ( flag.startsWith( AKONADI_FLAG_MIMETYPE ) ) {
mt = parseFlag( flag );
} else if ( flag.startsWith( AKONADI_FLAG_REMOTEID ) ) {
remote_id = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_REMOTEREVISION ) ) {
remote_revision = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_GID ) ) {
gid = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( "+" AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = true;
itemTagsGID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "-" AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = true;
itemTagsGID.removed.append( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = false;
itemTagsGID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "+" AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = true;
itemTagsRID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "-" AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = true;
itemTagsRID.removed.append( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = false;
itemTagsRID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( '+' ) ) {
itemFlags.incremental = true;
itemFlags.added.append( flag.mid( 1 ) );
} else if ( flag.startsWith( '-' ) ) {
itemFlags.incremental = true;
itemFlags.removed.append( flag.mid( 1 ) );
} else {
itemFlags.incremental = false;
itemFlags.added.append( flag );
}
}
// standard imap does not know this attribute, so that's mail
if ( mt.isEmpty() ) {
mt = "message/rfc822";
}
MimeType mimeType = MimeType::retrieveByName( QString::fromLatin1( mt ) );
if ( !mimeType.isValid() ) {
MimeType m( QString::fromLatin1( mt ) );
if ( !m.insert() ) {
return failureResponse( QByteArray( "Unable to create mimetype '" ) + mt + QByteArray( "'." ) );
}
mimeType = m;
}
item.setRev( 0 );
item.setSize( size );
item.setMimeTypeId( mimeType.id() );
item.setCollectionId( col.id() );
if ( dateTime.isValid() ) {
item.setDatetime( dateTime );
}
if ( remote_id.isEmpty() ) {
// from application
item.setDirty( true );
} else {
// from resource
item.setRemoteId( remote_id );
item.setDirty( false );
}
item.setRemoteRevision( remote_revision );
item.setGid( gid );
item.setAtime( QDateTime::currentDateTime() );
return true;
}
// This is used for clients that don't support item streaming
bool AkAppend::readParts( PimItem &pimItem )
{
// parse part specification
QVector<QPair<QByteArray, QPair<qint64, int> > > partSpecs;
QByteArray partName = "";
qint64 partSize = -1;
qint64 partSizes = 0;
bool ok = false;
qint64 realSize = pimItem.size();
const QList<QByteArray> list = m_streamParser->readParenthesizedList();
Q_FOREACH ( const QByteArray &item, list ) {
if ( partName.isEmpty() && partSize == -1 ) {
partName = item;
continue;
}
if ( item.startsWith( ':' ) ) {
int pos = 1;
ImapParser::parseNumber( item, partSize, &ok, pos );
if ( !ok ) {
partSize = 0;
}
int version = 0;
QByteArray plainPartName;
ImapParser::splitVersionedKey( partName, plainPartName, version );
partSpecs.append( qMakePair( plainPartName, qMakePair( partSize, version ) ) );
partName = "";
partSizes += partSize;
partSize = -1;
}
}
realSize = qMax( partSizes, realSize );
const QByteArray allParts = m_streamParser->readString();
// chop up literal data in parts
int pos = 0; // traverse through part data now
QPair<QByteArray, QPair<qint64, int> > partSpec;
Q_FOREACH ( partSpec, partSpecs ) {
// wrap data into a part
Part part;
part.setPimItemId( pimItem.id() );
part.setPartType( PartTypeHelper::fromFqName( partSpec.first ) );
part.setData( allParts.mid( pos, partSpec.second.first ) );
if ( partSpec.second.second != 0 ) {
part.setVersion( partSpec.second.second );
}
part.setDatasize( partSpec.second.first );
if ( !PartHelper::insert( &part ) ) {
return failureResponse( "Unable to append item part" );
}
pos += partSpec.second.first;
}
if ( realSize != pimItem.size() ) {
pimItem.setSize( realSize );
pimItem.update();
}
return true;
}
bool AkAppend::insertItem( PimItem &item, const Collection &parentCol,
const QVector<QByteArray> &itemFlags,
const QVector<QByteArray> &itemTagsRID,
const QVector<QByteArray> &itemTagsGID )
{
if ( !item.insert() ) {
return failureResponse( "Failed to append item" );
}
// set message flags
// This will hit an entry in cache inserted there in buildPimItem()
const Flag::List flagList = HandlerHelper::resolveFlags( itemFlags );
bool flagsChanged = false;
if ( !DataStore::self()->appendItemsFlags( PimItem::List() << item, flagList, flagsChanged, false, parentCol, true ) ) {
return failureResponse( "Unable to append item flags." );
}
Tag::List tagList;
if ( !itemTagsGID.isEmpty() ) {
tagList << HandlerHelper::resolveTagsByGID( itemTagsGID );
}
if ( !itemTagsRID.isEmpty() ) {
tagList << HandlerHelper::resolveTagsByRID( itemTagsRID, connection()->context() );
}
bool tagsChanged;
if ( !DataStore::self()->appendItemsTags( PimItem::List() << item, tagList, tagsChanged, false, parentCol, true ) ) {
return failureResponse( "Unable to append item tags." );
}
// Handle individual parts
qint64 partSizes = 0;
if ( connection()->capabilities().akAppendStreaming() ) {
QByteArray partName /* unused */;
qint64 partSize;
m_streamParser->beginList();
PartStreamer streamer(connection(), m_streamParser, item, this);
connect( &streamer, SIGNAL(responseAvailable(Akonadi::Server::Response)),
this, SIGNAL(responseAvailable(Akonadi::Server::Response)) );
while ( !m_streamParser->atListEnd() ) {
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) {
throw HandlerException( "Syntax error" );
}
if ( !streamer.stream( command, false, partName, partSize ) ) {
throw HandlerException( streamer.error() );
}
partSizes += partSize;
}
// TODO: Try to avoid this addition query
if ( partSizes > item.size() ) {
item.setSize( partSizes );
item.update();
}
} else {
if ( !readParts( item ) ) {
return false;
}
}
// Preprocessing
if ( PreprocessorManager::instance()->isActive() ) {
Part hiddenAttribute;
hiddenAttribute.setPimItemId( item.id() );
hiddenAttribute.setPartType( PartTypeHelper::fromFqName( QString::fromLatin1( AKONADI_ATTRIBUTE_HIDDEN ) ) );
hiddenAttribute.setData( QByteArray() );
// TODO: Handle errors? Technically, this is not a critical issue as no data are lost
PartHelper::insert( &hiddenAttribute );
}
return true;
}
bool AkAppend::notify( const PimItem &item, const Collection &collection )
{
DataStore::self()->notificationCollector()->itemAdded( item, collection );
if ( PreprocessorManager::instance()->isActive() ) {
// enqueue the item for preprocessing
PreprocessorManager::instance()->beginHandleItem( item, DataStore::self() );
}
return true;
}
bool AkAppend::sendResponse( const QByteArray &responseStr, const PimItem &item )
{
// Date time is always stored in UTC time zone by the server.
const QString datetime = QLocale::c().toString( item.datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
Response response;
response.setTag( tag() );
response.setUserDefined();
response.setString( "[UIDNEXT " + QByteArray::number( item.id() ) + " DATETIME " + ImapParser::quote( datetime.toUtf8() ) + ']' );
Q_EMIT responseAvailable( response );
response.setSuccess();
response.setString( responseStr );
Q_EMIT responseAvailable( response );
return true;
}
bool AkAppend::parseStream()
{
// FIXME: The streaming/reading of all item parts can hold the transaction for
// unnecessary long time -> should we wrap the PimItem into one transaction
// and try to insert Parts independently? In case we fail to insert a part,
// it's not a problem as it can be re-fetched at any time, except for attributes.
DataStore *db = DataStore::self();
Transaction transaction( db );
ChangedAttributes itemFlags, itemTagsRID, itemTagsGID;
Collection parentCol;
PimItem item;
if ( !buildPimItem( item, parentCol, itemFlags, itemTagsRID, itemTagsGID ) ) {
return false;
}
if ( itemFlags.incremental ) {
throw HandlerException( "Incremental flags changes are not allowed in AK-APPEND" );
}
if ( itemTagsRID.incremental || itemTagsRID.incremental ) {
throw HandlerException( "Incremental tags changes are not allowed in AK-APPEND" );
}
if ( !insertItem( item, parentCol, itemFlags.added, itemTagsRID.added, itemTagsGID.added ) ) {
return false;
}
// All SQL is done, let's commit!
if ( !transaction.commit() ) {
return failureResponse( "Failed to commit transaction" );
}
notify( item, parentCol );
return sendResponse( "Append completed", item );
}
<commit_msg>Explicitly set size of hiddenAttribute<commit_after>/***************************************************************************
* Copyright (C) 2007 by Robert Zwerus <arzie@dds.nl> *
* *
* 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 Library 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 "akappend.h"
#include "libs/imapparser_p.h"
#include "imapstreamparser.h"
#include "append.h"
#include "response.h"
#include "handlerhelper.h"
#include "akonadi.h"
#include "connection.h"
#include "preprocessormanager.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "storage/transaction.h"
#include "storage/parttypehelper.h"
#include "storage/dbconfig.h"
#include "storage/partstreamer.h"
#include "storage/parthelper.h"
#include "libs/protocol_p.h"
#include <QtCore/QDebug>
using namespace Akonadi;
using namespace Akonadi::Server;
AkAppend::AkAppend()
: Handler()
{
}
AkAppend::~AkAppend()
{
}
QByteArray AkAppend::parseFlag( const QByteArray &flag ) const
{
const int pos1 = flag.indexOf( '[' );
const int pos2 = flag.lastIndexOf( ']' );
return flag.mid( pos1 + 1, pos2 - pos1 - 1 );
}
bool AkAppend::buildPimItem( PimItem &item, Collection &col,
ChangedAttributes &itemFlags,
ChangedAttributes &itemTagsRID,
ChangedAttributes &itemTagsGID )
{
// Arguments: mailbox name
// OPTIONAL flag parenthesized list
// OPTIONAL date/time string
// (partname literal)+
//
// Syntax:
// x-akappend = "X-AKAPPEND" SP mailbox SP size [SP flag-list] [SP date-time] SP (partname SP literal)+
const QByteArray mailbox = m_streamParser->readString();
const qint64 size = m_streamParser->readNumber();
// parse optional flag parenthesized list
// Syntax:
// flag-list = "(" [flag *(SP flag)] ")"
// flag = "\ANSWERED" / "\FLAGGED" / "\DELETED" / "\SEEN" /
// "\DRAFT" / flag-keyword / flag-extension
// ; Does not include "\Recent"
// flag-extension = "\" atom
// flag-keyword = atom
QList<QByteArray> flags;
if ( m_streamParser->hasList() ) {
flags = m_streamParser->readParenthesizedList();
}
// parse optional date/time string
QDateTime dateTime;
if ( m_streamParser->hasDateTime() ) {
dateTime = m_streamParser->readDateTime().toUTC();
// FIXME Should we return an error if m_dateTime is invalid?
} else {
// if date/time is not given then it will be set to the current date/time
// converted to UTC.
dateTime = QDateTime::currentDateTime().toUTC();
}
Response response;
col = HandlerHelper::collectionFromIdOrName( mailbox );
if ( !col.isValid() ) {
throw HandlerException( QByteArray( "Unknown collection for '" ) + mailbox + QByteArray( "'." ) );
}
if ( col.isVirtual() ) {
throw HandlerException( "Cannot append item into virtual collection" );
}
QByteArray mt;
QString remote_id;
QString remote_revision;
QString gid;
Q_FOREACH ( const QByteArray &flag, flags ) {
if ( flag.startsWith( AKONADI_FLAG_MIMETYPE ) ) {
mt = parseFlag( flag );
} else if ( flag.startsWith( AKONADI_FLAG_REMOTEID ) ) {
remote_id = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_REMOTEREVISION ) ) {
remote_revision = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_GID ) ) {
gid = QString::fromUtf8( parseFlag( flag ) );
} else if ( flag.startsWith( "+" AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = true;
itemTagsGID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "-" AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = true;
itemTagsGID.removed.append( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_TAG ) ) {
itemTagsGID.incremental = false;
itemTagsGID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "+" AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = true;
itemTagsRID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( "-" AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = true;
itemTagsRID.removed.append( parseFlag( flag ) );
} else if ( flag.startsWith( AKONADI_FLAG_RTAG ) ) {
itemTagsRID.incremental = false;
itemTagsRID.added.append( parseFlag( flag ) );
} else if ( flag.startsWith( '+' ) ) {
itemFlags.incremental = true;
itemFlags.added.append( flag.mid( 1 ) );
} else if ( flag.startsWith( '-' ) ) {
itemFlags.incremental = true;
itemFlags.removed.append( flag.mid( 1 ) );
} else {
itemFlags.incremental = false;
itemFlags.added.append( flag );
}
}
// standard imap does not know this attribute, so that's mail
if ( mt.isEmpty() ) {
mt = "message/rfc822";
}
MimeType mimeType = MimeType::retrieveByName( QString::fromLatin1( mt ) );
if ( !mimeType.isValid() ) {
MimeType m( QString::fromLatin1( mt ) );
if ( !m.insert() ) {
return failureResponse( QByteArray( "Unable to create mimetype '" ) + mt + QByteArray( "'." ) );
}
mimeType = m;
}
item.setRev( 0 );
item.setSize( size );
item.setMimeTypeId( mimeType.id() );
item.setCollectionId( col.id() );
if ( dateTime.isValid() ) {
item.setDatetime( dateTime );
}
if ( remote_id.isEmpty() ) {
// from application
item.setDirty( true );
} else {
// from resource
item.setRemoteId( remote_id );
item.setDirty( false );
}
item.setRemoteRevision( remote_revision );
item.setGid( gid );
item.setAtime( QDateTime::currentDateTime() );
return true;
}
// This is used for clients that don't support item streaming
bool AkAppend::readParts( PimItem &pimItem )
{
// parse part specification
QVector<QPair<QByteArray, QPair<qint64, int> > > partSpecs;
QByteArray partName = "";
qint64 partSize = -1;
qint64 partSizes = 0;
bool ok = false;
qint64 realSize = pimItem.size();
const QList<QByteArray> list = m_streamParser->readParenthesizedList();
Q_FOREACH ( const QByteArray &item, list ) {
if ( partName.isEmpty() && partSize == -1 ) {
partName = item;
continue;
}
if ( item.startsWith( ':' ) ) {
int pos = 1;
ImapParser::parseNumber( item, partSize, &ok, pos );
if ( !ok ) {
partSize = 0;
}
int version = 0;
QByteArray plainPartName;
ImapParser::splitVersionedKey( partName, plainPartName, version );
partSpecs.append( qMakePair( plainPartName, qMakePair( partSize, version ) ) );
partName = "";
partSizes += partSize;
partSize = -1;
}
}
realSize = qMax( partSizes, realSize );
const QByteArray allParts = m_streamParser->readString();
// chop up literal data in parts
int pos = 0; // traverse through part data now
QPair<QByteArray, QPair<qint64, int> > partSpec;
Q_FOREACH ( partSpec, partSpecs ) {
// wrap data into a part
Part part;
part.setPimItemId( pimItem.id() );
part.setPartType( PartTypeHelper::fromFqName( partSpec.first ) );
part.setData( allParts.mid( pos, partSpec.second.first ) );
if ( partSpec.second.second != 0 ) {
part.setVersion( partSpec.second.second );
}
part.setDatasize( partSpec.second.first );
if ( !PartHelper::insert( &part ) ) {
return failureResponse( "Unable to append item part" );
}
pos += partSpec.second.first;
}
if ( realSize != pimItem.size() ) {
pimItem.setSize( realSize );
pimItem.update();
}
return true;
}
bool AkAppend::insertItem( PimItem &item, const Collection &parentCol,
const QVector<QByteArray> &itemFlags,
const QVector<QByteArray> &itemTagsRID,
const QVector<QByteArray> &itemTagsGID )
{
if ( !item.insert() ) {
return failureResponse( "Failed to append item" );
}
// set message flags
// This will hit an entry in cache inserted there in buildPimItem()
const Flag::List flagList = HandlerHelper::resolveFlags( itemFlags );
bool flagsChanged = false;
if ( !DataStore::self()->appendItemsFlags( PimItem::List() << item, flagList, flagsChanged, false, parentCol, true ) ) {
return failureResponse( "Unable to append item flags." );
}
Tag::List tagList;
if ( !itemTagsGID.isEmpty() ) {
tagList << HandlerHelper::resolveTagsByGID( itemTagsGID );
}
if ( !itemTagsRID.isEmpty() ) {
tagList << HandlerHelper::resolveTagsByRID( itemTagsRID, connection()->context() );
}
bool tagsChanged;
if ( !DataStore::self()->appendItemsTags( PimItem::List() << item, tagList, tagsChanged, false, parentCol, true ) ) {
return failureResponse( "Unable to append item tags." );
}
// Handle individual parts
qint64 partSizes = 0;
if ( connection()->capabilities().akAppendStreaming() ) {
QByteArray partName /* unused */;
qint64 partSize;
m_streamParser->beginList();
PartStreamer streamer(connection(), m_streamParser, item, this);
connect( &streamer, SIGNAL(responseAvailable(Akonadi::Server::Response)),
this, SIGNAL(responseAvailable(Akonadi::Server::Response)) );
while ( !m_streamParser->atListEnd() ) {
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) {
throw HandlerException( "Syntax error" );
}
if ( !streamer.stream( command, false, partName, partSize ) ) {
throw HandlerException( streamer.error() );
}
partSizes += partSize;
}
// TODO: Try to avoid this addition query
if ( partSizes > item.size() ) {
item.setSize( partSizes );
item.update();
}
} else {
if ( !readParts( item ) ) {
return false;
}
}
// Preprocessing
if ( PreprocessorManager::instance()->isActive() ) {
Part hiddenAttribute;
hiddenAttribute.setPimItemId( item.id() );
hiddenAttribute.setPartType( PartTypeHelper::fromFqName( QString::fromLatin1( AKONADI_ATTRIBUTE_HIDDEN ) ) );
hiddenAttribute.setData( QByteArray() );
hiddenAttribute.setDatasize( 0 );
// TODO: Handle errors? Technically, this is not a critical issue as no data are lost
PartHelper::insert( &hiddenAttribute );
}
return true;
}
bool AkAppend::notify( const PimItem &item, const Collection &collection )
{
DataStore::self()->notificationCollector()->itemAdded( item, collection );
if ( PreprocessorManager::instance()->isActive() ) {
// enqueue the item for preprocessing
PreprocessorManager::instance()->beginHandleItem( item, DataStore::self() );
}
return true;
}
bool AkAppend::sendResponse( const QByteArray &responseStr, const PimItem &item )
{
// Date time is always stored in UTC time zone by the server.
const QString datetime = QLocale::c().toString( item.datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
Response response;
response.setTag( tag() );
response.setUserDefined();
response.setString( "[UIDNEXT " + QByteArray::number( item.id() ) + " DATETIME " + ImapParser::quote( datetime.toUtf8() ) + ']' );
Q_EMIT responseAvailable( response );
response.setSuccess();
response.setString( responseStr );
Q_EMIT responseAvailable( response );
return true;
}
bool AkAppend::parseStream()
{
// FIXME: The streaming/reading of all item parts can hold the transaction for
// unnecessary long time -> should we wrap the PimItem into one transaction
// and try to insert Parts independently? In case we fail to insert a part,
// it's not a problem as it can be re-fetched at any time, except for attributes.
DataStore *db = DataStore::self();
Transaction transaction( db );
ChangedAttributes itemFlags, itemTagsRID, itemTagsGID;
Collection parentCol;
PimItem item;
if ( !buildPimItem( item, parentCol, itemFlags, itemTagsRID, itemTagsGID ) ) {
return false;
}
if ( itemFlags.incremental ) {
throw HandlerException( "Incremental flags changes are not allowed in AK-APPEND" );
}
if ( itemTagsRID.incremental || itemTagsRID.incremental ) {
throw HandlerException( "Incremental tags changes are not allowed in AK-APPEND" );
}
if ( !insertItem( item, parentCol, itemFlags.added, itemTagsRID.added, itemTagsGID.added ) ) {
return false;
}
// All SQL is done, let's commit!
if ( !transaction.commit() ) {
return failureResponse( "Failed to commit transaction" );
}
notify( item, parentCol );
return sendResponse( "Append completed", item );
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 SLIBIO. All Rights Reserved.
*
* This file is part of the SLib.io project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <slib/core.h>
#include <slib.h>
using namespace slib;
int main(int argc, const char * argv[])
{
// List Example
{
int i;
List<String> list = {"a", "b", "c", "de", "a", "b"};
Println("List Original (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
Println("Member Access");
Println("[3]=%s", list[3]);
// Insert some values into the list
for (i = 0; i < 5; i++) {
list.add(String::format("t%d", i));
}
Println("List after insertion (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
// Remove some values from the list
list.removeRange(7, 3);
list.removeAt(3);
list.removeValues("b");
Println("List after removal (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
}
// Map Example
{
HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};
Println("HashMap Original (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
Println("Member Access");
Println("[ab]=%s", map["ab"]);
// Insert some values into the map
map.put("ab", 12);
map.put("aaa", 111);
map.put("abc", 123);
map.put("baa", 211);
map.put("bac", 213);
Println("HashMap after insertion (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Remove some values from the map
map.remove("ab");
map.remove("cd");
Println("HashMap after removal (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Convert to Ordered Map
Map<String, int> tree;
tree.putAll(map);
Println("Ordered Map (Count: %d)", tree.getCount());
for (auto& item : tree) {
Println("[%s]=%d", item.key, item.value);
}
}
return 0;
}
<commit_msg>minor update on example<commit_after>/*
* Copyright (c) 2017 SLIBIO. All Rights Reserved.
*
* This file is part of the SLib.io project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <slib/core.h>
using namespace slib;
int main(int argc, const char * argv[])
{
// List Example
{
int i;
List<String> list = {"a", "b", "c", "de", "a", "b"};
Println("List Original (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
Println("Member Access");
Println("[3]=%s", list[3]);
// Insert some values into the list
for (i = 0; i < 5; i++) {
list.add(String::format("t%d", i));
}
Println("List after insertion (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
// Remove some values from the list
list.removeRange(7, 3);
list.removeAt(3);
list.removeValues("b");
Println("List after removal (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
}
// Map Example
{
HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};
Println("HashMap Original (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
Println("Member Access");
Println("[ab]=%s", map["ab"]);
// Insert some values into the map
map.put("ab", 12);
map.put("aaa", 111);
map.put("abc", 123);
map.put("baa", 211);
map.put("bac", 213);
Println("HashMap after insertion (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Remove some values from the map
map.remove("ab");
map.remove("cd");
Println("HashMap after removal (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Convert to Ordered Map
Map<String, int> tree;
tree.putAll(map);
Println("Ordered Map (Count: %d)", tree.getCount());
for (auto& item : tree) {
Println("[%s]=%d", item.key, item.value);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file kmeans_main.cpp
* @author Ryan Curtin
*
* Executable for running K-Means.
*/
#include <mlpack/core.hpp>
#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"
using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;
// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
"on the given dataset, storing the learned cluster assignments either as "
"a column of labels in the file containing the input dataset or in a "
"separate file. Empty clusters are not allowed by default; when a cluster "
"becomes empty, the point furthest from the centroid of the cluster with "
"maximum variance is taken to fill that cluster."
"\n\n"
"Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
" k-means clustering\", 1998) can be used to select initial points by "
"specifying the --refined_start (-r) option. This approach works by taking"
" random samples of the dataset; to specify the number of samples, the "
"--samples parameter is used, and to specify the percentage of the dataset "
"to be used in each sample, the --percentage parameter is used (it should "
"be a value between 0.0 and 1.0)."
"\n\n"
"If you want to specify your own initial cluster assignments or initial "
"cluster centroids, this functionality is available in the C++ interface. "
"Alternately, file a bug (well, a feature request) on the mlpack bug "
"tracker.");
// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find.", "c");
// Output options.
PARAM_FLAG("in_place", "If specified, a column of the learned cluster "
"assignments will be added to the input dataset file. In this case, "
"--outputFile is not necessary.", "p");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
"o", "output.csv");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
" be written to the given file.", "c", "");
// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_DOUBLE("overclustering", "Finds (overclustering * clusters) clusters, "
"then merges them together until only the desired number of clusters are "
"left.", "O", 1.0);
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
"terminates.", "m", 1000);
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
// This is known to not work (#251).
//PARAM_FLAG("fast_kmeans", "Use the experimental fast k-means algorithm by "
// "Pelleg and Moore.", "f");
// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
"and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
"when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
" sampling (use when --refined_start is specified).", "p", 0.02);
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
// Initialize random seed.
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Now do validation of options.
string inputFile = CLI::GetParam<string>("inputFile");
int clusters = CLI::GetParam<int>("clusters");
if (clusters < 1)
{
Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
<< "Must be greater than or equal to 1." << std::endl;
}
int maxIterations = CLI::GetParam<int>("max_iterations");
if (maxIterations < 0)
{
Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
")! Must be greater than or equal to 0." << std::endl;
}
double overclustering = CLI::GetParam<double>("overclustering");
if (overclustering < 1)
{
Log::Fatal << "Invalid value for overclustering (" << overclustering <<
")! Must be greater than or equal to 1." << std::endl;
}
// Make sure we have an output file if we're not doing the work in-place.
if (!CLI::HasParam("in_place") && !CLI::HasParam("outputFile"))
{
Log::Fatal << "--outputFile not specified (and --in_place not set)."
<< std::endl;
}
// Load our dataset.
arma::mat dataset;
data::Load(inputFile.c_str(), dataset);
// Now create the KMeans object. Because we could be using different types,
// it gets a little weird...
arma::Col<size_t> assignments;
arma::mat centroids;
if (CLI::HasParam("allow_empty_clusters"))
{
if (CLI::HasParam("refined_start"))
{
KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
k(maxIterations, overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
else
{
KMeans<metric::SquaredEuclideanDistance, RandomPartition,
AllowEmptyClusters> k(maxIterations, overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
}
else
{
if (CLI::HasParam("refined_start"))
{
KMeans<metric::SquaredEuclideanDistance, RefinedStart> k(maxIterations,
overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
else
{
KMeans<> k(maxIterations, overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
}
// Now figure out what to do with our results.
if (CLI::HasParam("in_place"))
{
// Add the column of assignments to the dataset; but we have to convert them
// to type double first.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Save the dataset.
data::Save(inputFile, dataset);
}
else
{
if (CLI::HasParam("labels_only"))
{
// Save only the labels.
string outputFile = CLI::GetParam<string>("outputFile");
arma::Mat<size_t> output = trans(assignments);
data::Save(outputFile.c_str(), output);
}
else
{
// Convert the assignments to doubles.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Now save, in the different file.
string outputFile = CLI::GetParam<string>("outputFile");
data::Save(outputFile, dataset);
}
}
// Should we write the centroids to a file?
if (CLI::HasParam("centroids_file"))
data::Save(CLI::GetParam<std::string>("centroids_file"), centroids);
}
<commit_msg>Oh yeah -- actually allow the user-specified parameters to *do* something...<commit_after>/**
* @file kmeans_main.cpp
* @author Ryan Curtin
*
* Executable for running K-Means.
*/
#include <mlpack/core.hpp>
#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"
using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;
// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
"on the given dataset, storing the learned cluster assignments either as "
"a column of labels in the file containing the input dataset or in a "
"separate file. Empty clusters are not allowed by default; when a cluster "
"becomes empty, the point furthest from the centroid of the cluster with "
"maximum variance is taken to fill that cluster."
"\n\n"
"Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
" k-means clustering\", 1998) can be used to select initial points by "
"specifying the --refined_start (-r) option. This approach works by taking"
" random samples of the dataset; to specify the number of samples, the "
"--samples parameter is used, and to specify the percentage of the dataset "
"to be used in each sample, the --percentage parameter is used (it should "
"be a value between 0.0 and 1.0)."
"\n\n"
"If you want to specify your own initial cluster assignments or initial "
"cluster centroids, this functionality is available in the C++ interface. "
"Alternately, file a bug (well, a feature request) on the mlpack bug "
"tracker.");
// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find.", "c");
// Output options.
PARAM_FLAG("in_place", "If specified, a column of the learned cluster "
"assignments will be added to the input dataset file. In this case, "
"--outputFile is not necessary.", "p");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
"o", "output.csv");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
" be written to the given file.", "c", "");
// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_DOUBLE("overclustering", "Finds (overclustering * clusters) clusters, "
"then merges them together until only the desired number of clusters are "
"left.", "O", 1.0);
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
"terminates.", "m", 1000);
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
// This is known to not work (#251).
//PARAM_FLAG("fast_kmeans", "Use the experimental fast k-means algorithm by "
// "Pelleg and Moore.", "f");
// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
"and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
"when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
" sampling (use when --refined_start is specified).", "p", 0.02);
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
// Initialize random seed.
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Now do validation of options.
string inputFile = CLI::GetParam<string>("inputFile");
int clusters = CLI::GetParam<int>("clusters");
if (clusters < 1)
{
Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
<< "Must be greater than or equal to 1." << std::endl;
}
int maxIterations = CLI::GetParam<int>("max_iterations");
if (maxIterations < 0)
{
Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
")! Must be greater than or equal to 0." << std::endl;
}
double overclustering = CLI::GetParam<double>("overclustering");
if (overclustering < 1)
{
Log::Fatal << "Invalid value for overclustering (" << overclustering <<
")! Must be greater than or equal to 1." << std::endl;
}
// Make sure we have an output file if we're not doing the work in-place.
if (!CLI::HasParam("in_place") && !CLI::HasParam("outputFile"))
{
Log::Fatal << "--outputFile not specified (and --in_place not set)."
<< std::endl;
}
// Load our dataset.
arma::mat dataset;
data::Load(inputFile.c_str(), dataset);
// Now create the KMeans object. Because we could be using different types,
// it gets a little weird...
arma::Col<size_t> assignments;
arma::mat centroids;
if (CLI::HasParam("allow_empty_clusters"))
{
if (CLI::HasParam("refined_start"))
{
const int samplings = CLI::GetParam<int>("samplings");
const double percentage = CLI::GetParam<int>("percentage");
if (samplings < 0)
Log::Fatal << "Number of samplings (" << samplings << ") must be "
<< "greater than 0!" << std::endl;
if (percentage <= 0.0 || percentage > 1.0)
Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
<< "greater than 0.0 and less than or equal to 1.0!" << std::endl;
KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
RefinedStart(samplings, percentage));
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
else
{
KMeans<metric::SquaredEuclideanDistance, RandomPartition,
AllowEmptyClusters> k(maxIterations, overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
}
else
{
if (CLI::HasParam("refined_start"))
{
const int samplings = CLI::GetParam<int>("samplings");
const double percentage = CLI::GetParam<int>("percentage");
if (samplings < 0)
Log::Fatal << "Number of samplings (" << samplings << ") must be "
<< "greater than 0!" << std::endl;
if (percentage <= 0.0 || percentage > 1.0)
Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
<< "greater than 0.0 and less than or equal to 1.0!" << std::endl;
KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
RefinedStart(samplings, percentage));
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
else
{
KMeans<> k(maxIterations, overclustering);
Timer::Start("clustering");
if (CLI::HasParam("fast_kmeans"))
k.FastCluster(dataset, clusters, assignments);
else
k.Cluster(dataset, clusters, assignments, centroids);
Timer::Stop("clustering");
}
}
// Now figure out what to do with our results.
if (CLI::HasParam("in_place"))
{
// Add the column of assignments to the dataset; but we have to convert them
// to type double first.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Save the dataset.
data::Save(inputFile, dataset);
}
else
{
if (CLI::HasParam("labels_only"))
{
// Save only the labels.
string outputFile = CLI::GetParam<string>("outputFile");
arma::Mat<size_t> output = trans(assignments);
data::Save(outputFile.c_str(), output);
}
else
{
// Convert the assignments to doubles.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Now save, in the different file.
string outputFile = CLI::GetParam<string>("outputFile");
data::Save(outputFile, dataset);
}
}
// Should we write the centroids to a file?
if (CLI::HasParam("centroids_file"))
data::Save(CLI::GetParam<std::string>("centroids_file"), centroids);
}
<|endoftext|>
|
<commit_before>/**
* @file cnn_pooling_connection.hpp
* @author Shangtong Zhang
* @author Marcus Edel
*
* Implementation of the pooling connection between input layer and output layer
* for the convolutional neural network.
*/
#ifndef __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP
#define __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/optimizer/steepest_descent.hpp>
#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>
#include <mlpack/methods/ann/pooling_rules/max_pooling.hpp>
#include <mlpack/methods/ann/connections/connection_traits.hpp>
namespace mlpack{
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the pooling connection class for the convolutional neural
* network. The pooling connection connects input layer with the output layer
* using the specified pooling rule.
*
* @tparam InputLayerType Type of the connected input layer.
* @tparam OutputLayerType Type of the connected output layer.
* @tparam PoolingRule Type of the pooling strategy.
* @tparam OptimizerType Type of the optimizer used to update the weights.
* @tparam DataType Type of data (arma::mat, arma::sp_mat or arma::cube).
*/
template<
typename InputLayerType,
typename OutputLayerType,
typename PoolingRule = MaxPooling,
template<typename, typename> class OptimizerType = mlpack::ann::RMSPROP,
typename DataType = arma::cube
>
class PoolingConnection
{
public:
/**
* Create the PoolingConnection object using the specified input layer, output
* layer, optimizer and pooling strategy.
*
* @param InputLayerType The input layer which is connected with the output
* layer.
* @param OutputLayerType The output layer which is connected with the input
* layer.
* @param PoolingRule The strategy of pooling.
*/
PoolingConnection(InputLayerType& inputLayer,
OutputLayerType& outputLayer,
PoolingRule pooling = PoolingRule()) :
inputLayer(inputLayer),
outputLayer(outputLayer),
optimizer(0),
weights(0),
pooling(pooling),
delta(arma::zeros<DataType>(inputLayer.Delta().n_rows,
inputLayer.Delta().n_cols, inputLayer.Delta().n_slices))
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of a neural network, apply pooling to the
* neurons (dense matrix) in the input layer.
*
* @param input Input data used for pooling.
*/
template<typename eT>
void FeedForward(const arma::Mat<eT>& input)
{
Pooling(input, outputLayer.InputActivation());
}
/**
* Ordinary feed forward pass of a neural network, apply pooling to the
* neurons (3rd order tensor) in the input layer.
*
* @param input Input data used for pooling.
*/
template<typename eT>
void FeedForward(const arma::Cube<eT>& input)
{
for (size_t s = 0; s < input.n_slices; s++)
Pooling(input.slice(s), outputLayer.InputActivation().slice(s));
}
/**
* Ordinary feed backward pass of a neural network. Apply unsampling to the
* error in output layer (dense matrix) to pass the error to input layer.
*
* @param error The backpropagated error.
*/
template<typename eT>
void FeedBackward(const arma::Mat<eT>& error)
{
delta.zeros();
Unpooling(inputLayer.InputActivation(), error, inputLayer.Delta());
}
/**
* Ordinary feed backward pass of a neural network. Apply unsampling to the
* error in output layer (3rd order tensor) to pass the error to input layer.
*
* @param error The backpropagated error.
*/
template<typename eT>
void FeedBackward(const arma::Cube<eT>& error)
{
delta.zeros();
for (size_t s = 0; s < error.n_slices; s++)
{
Unpooling(inputLayer.InputActivation().slice(s), error.slice(s),
delta.slice(s));
}
}
/*
* Calculate the gradient using the output delta and the input activation.
*
* @param gradient The calculated gradient.
*/
template<typename GradientType>
void Gradient(GradientType& /* unused */)
{
// Nothing to do here.
}
//! Get the weights.
DataType& Weights() const { return *weights; }
//! Modify the weights.
DataType& Weights() { return *weights; }
//! Get the input layer.
InputLayerType& InputLayer() const { return inputLayer; }
//! Modify the input layer.
InputLayerType& InputLayer() { return inputLayer; }
//! Get the output layer.
OutputLayerType& OutputLayer() const { return outputLayer; }
//! Modify the output layer.
OutputLayerType& OutputLayer() { return outputLayer; }
//! Get the optimizer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>& Optimzer() const
{
return *optimizer;
}
//! Modify the optimzer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>& Optimzer()
{
return *optimizer;
}
//! Get the passed error in backward propagation.
DataType& Delta() const { return delta; }
//! Modify the passed error in backward propagation.
DataType& Delta() { return delta; }
//! Get the pooling strategy.
PoolingRule& Pooling() const { return pooling; }
//! Modify the pooling strategy.
PoolingRule& Pooling() { return pooling; }
private:
/**
* Apply pooling to the input and store the results.
*
* @param input The input to be apply the pooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Pooling(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / outputLayer.LayerRows();
const size_t cStep = input.n_cols / outputLayer.LayerCols();
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
output(i / rStep, j / cStep) += pooling.Pooling(
input(arma::span(i, i + rStep -1), arma::span(j, j + cStep - 1)));
}
}
}
/**
* Apply unpooling to the input and store the results.
*
* @param input The input to be apply the unpooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Unpooling(const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / error.n_rows;
const size_t cStep = input.n_cols / error.n_cols;
arma::Mat<eT> unpooledError;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
const arma::Mat<eT>& inputArea = input(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1));
pooling.Unpooling(inputArea, error(i / rStep, j / cStep),
unpooledError);
output(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1)) += unpooledError;
}
}
}
//! Locally-stored input layer.
InputLayerType& inputLayer;
//! Locally-stored output layer.
OutputLayerType& outputLayer;
//! Locally-stored optimizer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>* optimizer;
//! Locally-stored weight object.
DataType* weights;
//! Locally-stored pooling strategy.
PoolingRule pooling;
//! Locally-stored passed error in backward propagation.
DataType delta;
}; // PoolingConnection class.
//! Connection traits for the pooling connection.
template<
typename InputLayerType,
typename OutputLayerType,
typename PoolingRule,
template<typename, typename> class OptimizerType,
typename DataType
>
class ConnectionTraits<
PoolingConnection<InputLayerType, OutputLayerType, PoolingRule,
OptimizerType, DataType> >
{
public:
static const bool IsSelfConnection = false;
static const bool IsFullselfConnection = false;
static const bool IsPoolingConnection = true;
};
}; // namespace ann
}; // namespace mlpack
#endif<commit_msg>Update the connection trait and there is no need to reset the delta, we already reset the delta in the network class (cnn, ffn).<commit_after>/**
* @file pooling_connection.hpp
* @author Shangtong Zhang
* @author Marcus Edel
*
* Implementation of the pooling connection between input layer and output layer
* for the convolutional neural network.
*/
#ifndef __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP
#define __MLPACK_METHODS_ANN_CONNECTIONS_POOLING_CONNECTION_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/optimizer/steepest_descent.hpp>
#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>
#include <mlpack/methods/ann/pooling_rules/max_pooling.hpp>
#include <mlpack/methods/ann/connections/connection_traits.hpp>
namespace mlpack{
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the pooling connection class for the convolutional neural
* network. The pooling connection connects input layer with the output layer
* using the specified pooling rule.
*
* @tparam InputLayerType Type of the connected input layer.
* @tparam OutputLayerType Type of the connected output layer.
* @tparam PoolingRule Type of the pooling strategy.
* @tparam OptimizerType Type of the optimizer used to update the weights.
* @tparam DataType Type of data (arma::mat, arma::sp_mat or arma::cube).
*/
template<
typename InputLayerType,
typename OutputLayerType,
typename PoolingRule = MaxPooling,
template<typename, typename> class OptimizerType = mlpack::ann::RMSPROP,
typename DataType = arma::cube
>
class PoolingConnection
{
public:
/**
* Create the PoolingConnection object using the specified input layer, output
* layer, optimizer and pooling strategy.
*
* @param InputLayerType The input layer which is connected with the output
* layer.
* @param OutputLayerType The output layer which is connected with the input
* layer.
* @param PoolingRule The strategy of pooling.
*/
PoolingConnection(InputLayerType& inputLayer,
OutputLayerType& outputLayer,
PoolingRule pooling = PoolingRule()) :
inputLayer(inputLayer),
outputLayer(outputLayer),
optimizer(0),
weights(0),
pooling(pooling),
delta(arma::zeros<DataType>(inputLayer.Delta().n_rows,
inputLayer.Delta().n_cols, inputLayer.Delta().n_slices))
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of a neural network, apply pooling to the
* neurons (dense matrix) in the input layer.
*
* @param input Input data used for pooling.
*/
template<typename eT>
void FeedForward(const arma::Mat<eT>& input)
{
Pooling(input, outputLayer.InputActivation());
}
/**
* Ordinary feed forward pass of a neural network, apply pooling to the
* neurons (3rd order tensor) in the input layer.
*
* @param input Input data used for pooling.
*/
template<typename eT>
void FeedForward(const arma::Cube<eT>& input)
{
for (size_t s = 0; s < input.n_slices; s++)
Pooling(input.slice(s), outputLayer.InputActivation().slice(s));
}
/**
* Ordinary feed backward pass of a neural network. Apply unsampling to the
* error in output layer (dense matrix) to pass the error to input layer.
*
* @param error The backpropagated error.
*/
template<typename eT>
void FeedBackward(const arma::Mat<eT>& error)
{
Unpooling(inputLayer.InputActivation(), error, inputLayer.Delta());
}
/**
* Ordinary feed backward pass of a neural network. Apply unsampling to the
* error in output layer (3rd order tensor) to pass the error to input layer.
*
* @param error The backpropagated error.
*/
template<typename eT>
void FeedBackward(const arma::Cube<eT>& error)
{
for (size_t s = 0; s < error.n_slices; s++)
{
Unpooling(inputLayer.InputActivation().slice(s), error.slice(s),
delta.slice(s));
}
}
/*
* Calculate the gradient using the output delta and the input activation.
*
* @param gradient The calculated gradient.
*/
template<typename GradientType>
void Gradient(GradientType& /* unused */)
{
// Nothing to do here.
}
//! Get the weights.
DataType& Weights() const { return *weights; }
//! Modify the weights.
DataType& Weights() { return *weights; }
//! Get the input layer.
InputLayerType& InputLayer() const { return inputLayer; }
//! Modify the input layer.
InputLayerType& InputLayer() { return inputLayer; }
//! Get the output layer.
OutputLayerType& OutputLayer() const { return outputLayer; }
//! Modify the output layer.
OutputLayerType& OutputLayer() { return outputLayer; }
//! Get the optimizer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>& Optimzer() const
{
return *optimizer;
}
//! Modify the optimzer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>& Optimzer()
{
return *optimizer;
}
//! Get the passed error in backward propagation.
DataType& Delta() const { return delta; }
//! Modify the passed error in backward propagation.
DataType& Delta() { return delta; }
//! Get the pooling strategy.
PoolingRule& Pooling() const { return pooling; }
//! Modify the pooling strategy.
PoolingRule& Pooling() { return pooling; }
private:
/**
* Apply pooling to the input and store the results.
*
* @param input The input to be apply the pooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Pooling(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / outputLayer.LayerRows();
const size_t cStep = input.n_cols / outputLayer.LayerCols();
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
output(i / rStep, j / cStep) += pooling.Pooling(
input(arma::span(i, i + rStep -1), arma::span(j, j + cStep - 1)));
}
}
}
/**
* Apply unpooling to the input and store the results.
*
* @param input The input to be apply the unpooling rule.
* @param output The pooled result.
*/
template<typename eT>
void Unpooling(const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& output)
{
const size_t rStep = input.n_rows / error.n_rows;
const size_t cStep = input.n_cols / error.n_cols;
arma::Mat<eT> unpooledError;
for (size_t j = 0; j < input.n_cols; j += cStep)
{
for (size_t i = 0; i < input.n_rows; i += rStep)
{
const arma::Mat<eT>& inputArea = input(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1));
pooling.Unpooling(inputArea, error(i / rStep, j / cStep),
unpooledError);
output(arma::span(i, i + rStep - 1),
arma::span(j, j + cStep - 1)) += unpooledError;
}
}
}
//! Locally-stored input layer.
InputLayerType& inputLayer;
//! Locally-stored output layer.
OutputLayerType& outputLayer;
//! Locally-stored optimizer.
OptimizerType<PoolingConnection<InputLayerType,
OutputLayerType,
PoolingRule,
OptimizerType,
DataType>, DataType>* optimizer;
//! Locally-stored weight object.
DataType* weights;
//! Locally-stored pooling strategy.
PoolingRule pooling;
//! Locally-stored passed error in backward propagation.
DataType delta;
}; // PoolingConnection class.
//! Connection traits for the pooling connection.
template<
typename InputLayerType,
typename OutputLayerType,
typename PoolingRule,
template<typename, typename> class OptimizerType,
typename DataType
>
class ConnectionTraits<
PoolingConnection<InputLayerType, OutputLayerType, PoolingRule,
OptimizerType, DataType> >
{
public:
static const bool IsSelfConnection = false;
static const bool IsFullselfConnection = false;
static const bool IsPoolingConnection = true;
static const bool IsIdentityConnection = false;
};
}; // namespace ann
}; // namespace mlpack
#endif<|endoftext|>
|
<commit_before>/**
* @file dual_tree_kmeans_rules_impl.hpp
* @author Ryan Curtin
*
* A set of tree traversal rules for dual-tree k-means clustering.
*/
#ifndef __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "dual_tree_kmeans_rules.hpp"
namespace mlpack {
namespace kmeans {
template<typename MetricType, typename TreeType>
DualTreeKMeansRules<MetricType, TreeType>::DualTreeKMeansRules(
const typename TreeType::Mat& dataset,
const arma::mat& centroids,
arma::mat& newCentroids,
arma::Col<size_t>& counts,
const std::vector<size_t>& mappings,
const size_t iteration,
const arma::vec& clusterDistances,
arma::vec& distances,
arma::Col<size_t>& assignments,
arma::Col<size_t>& distanceIteration,
const arma::mat& interclusterDistances,
MetricType& metric) :
dataset(dataset),
centroids(centroids),
newCentroids(newCentroids),
counts(counts),
mappings(mappings),
iteration(iteration),
clusterDistances(clusterDistances),
distances(distances),
assignments(assignments),
distanceIteration(distanceIteration),
interclusterDistances(interclusterDistances),
metric(metric),
distanceCalculations(0)
{
// Nothing has been visited yet.
visited.zeros(dataset.n_cols);
}
template<typename MetricType, typename TreeType>
inline force_inline double DualTreeKMeansRules<MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// Log::Info << "Base case, query " << queryIndex << " (" << mappings[queryIndex]
// << "), reference " << referenceIndex << ".\n";
// Collect the number of clusters that have been pruned during the traversal.
// The ternary operator may not be necessary.
const size_t traversalPruned = (traversalInfo.LastReferenceNode() != NULL) ?
// traversalInfo.LastReferenceNode()->Stat().Iteration() == iteration) ?
traversalInfo.LastReferenceNode()->Stat().ClustersPruned() : 0;
// It's possible that the reference node has been pruned before we got to the
// base case. In that case, don't do the base case, and just return.
if (traversalInfo.LastReferenceNode()->Stat().ClustersPruned() +
visited[referenceIndex] == centroids.n_cols)
return 0.0;
++distanceCalculations;
const double distance = metric.Evaluate(centroids.col(queryIndex),
dataset.col(referenceIndex));
// Iteration change check.
if (distanceIteration[referenceIndex] < iteration)
{
distanceIteration[referenceIndex] = iteration;
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
else if (distance < distances[referenceIndex])
{
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
++visited[referenceIndex];
if (visited[referenceIndex] + traversalPruned == centroids.n_cols)
{
// Log::Warn << "Commit reference index " << referenceIndex << " to cluster "
// << assignments[referenceIndex] << ".\n";
newCentroids.col(assignments[referenceIndex]) +=
dataset.col(referenceIndex);
++counts(assignments[referenceIndex]);
}
return distance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode)
{
// Update from previous iteration, if necessary.
// IterationUpdate(referenceNode);
// No pruning here, for now.
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
if (referenceNode.Stat().ClustersPruned() == size_t(-1))
referenceNode.Stat().ClustersPruned() =
referenceNode.Parent()->Stat().ClustersPruned();
traversalInfo.LastReferenceNode() = &referenceNode;
double score = ElkanTypeScore(queryNode, referenceNode);
// We also have to update things if the closest query node is null. This can
// probably be improved.
if (score != DBL_MAX || referenceNode.Stat().ClosestQueryNode() == NULL)
{
// Can we update the minimum query node distance for this reference node?
const double minDistance = referenceNode.MinDistance(&queryNode);
const double maxDistance = referenceNode.MaxDistance(&queryNode);
distanceCalculations += 2;
if (maxDistance < referenceNode.Stat().MaxQueryNodeDistance())
{
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
// referenceNode.MaxDistance(&queryNode);
// ++distanceCalculations;
return 0.0; // Pruning is not possible.
}
else if (IsDescendantOf(
*((TreeType*) referenceNode.Stat().ClosestQueryNode()), queryNode))
{
// Just update.
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() =
referenceNode.MaxDistance(&queryNode);
++distanceCalculations;
return 0.0; // Pruning is not possible.
}
score = PellegMooreScore(queryNode, referenceNode, minDistance);
}
if (score == DBL_MAX)
{
referenceNode.Stat().ClustersPruned() += queryNode.NumDescendants();
// Have we pruned everything?
if (referenceNode.Stat().ClustersPruned() == centroids.n_cols - 1)
{
// Then the best query node must contain just one point.
const TreeType* bestQueryNode = (TreeType*)
referenceNode.Stat().ClosestQueryNode();
const size_t cluster = mappings[bestQueryNode->Descendant(0)];
referenceNode.Stat().Owner() = cluster;
newCentroids.col(cluster) += referenceNode.NumDescendants() *
referenceNode.Stat().Centroid();
counts(cluster) += referenceNode.NumDescendants();
referenceNode.Stat().ClustersPruned()++;
}
else if (referenceNode.Stat().ClustersPruned() +
visited[referenceNode.Descendant(0)] == centroids.n_cols)
{
for (size_t i = 0; i < referenceNode.NumPoints(); ++i)
{
const size_t cluster = assignments[referenceNode.Point(i)];
newCentroids.col(cluster) += dataset.col(referenceNode.Point(i));
counts(cluster)++;
}
}
}
return score;
// return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
const size_t /* queryIndex */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
TreeType& /* queryNode */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
// if (oldScore == DBL_MAX)
// return oldScore; // We can't unprune something. This shouldn't happen.
// return ElkanTypeScore(queryNode, referenceNode, oldScore);
}
template<typename MetricType, typename TreeType>
inline double DualTreeKMeansRules<MetricType, TreeType>::IterationUpdate(
TreeType& referenceNode)
{
Log::Fatal << "Update! Why!\n";
if (referenceNode.Stat().Iteration() == iteration)
return 0;
const size_t itDiff = iteration - referenceNode.Stat().Iteration();
referenceNode.Stat().Iteration() = iteration;
referenceNode.Stat().ClustersPruned() = (referenceNode.Parent() == NULL) ?
0 : referenceNode.Parent()->Stat().ClustersPruned();
referenceNode.Stat().ClosestQueryNode() = (referenceNode.Parent() == NULL) ?
NULL : referenceNode.Parent()->Stat().ClosestQueryNode();
if (referenceNode.Stat().ClosestQueryNode() != NULL)
{
referenceNode.Stat().MinQueryNodeDistance() =
referenceNode.MinDistance((TreeType*)
referenceNode.Stat().ClosestQueryNode());
referenceNode.Stat().MaxQueryNodeDistance() =
referenceNode.MaxDistance((TreeType*)
referenceNode.Stat().ClosestQueryNode());
distanceCalculations += 2;
}
if (itDiff > 1)
{
// referenceNode.Stat().BestMaxDistance() = DBL_MAX;
referenceNode.Stat().MinQueryNodeDistance() = DBL_MAX;
referenceNode.Stat().MaxQueryNodeDistance() = DBL_MAX;
}
else
{
if (referenceNode.Stat().MinQueryNodeDistance() != DBL_MAX)
{
// Update the distance to the closest query node. If this node has an
// owner, we know how far to increase the bound. Otherwise, increase it
// by the furthest amount that any centroid moved.
if (referenceNode.Stat().Owner() < centroids.n_cols)
{
referenceNode.Stat().MinQueryNodeDistance() +=
clusterDistances(referenceNode.Stat().Owner());
referenceNode.Stat().MaxQueryNodeDistance() +=
clusterDistances(referenceNode.Stat().Owner());
}
else
{
referenceNode.Stat().MinQueryNodeDistance() +=
clusterDistances(centroids.n_cols);
referenceNode.Stat().MaxQueryNodeDistance() +=
clusterDistances(centroids.n_cols);
}
}
else
{
referenceNode.Stat().MinQueryNodeDistance() = DBL_MAX;
referenceNode.Stat().MaxQueryNodeDistance() = DBL_MAX;
}
}
// if (referenceNode.Stat().BestMaxDistance() != DBL_MAX)
// {
// if (referenceNode.Stat().Owner() < centroids.n_cols)
// referenceNode.Stat().BestMaxDistance() +=
// clusterDistances(referenceNode.Stat().Owner());
// else
// referenceNode.Stat().BestMaxDistance() +=
// clusterDistances(centroids.n_cols);
// }
// }
return 1;
}
template<typename MetricType, typename TreeType>
bool DualTreeKMeansRules<MetricType, TreeType>::IsDescendantOf(
const TreeType& potentialParent,
const TreeType& potentialChild) const
{
if (potentialChild.Parent() == &potentialParent)
return true;
else if (potentialChild.Parent() == NULL)
return false;
else
return IsDescendantOf(potentialParent, *potentialChild.Parent());
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& queryNode,
TreeType& referenceNode)
{
// We have to calculate the minimum distance between the query node and the
// reference node's best query node. First, try to use the cached distance.
// const double minQueryDistance = queryNode.Stat().FirstBound();
if (queryNode.NumDescendants() == 1)
{
const double score = ElkanTypeScore(queryNode, referenceNode,
interclusterDistances[queryNode.Descendant(0)]);
// Log::Warn << "Elkan scoring: " << score << ".\n";
return score;
}
else
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minQueryDistance) const
{
// See if we can do an Elkan-type prune on between-centroid distances.
const double maxDistance = referenceNode.Stat().MaxQueryNodeDistance();
if (maxDistance == DBL_MAX)
return minQueryDistance;
if (minQueryDistance > 2.0 * maxDistance)
{
// Then we can conclude d_max(best(N_r), N_r) <= d_min(N_q, N_r) which
// means that N_q cannot possibly hold any clusters that own any points in
// N_r.
return DBL_MAX;
}
return minQueryDistance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::PellegMooreScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minDistance) const
{
// If the minimum distance to the node is greater than the bound, then every
// cluster in the query node cannot possibly be the nearest neighbor of any of
// the points in the reference node.
if (minDistance > referenceNode.Stat().MaxQueryNodeDistance())
return DBL_MAX;
return minDistance;
}
} // namespace kmeans
} // namespace mlpack
#endif
<commit_msg>Fix all -Wunused-parameter.<commit_after>/**
* @file dual_tree_kmeans_rules_impl.hpp
* @author Ryan Curtin
*
* A set of tree traversal rules for dual-tree k-means clustering.
*/
#ifndef __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
#define __MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "dual_tree_kmeans_rules.hpp"
namespace mlpack {
namespace kmeans {
template<typename MetricType, typename TreeType>
DualTreeKMeansRules<MetricType, TreeType>::DualTreeKMeansRules(
const typename TreeType::Mat& dataset,
const arma::mat& centroids,
arma::mat& newCentroids,
arma::Col<size_t>& counts,
const std::vector<size_t>& mappings,
const size_t iteration,
const arma::vec& clusterDistances,
arma::vec& distances,
arma::Col<size_t>& assignments,
arma::Col<size_t>& distanceIteration,
const arma::mat& interclusterDistances,
MetricType& metric) :
dataset(dataset),
centroids(centroids),
newCentroids(newCentroids),
counts(counts),
mappings(mappings),
iteration(iteration),
clusterDistances(clusterDistances),
distances(distances),
assignments(assignments),
distanceIteration(distanceIteration),
interclusterDistances(interclusterDistances),
metric(metric),
distanceCalculations(0)
{
// Nothing has been visited yet.
visited.zeros(dataset.n_cols);
}
template<typename MetricType, typename TreeType>
inline force_inline double DualTreeKMeansRules<MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// Log::Info << "Base case, query " << queryIndex << " (" << mappings[queryIndex]
// << "), reference " << referenceIndex << ".\n";
// Collect the number of clusters that have been pruned during the traversal.
// The ternary operator may not be necessary.
const size_t traversalPruned = (traversalInfo.LastReferenceNode() != NULL) ?
// traversalInfo.LastReferenceNode()->Stat().Iteration() == iteration) ?
traversalInfo.LastReferenceNode()->Stat().ClustersPruned() : 0;
// It's possible that the reference node has been pruned before we got to the
// base case. In that case, don't do the base case, and just return.
if (traversalInfo.LastReferenceNode()->Stat().ClustersPruned() +
visited[referenceIndex] == centroids.n_cols)
return 0.0;
++distanceCalculations;
const double distance = metric.Evaluate(centroids.col(queryIndex),
dataset.col(referenceIndex));
// Iteration change check.
if (distanceIteration[referenceIndex] < iteration)
{
distanceIteration[referenceIndex] = iteration;
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
else if (distance < distances[referenceIndex])
{
distances[referenceIndex] = distance;
assignments[referenceIndex] = mappings[queryIndex];
}
++visited[referenceIndex];
if (visited[referenceIndex] + traversalPruned == centroids.n_cols)
{
// Log::Warn << "Commit reference index " << referenceIndex << " to cluster "
// << assignments[referenceIndex] << ".\n";
newCentroids.col(assignments[referenceIndex]) +=
dataset.col(referenceIndex);
++counts(assignments[referenceIndex]);
}
return distance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
const size_t /* queryIndex */,
TreeType& referenceNode)
{
// Update from previous iteration, if necessary.
// IterationUpdate(referenceNode);
// No pruning here, for now.
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
if (referenceNode.Stat().ClustersPruned() == size_t(-1))
referenceNode.Stat().ClustersPruned() =
referenceNode.Parent()->Stat().ClustersPruned();
traversalInfo.LastReferenceNode() = &referenceNode;
double score = ElkanTypeScore(queryNode, referenceNode);
// We also have to update things if the closest query node is null. This can
// probably be improved.
if (score != DBL_MAX || referenceNode.Stat().ClosestQueryNode() == NULL)
{
// Can we update the minimum query node distance for this reference node?
const double minDistance = referenceNode.MinDistance(&queryNode);
const double maxDistance = referenceNode.MaxDistance(&queryNode);
distanceCalculations += 2;
if (maxDistance < referenceNode.Stat().MaxQueryNodeDistance())
{
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() = maxDistance;
// referenceNode.MaxDistance(&queryNode);
// ++distanceCalculations;
return 0.0; // Pruning is not possible.
}
else if (IsDescendantOf(
*((TreeType*) referenceNode.Stat().ClosestQueryNode()), queryNode))
{
// Just update.
referenceNode.Stat().ClosestQueryNode() = (void*) &queryNode;
referenceNode.Stat().MinQueryNodeDistance() = minDistance;
referenceNode.Stat().MaxQueryNodeDistance() =
referenceNode.MaxDistance(&queryNode);
++distanceCalculations;
return 0.0; // Pruning is not possible.
}
score = PellegMooreScore(queryNode, referenceNode, minDistance);
}
if (score == DBL_MAX)
{
referenceNode.Stat().ClustersPruned() += queryNode.NumDescendants();
// Have we pruned everything?
if (referenceNode.Stat().ClustersPruned() == centroids.n_cols - 1)
{
// Then the best query node must contain just one point.
const TreeType* bestQueryNode = (TreeType*)
referenceNode.Stat().ClosestQueryNode();
const size_t cluster = mappings[bestQueryNode->Descendant(0)];
referenceNode.Stat().Owner() = cluster;
newCentroids.col(cluster) += referenceNode.NumDescendants() *
referenceNode.Stat().Centroid();
counts(cluster) += referenceNode.NumDescendants();
referenceNode.Stat().ClustersPruned()++;
}
else if (referenceNode.Stat().ClustersPruned() +
visited[referenceNode.Descendant(0)] == centroids.n_cols)
{
for (size_t i = 0; i < referenceNode.NumPoints(); ++i)
{
const size_t cluster = assignments[referenceNode.Point(i)];
newCentroids.col(cluster) += dataset.col(referenceNode.Point(i));
counts(cluster)++;
}
}
}
return score;
// return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
const size_t /* queryIndex */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::Rescore(
TreeType& /* queryNode */,
TreeType& /* referenceNode */,
const double oldScore) const
{
return oldScore;
// if (oldScore == DBL_MAX)
// return oldScore; // We can't unprune something. This shouldn't happen.
// return ElkanTypeScore(queryNode, referenceNode, oldScore);
}
template<typename MetricType, typename TreeType>
inline double DualTreeKMeansRules<MetricType, TreeType>::IterationUpdate(
TreeType& referenceNode)
{
Log::Fatal << "Update! Why!\n";
if (referenceNode.Stat().Iteration() == iteration)
return 0;
const size_t itDiff = iteration - referenceNode.Stat().Iteration();
referenceNode.Stat().Iteration() = iteration;
referenceNode.Stat().ClustersPruned() = (referenceNode.Parent() == NULL) ?
0 : referenceNode.Parent()->Stat().ClustersPruned();
referenceNode.Stat().ClosestQueryNode() = (referenceNode.Parent() == NULL) ?
NULL : referenceNode.Parent()->Stat().ClosestQueryNode();
if (referenceNode.Stat().ClosestQueryNode() != NULL)
{
referenceNode.Stat().MinQueryNodeDistance() =
referenceNode.MinDistance((TreeType*)
referenceNode.Stat().ClosestQueryNode());
referenceNode.Stat().MaxQueryNodeDistance() =
referenceNode.MaxDistance((TreeType*)
referenceNode.Stat().ClosestQueryNode());
distanceCalculations += 2;
}
if (itDiff > 1)
{
// referenceNode.Stat().BestMaxDistance() = DBL_MAX;
referenceNode.Stat().MinQueryNodeDistance() = DBL_MAX;
referenceNode.Stat().MaxQueryNodeDistance() = DBL_MAX;
}
else
{
if (referenceNode.Stat().MinQueryNodeDistance() != DBL_MAX)
{
// Update the distance to the closest query node. If this node has an
// owner, we know how far to increase the bound. Otherwise, increase it
// by the furthest amount that any centroid moved.
if (referenceNode.Stat().Owner() < centroids.n_cols)
{
referenceNode.Stat().MinQueryNodeDistance() +=
clusterDistances(referenceNode.Stat().Owner());
referenceNode.Stat().MaxQueryNodeDistance() +=
clusterDistances(referenceNode.Stat().Owner());
}
else
{
referenceNode.Stat().MinQueryNodeDistance() +=
clusterDistances(centroids.n_cols);
referenceNode.Stat().MaxQueryNodeDistance() +=
clusterDistances(centroids.n_cols);
}
}
else
{
referenceNode.Stat().MinQueryNodeDistance() = DBL_MAX;
referenceNode.Stat().MaxQueryNodeDistance() = DBL_MAX;
}
}
// if (referenceNode.Stat().BestMaxDistance() != DBL_MAX)
// {
// if (referenceNode.Stat().Owner() < centroids.n_cols)
// referenceNode.Stat().BestMaxDistance() +=
// clusterDistances(referenceNode.Stat().Owner());
// else
// referenceNode.Stat().BestMaxDistance() +=
// clusterDistances(centroids.n_cols);
// }
// }
return 1;
}
template<typename MetricType, typename TreeType>
bool DualTreeKMeansRules<MetricType, TreeType>::IsDescendantOf(
const TreeType& potentialParent,
const TreeType& potentialChild) const
{
if (potentialChild.Parent() == &potentialParent)
return true;
else if (potentialChild.Parent() == NULL)
return false;
else
return IsDescendantOf(potentialParent, *potentialChild.Parent());
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& queryNode,
TreeType& referenceNode)
{
// We have to calculate the minimum distance between the query node and the
// reference node's best query node. First, try to use the cached distance.
// const double minQueryDistance = queryNode.Stat().FirstBound();
if (queryNode.NumDescendants() == 1)
{
const double score = ElkanTypeScore(queryNode, referenceNode,
interclusterDistances[queryNode.Descendant(0)]);
// Log::Warn << "Elkan scoring: " << score << ".\n";
return score;
}
else
return 0.0;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::ElkanTypeScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minQueryDistance) const
{
// See if we can do an Elkan-type prune on between-centroid distances.
const double maxDistance = referenceNode.Stat().MaxQueryNodeDistance();
if (maxDistance == DBL_MAX)
return minQueryDistance;
if (minQueryDistance > 2.0 * maxDistance)
{
// Then we can conclude d_max(best(N_r), N_r) <= d_min(N_q, N_r) which
// means that N_q cannot possibly hold any clusters that own any points in
// N_r.
return DBL_MAX;
}
return minQueryDistance;
}
template<typename MetricType, typename TreeType>
double DualTreeKMeansRules<MetricType, TreeType>::PellegMooreScore(
TreeType& /* queryNode */,
TreeType& referenceNode,
const double minDistance) const
{
// If the minimum distance to the node is greater than the bound, then every
// cluster in the query node cannot possibly be the nearest neighbor of any of
// the points in the reference node.
if (minDistance > referenceNode.Stat().MaxQueryNodeDistance())
return DBL_MAX;
return minDistance;
}
} // namespace kmeans
} // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>#include "ctextparser.h"
DISABLE_COMPILER_WARNINGS
#include <QDebug>
RESTORE_COMPILER_WARNINGS
#include <set>
inline int priority(TextFragment::Delimiter delimiter)
{
return delimiter;
}
CStructuredText CTextParser::parse(const QString& text)
{
struct Delimiter {
QChar delimiterCharacter;
TextFragment::Delimiter delimiterType;
inline bool operator< (const Delimiter& other) const {
return delimiterCharacter < other.delimiterCharacter;
}
};
QString fixedText = text;
fixedText
.replace(QChar(0x00A0), ' ') // Non-breaking space -> regular space
.replace(". . .", QChar(0x2026)) // 3 space-separated dots -> ellipsis // TODO: regexp
.replace("...", QChar(0x2026)); // 3 dots -> ellipsis // TODO: regexp
static const std::set<Delimiter> delimiters {
{' ', TextFragment::Space},
{'.', TextFragment::Point},
{':', TextFragment::Colon},
{';', TextFragment::Semicolon},
{',', TextFragment::Comma},
// TODO: dash should be ignored unless it has an adjacent space!
{'-', TextFragment::Dash},
{0x2014, TextFragment::Dash},
{0x2026, TextFragment::Ellipsis},
{'!', TextFragment::ExclamationMark},
{'\n', TextFragment::Newline},
{'?', TextFragment::QuestionMark},
{'\"', TextFragment::Quote},
{')', TextFragment::Bracket},
{'(', TextFragment::Bracket},
{'[', TextFragment::Bracket},
{']', TextFragment::Bracket},
{'{', TextFragment::Bracket},
{'}', TextFragment::Bracket}
};
// Sanity check
#ifdef _DEBUG
for (const auto delimiter: TextFragment::Delimiter())
assert(std::find_if(delimiters.begin(), delimiters.end(), [delimiter](const Delimiter& item){
return delimiter.id == TextFragment::NoDelimiter || item.delimiterType == delimiter.id;
}) != delimiters.end());
#endif
_fragmentCounter = 0;
_parsedText.clear();
qDebug() << "Parsing text of" << fixedText.length() << "characters";
_parsedText.setExpectedChaptersCount(fixedText.length() / 20000);
for (QChar ch: fixedText)
{
if (ch == '\r')
continue;
const auto delimiterItem = delimiters.find({ch, TextFragment::NoDelimiter});
if (delimiterItem == delimiters.end()) // Not a delimiter
{
if (_wordEnded) // This is the first letter of a new word
finalizeFragment();
_lastDelimiter = TextFragment::NoDelimiter;
_wordBuffer += ch;
}
else // This is a delimiter. Append it to the current word.
{
// The opening quote is not a delimiter; the closing one is.
if (delimiterItem->delimiterType == TextFragment::Quote)
{
_quoteOpened = !_quoteOpened;
if (_quoteOpened) // This is an opening quote! Dump the previously accumulated fragment and assign this quote to the new one.
{
finalizeFragment();
_wordBuffer += ch;
}
else // Business as usual
{
// Don't let space, comma and quote in e. g. ", " override other punctuation marks
if (priority(delimiterItem->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = delimiterItem->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
else
{
// Don't let space, comma and quote in e. g. ", " override other punctuation marks
if (priority(delimiterItem->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = delimiterItem->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
}
finalizeFragment();
_parsedText.removeEmptyItems();
return _parsedText;
}
void CTextParser::setAddEmptyFragmentAfterSentence(bool add)
{
_addEmptyFragmentAfterSentenceEnd = add;
}
inline bool isUpperCaseText(const QString& str)
{
bool letterDetected = false;
for (QChar ch : str)
{
if (ch.isLetterOrNumber())
{
letterDetected = true;
if (!ch.isNumber() && !ch.isUpper())
return false;
}
}
return letterDetected;
}
void CTextParser::finalizeFragment()
{
_delimitersBuffer = _delimitersBuffer.trimmed();
if (!_delimitersBuffer.isEmpty() || !_wordBuffer.isEmpty())
{
if (_lastDelimiter == TextFragment::Newline)
{
// A whole line in uppercase is likely the chapter name.
// The _delimitersBuffer is already trimmed so no need to worry about it consisting of whitespace without any meaningful characters.
// This condition has to be checked first so that the chapter name properly starts the new chapter.
if (_delimitersBuffer.isEmpty() && isUpperCaseText(_wordBuffer))
{
// Start the new chapter
_parsedText.addEmptyChapter(_wordBuffer).addEmptyParagraph();
}
}
// Creating empty containers if necessary
if (_parsedText.empty()) // This should only happen once, when parsing the first line
_parsedText.addEmptyChapter(_wordBuffer).addEmptyParagraph();
TextFragment fragment(_wordBuffer, _delimitersBuffer, _lastDelimiter);
if (_addEmptyFragmentAfterSentenceEnd && fragment.isEndOfSentence())
{
_parsedText.lastParagraph().addFragment({_wordBuffer, _delimitersBuffer, TextFragment::Comma}, _fragmentCounter++);
// Moving the end-of-sentence delimiter off to a dummy fragment with no text - just so that we can fade the text out and hold the screen empty for a bit
_parsedText.lastParagraph().addFragment({QString::null, QString::null, _lastDelimiter}, _fragmentCounter++);
}
else
{
_parsedText.lastParagraph().addFragment(fragment, _fragmentCounter++);
}
if (_lastDelimiter == TextFragment::Newline)
// Start a new paragraph
_parsedText.lastChapter().addEmptyParagraph();
}
_wordEnded = false;
_delimitersBuffer.clear();
_wordBuffer.clear();
}
<commit_msg>Closed #33; minor CTextParser refactoring<commit_after>#include "ctextparser.h"
DISABLE_COMPILER_WARNINGS
#include <QDebug>
RESTORE_COMPILER_WARNINGS
#include <map>
inline int priority(TextFragment::Delimiter delimiter)
{
return delimiter;
}
CStructuredText CTextParser::parse(const QString& text)
{
QString fixedText = text;
fixedText
.replace(QChar(0x00A0), ' ') // Non-breaking space -> regular space
.replace(". . .", QChar(0x2026)) // 3 space-separated dots -> ellipsis // TODO: regexp
.replace("...", QChar(0x2026)); // 3 dots -> ellipsis // TODO: regexp
static const std::map<QChar, TextFragment::Delimiter> delimiters {
{' ', TextFragment::Space},
{'.', TextFragment::Point},
{':', TextFragment::Colon},
{';', TextFragment::Semicolon},
{',', TextFragment::Comma},
// TODO: dash should be ignored unless it has an adjacent space!
{'-', TextFragment::Dash},
{0x2014, TextFragment::Dash},
{0x2026, TextFragment::Ellipsis},
{'!', TextFragment::ExclamationMark},
{'\n', TextFragment::Newline},
{'?', TextFragment::QuestionMark},
{'\"', TextFragment::Quote},
{0x201C, TextFragment::Quote}, //
{0x201D, TextFragment::Quote}, //
{0x00AB, TextFragment::Quote}, //
{0x00BB, TextFragment::Quote}, //
{')', TextFragment::Bracket},
{'(', TextFragment::Bracket},
{'[', TextFragment::Bracket},
{']', TextFragment::Bracket},
{'{', TextFragment::Bracket},
{'}', TextFragment::Bracket}
};
// Sanity check
// #ifdef _DEBUG
// for (const auto delimiter: TextFragment::Delimiter())
// assert(std::find_if(delimiters.begin(), delimiters.end(), [delimiter](const Delimiter& item){
// return delimiter.id == TextFragment::NoDelimiter || item.delimiterType == delimiter.id;
// }) != delimiters.end());
// #endif
_fragmentCounter = 0;
_parsedText.clear();
qDebug() << "Parsing text of" << fixedText.length() << "characters";
_parsedText.setExpectedChaptersCount(fixedText.length() / 20000);
for (QChar ch: fixedText)
{
if (ch == '\r')
continue;
const auto delimiterItem = delimiters.find(ch);
if (delimiterItem == delimiters.end()) // Not a delimiter
{
if (_wordEnded) // This is the first letter of a new word
finalizeFragment();
_lastDelimiter = TextFragment::NoDelimiter;
_wordBuffer += ch;
}
else // This is a delimiter. Append it to the current word.
{
const TextFragment::Delimiter delimiter = delimiterItem->second;
// The opening quote is not a delimiter; the closing one is.
if (delimiter == TextFragment::Quote)
{
_quoteOpened = !_quoteOpened;
if (_quoteOpened) // This is an opening quote! Dump the previously accumulated fragment and assign this quote to the new one.
{
finalizeFragment();
_wordBuffer += ch;
}
else // Business as usual
{
// Don't let space, comma and quote in e. g. ", " override other punctuation marks
if (priority(delimiter) >= priority(_lastDelimiter))
_lastDelimiter = delimiter;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
else
{
// Don't let space, comma and quote in e. g. ", " override other punctuation marks
if (priority(delimiter) >= priority(_lastDelimiter))
_lastDelimiter = delimiter;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
}
finalizeFragment();
_parsedText.removeEmptyItems();
return _parsedText;
}
void CTextParser::setAddEmptyFragmentAfterSentence(bool add)
{
_addEmptyFragmentAfterSentenceEnd = add;
}
inline bool isUpperCaseText(const QString& str)
{
bool letterDetected = false;
for (QChar ch : str)
{
if (ch.isLetterOrNumber())
{
letterDetected = true;
if (!ch.isNumber() && !ch.isUpper())
return false;
}
}
return letterDetected;
}
void CTextParser::finalizeFragment()
{
_delimitersBuffer = _delimitersBuffer.trimmed();
if (!_delimitersBuffer.isEmpty() || !_wordBuffer.isEmpty())
{
if (_lastDelimiter == TextFragment::Newline)
{
// A whole line in uppercase is likely the chapter name.
// The _delimitersBuffer is already trimmed so no need to worry about it consisting of whitespace without any meaningful characters.
// This condition has to be checked first so that the chapter name properly starts the new chapter.
if (_delimitersBuffer.isEmpty() && isUpperCaseText(_wordBuffer))
{
// Start the new chapter
_parsedText.addEmptyChapter(_wordBuffer).addEmptyParagraph();
}
}
// Creating empty containers if necessary
if (_parsedText.empty()) // This should only happen once, when parsing the first line
_parsedText.addEmptyChapter(_wordBuffer).addEmptyParagraph();
TextFragment fragment(_wordBuffer, _delimitersBuffer, _lastDelimiter);
if (_addEmptyFragmentAfterSentenceEnd && fragment.isEndOfSentence())
{
_parsedText.lastParagraph().addFragment({_wordBuffer, _delimitersBuffer, TextFragment::Comma}, _fragmentCounter++);
// Moving the end-of-sentence delimiter off to a dummy fragment with no text - just so that we can fade the text out and hold the screen empty for a bit
_parsedText.lastParagraph().addFragment({QString::null, QString::null, _lastDelimiter}, _fragmentCounter++);
}
else
{
_parsedText.lastParagraph().addFragment(fragment, _fragmentCounter++);
}
if (_lastDelimiter == TextFragment::Newline)
// Start a new paragraph
_parsedText.lastChapter().addEmptyParagraph();
}
_wordEnded = false;
_delimitersBuffer.clear();
_wordBuffer.clear();
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2013 by Martin Moene
//
// 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 "eng_format.hpp"
#include <iomanip>
#include <iostream>
#include <limits>
#include <math.h>
#if defined _MSC_VER && _MSC_VER <= 1200 // VC6
namespace std {
double max( double const a, double const b ) { return a >= b ? a : b; }
}
#endif
bool approx( double const a, double const b )
{
const double scale = 1.0;
const double epsilon = 100 * std::numeric_limits<double>::epsilon();
return fabs(a - b) < epsilon * (scale + (std::max)( fabs(a), fabs(b) ) );
}
int main()
{
std::cout <<
"to_engineering_string( 1234, 3, eng_prefixed, \"Pa\" ): '" << to_engineering_string( 1234, 3, eng_prefixed, "Pa") << "'" << std::endl <<
"to_engineering_string( 1e-23, 3, eng_prefixed ): '" << to_engineering_string( 1e-23, 3, eng_prefixed ) << "'\n" << std::endl;
for ( int i = -24; i < +24; ++i )
{
const double x = +1.00 * pow(10.0,i);
const std::string text_inp = to_engineering_string( x, 3, eng_prefixed );
const double y = from_engineering_string( text_inp );
const std::string text_out = to_engineering_string( y, 3, eng_prefixed );
const std::string result = approx( x, y) ? "OK":"ERROR";
std::cout <<
result << "\t" <<
x << " \t" <<
y << " \t" <<
"'" << text_inp << "' \t" <<
"'" << text_out << "'" << std::endl;
}
return 0; // VC6
}
// VC6, VC8, VC2010, g++4.8.1
// cl -nologo -W3 -EHsc -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
// g++ -Wall -std=c++03 -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src -o demo_eng_format.exe demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
// g++ -Wall -std=c++11 -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src -o demo_eng_format.exe demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
<commit_msg>Include e+24 (1.00 Y), correct table column layout<commit_after>// Copyright (C) 2013 by Martin Moene
//
// 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 "eng_format.hpp"
#include <iomanip>
#include <iostream>
#include <limits>
#include <math.h>
#if defined _MSC_VER && _MSC_VER <= 1200 // VC6
namespace std {
double max( double const a, double const b ) { return a >= b ? a : b; }
}
#endif
bool approx( double const a, double const b )
{
const double scale = 1.0;
const double epsilon = 100 * std::numeric_limits<double>::epsilon();
return fabs(a - b) < epsilon * (scale + (std::max)( fabs(a), fabs(b) ) );
}
int main()
{
std::cout <<
"to_engineering_string( 1234, 3, eng_prefixed, \"Pa\" ): '" << to_engineering_string( 1234, 3, eng_prefixed, "Pa") << "'" << std::endl <<
"to_engineering_string( 1e-23, 3, eng_prefixed ): '" << to_engineering_string( 1e-23, 3, eng_prefixed ) << "'\n" << std::endl;
for ( int i = -24; i <= +24; ++i )
{
const double x = +1.00 * pow(10.0,i);
const std::string text_inp = to_engineering_string( x, 3, eng_prefixed );
const double y = from_engineering_string( text_inp );
const std::string text_out = to_engineering_string( y, 3, eng_prefixed );
const std::string result = approx( x, y) ? "OK":"ERROR";
std::cout <<
result << "\t" <<
x << " \t" <<
y << " \t" <<
"'" << text_inp << "' \t" <<
"'" << text_out << "'" << std::endl;
}
return 0; // VC6
}
// VC6, VC8, VC2010, g++4.8.1
// cl -nologo -W3 -EHsc -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
// g++ -Wall -std=c++03 -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src -o demo_eng_format.exe demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
// g++ -Wall -std=c++11 -DENG_FORMAT_MICRO_GLYPH=\"u\" -I../src -o demo_eng_format.exe demo_eng_format.cpp ../src/eng_format.cpp && demo_eng_format
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.