text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (C) 2004-2019 ZNC, see the NOTICE file for details.
*
* 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.
*
*
* ==================================================
* BotStatus module by QueenElsa • Version 1.0
* --------------------------------------------------
* Designed for use by the Undernet User-Committee
* --------------------------------------------------
* Channel: #development @ irc.undernet.org
* Contact: [email protected]
* --------------------------------------------------
* Announces the status of an attached bot. Based
* of ClientNotify module.
* ==================================================
*/
#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <znc/User.h>
using std::set;
class CBotStatus : public CModule {
protected:
CString m_sMethod;
bool m_bOnDisconnect{};
bool m_bOnConnect{};
set<CString> m_sBotsSeen;
void SaveSettings() {
SetNV("method", m_sMethod);
SetNV("ondisconnect", m_bOnDisconnect ? "1" : "0");
SetNV("onconnect", m_bOnConnect ? "1" : "0");
}
void SendNotification(const CString& sMessage) {
if(m_sMethod == "message") {
PutIRC("PRIVMSG #Arendelle :" +sMessage);
PutIRC("PRIVMSG #Uback :" +sMessage);
}
else if(m_sMethod == "notice") {
PutIRC("NOTICE #Arendelle :" +sMessage);
PutIRC("NOTICE #Uback :" +sMessage);
}
}
public:
MODCONSTRUCTOR(CBotStatus) {
AddHelpCommand();
AddCommand("Method", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnMethodCommand), "<message|notice|off>", "Sets the notify method");
AddCommand("OnDisconnect", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnDisconnectCommand), "<on|off>", "Turns notifications on disconnect only.");
AddCommand("OnConnect", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnConnectCommand), "<on|off>", "Turns notifications on connect only.");
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CBotStatus::OnShowCommand), "", "Show the current settings");
}
bool OnLoad(const CString& sArgs, CString& sMessage) override {
m_sMethod = GetNV("method");
if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") {
m_sMethod = "message";
}
// default = off for these:
m_bOnDisconnect = (GetNV("ondisconnect") == "0");
m_bOnConnect = (GetNV("onconnect") == "0");
return true;
}
void OnClientLogin() override {
if(m_bOnConnect) {
SendNotification("[ONLINE] Bot services have been restored. I will respond to commands I receive from ops.");
}
}
void OnClientDisconnect() override {
if(m_bOnDisconnect) {
SendNotification("[OFFLINE] Bot services are unavailable. I will not respond to any commands received. Please contact a User-Com Administrator.");
}
}
void OnMethodCommand(const CString& sCommand) {
const CString& sArg = sCommand.Token(1, true).AsLower();
if (sArg != "notice" && sArg != "message" && sArg != "off") {
PutModule("Usage: Method <message|notice|off>");
return;
}
if (sArg == "off") {
PutModule("MESSAGE METHOD CHANGED: Off - You will not be informed if your bot goes offline.");
PutModule("WARNING: Status updates will remain turned off until you change the method to NOTICE or MESSAGE.");
}
if (sArg == "notice") {
PutModule("MESSAGE METHOD CHANGED: Notice - You will be informed if your bot has gone offline via a channel notice.");
}
if (sArg == "message") {
PutModule("MESSAGE METHOD CHANGED: Message - You will be informed if your bot has gone offline via a channel message.");
}
m_sMethod = sArg;
SaveSettings();
}
void OnDisconnectCommand(const CString& sCommand) {
const CString& sArg = sCommand.Token(1, true).AsLower();
if (sArg.empty()) {
PutModule("Usage: OnDisconnect <on|off>");
return;
}
if (sArg == "off") {
PutModule("DISCONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot goes offline.");
PutModule("WARNING: This setting will remain turned off until you manually turn it back on.");
}
if (sArg == "on") {
PutModule("DISCONNECT NOTIFICATION CHANGED: On - You will be informed if your bot goes offline.");
}
m_bOnDisconnect = sArg.ToBool();
SaveSettings();
PutModule("Saved.");
}
void OnConnectCommand(const CString& sCommand) {
const CString& sArg = sCommand.Token(1, true).AsLower();
if (sArg.empty()) {
PutModule("Usage: OnConnect <on|off>");
return;
}
if (sArg == "off") {
PutModule("CONNECT NOTIFICATION CHANGED: Off - You will not be informed if your bot comes online.");
PutModule("WARNING: This setting will remain turned off until you manually turn it back on.");
}
if (sArg == "on") {
PutModule("CONNECT NOTIFICATION CHANGED: On - You will be informed if your bot comes online.");
}
m_bOnConnect = sArg.ToBool();
SaveSettings();
PutModule("Saved.");
}
void OnShowCommand(const CString& sLine) {
PutModule("Current settings: Message Method: " + m_sMethod + ", Notify if bot disconnected: " + CString(m_bOnDisconnect) + ", Notify if bot reconnects: " + CString(m_bOnConnect));
}
};
template<> void TModInfo<CBotStatus>(CModInfo& Info) {
Info.SetWikiPage("BotStatus");
}
USERMODULEDEFS(CBotStatus, "Notifies you when your bot has come online or gone offline. Configurable.")
<commit_msg>Delete BotStatus.cpp<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inspagob.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:44:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SD_INSPAGOB_HXX
#define _SD_INSPAGOB_HXX
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SDTREELB_HXX
#include "sdtreelb.hxx"
#endif
class SdDrawDocument;
//------------------------------------------------------------------------
class SdInsertPagesObjsDlg : public ModalDialog
{
private:
SdPageObjsTLB aLbTree;
CheckBox aCbxLink;
CheckBox aCbxMasters;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
SfxMedium* pMedium;
const SdDrawDocument* pDoc;
const String& rName;
void Reset();
DECL_LINK( SelectObjectHdl, void * );
public:
SdInsertPagesObjsDlg( Window* pParent,
const SdDrawDocument* pDoc,
SfxMedium* pSfxMedium,
const String& rFileName );
~SdInsertPagesObjsDlg();
List* GetList( USHORT nType );
BOOL IsLink();
BOOL IsRemoveUnnessesaryMasterPages() const;
};
#endif // _SD_INSPAGOB_HXX
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006/11/22 12:42:04 cl 1.3.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inspagob.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-12-12 17:44:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SD_INSPAGOB_HXX
#define _SD_INSPAGOB_HXX
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SDTREELB_HXX
#include "sdtreelb.hxx"
#endif
class SdDrawDocument;
//------------------------------------------------------------------------
class SdInsertPagesObjsDlg : public ModalDialog
{
private:
SdPageObjsTLB aLbTree;
CheckBox aCbxLink;
CheckBox aCbxMasters;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
SfxMedium* pMedium;
const SdDrawDocument* mpDoc;
const String& rName;
void Reset();
DECL_LINK( SelectObjectHdl, void * );
public:
SdInsertPagesObjsDlg( Window* pParent,
const SdDrawDocument* pDoc,
SfxMedium* pSfxMedium,
const String& rFileName );
~SdInsertPagesObjsDlg();
List* GetList( USHORT nType );
BOOL IsLink();
BOOL IsRemoveUnnessesaryMasterPages() const;
};
#endif // _SD_INSPAGOB_HXX
<|endoftext|> |
<commit_before>//*****************************************************************************
//
// Window.cpp
//
// Class responsible for spawning, managing, and closing the OpenGL context.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 27, 2015
//
// Modified:
// December 28, 2015
//
//*****************************************************************************
#include "Window.h"
#include <iostream>
#include <SDL.h>
//*****************************************************************************
//
//! Constructor for Window. Acquires resources for window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::Window()
: _window(NULL), _renderer(NULL), _width(_DEFAULT_WIDTH),
_height(_DEFAULT_HEIGHT)
{
//
// Initialize window
//
if (!_initialize())
{
std::cerr << "[ERROR] Window::Window(): Failed to initialize." <<
std::endl;
return;
}
//
// Creates base hand image
//
_baseImage = std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_base.png"));
//
// Creates and add images to finger image list
//
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_thumb.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_index.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_middle.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_ring.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_pinky.png")));
//
// Centre all images for aesthetic purposes
//
_centreImage(_baseImage);
for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)
{
_centreImage(*it);
}
}
//*****************************************************************************
//
//! Destructor for Window. Releases resources used by window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::~Window()
{
_terminate();
}
//*****************************************************************************
//
//! Updates the window. Called once every frame.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::update()
{
_processInput();
_update();
_render();
}
//*****************************************************************************
//
//! Initializes the window.
//!
//! \param None.
//!
//! \return Returns \b true if the window was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Window::_initialize()
{
int iRetVal = 0;
//
// Creates OpenGL context
//
_window = SDL_CreateWindow("Human Interface for Robotic Control",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,
SDL_WINDOW_SHOWN);
if (_window == NULL)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_CreateWindow() "\
"failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Creates renderer
//
_renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_TARGETTEXTURE);
if (_renderer == NULL)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_CreateRenderer() "\
"failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Sets renderer to default to an Opqaue White color on screen clear
//
iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,
SDL_ALPHA_OPAQUE);
if (iRetVal < 0)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()"\
" failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Sets a device independent resolution for rendering
//
iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);
if (iRetVal < 0)
{
std::cerr << "[ERROR] Window::_initialize(): "\
"SDL_RenderSetLogicalSize() failed. SDL Error " << SDL_GetError()
<< std::endl;
return false;
}
return true;
}
//*****************************************************************************
//
//! Terminates the window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_terminate()
{
if (_renderer != NULL)
{
SDL_DestroyRenderer(_renderer);
}
if (_window != NULL)
{
SDL_DestroyWindow(_window);
}
}
//*****************************************************************************
//
//! Processes user input. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_processInput()
{
SDL_Event event;
//
// Polls the event queue for pending events
//
while (SDL_PollEvent(&event))
{
//
// Notifies the Application class that the user wants to quit
//
if (event.type == SDL_QUIT)
{
notify(SDL_QUIT);
}
}
}
//*****************************************************************************
//
//! Updates program logic. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_update()
{
// TODO (Brandon): Implement
}
//*****************************************************************************
//
//! Renders frame. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_render()
{
//
// Clears screen
//
SDL_RenderClear(_renderer);
//
// Renders all images to screen
//
_baseImage->onRender();
for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();
it++)
{
(*it)->onRender();
}
//
// Updates screen (swaps screen buffers)
//
SDL_RenderPresent(_renderer);
}
//*****************************************************************************
//
//! Centre the image on the screen.
//!
//! \param image the image to be centred.
//!
//! \return None.
//
//*****************************************************************************
void Window::_centreImage(const std::unique_ptr<Image> &image)
{
SDL_Rect centredRect;
centredRect.w = image->getWidth();
centredRect.h = image->getHeight();
centredRect.x = (_width - centredRect.w) / 2;
centredRect.y = (_height - centredRect.h) / 2;
image->setRenderRect(¢redRect);
}
<commit_msg>Changed occurrences of NULL to nullptr when dealing with pointers.<commit_after>//*****************************************************************************
//
// Window.cpp
//
// Class responsible for spawning, managing, and closing the OpenGL context.
//
// Copyright (c) 2015 Brandon To, Minh Mai, and Yuzhou Liu
// This code is licensed under BSD license (see LICENSE.txt for details)
//
// Created:
// December 27, 2015
//
// Modified:
// December 28, 2015
//
//*****************************************************************************
#include "Window.h"
#include <iostream>
#include <SDL.h>
//*****************************************************************************
//
//! Constructor for Window. Acquires resources for window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::Window()
: _window(nullptr), _renderer(nullptr), _width(_DEFAULT_WIDTH),
_height(_DEFAULT_HEIGHT)
{
//
// Initialize window
//
if (!_initialize())
{
std::cerr << "[ERROR] Window::Window(): Failed to initialize." <<
std::endl;
return;
}
//
// Creates base hand image
//
_baseImage = std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_base.png"));
//
// Creates and add images to finger image list
//
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_thumb.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_index.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_middle.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_ring.png")));
_fingerImageList.push_back(std::unique_ptr<Image>(new Image(_renderer, "data/gfx/hand_right_pinky.png")));
//
// Centre all images for aesthetic purposes
//
_centreImage(_baseImage);
for (auto it = _fingerImageList.begin(); it != _fingerImageList.end(); it++)
{
_centreImage(*it);
}
}
//*****************************************************************************
//
//! Destructor for Window. Releases resources used by window and renderer.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
Window::~Window()
{
_terminate();
}
//*****************************************************************************
//
//! Updates the window. Called once every frame.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::update()
{
_processInput();
_update();
_render();
}
//*****************************************************************************
//
//! Initializes the window.
//!
//! \param None.
//!
//! \return Returns \b true if the window was initialized successfully and
//! \b false otherwise.
//
//*****************************************************************************
bool Window::_initialize()
{
int iRetVal = 0;
//
// Creates OpenGL context
//
_window = SDL_CreateWindow("Human Interface for Robotic Control",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _width, _height,
SDL_WINDOW_SHOWN);
if (_window == nullptr)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_CreateWindow() "\
"failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Creates renderer
//
_renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_TARGETTEXTURE);
if (_renderer == nullptr)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_CreateRenderer() "\
"failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Sets renderer to default to an Opqaue White color on screen clear
//
iRetVal = SDL_SetRenderDrawColor(_renderer, 0xFF, 0xFF, 0xFF,
SDL_ALPHA_OPAQUE);
if (iRetVal < 0)
{
std::cerr << "[ERROR] Window::_initialize(): SDL_SetRenderDrawColor()"\
" failed. SDL Error " << SDL_GetError() << std::endl;
return false;
}
//
// Sets a device independent resolution for rendering
//
iRetVal = SDL_RenderSetLogicalSize(_renderer, _width, _height);
if (iRetVal < 0)
{
std::cerr << "[ERROR] Window::_initialize(): "\
"SDL_RenderSetLogicalSize() failed. SDL Error " << SDL_GetError()
<< std::endl;
return false;
}
return true;
}
//*****************************************************************************
//
//! Terminates the window.
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_terminate()
{
if (_renderer != nullptr)
{
SDL_DestroyRenderer(_renderer);
}
if (_window != nullptr)
{
SDL_DestroyWindow(_window);
}
}
//*****************************************************************************
//
//! Processes user input. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_processInput()
{
SDL_Event event;
//
// Polls the event queue for pending events
//
while (SDL_PollEvent(&event))
{
//
// Notifies the Application class that the user wants to quit
//
if (event.type == SDL_QUIT)
{
notify(SDL_QUIT);
}
}
}
//*****************************************************************************
//
//! Updates program logic. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_update()
{
// TODO (Brandon): Implement
}
//*****************************************************************************
//
//! Renders frame. Called once per frame by update().
//!
//! \param None.
//!
//! \return None.
//
//*****************************************************************************
void Window::_render()
{
//
// Clears screen
//
SDL_RenderClear(_renderer);
//
// Renders all images to screen
//
_baseImage->onRender();
for (auto it = _fingerImageList.begin(); it != _fingerImageList.end();
it++)
{
(*it)->onRender();
}
//
// Updates screen (swaps screen buffers)
//
SDL_RenderPresent(_renderer);
}
//*****************************************************************************
//
//! Centre the image on the screen.
//!
//! \param image the image to be centred.
//!
//! \return None.
//
//*****************************************************************************
void Window::_centreImage(const std::unique_ptr<Image> &image)
{
SDL_Rect centredRect;
centredRect.w = image->getWidth();
centredRect.h = image->getHeight();
centredRect.x = (_width - centredRect.w) / 2;
centredRect.y = (_height - centredRect.h) / 2;
image->setRenderRect(¢redRect);
}
<|endoftext|> |
<commit_before>// OfficeXlsFile.cpp : Implementation of COfficeXlsFile
#include "stdafx.h"
#include <string>
#include <iostream>
#include <boost/uuid/uuid.hpp>
#pragma warning(push)
#pragma warning(disable : 4244)
#include <boost/uuid/random_generator.hpp>
#pragma warning(pop)
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include <boost_filesystem_version.h>
#include "source\ConvertXls2Xlsx.h"
#include "..\Common\XmlUtils.h"
#include "..\Common\ASCATLError.h"
#include "OfficeXlsFile.h"
// : 1 , xlsx docx
// 0 , package
#ifndef STANDALONE_USE
#define STANDALONE_USE 0// : (1) (0)
#endif
// - uuid
boost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)
{
boost::uuids::random_generator gen;
boost::uuids::uuid u = gen();
boost::filesystem::wpath path = boost::filesystem::wpath(Dst) / boost::lexical_cast<std::wstring>(u);
return path;
}
std::wstring bstr2wstring(BSTR str)
{
return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L"";
}
boost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)
{
return MakeTempDirectoryName(bstr2wstring(Dst));
}
///------------------------------------------------------------------------------------
// COfficeXlsFile
COfficeXlsFile::COfficeXlsFile()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils));
#endif
}
HRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)
{
return E_NOTIMPL;
}
HRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)
{
HRESULT hr;
if (!initialized())
return E_FAIL;
if (!sDstPath)
{
_ASSERTE(!!sDstPath);
return E_FAIL;
}
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();
#else
boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));
#endif
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));
#else
boost::filesystem::wpath dstTempPath = outputDir.string();
#endif
try
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
//
boost::filesystem::create_directory(dstTempPath);
#endif
hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));
}
catch(...)
{
hr = E_FAIL;
}
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
// ( )
try
{
boost::filesystem::remove_all(dstTempPath);
}
catch(...)
{
}
#endif
return hr;
}
HRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,
const std::wstring & dstTempPath,
const std::wstring & dstPath)
{
HRESULT hr = AVS_ERROR_UNEXPECTED;
ProgressCallback ffCallBack;
ffCallBack.OnProgress = OnProgressFunc;
ffCallBack.OnProgressEx = OnProgressExFunc;
ffCallBack.caller = this;
hr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);
if (hr != S_OK) return hr;
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))
return hr;
#endif
return S_OK;
}
bool COfficeXlsFile::initialized()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
return (!!office_utils_);
#endif
return true;
}
void COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)
{
//g_oCriticalSection.Enter();
COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
if (pXlsFile != NULL)
{
pXlsFile->OnProgress(nID, nPercent);
}
//g_oCriticalSection.Leave();
}
void COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)
{
//g_oCriticalSection.Enter();
COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
if (pXlsFile != NULL)
{
pXlsFile->OnProgressEx(nID, nPercent, pStop);
}
//g_oCriticalSection.Leave();
}
<commit_msg> <commit_after>// OfficeXlsFile.cpp : Implementation of COfficeXlsFile
#include "stdafx.h"
#include <string>
#include <iostream>
#include <boost/uuid/uuid.hpp>
#pragma warning(push)
#pragma warning(disable : 4244)
#include <boost/uuid/random_generator.hpp>
#pragma warning(pop)
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "../Common/boost_filesystem_version.h"
#include "source/ConvertXls2Xlsx.h"
#include "../Common/XmlUtils.h"
#include "../Common/ASCATLError.h"
#include "OfficeXlsFile.h"
// : 1 , xlsx docx
// 0 , package
#ifndef STANDALONE_USE
#define STANDALONE_USE 0// : (1) (0)
#endif
// - uuid
boost::filesystem::wpath MakeTempDirectoryName(const std::wstring & Dst)
{
boost::uuids::random_generator gen;
boost::uuids::uuid u = gen();
boost::filesystem::wpath path = boost::filesystem::wpath(Dst) / boost::lexical_cast<std::wstring>(u);
return path;
}
std::wstring bstr2wstring(BSTR str)
{
return str ? std::wstring(&str[0], &str[::SysStringLen(str)]) : L"";
}
boost::filesystem::wpath MakeTempDirectoryName(BSTR Dst)
{
return MakeTempDirectoryName(bstr2wstring(Dst));
}
///------------------------------------------------------------------------------------
// COfficeXlsFile
COfficeXlsFile::COfficeXlsFile()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
office_utils_.CoCreateInstance(__uuidof(ASCOfficeUtils::COfficeUtils));
#endif
}
HRESULT COfficeXlsFile::SaveToFile(BSTR sDstFileName, BSTR sSrcPath, BSTR sXMLOptions)
{
return E_NOTIMPL;
}
HRESULT COfficeXlsFile::LoadFromFile(BSTR sSrcFileName, BSTR sDstPath, BSTR sXMLOptions)
{
HRESULT hr;
if (!initialized())
return E_FAIL;
if (!sDstPath)
{
_ASSERTE(!!sDstPath);
return E_FAIL;
}
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath)).parent_path();
#else
boost::filesystem::wpath outputDir = boost::filesystem::wpath(bstr2wstring(sDstPath));
#endif
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
boost::filesystem::wpath dstTempPath = MakeTempDirectoryName(BOOST_STRING_PATH(outputDir));
#else
boost::filesystem::wpath dstTempPath = outputDir.string();
#endif
try
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
//
boost::filesystem::create_directory(dstTempPath);
#endif
hr = LoadFromFileImpl(bstr2wstring(sSrcFileName), BOOST_STRING_PATH(dstTempPath), bstr2wstring(sDstPath));
}
catch(...)
{
hr = E_FAIL;
}
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
// ( )
try
{
boost::filesystem::remove_all(dstTempPath);
}
catch(...)
{
}
#endif
return hr;
}
HRESULT COfficeXlsFile::LoadFromFileImpl(const std::wstring & srcFileName,
const std::wstring & dstTempPath,
const std::wstring & dstPath)
{
HRESULT hr = AVS_ERROR_UNEXPECTED;
ProgressCallback ffCallBack;
ffCallBack.OnProgress = OnProgressFunc;
ffCallBack.OnProgressEx = OnProgressExFunc;
ffCallBack.caller = this;
hr = ConvertXls2Xlsx(srcFileName, dstTempPath, &ffCallBack);
if (hr != S_OK) return hr;
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
if FAILED(hr = office_utils_->CompressFileOrDirectory(ATL::CComBSTR(dstTempPath.c_str()), ATL::CComBSTR(dstPath.c_str()), (-1)))
return hr;
#endif
return S_OK;
}
bool COfficeXlsFile::initialized()
{
#if defined(STANDALONE_USE) && (STANDALONE_USE == 1)
return (!!office_utils_);
#endif
return true;
}
void COfficeXlsFile::OnProgressFunc (LPVOID lpParam, long nID, long nPercent)
{
//g_oCriticalSection.Enter();
COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
if (pXlsFile != NULL)
{
pXlsFile->OnProgress(nID, nPercent);
}
//g_oCriticalSection.Leave();
}
void COfficeXlsFile::OnProgressExFunc (LPVOID lpParam, long nID, long nPercent, short* pStop)
{
//g_oCriticalSection.Enter();
COfficeXlsFile* pXlsFile = reinterpret_cast<COfficeXlsFile*>(lpParam);
if (pXlsFile != NULL)
{
pXlsFile->OnProgressEx(nID, nPercent, pStop);
}
//g_oCriticalSection.Leave();
}
<|endoftext|> |
<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - [email protected]
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Utils.h"
void myStrcpy(char *str1, const char *str2)
{
int bufsize = sizeof(str1);
int len = (int) strlen(str2);
if (len < bufsize)
{
strcpy(str1, str2);
}
else
{
strncpy(str1, str2, bufsize);
str1[bufsize - 1] = 0;
}
}
#ifdef ARDUINO
long Millis()
{
return millis();
}
#endif
#ifdef DOS
clock_t Millis()
{
return clock();
}
long timediff(clock_t t2, clock_t t1)
{
long elapsed;
elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000;
return elapsed;
}
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void getCursorXY(int &x, int&y)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
x = csbi.dwCursorPosition.X;
y = csbi.dwCursorPosition.Y;
}
}
void setcolor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
return;
}
void clrscr()
{
COORD coordScreen = { 0, 0 };
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &csbi);
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
GetConsoleScreenBufferInfo(hConsole, &csbi);
FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
SetConsoleCursorPosition(hConsole, coordScreen);
return;
}
void box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])
{
unsigned i, j, m;
{
m = (sx - x); //differential
j = m / 8; //adjust
j = j - 1; //more adjustment
gotoxy(x, y); cprintf("┌"); //Top left corner of box
gotoxy(sx, y); cprintf("¬"); //Top right corner of box
gotoxy(x, sy); cprintf("└"); //Bottom left corner of box
gotoxy(sx, sy); cprintf("┌"); //Bottom right corner of box
for (i = x + 1; i<sx; i++)
{
gotoxy(i, y); cprintf("-"); // Top horizontol line
gotoxy(i, sy); cprintf("-"); // Bottom Horizontal line
}
for (i = y + 1; i<sy; i++)
{
gotoxy(x, i); cprintf("|"); //Left Vertical line
gotoxy(sx, i); cprintf("|"); //Right Vertical Line
}
gotoxy(x + j, y); cprintf(text_); //put Title
gotoxy(1, 24);
}
}
void clrbox(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2, unsigned char bkcol)
{
int x, y;
setcolor(bkcol); //Set to color bkcol
for (y = y1; y<y2; y++) //Fill Y Region Loop
{
for (x = x1; x<x2; x++) //Fill X region Loop
{
gotoxy(x, y); cprintf(" "); //Draw Solid space
}
}
}
void putbox(unsigned x, unsigned y, unsigned sx, unsigned sy,unsigned char col, unsigned char col2, unsigned char bkcol, char text_[])
{
clrbox(x, y, sx, sy, bkcol);
box(x, y, sx, sy, col, col2, text_);
}
void txtPlot(unsigned char x, unsigned char y, unsigned char Color)
{
setcolor(Color);
gotoxy(x, y); cprintf(".");
}
void delay(unsigned int milliseconds)
{
clock_t ticks1, ticks2;
unsigned int tic1 = 0, tic2 = 0, tick = 0;
ticks1 = clock();
while (tick<milliseconds)
{
ticks2 = clock();
tic1 = ticks2 / CLOCKS_PER_SEC - ticks1;
tic2 = ticks1 / CLOCKS_PER_SEC;
tick = ticks2 - ticks1;
}
ticks2 = clock();
}
#endif
<commit_msg>Fixed square<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - [email protected]
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Utils.h"
#pragma execution_character_set("utf-8")
void myStrcpy(char *str1, const char *str2)
{
int bufsize = sizeof(str1);
int len = (int) strlen(str2);
if (len < bufsize)
{
strcpy(str1, str2);
}
else
{
strncpy(str1, str2, bufsize);
str1[bufsize - 1] = 0;
}
}
#ifdef ARDUINO
long Millis()
{
return millis();
}
#endif
#ifdef DOS
clock_t Millis()
{
return clock();
}
long timediff(clock_t t2, clock_t t1)
{
long elapsed;
elapsed = (long) ((double)t2 - t1) / CLOCKS_PER_SEC * 1000;
return elapsed;
}
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void getCursorXY(int &x, int&y)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
x = csbi.dwCursorPosition.X;
y = csbi.dwCursorPosition.Y;
}
}
void setcolor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
return;
}
void clrscr()
{
COORD coordScreen = { 0, 0 };
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &csbi);
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
GetConsoleScreenBufferInfo(hConsole, &csbi);
FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
SetConsoleCursorPosition(hConsole, coordScreen);
return;
}
void box(unsigned x, unsigned y, unsigned sx, unsigned sy, unsigned char col, unsigned char col2, char text_[])
{
unsigned i, j, m;
{
m = (sx - x); //differential
j = m / 8; //adjust
j = j - 1; //more adjustment
gotoxy(x, y); cprintf("*"); // ┌ //Top left corner of box
gotoxy(sx, y); cprintf("*"); // ┐ //Top right corner of box
gotoxy(x, sy); cprintf("*"); // └ //Bottom left corner of box
gotoxy(sx, sy); cprintf("*"); // ┘ //Bottom right corner of box
for (i = x + 1; i<sx; i++)
{
gotoxy(i, y); cprintf("-"); // Top horizontol line
gotoxy(i, sy); cprintf("-"); // Bottom Horizontal line
}
for (i = y + 1; i<sy; i++)
{
gotoxy(x, i); cprintf("|"); //Left Vertical line
gotoxy(sx, i); cprintf("|"); //Right Vertical Line
}
gotoxy(x + j, y); cprintf(text_); //put Title
gotoxy(1, 24);
}
}
void clrbox(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2, unsigned char bkcol)
{
int x, y;
setcolor(bkcol); //Set to color bkcol
for (y = y1; y<y2; y++) //Fill Y Region Loop
{
for (x = x1; x<x2; x++) //Fill X region Loop
{
gotoxy(x, y); cprintf(" "); //Draw Solid space
}
}
}
void putbox(unsigned x, unsigned y, unsigned sx, unsigned sy,unsigned char col, unsigned char col2, unsigned char bkcol, char text_[])
{
clrbox(x, y, sx, sy, bkcol);
box(x, y, sx, sy, col, col2, text_);
}
void txtPlot(unsigned char x, unsigned char y, unsigned char Color)
{
setcolor(Color);
gotoxy(x, y); cprintf(".");
}
void delay(unsigned int milliseconds)
{
clock_t ticks1, ticks2;
unsigned int tic1 = 0, tic2 = 0, tick = 0;
ticks1 = clock();
while (tick<milliseconds)
{
ticks2 = clock();
tic1 = ticks2 / CLOCKS_PER_SEC - ticks1;
tic2 = ticks1 / CLOCKS_PER_SEC;
tick = ticks2 - ticks1;
}
ticks2 = clock();
}
#endif
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "QtHttpAssetProvider.h"
#include "ConfigurationManager.h"
#include "EventManager.h"
#include "AssetModule.h"
#include "RexAsset.h"
#include "AssetMetadataInterface.h"
#include "AssetServiceInterface.h"
#include "AssetEvents.h"
#include <QUuid>
#include <QNetworkReply>
#include <QByteArray>
#include <QDebug>
#include <QStringList>
#define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections
namespace Asset
{
QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :
QObject(),
framework_(framework),
event_manager_(framework->GetEventManager().get()),
name_("QtHttpAssetProvider"),
network_manager_(new QNetworkAccessManager()),
filling_stack_(false),
get_texture_cap_(QUrl())
{
asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0);
if (event_manager_)
asset_event_category_ = event_manager_->QueryEventCategory("Asset");
if (!asset_event_category_)
AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events");
connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));
AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());
}
QtHttpAssetProvider::~QtHttpAssetProvider()
{
SAFE_DELETE(network_manager_);
}
void QtHttpAssetProvider::SetGetTextureCap(std::string url)
{
get_texture_cap_ = QUrl(QString::fromStdString(url));
}
// Interface implementation
void QtHttpAssetProvider::Update(f64 frametime)
{
StartTransferFromQueue();
}
const std::string& QtHttpAssetProvider::Name()
{
return name_;
}
bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)
{
// Textures over http with the GetTexture cap
if (IsAcceptableAssetType(asset_type))
if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
return true;
QString id(asset_id.c_str());
if (!id.startsWith("http://"))
return false;
QUrl asset_url(id);
if (asset_url.isValid())
return true;
else
return false;
}
bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
{
if (!IsValidId(asset_id, asset_type))
return false;
QString asset_id_qstring = QString::fromStdString(asset_id);
if (assetid_to_transfer_map_.contains(asset_id_qstring))
{
assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);
}
else
{
asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);
QtHttpAssetTransfer *transfer = 0;
if (IsAcceptableAssetType(asset_type))
{
// Http texture via cap url
QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring;
QUrl texture_url(texture_url_string);
transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);
}
else
{
// Normal http get
QUrl asset_url = CreateUrl(asset_id_qstring);
transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);
}
if (!transfer)
return false;
transfer->setOriginatingObject(transfer);
if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)
{
assetid_to_transfer_map_[asset_id_qstring] = transfer;
network_manager_->get(*transfer);
AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type);
}
else
pending_request_queue_.append(transfer);
}
return true;
}
bool QtHttpAssetProvider::InProgress(const std::string& asset_id)
{
QString qt_asset_id = QString::fromStdString(asset_id);
if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))
return true;
else
return false;
}
bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
{
if (InProgress(asset_id))
{
// We dont know, QNetworkAccessManager handles these
size = 0;
received = 0;
received_continuous = 0;
return true;
}
else
return false;
}
Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
{
return Foundation::AssetPtr();
}
Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()
{
Foundation::AssetTransferInfoVector info_vector;
foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
{
HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();
// What we know
Foundation::AssetTransferInfo info;
info.id_ = iter_info.id.toStdString();
info.type_ = RexTypes::GetAssetTypeString(iter_info.type);
info.provider_ = Name();
// The following we dont know, QNetworkAccessManager handles these
info.size_ = 0;
info.received_ = 0;
info.received_continuous_ = 0;
info_vector.push_back(info);
}
return info_vector;
}
// Private
QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)
{
if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://"))
assed_id = "http://" + assed_id;
return QUrl(assed_id);
}
void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)
{
fake_metadata_fetch_ = false;
QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject());
/**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/
if (reply->error() != QNetworkReply::NoError && transfer)
{
// Send asset canceled events
HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();
Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));
Foundation::EventDataPtr data_ptr(data);
event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);
// Clean up
RemoveFinishedTransfers(error_transfer_data.id, reply->url());
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled");
reply->deleteLater();
return;
}
/**** THIS IS A /data REQUEST REPLY ****/
if (transfer)
{
// Create asset pointer
HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();
std::string id = tranfer_info.id.toStdString();
std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);
Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));
// Fill asset data with reply data
RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal();
QByteArray data_array = reply->readAll();
for (int index = 0; index < data_array.count(); ++index)
data_vector.push_back(data_array.at(index));
// Get metadata if available
QString url_path = tranfer_info.url.path();
if (url_path.endsWith("/data") || url_path.endsWith("/data/"))
{
// Generate metada url
int clip_count;
if (url_path.endsWith("/data"))
clip_count = 5;
else if (url_path.endsWith("/data/"))
clip_count = 6;
else
{
reply->deleteLater();
return;
}
QUrl metadata_url = tranfer_info.url;
url_path = url_path.left(url_path.count()-clip_count);
url_path = url_path + "/metadata";
metadata_url.setPath(url_path);
tranfer_info.url = metadata_url;
QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);
// Store tranfer data and asset data pointer internally
QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair;
data_pair.first = tranfer_info;
data_pair.second = asset_ptr;
metadata_to_assetptr_[metada_request->url()] = data_pair;
// Send metadata network request
//network_manager_->get(*metada_request);
// HACK to avoid metadata fetch for now
fake_metadata_url_ = metada_request->url();
fake_metadata_fetch_ = true;
}
// Asset data feched, lets store
else
{
// Store asset
boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
if (asset_service)
asset_service->StoreAsset(asset_ptr);
// Send asset ready events
foreach (request_tag_t tag, tranfer_info.tags)
{
Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);
event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
}
RemoveFinishedTransfers(tranfer_info.id, QUrl());
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed");
}
}
// Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata
// or actually we dont use metadata in naali so thats the main reason its not fetched
if (fake_metadata_fetch_)
{
/**** THIS IS A /metadata REQUEST REPLY ****/
if (metadata_to_assetptr_.contains(fake_metadata_url_))
{
// Pull out transfer data and asset pointer assosiated with this reply url
QUrl metadata_transfer_url = fake_metadata_url_;
HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;
Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;
if (!ready_asset_ptr)
{
reply->deleteLater();
return;
}
// Fill metadata
/*
const QByteArray &inbound_metadata = reply->readAll();
QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());
#if defined(__GNUC__)
RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata());
#else
Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();
RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata);
#endif
std::string std_md(decoded_metadata.toStdString());
m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser.
*/
// Store asset
boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
if (asset_service)
asset_service->StoreAsset(ready_asset_ptr);
// Send asset ready events
foreach (request_tag_t tag, transfer_data.tags)
{
Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);
event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
}
RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata");
}
}
reply->deleteLater();
}
void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)
{
QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];
assetid_to_transfer_map_.remove(asset_transfer_key);
if (metadata_transfer_key.isValid())
metadata_to_assetptr_.remove(metadata_transfer_key);
SAFE_DELETE(remove_transfer);
}
void QtHttpAssetProvider::ClearAllTransfers()
{
foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
SAFE_DELETE(transfer);
assetid_to_transfer_map_.clear();
foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
SAFE_DELETE(transfer);
pending_request_queue_.clear();
}
void QtHttpAssetProvider::StartTransferFromQueue()
{
if (pending_request_queue_.count() == 0)
return;
// If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets
if (assetid_to_transfer_map_.count() == 0)
filling_stack_ = true;
if (!filling_stack_)
return;
if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)
{
if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)
filling_stack_ = false;
else
{
QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);
assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;
network_manager_->get(*new_transfer);
AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));
StartTransferFromQueue(); // Recursivly fill the transfer map
}
}
}
bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)
{
foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
if (transfer->GetTranferInfo().id == assed_id)
return true;
return false;
}
bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)
{
using namespace RexTypes;
bool accepted = false;
switch (GetAssetTypeFromTypeName(asset_type))
{
case RexAT_Texture:
case RexAT_Mesh:
accepted = true;
break;
default:
accepted = false;
break;
}
return accepted;
}
}<commit_msg>Bug fix to handle urls properly if caps url not set (modrex addurls etc). Printing a info line to console if server has http assets enabled.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "QtHttpAssetProvider.h"
#include "ConfigurationManager.h"
#include "EventManager.h"
#include "AssetModule.h"
#include "RexAsset.h"
#include "AssetMetadataInterface.h"
#include "AssetServiceInterface.h"
#include "AssetEvents.h"
#include <QUuid>
#include <QNetworkReply>
#include <QByteArray>
#include <QDebug>
#include <QStringList>
#define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections
namespace Asset
{
QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) :
QObject(),
framework_(framework),
event_manager_(framework->GetEventManager().get()),
name_("QtHttpAssetProvider"),
network_manager_(new QNetworkAccessManager()),
filling_stack_(false),
get_texture_cap_(QUrl())
{
asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0);
if (event_manager_)
asset_event_category_ = event_manager_->QueryEventCategory("Asset");
if (!asset_event_category_)
AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events");
connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*)));
AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString());
}
QtHttpAssetProvider::~QtHttpAssetProvider()
{
SAFE_DELETE(network_manager_);
}
void QtHttpAssetProvider::SetGetTextureCap(std::string url)
{
get_texture_cap_ = QUrl(QString::fromStdString(url));
if (get_texture_cap_.isValid())
AssetModule::LogInfo("Server supports HTTP assets: using HTTP to fetch textures and meshes.");
}
// Interface implementation
void QtHttpAssetProvider::Update(f64 frametime)
{
StartTransferFromQueue();
}
const std::string& QtHttpAssetProvider::Name()
{
return name_;
}
bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type)
{
// Textures over http with the GetTexture cap
if (IsAcceptableAssetType(asset_type))
if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
return true;
QString id(asset_id.c_str());
if (!id.startsWith("http://"))
return false;
QUrl asset_url(id);
if (asset_url.isValid())
return true;
else
return false;
}
bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
{
if (!IsValidId(asset_id, asset_type))
return false;
QString asset_id_qstring = QString::fromStdString(asset_id);
if (assetid_to_transfer_map_.contains(asset_id_qstring))
{
assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag);
}
else
{
asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type);
QtHttpAssetTransfer *transfer = 0;
if (IsAcceptableAssetType(asset_type) && RexUUID::IsValid(asset_id) && get_texture_cap_.isValid())
{
// Http texture/meshes via cap url
QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring;
QUrl texture_url(texture_url_string);
transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag);
}
else
{
// Normal http get
QUrl asset_url = CreateUrl(asset_id_qstring);
transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag);
}
if (!transfer)
return false;
transfer->setOriginatingObject(transfer);
if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS)
{
assetid_to_transfer_map_[asset_id_qstring] = transfer;
network_manager_->get(*transfer);
AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type);
}
else
pending_request_queue_.append(transfer);
}
return true;
}
bool QtHttpAssetProvider::InProgress(const std::string& asset_id)
{
QString qt_asset_id = QString::fromStdString(asset_id);
if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id))
return true;
else
return false;
}
bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
{
if (InProgress(asset_id))
{
// We dont know, QNetworkAccessManager handles these
size = 0;
received = 0;
received_continuous = 0;
return true;
}
else
return false;
}
Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
{
return Foundation::AssetPtr();
}
Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo()
{
Foundation::AssetTransferInfoVector info_vector;
foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
{
HttpAssetTransferInfo iter_info = transfer->GetTranferInfo();
// What we know
Foundation::AssetTransferInfo info;
info.id_ = iter_info.id.toStdString();
info.type_ = RexTypes::GetAssetTypeString(iter_info.type);
info.provider_ = Name();
// The following we dont know, QNetworkAccessManager handles these
info.size_ = 0;
info.received_ = 0;
info.received_continuous_ = 0;
info_vector.push_back(info);
}
return info_vector;
}
// Private
QUrl QtHttpAssetProvider::CreateUrl(QString assed_id)
{
if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://"))
assed_id = "http://" + assed_id;
return QUrl(assed_id);
}
void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply)
{
fake_metadata_fetch_ = false;
QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject());
/**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/
if (reply->error() != QNetworkReply::NoError && transfer)
{
// Send asset canceled events
HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo();
Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type));
Foundation::EventDataPtr data_ptr(data);
event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0);
// Clean up
RemoveFinishedTransfers(error_transfer_data.id, reply->url());
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled");
reply->deleteLater();
return;
}
/**** THIS IS A /data REQUEST REPLY ****/
if (transfer)
{
// Create asset pointer
HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo();
std::string id = tranfer_info.id.toStdString();
std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type);
Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type));
// Fill asset data with reply data
RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal();
QByteArray data_array = reply->readAll();
for (int index = 0; index < data_array.count(); ++index)
data_vector.push_back(data_array.at(index));
// Get metadata if available
QString url_path = tranfer_info.url.path();
if (url_path.endsWith("/data") || url_path.endsWith("/data/"))
{
// Generate metada url
int clip_count;
if (url_path.endsWith("/data"))
clip_count = 5;
else if (url_path.endsWith("/data/"))
clip_count = 6;
else
{
reply->deleteLater();
return;
}
QUrl metadata_url = tranfer_info.url;
url_path = url_path.left(url_path.count()-clip_count);
url_path = url_path + "/metadata";
metadata_url.setPath(url_path);
tranfer_info.url = metadata_url;
QNetworkRequest *metada_request = new QNetworkRequest(metadata_url);
// Store tranfer data and asset data pointer internally
QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair;
data_pair.first = tranfer_info;
data_pair.second = asset_ptr;
metadata_to_assetptr_[metada_request->url()] = data_pair;
// Send metadata network request
//network_manager_->get(*metada_request);
// HACK to avoid metadata fetch for now
fake_metadata_url_ = metada_request->url();
fake_metadata_fetch_ = true;
}
// Asset data feched, lets store
else
{
// Store asset
boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
if (asset_service)
asset_service->StoreAsset(asset_ptr);
// Send asset ready events
foreach (request_tag_t tag, tranfer_info.tags)
{
Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag);
event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
}
RemoveFinishedTransfers(tranfer_info.id, QUrl());
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed");
}
}
// Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata
// or actually we dont use metadata in naali so thats the main reason its not fetched
if (fake_metadata_fetch_)
{
/**** THIS IS A /metadata REQUEST REPLY ****/
if (metadata_to_assetptr_.contains(fake_metadata_url_))
{
// Pull out transfer data and asset pointer assosiated with this reply url
QUrl metadata_transfer_url = fake_metadata_url_;
HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first;
Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second;
if (!ready_asset_ptr)
{
reply->deleteLater();
return;
}
// Fill metadata
/*
const QByteArray &inbound_metadata = reply->readAll();
QString decoded_metadata = QString::fromUtf8(inbound_metadata.data());
#if defined(__GNUC__)
RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata());
#else
Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata();
RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata);
#endif
std::string std_md(decoded_metadata.toStdString());
m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser.
*/
// Store asset
boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
if (asset_service)
asset_service->StoreAsset(ready_asset_ptr);
// Send asset ready events
foreach (request_tag_t tag, transfer_data.tags)
{
Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag);
event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data);
}
RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url);
StartTransferFromQueue();
AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata");
}
}
reply->deleteLater();
}
void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key)
{
QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key];
assetid_to_transfer_map_.remove(asset_transfer_key);
if (metadata_transfer_key.isValid())
metadata_to_assetptr_.remove(metadata_transfer_key);
SAFE_DELETE(remove_transfer);
}
void QtHttpAssetProvider::ClearAllTransfers()
{
foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values())
SAFE_DELETE(transfer);
assetid_to_transfer_map_.clear();
foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
SAFE_DELETE(transfer);
pending_request_queue_.clear();
}
void QtHttpAssetProvider::StartTransferFromQueue()
{
if (pending_request_queue_.count() == 0)
return;
// If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets
if (assetid_to_transfer_map_.count() == 0)
filling_stack_ = true;
if (!filling_stack_)
return;
if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0)
{
if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0)
filling_stack_ = false;
else
{
QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0);
assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer;
network_manager_->get(*new_transfer);
AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type));
StartTransferFromQueue(); // Recursivly fill the transfer map
}
}
}
bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id)
{
foreach (QtHttpAssetTransfer *transfer, pending_request_queue_)
if (transfer->GetTranferInfo().id == assed_id)
return true;
return false;
}
bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type)
{
using namespace RexTypes;
bool accepted = false;
switch (GetAssetTypeFromTypeName(asset_type))
{
case RexAT_Texture:
case RexAT_Mesh:
accepted = true;
break;
default:
accepted = false;
break;
}
return accepted;
}
}<|endoftext|> |
<commit_before>/*
* IcarusFitnessCalculator.cpp
*
* Created on: 26/03/2015
* Author: Vitor
*/
#include "IcarusFitnessCalculator.h"
double IcarusFitnessCalculator::fitness() {
gerar_arquivo_top();
if (system("iverilog top.v genetico.v -o individuo") == -1) {
std::cerr << "Erro na chamada iverilog.\n";
exit(1);
}
FILE* simulador = popen("vvp individuo", "r");
if (simulador == nullptr) {
std::cerr << "Nao consegui executar o simulador vvp.\n";
std::exit(1);
}
auto parsed_output = parse_output(simulador);
pclose(simulador);
return fitness_calculator(parsed_output);
}
void IcarusFitnessCalculator::gerar_arquivo_top() {
std::ofstream top;
top.open("top.v");
top << "module top();\n\n";
top << "\tinteger i;\n";
top << "\treg [" << num_inputs - 1 << ":0] in;\n";
top << "\twire [" << num_outputs - 1 << ":0] out;\n\n";
top << "initial begin\n";
top << "\t$monitor(\"";
for (int i = 0; i < num_inputs; i++) {
top << "%b";
}
top << " ";
for (int i = 0; i < num_outputs; i++) {
top << "%b";
}
top << "\", ";
for (int i = num_inputs - 1; i >= 0; i--) {
top << "in[" << i << "], ";
}
for (int i = num_outputs - 1; i >= 1; i--) {
top << "out[" << i << "], ";
}
top << "out);\n";
top << "\tfor (i = 0; i < " << (int) pow(2, num_inputs)
<< "; i = i + 1) begin\n";
top << "\t\t#5 in = i;\n";
top << "\tend\n";
top << "end\n\n";
top << "genetico genetico(\n";
top << "\t.in(in),\n";
top << "\t.out(out)\n";
top << ");\n\n";
top << "endmodule";
}
std::vector<std::vector<std::bitset<8>>>
IcarusFitnessCalculator::parse_output(FILE* simulador) {
std::vector<std::vector<std::bitset<8>>> results;
char entrada[100];
char saida[100];
// Ignorando os x's
fscanf(simulador, "%s", entrada);
fscanf(simulador, "%s", saida);
for (int i = 0; i < (int) pow(2, num_inputs); i++) {
fscanf(simulador, "%s", entrada);
fscanf(simulador, "%s", saida);
results.push_back(std::vector<std::bitset<8>>());
results[i].push_back(std::bitset<8>(saida));
}
return results;
}
<commit_msg>Adicionado logic_e.v na linha de compilacao do individuo.<commit_after>/*
* IcarusFitnessCalculator.cpp
*
* Created on: 26/03/2015
* Author: Vitor
*/
#include "IcarusFitnessCalculator.h"
double IcarusFitnessCalculator::fitness() {
gerar_arquivo_top();
if (system("iverilog top.v genetico.v logic_e.v -o individuo") == -1) {
std::cerr << "Erro na chamada iverilog.\n";
exit(1);
}
FILE* simulador = popen("vvp individuo", "r");
if (simulador == nullptr) {
std::cerr << "Nao consegui executar o simulador vvp.\n";
std::exit(1);
}
auto parsed_output = parse_output(simulador);
pclose(simulador);
return fitness_calculator(parsed_output);
}
void IcarusFitnessCalculator::gerar_arquivo_top() {
std::ofstream top;
top.open("top.v");
top << "module top();\n\n";
top << "\tinteger i;\n";
top << "\treg [" << num_inputs - 1 << ":0] in;\n";
top << "\twire [" << num_outputs - 1 << ":0] out;\n\n";
top << "initial begin\n";
top << "\t$monitor(\"";
for (int i = 0; i < num_inputs; i++) {
top << "%b";
}
top << " ";
for (int i = 0; i < num_outputs; i++) {
top << "%b";
}
top << "\", ";
for (int i = num_inputs - 1; i >= 0; i--) {
top << "in[" << i << "], ";
}
for (int i = num_outputs - 1; i >= 1; i--) {
top << "out[" << i << "], ";
}
top << "out);\n";
top << "\tfor (i = 0; i < " << (int) pow(2, num_inputs)
<< "; i = i + 1) begin\n";
top << "\t\t#5 in = i;\n";
top << "\tend\n";
top << "end\n\n";
top << "genetico genetico(\n";
top << "\t.in(in),\n";
top << "\t.out(out)\n";
top << ");\n\n";
top << "endmodule";
}
std::vector<std::vector<std::bitset<8>>>
IcarusFitnessCalculator::parse_output(FILE* simulador) {
std::vector<std::vector<std::bitset<8>>> results;
char entrada[100];
char saida[100];
// Ignorando os x's
fscanf(simulador, "%s", entrada);
fscanf(simulador, "%s", saida);
for (int i = 0; i < (int) pow(2, num_inputs); i++) {
fscanf(simulador, "%s", entrada);
fscanf(simulador, "%s", saida);
results.push_back(std::vector<std::bitset<8>>());
results[i].push_back(std::bitset<8>(saida));
}
return results;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2010, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 <boost/python.hpp>
#include "IECoreGL/IECoreGL.h"
#include "IECoreGL/bindings/RendererBinding.h"
#include "IECoreGL/bindings/BindableBinding.h"
#include "IECoreGL/bindings/ShaderBinding.h"
#include "IECoreGL/bindings/TextureBinding.h"
#include "IECoreGL/bindings/WindowBinding.h"
#include "IECoreGL/bindings/StateBinding.h"
#include "IECoreGL/bindings/RenderableBinding.h"
#include "IECoreGL/bindings/SceneBinding.h"
#include "IECoreGL/bindings/SceneViewerBinding.h"
#include "IECoreGL/bindings/ShaderManagerBinding.h"
#include "IECoreGL/bindings/TextureLoaderBinding.h"
#include "IECoreGL/bindings/GroupBinding.h"
#include "IECoreGL/bindings/FrameBufferBinding.h"
#include "IECoreGL/bindings/ColorTextureBinding.h"
#include "IECoreGL/bindings/DepthTextureBinding.h"
#include "IECoreGL/bindings/CameraBinding.h"
#include "IECoreGL/bindings/OrthographicCameraBinding.h"
#include "IECoreGL/bindings/PerspectiveCameraBinding.h"
#include "IECoreGL/bindings/CameraControllerBinding.h"
#include "IECoreGL/bindings/StateComponentBinding.h"
#include "IECoreGL/bindings/TypedStateComponentBinding.h"
#include "IECoreGL/bindings/NameStateComponentBinding.h"
#include "IECoreGL/bindings/HitRecordBinding.h"
#include "IECoreGL/bindings/ToGLConverterBinding.h"
#include "IECoreGL/bindings/ToGLCameraConverterBinding.h"
#include "IECoreGL/bindings/AlphaTextureBinding.h"
#include "IECoreGL/bindings/LuminanceTextureBinding.h"
#include "IECoreGL/bindings/ToGLTextureConverterBinding.h"
#include "IECoreGL/bindings/PrimitiveBinding.h"
#include "IECoreGL/bindings/PointsPrimitiveBinding.h"
using namespace IECoreGL;
using namespace boost::python;
BOOST_PYTHON_MODULE( _IECoreGL )
{
bindRenderer();
bindBindable();
bindShader();
bindTexture();
bindWindow();
bindState();
bindRenderable();
bindScene();
bindSceneViewer();
bindShaderManager();
bindTextureLoader();
bindGroup();
bindFrameBuffer();
bindColorTexture();
bindDepthTexture();
bindCamera();
bindOrthographicCamera();
bindPerspectiveCamera();
bindCameraController();
bindStateComponent();
bindTypedStateComponents();
bindNameStateComponent();
bindHitRecord();
bindToGLConverter();
bindToGLCameraConverter();
bindAlphaTexture();
bindLuminanceTexture();
bindToGLTextureConverter();
bindPrimitive();
bindPointsPrimitive();
def( "init", &IECoreGL::init );
}
<commit_msg>Adding missing changes which should have been in revision 4552.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2012, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 <boost/python.hpp>
#include "IECoreGL/IECoreGL.h"
#include "IECoreGL/bindings/RendererBinding.h"
#include "IECoreGL/bindings/BindableBinding.h"
#include "IECoreGL/bindings/ShaderBinding.h"
#include "IECoreGL/bindings/TextureBinding.h"
#include "IECoreGL/bindings/WindowBinding.h"
#include "IECoreGL/bindings/StateBinding.h"
#include "IECoreGL/bindings/RenderableBinding.h"
#include "IECoreGL/bindings/SceneBinding.h"
#include "IECoreGL/bindings/SceneViewerBinding.h"
#include "IECoreGL/bindings/ShaderManagerBinding.h"
#include "IECoreGL/bindings/TextureLoaderBinding.h"
#include "IECoreGL/bindings/GroupBinding.h"
#include "IECoreGL/bindings/FrameBufferBinding.h"
#include "IECoreGL/bindings/ColorTextureBinding.h"
#include "IECoreGL/bindings/DepthTextureBinding.h"
#include "IECoreGL/bindings/CameraBinding.h"
#include "IECoreGL/bindings/OrthographicCameraBinding.h"
#include "IECoreGL/bindings/PerspectiveCameraBinding.h"
#include "IECoreGL/bindings/CameraControllerBinding.h"
#include "IECoreGL/bindings/StateComponentBinding.h"
#include "IECoreGL/bindings/TypedStateComponentBinding.h"
#include "IECoreGL/bindings/NameStateComponentBinding.h"
#include "IECoreGL/bindings/HitRecordBinding.h"
#include "IECoreGL/bindings/ToGLConverterBinding.h"
#include "IECoreGL/bindings/ToGLCameraConverterBinding.h"
#include "IECoreGL/bindings/AlphaTextureBinding.h"
#include "IECoreGL/bindings/LuminanceTextureBinding.h"
#include "IECoreGL/bindings/ToGLTextureConverterBinding.h"
#include "IECoreGL/bindings/PrimitiveBinding.h"
#include "IECoreGL/bindings/PointsPrimitiveBinding.h"
#include "IECoreGL/bindings/SelectorBinding.h"
using namespace IECoreGL;
using namespace boost::python;
BOOST_PYTHON_MODULE( _IECoreGL )
{
bindRenderer();
bindBindable();
bindShader();
bindTexture();
bindWindow();
bindState();
bindRenderable();
bindScene();
bindSceneViewer();
bindShaderManager();
bindTextureLoader();
bindGroup();
bindFrameBuffer();
bindColorTexture();
bindDepthTexture();
bindCamera();
bindOrthographicCamera();
bindPerspectiveCamera();
bindCameraController();
bindStateComponent();
bindTypedStateComponents();
bindNameStateComponent();
bindHitRecord();
bindToGLConverter();
bindToGLCameraConverter();
bindAlphaTexture();
bindLuminanceTexture();
bindToGLTextureConverter();
bindPrimitive();
bindPointsPrimitive();
bindSelector();
def( "init", &IECoreGL::init );
}
<|endoftext|> |
<commit_before>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>
namespace orm
{
Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)
{
int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);
#if ORM_VERBOSITY & ORM_ERROR
if (result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
};
Sqlite3Query::Sqlite3Query(Bdd* bdd,std::string&& query) : Query(bdd,query), statement(0)
{
int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);
#if ORM_VERBOSITY & ORM_ERROR
if (result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
};
Sqlite3Query::~Sqlite3Query()
{
if(statement)
{
int result = sqlite3_finalize(statement);
#if ORM_VERBOSITY & ORM_ERROR
if(result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
}
};
int Sqlite3Query::count()const
{
return sqlite3_data_count(statement);
};
bool Sqlite3Query::get(bool& value,const int& column)const
{
value = (bool)sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(int& value,const int& column)const
{
value = sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(unsigned int& value,const int& column)const
{
value = (unsigned int)sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(long long int& value,const int& column)const
{
value = (long long int)sqlite3_column_int64(statement,column);
return true;
};
bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
{
value = (unsigned long long int)sqlite3_column_int64(statement,column);
return true;
};
bool Sqlite3Query::get(float& value,const int& column)const
{
value = (float)sqlite3_column_double(statement,column);
return true;
};
bool Sqlite3Query::get(long double& value,const int& column)const
{
value = (long double)sqlite3_column_double(statement,column);
return true;
};
bool Sqlite3Query::get(std::string& value,const int& column)const
{
const unsigned char* res = sqlite3_column_text(statement,column);
if (res)
value = (const char*)res;
else
value = "";
return true;
};
bool Sqlite3Query::next()
{
int result = sqlite3_step(statement);
if(result == SQLITE_ROW)
return true;
ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
///\ todo sqlite3_errstr(result)<<std::endl;
return false;
}
bool Sqlite3Query::set(const bool& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const float& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long double& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_text(statement,(int)column,value.c_str(),value.size()+1,SQLITE_TRANSIENT)== SQLITE_OK);
};
bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
};
void Sqlite3Query::executeQuery()
{
};
};
<commit_msg>fix bug with sqlite string<commit_after>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>
namespace orm
{
Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)
{
int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);
#if ORM_VERBOSITY & ORM_ERROR
if (result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
};
Sqlite3Query::Sqlite3Query(Bdd* bdd,std::string&& query) : Query(bdd,query), statement(0)
{
int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);
#if ORM_VERBOSITY & ORM_ERROR
if (result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
};
Sqlite3Query::~Sqlite3Query()
{
if(statement)
{
int result = sqlite3_finalize(statement);
#if ORM_VERBOSITY & ORM_ERROR
if(result != SQLITE_OK)
{
ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
/// \todo <<sqlite3_errstr(result)<<std::endl;
}
#endif
}
};
int Sqlite3Query::count()const
{
return sqlite3_data_count(statement);
};
bool Sqlite3Query::get(bool& value,const int& column)const
{
value = (bool)sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(int& value,const int& column)const
{
value = sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(unsigned int& value,const int& column)const
{
value = (unsigned int)sqlite3_column_int(statement,column);
return true;
};
bool Sqlite3Query::get(long long int& value,const int& column)const
{
value = (long long int)sqlite3_column_int64(statement,column);
return true;
};
bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
{
value = (unsigned long long int)sqlite3_column_int64(statement,column);
return true;
};
bool Sqlite3Query::get(float& value,const int& column)const
{
value = (float)sqlite3_column_double(statement,column);
return true;
};
bool Sqlite3Query::get(long double& value,const int& column)const
{
value = (long double)sqlite3_column_double(statement,column);
return true;
};
bool Sqlite3Query::get(std::string& value,const int& column)const
{
const unsigned char* res = sqlite3_column_text(statement,column);
if (res)
value = (const char*)res;
else
value = "";
return true;
};
bool Sqlite3Query::next()
{
int result = sqlite3_step(statement);
if(result == SQLITE_ROW)
return true;
ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
///\ todo sqlite3_errstr(result)<<std::endl;
return false;
}
bool Sqlite3Query::set(const bool& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const float& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const long double& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
};
bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_text(statement,(int)column,value.c_str(),-1,SQLITE_TRANSIENT)== SQLITE_OK);
};
bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
{
if(not prepared)
return false;
return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
};
void Sqlite3Query::executeQuery()
{
};
};
<|endoftext|> |
<commit_before>#include "BathRoomMirrorHeatingCtrl.h"
#include <HardwareSerial.h>
#include <stdio.h>
#include "C:/eclipseArduino/sloeber/arduinoPlugin/packages/arduino/hardware/avr/1.6.18/variants/standard/pins_arduino.h"
#include "D:/HomeAutomation/ArduinoLibs/DHT/DHT.h"
#include "D:/HomeAutomation/ArduinoLibs/Timer/Timer.h"
Timer resetAnalogPinTimer;
Timer offTimer;
Timer humiditySensorReadTimer;
DHT dhtSensor(DHT_PIN, DHT22);
volatile DhtSensorData sensorData;
volatile boolean isHeatingAndLightDesired;
volatile int analogSensorReading;
bool debug = true;
bool ignoreHumiditySensor = true;
//The setup function is called once at startup of the sketch
void setup() {
Serial.begin(115200);
Serial.println("Setup starts here...");
isHeatingAndLightDesired = false;
sensorData.temperature = 25;
sensorData.humidity = 55;
pinMode(INPUT_PIN_IR_TRIGGER, INPUT);
analogReadInputPin();
resetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);
pinMode(LIGHTS_PIN, OUTPUT);
setRelay(LIGHTS_PIN, OFF);
pinMode(HEAT_PIN, OUTPUT);
setRelay(HEAT_PIN, OFF);
dhtSensor.begin();
readDhtInfo();
humiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);
Serial.println("Setup ends here...");
}
// The loop function is called in an endless loop
void loop() {
offTimer.update();
humiditySensorReadTimer.update();
resetAnalogPinTimer.update();
decisionMaker();
analogReadInputPin();
}
void resetReadingAndUpdateDecision() {
if(analogSensorReading > ANALOG_TRESHOLD) {
isHeatingAndLightDesired = !isHeatingAndLightDesired;
}
Serial.print("AnalogSensor last value:");
Serial.println(analogSensorReading);
analogSensorReading = 0;
Serial.print("AnalogSensor new value:");
Serial.println(analogSensorReading);
}
void offTimerExpired() {
isHeatingAndLightDesired = false;;
}
void reattachInterrupt() {
if(debug) {
Serial.println("ReattachInterrupt triggered");
}
attachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);
resetAnalogPinTimer.stop(millis());
}
void readDhtInfo() {
float humidity = dhtSensor.readHumidity();
float temperature = dhtSensor.readTemperature();
// simple error check. Do not update data if sensor reading is wrong.
if(humidity > 0 && temperature > -30) {
sensorData.humidity = humidity;
sensorData.temperature = temperature;
ignoreHumiditySensor = false;
} else {
ignoreHumiditySensor = true;
if(debug) {
Serial.println("DHT wrong data received...");
Serial.print("Humidity:"); Serial.println(humidity);
Serial.print("Temperature:"); Serial.println(temperature);
}
}
if(debug) {
// sensorData.humidity = random(100);
// sensorData.temperature = random(30);
Serial.print("Humidity:");Serial.println(sensorData.humidity);
Serial.print("Temperature:");Serial.println(sensorData.temperature);
return;
}
}
void decisionMaker() {
if(isHeatingAndLightDesired) {
if(!lightIsOn()) {
setRelay(LIGHTS_PIN, ON);
}
if((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {
setRelay(HEAT_PIN, ON);
}
} else {
if(lightIsOn()) {
setRelay(LIGHTS_PIN, OFF);
}
if(heatingIsOn()) {
setRelay(HEAT_PIN, OFF);
}
}
}
void setRelay(byte pin, byte state) {
digitalWrite(pin, state);
if (debug) {
Serial.print("Pin ");Serial.print(pin);Serial.print(" state changed to ");Serial.println(state);
}
}
boolean lightIsOn() {
return digitalRead(LIGHTS_PIN);
}
boolean heatingIsOn() {
return digitalRead(HEAT_PIN);
}
void analogReadInputPin() {
int sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);
if(sensorReading > 100 && sensorReading > analogSensorReading) {
analogSensorReading = sensorReading;
}
}
<commit_msg>Added off-timer 15 mins<commit_after>#include "BathRoomMirrorHeatingCtrl.h"
#include <HardwareSerial.h>
#include <stdio.h>
#include "C:/eclipseArduino/sloeber/arduinoPlugin/packages/arduino/hardware/avr/1.6.18/variants/standard/pins_arduino.h"
#include "D:/HomeAutomation/ArduinoLibs/DHT/DHT.h"
#include "D:/HomeAutomation/ArduinoLibs/Timer/Timer.h"
Timer resetAnalogPinTimer;
Timer offTimer;
Timer humiditySensorReadTimer;
DHT dhtSensor(DHT_PIN, DHT22);
volatile DhtSensorData sensorData;
volatile boolean isHeatingAndLightDesired;
volatile int analogSensorReading;
bool debug = true;
bool ignoreHumiditySensor = true;
//The setup function is called once at startup of the sketch
void setup() {
Serial.begin(115200);
Serial.println("Setup starts here...");
isHeatingAndLightDesired = false;
sensorData.temperature = 25;
sensorData.humidity = 55;
pinMode(INPUT_PIN_IR_TRIGGER, INPUT);
analogReadInputPin();
resetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);
pinMode(LIGHTS_PIN, OUTPUT);
setRelay(LIGHTS_PIN, OFF);
pinMode(HEAT_PIN, OUTPUT);
setRelay(HEAT_PIN, OFF);
dhtSensor.begin();
readDhtInfo();
humiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);
Serial.println("Setup ends here...");
}
// The loop function is called in an endless loop
void loop() {
offTimer.update();
humiditySensorReadTimer.update();
resetAnalogPinTimer.update();
decisionMaker();
analogReadInputPin();
}
void resetReadingAndUpdateDecision() {
if(analogSensorReading > ANALOG_TRESHOLD) {
isHeatingAndLightDesired = !isHeatingAndLightDesired;
if(isHeatingAndLightDesired) {
offTimer.after(OFF_TIME_TIMER_OFFSET, offTimerExpired);
} else {
offTimer.stop(0);
}
}
if(debug) {
Serial.print("AnalogSensor last value:");
Serial.println(analogSensorReading);
}
analogSensorReading = 0;
}
void offTimerExpired() {
isHeatingAndLightDesired = false;;
}
void reattachInterrupt() {
if(debug) {
Serial.println("ReattachInterrupt triggered");
}
attachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);
resetAnalogPinTimer.stop(millis());
}
void readDhtInfo() {
float humidity = dhtSensor.readHumidity();
float temperature = dhtSensor.readTemperature();
// simple error check. Do not update data if sensor reading is wrong.
if(humidity > 0 && temperature > -30) {
sensorData.humidity = humidity;
sensorData.temperature = temperature;
ignoreHumiditySensor = false;
} else {
ignoreHumiditySensor = true;
if(debug) {
Serial.println("DHT wrong data received...");
Serial.print("Humidity:"); Serial.println(humidity);
Serial.print("Temperature:"); Serial.println(temperature);
}
}
if(debug) {
// sensorData.humidity = random(100);
// sensorData.temperature = random(30);
Serial.print("Humidity:");Serial.println(sensorData.humidity);
Serial.print("Temperature:");Serial.println(sensorData.temperature);
return;
}
}
void decisionMaker() {
if(isHeatingAndLightDesired) {
if(!lightIsOn()) {
setRelay(LIGHTS_PIN, ON);
}
if((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {
setRelay(HEAT_PIN, ON);
}
} else {
if(lightIsOn()) {
setRelay(LIGHTS_PIN, OFF);
}
if(heatingIsOn()) {
setRelay(HEAT_PIN, OFF);
}
}
}
void setRelay(byte pin, byte state) {
digitalWrite(pin, state);
if (debug) {
Serial.print("Pin ");Serial.print(pin);Serial.print(" state changed to ");Serial.println(state);
}
}
boolean lightIsOn() {
return digitalRead(LIGHTS_PIN);
}
boolean heatingIsOn() {
return digitalRead(HEAT_PIN);
}
void analogReadInputPin() {
int sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);
if(sensorReading > 100 && sensorReading > analogSensorReading) {
analogSensorReading = sensorReading;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
Copyright (c) 2016 Yuji Toki(tokineco)
- MIT license
****************************************************************************/
#pragma execution_character_set("utf-8")
#include "Converter.h"
USING_NS_CC;
// "0xARGB"の文字列からアルファ付きのColor4Bを返す
cocos2d::Color4B Converter::fromARGB(std::string code) {
// 0xARGBコードが見つかったら
if (code.find("0x") == 0 && code.length() == 10) {
try {
// A
int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);
// R
int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);
// G
int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);
// B
int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);
return cocos2d::Color4B(r, g, b, a);
} catch (...) {
// Error
CCLOG("illegal color code : %s", code.c_str());
}
} else {
// Error
CCLOG("not supeert format : %s", code.c_str());
}
return cocos2d::Color4B::BLACK;
}
// 文字列の "true" or "false" を bool型の true or false に変換する
// "1"もtrueとして扱う
bool Converter::stringToBool(std::string strBool, bool def) {
if (strBool == "true" || strBool == "1") {
return true;
} else if (strBool == "false" || strBool == "0") {
return false;
}
return def;
}
bool Converter::stringToBool(std::string strBool) {
return stringToBool(strBool, false);
}
// 文字列のSplit
std::vector<std::string> Converter::split(std::string str, char delim) {
std::vector<std::string> result;
std::string::size_type current = 0, delimIdx;
while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {
result.push_back(std::string(str, current, delimIdx - current));
current = delimIdx + 1;
}
result.push_back(std::string(str, current, str.size() - current));
return result;
}
// 文字列の全置換
std::string Converter::replaceAll(std::string str, std::string before, std::string after) {
std::string::size_type pos(str.find(before));
while (pos != std::string::npos) {
str.replace(pos, before.length(), after);
pos = str.find(before, pos + after.length());
}
return str;
}
// 文字列の先頭と末尾にあるホワイトスペースを取り除く
std::string Converter::trim(const std::string& str, const char* trimChars /* = " \t\v\r\n" */) {
std::string result;
std::string::size_type left = str.find_first_not_of(trimChars);
if (left != std::string::npos) {
std::string::size_type right = str.find_last_not_of(trimChars);
result = str.substr(left, right - left + 1);
}
return result;
}
<commit_msg>Fixed error message typo<commit_after>/****************************************************************************
Copyright (c) 2016 Yuji Toki(tokineco)
- MIT license
****************************************************************************/
#pragma execution_character_set("utf-8")
#include "Converter.h"
USING_NS_CC;
// "0xARGB"の文字列からアルファ付きのColor4Bを返す
cocos2d::Color4B Converter::fromARGB(std::string code) {
// 0xARGBコードが見つかったら
if (code.find("0x") == 0 && code.length() == 10) {
try {
// A
int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);
// R
int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);
// G
int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);
// B
int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);
return cocos2d::Color4B(r, g, b, a);
} catch (...) {
// Error
CCLOG("illegal color code : %s", code.c_str());
}
} else {
// Error
CCLOG("not support format : %s", code.c_str());
}
return cocos2d::Color4B::BLACK;
}
// 文字列の "true" or "false" を bool型の true or false に変換する
// "1"もtrueとして扱う
bool Converter::stringToBool(std::string strBool, bool def) {
if (strBool == "true" || strBool == "1") {
return true;
} else if (strBool == "false" || strBool == "0") {
return false;
}
return def;
}
bool Converter::stringToBool(std::string strBool) {
return stringToBool(strBool, false);
}
// 文字列のSplit
std::vector<std::string> Converter::split(std::string str, char delim) {
std::vector<std::string> result;
std::string::size_type current = 0, delimIdx;
while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {
result.push_back(std::string(str, current, delimIdx - current));
current = delimIdx + 1;
}
result.push_back(std::string(str, current, str.size() - current));
return result;
}
// 文字列の全置換
std::string Converter::replaceAll(std::string str, std::string before, std::string after) {
std::string::size_type pos(str.find(before));
while (pos != std::string::npos) {
str.replace(pos, before.length(), after);
pos = str.find(before, pos + after.length());
}
return str;
}
// 文字列の先頭と末尾にあるホワイトスペースを取り除く
std::string Converter::trim(const std::string& str, const char* trimChars /* = " \t\v\r\n" */) {
std::string result;
std::string::size_type left = str.find_first_not_of(trimChars);
if (left != std::string::npos) {
std::string::size_type right = str.find_last_not_of(trimChars);
result = str.substr(left, right - left + 1);
}
return result;
}
<|endoftext|> |
<commit_before>void Draw(string s_Exo, string s_Run)
{
gStyle->SetOptStat(0);
string s_TFile_Cyclus = s_Exo + "/" + s_Run + "/cyclus.root";
string s_TFile_Class = s_Exo + "/" + s_Run + "/Scenario.root";
cout<<s_TFile_Cyclus<<endl;
cout<<s_TFile_Class<<endl;
TFile *FCy = new TFile(s_TFile_Cyclus.c_str());
TFile *FCl = new TFile(s_TFile_Class.c_str());
TTree *TCy = (TTree *) FCy->Get("TT");
TTree *TCl = (TTree *) FCl->Get("TreeScenario");
TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);
TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);
// ################################################################################
// Legend
// ################################################################################
TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);
L01->AddEntry(TCy, "Cyclus", "L");
L01->AddEntry(TCl, "CLASS", "L");
// ################################################################################
// ENERGY
// ################################################################################
TCanvas *C00 = new TCanvas("C00","C00",700,500);
TCy->Draw("P:T","","L");
TCl->Draw("P:T","","Lsame");
TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Power (W)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
// ################################################################################
// Plutonium
// ################################################################################
TCanvas *C0 = new TCanvas("C0","Pu",1400,900);
C0->Divide(2,2,0.01,0.01);
C0->cd(1);
TCy->Draw("B93/1000:T","","L");
TCl->Draw("B93:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(2);
TCy->Draw("B3/1000:T","","L");
TCl->Draw("B3:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(3);
TCy->Draw("B98/1000:T","","L");
TCl->Draw("B98:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(4);
TCy->Draw("B8/1000:T","","L");
TCl->Draw("B8:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
// ################################################################################
// MA
// ################################################################################
TCanvas *C1 = new TCanvas("C1","MA",1400,900);
C1->Divide(2,2,0.01,0.01);
C1->cd(1);
TCy->Draw("B96/1000:T","","L");
TCl->Draw("B96:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(2);
TCy->Draw("B94/1000:T","","L");
TCl->Draw("B94:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(3);
TCy->Draw("B92/1000:T","","L");
TCl->Draw("B92:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(4);
TCy->Draw("B95/1000:T","","L");
TCl->Draw("B95:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
}
<commit_msg>Update general Draw script<commit_after>void Draw(string s_Exo, string s_Run)
{
gStyle->SetOptStat(0);
string s_TFile_Cyclus = s_Exo + "/" + s_Run + "/cyclus.root";
string s_TFile_Class = s_Exo + "/" + s_Run + "/Scenario.root";
cout<<s_TFile_Cyclus<<endl;
cout<<s_TFile_Class<<endl;
TFile *FCy = new TFile(s_TFile_Cyclus.c_str());
TFile *FCl = new TFile(s_TFile_Class.c_str());
TTree *TCy = (TTree *) FCy->Get("TT");
TTree *TCl = (TTree *) FCl->Get("TreeScenario");
TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);
TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);
// ################################################################################
// Legend
// ################################################################################
TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);
L01->AddEntry(TCy, "Cyclus", "L");
L01->AddEntry(TCl, "CLASS", "L");
// ################################################################################
// ENERGY
// ################################################################################
TCanvas *C00 = new TCanvas("C00","C00",700,500);
TCy->Draw("P:T","","L");
TCl->Draw("P:T","","Lsame");
TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Power (W)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
// ################################################################################
// Plutonium
// ################################################################################
TCanvas *C0 = new TCanvas("C0","Pu",1500,900);
C0->Divide(2,2,0.01,0.01);
C0->cd(1);
TCy->Draw("B93/1000:T","","L");
TCl->Draw("B93:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(2);
TCy->Draw("B3/1000:T","","L");
TCl->Draw("B3:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(3);
TCy->Draw("B98/1000:T","","L");
TCl->Draw("B98:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C0->cd(4);
TCy->Draw("B8/1000:T","","L");
TCl->Draw("B8:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
// ################################################################################
// MA
// ################################################################################
TCanvas *C1 = new TCanvas("C1","MA",1500,900);
C1->Divide(2,2,0.01,0.01);
C1->cd(1);
TCy->Draw("B96/1000:T","","L");
TCl->Draw("B96:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(2);
TCy->Draw("B94/1000:T","","L");
TCl->Draw("B94:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(3);
TCy->Draw("B92/1000:T","","L");
TCl->Draw("B92:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
C1->cd(4);
TCy->Draw("B95/1000:T","","L");
TCl->Draw("B95:T","","Lsame");
tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm");
tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05);
tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05);
gPad->Update();
L01->Draw();
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationToolStorage.h"
//Microservices
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
const std::string mitk::NavigationToolStorage::US_INTERFACE_NAME = "org.mitk.services.NavigationToolStorage"; // Name of the interface
const std::string mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + ".sourceID";
const std::string mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + ".name";
mitk::NavigationToolStorage::NavigationToolStorage()
: m_ToolCollection(std::vector<mitk::NavigationTool::Pointer>()),
m_DataStorage(NULL),
m_storageLocked(false)
{
this->SetName("ToolStorage (no name given)");
}
mitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)
: m_storageLocked(false)
{
m_ToolCollection = std::vector<mitk::NavigationTool::Pointer>();
this->m_DataStorage = ds;
this->SetName("Tool Storage (no name given)");
}
void mitk::NavigationToolStorage::SetName(std::string n)
{
m_Name = n;
m_props[ US_PROPKEY_STORAGE_NAME ] = m_Name;
}
std::string mitk::NavigationToolStorage::GetName() const
{
return m_Name;
}
void mitk::NavigationToolStorage::UpdateMicroservice()
{
if (m_ServiceRegistration) {m_ServiceRegistration.SetProperties(m_props);}
}
mitk::NavigationToolStorage::~NavigationToolStorage()
{
if (m_DataStorage.IsNotNull()) //remove all nodes from the data storage
{
for(std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)
m_DataStorage->Remove((*it)->GetDataNode());
}
}
void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){
if ( sourceID.empty() ) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice().";
// Get Context
us::ModuleContext* context = us::GetModuleContext();
// Define ServiceProps
m_props[ US_PROPKEY_SOURCE_ID ] = sourceID;
m_ServiceRegistration = context->RegisterService(this, m_props);
}
void mitk::NavigationToolStorage::UnRegisterMicroservice(){
if ( ! m_ServiceRegistration )
{
MITK_WARN("NavigationToolStorage")
<< "Cannot unregister microservice as it wasn't registered before.";
return;
}
m_ServiceRegistration.Unregister();
m_ServiceRegistration = 0;
}
bool mitk::NavigationToolStorage::DeleteTool(int number)
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
else if ((unsigned int)number > m_ToolCollection.size())
{
MITK_WARN << "Tool no " << number << "doesn't exist, can't delete it!";
return false;
}
std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin() + number;
if(m_DataStorage.IsNotNull())
m_DataStorage->Remove((*it)->GetDataNode());
m_ToolCollection.erase(it);
return true;
}
bool mitk::NavigationToolStorage::DeleteAllTools()
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
while(m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;
return true;
}
bool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
else if (GetTool(tool->GetIdentifier()).IsNotNull())
{
MITK_WARN << "Tool ID already exists in storage, can't add!";
return false;
}
else
{
m_ToolCollection.push_back(tool);
if(m_DataStorage.IsNotNull())
{
if (!m_DataStorage->Exists(tool->GetDataNode()))
m_DataStorage->Add(tool->GetDataNode());
}
return true;
}
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)
{
return m_ToolCollection.at(number);
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)
{
for (int i=0; i<GetToolCount(); i++) if ((GetTool(i)->GetIdentifier())==identifier) return GetTool(i);
return NULL;
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)
{
for (int i=0; i<GetToolCount(); i++) if ((GetTool(i)->GetToolName())==name) return GetTool(i);
return NULL;
}
int mitk::NavigationToolStorage::GetToolCount()
{
return m_ToolCollection.size();
}
bool mitk::NavigationToolStorage::isEmpty()
{
return m_ToolCollection.empty();
}
void mitk::NavigationToolStorage::LockStorage()
{
m_storageLocked = true;
}
void mitk::NavigationToolStorage::UnLockStorage()
{
m_storageLocked = false;
}
bool mitk::NavigationToolStorage::isLocked()
{
return m_storageLocked;
}
bool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)
{
if (this->GetTool(identifier1).IsNull())
{
MITK_WARN << "Identifier does not exist, cannot assign new number";
return false;
}
if ((number2 >= m_ToolCollection.size()) || (number2 < 0))
{
MITK_WARN << "Invalid number, cannot assign new number";
return false;
}
mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);
int number1 = -1;
for(int i = 0; i<m_ToolCollection.size(); i++)
{
if (m_ToolCollection.at(i)->GetIdentifier() == identifier1) {number1=i;}
}
m_ToolCollection[number2] = m_ToolCollection.at(number1);
m_ToolCollection[number1] = tool2;
MITK_DEBUG << "Swapped tool " << number2 << " with tool " << number1;
return true;
}
<commit_msg>Code format for better reading. White space changes only.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationToolStorage.h"
//Microservices
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
const std::string mitk::NavigationToolStorage::US_INTERFACE_NAME = "org.mitk.services.NavigationToolStorage"; // Name of the interface
const std::string mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + ".sourceID";
const std::string mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + ".name";
mitk::NavigationToolStorage::NavigationToolStorage()
: m_ToolCollection(std::vector<mitk::NavigationTool::Pointer>()),
m_DataStorage(NULL),
m_storageLocked(false)
{
this->SetName("ToolStorage (no name given)");
}
mitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)
: m_storageLocked(false)
{
m_ToolCollection = std::vector<mitk::NavigationTool::Pointer>();
this->m_DataStorage = ds;
this->SetName("Tool Storage (no name given)");
}
void mitk::NavigationToolStorage::SetName(std::string n)
{
m_Name = n;
m_props[US_PROPKEY_STORAGE_NAME] = m_Name;
}
std::string mitk::NavigationToolStorage::GetName() const
{
return m_Name;
}
void mitk::NavigationToolStorage::UpdateMicroservice()
{
if (m_ServiceRegistration) { m_ServiceRegistration.SetProperties(m_props); }
}
mitk::NavigationToolStorage::~NavigationToolStorage()
{
if (m_DataStorage.IsNotNull()) //remove all nodes from the data storage
{
for (std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)
m_DataStorage->Remove((*it)->GetDataNode());
}
}
void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){
if (sourceID.empty()) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice().";
// Get Context
us::ModuleContext* context = us::GetModuleContext();
// Define ServiceProps
m_props[US_PROPKEY_SOURCE_ID] = sourceID;
m_ServiceRegistration = context->RegisterService(this, m_props);
}
void mitk::NavigationToolStorage::UnRegisterMicroservice(){
if (!m_ServiceRegistration)
{
MITK_WARN("NavigationToolStorage")
<< "Cannot unregister microservice as it wasn't registered before.";
return;
}
m_ServiceRegistration.Unregister();
m_ServiceRegistration = 0;
}
bool mitk::NavigationToolStorage::DeleteTool(int number)
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
else if ((unsigned int)number > m_ToolCollection.size())
{
MITK_WARN << "Tool no " << number << "doesn't exist, can't delete it!";
return false;
}
std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin() + number;
if (m_DataStorage.IsNotNull())
m_DataStorage->Remove((*it)->GetDataNode());
m_ToolCollection.erase(it);
return true;
}
bool mitk::NavigationToolStorage::DeleteAllTools()
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
while (m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;
return true;
}
bool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)
{
if (m_storageLocked)
{
MITK_WARN << "Storage is locked, cannot modify it!";
return false;
}
else if (GetTool(tool->GetIdentifier()).IsNotNull())
{
MITK_WARN << "Tool ID already exists in storage, can't add!";
return false;
}
else
{
m_ToolCollection.push_back(tool);
if (m_DataStorage.IsNotNull())
{
if (!m_DataStorage->Exists(tool->GetDataNode()))
m_DataStorage->Add(tool->GetDataNode());
}
return true;
}
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)
{
return m_ToolCollection.at(number);
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)
{
for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetIdentifier()) == identifier) return GetTool(i);
return NULL;
}
mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)
{
for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetToolName()) == name) return GetTool(i);
return NULL;
}
int mitk::NavigationToolStorage::GetToolCount()
{
return m_ToolCollection.size();
}
bool mitk::NavigationToolStorage::isEmpty()
{
return m_ToolCollection.empty();
}
void mitk::NavigationToolStorage::LockStorage()
{
m_storageLocked = true;
}
void mitk::NavigationToolStorage::UnLockStorage()
{
m_storageLocked = false;
}
bool mitk::NavigationToolStorage::isLocked()
{
return m_storageLocked;
}
bool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)
{
if (this->GetTool(identifier1).IsNull())
{
MITK_WARN << "Identifier does not exist, cannot assign new number";
return false;
}
if ((number2 >= m_ToolCollection.size()) || (number2 < 0))
{
MITK_WARN << "Invalid number, cannot assign new number";
return false;
}
mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);
int number1 = -1;
for (int i = 0; i < m_ToolCollection.size(); i++)
{
if (m_ToolCollection.at(i)->GetIdentifier() == identifier1) { number1 = i; }
}
m_ToolCollection[number2] = m_ToolCollection.at(number1);
m_ToolCollection[number1] = tool2;
MITK_DEBUG << "Swapped tool " << number2 << " with tool " << number1;
return true;
}<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
//Poco headers
#include "Poco/Zip/Decompress.h"
#include "Poco/Path.h"
#include "Poco/File.h"
#include "mitkNavigationToolStorageDeserializer.h"
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include "mitkNavigationToolReader.h"
//POCO
#include <Poco/Exception.h>
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
mitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)
{
m_DataStorage = dataStorage;
//create temp directory for this reader
m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory("NavigationToolStorageDeserializerTmp_XXXXXX",mitk::IOUtil::GetTempPath());
}
mitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()
{
//remove temp directory
Poco::File myFile(m_tempDirectory);
try
{
if (myFile.exists()) myFile.remove();
}
catch(...)
{
MITK_ERROR << "Can't remove temp directory " << m_tempDirectory << "!";
}
}
mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)
{
//decomress zip file into temporary directory
decomressFiles(filename,m_tempDirectory);
//now read all files and convert them to navigation tools
mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);
bool cont = true;
int i;
for (i=0; cont==true; i++)
{
std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();
mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);
if (readTool.IsNull()) cont = false;
else returnValue->AddTool(readTool);
//delete file
std::remove(fileName.c_str());
}
if(i==1)
{
//throw an exception here in case of not finding any tool
m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?";
mitkThrowException(mitk::IGTException)<<"Error: did not find any tool. \n Is this a tool storage file?";
}
return returnValue;
}
std::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)
{
std::string s;
std::stringstream out;
out << i;
s = out.str();
return s;
}
void mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)
{
std::ifstream file( filename.c_str(), std::ios::binary );
if (!file.good())
{
m_ErrorMessage = "Cannot open '" + filename + "' for reading";
mitkThrowException(mitk::IGTException)<<"Cannot open"+filename+" for reading";
}
try
{
Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );
unzipper.decompressAllFiles();
file.close();
}
catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later!
{
m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)";
MITK_ERROR << m_ErrorMessage;
mitkThrowException(mitk::IGTException) << m_ErrorMessage;
}
}
<commit_msg>Remove logging of error message<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
//Poco headers
#include "Poco/Zip/Decompress.h"
#include "Poco/Path.h"
#include "Poco/File.h"
#include "mitkNavigationToolStorageDeserializer.h"
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include "mitkNavigationToolReader.h"
//POCO
#include <Poco/Exception.h>
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
mitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)
{
m_DataStorage = dataStorage;
//create temp directory for this reader
m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory("NavigationToolStorageDeserializerTmp_XXXXXX",mitk::IOUtil::GetTempPath());
}
mitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()
{
//remove temp directory
Poco::File myFile(m_tempDirectory);
try
{
if (myFile.exists()) myFile.remove();
}
catch(...)
{
MITK_ERROR << "Can't remove temp directory " << m_tempDirectory << "!";
}
}
mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)
{
//decomress zip file into temporary directory
decomressFiles(filename,m_tempDirectory);
//now read all files and convert them to navigation tools
mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);
bool cont = true;
int i;
for (i=0; cont==true; i++)
{
std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();
mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);
if (readTool.IsNull()) cont = false;
else returnValue->AddTool(readTool);
//delete file
std::remove(fileName.c_str());
}
if(i==1)
{
//throw an exception here in case of not finding any tool
m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?";
mitkThrowException(mitk::IGTException)<<"Error: did not find any tool. \n Is this a tool storage file?";
}
return returnValue;
}
std::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)
{
std::string s;
std::stringstream out;
out << i;
s = out.str();
return s;
}
void mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)
{
std::ifstream file( filename.c_str(), std::ios::binary );
if (!file.good())
{
m_ErrorMessage = "Cannot open '" + filename + "' for reading";
mitkThrowException(mitk::IGTException)<<"Cannot open"+filename+" for reading";
}
try
{
Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );
unzipper.decompressAllFiles();
file.close();
}
catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later!
{
m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)";
mitkThrowException(mitk::IGTException) << m_ErrorMessage;
}
}
<|endoftext|> |
<commit_before>/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 "D3MFImporter.h"
#include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h"
#include "StringUtils.h"
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>
#include <assimp/ai_assert.h>
#include "D3MFOpcPackage.h"
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
namespace Assimp {
namespace D3MF {
namespace XmlTag {
const std::string model = "model";
const std::string metadata = "metadata";
const std::string resources = "resources";
const std::string object = "object";
const std::string mesh = "mesh";
const std::string vertices = "vertices";
const std::string vertex = "vertex";
const std::string triangles = "triangles";
const std::string triangle = "triangle";
const std::string x = "x";
const std::string y = "y";
const std::string z = "z";
const std::string v1 = "v1";
const std::string v2 = "v2";
const std::string v3 = "v3";
const std::string id = "id";
const std::string name = "name";
const std::string type = "type";
const std::string build = "build";
const std::string item = "item";
const std::string objectid = "objectid";
const std::string transform = "transform";
}
class XmlSerializer
{
public:
XmlSerializer(XmlReader* xmlReader)
: xmlReader(xmlReader)
{
}
void ImportXml(aiScene* scene)
{
scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
scene->mRootNode = new aiNode();
std::vector<aiNode*> children;
while(ReadToEndElement(D3MF::XmlTag::model))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::object)
{
children.push_back(ReadObject(scene));
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::build)
{
}
}
if(scene->mRootNode->mName.length == 0)
scene->mRootNode->mName.Set("3MF");
scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
scene->mMeshes = new aiMesh*[scene->mNumMeshes]();
std::copy(meshes.begin(), meshes.end(), scene->mMeshes);
scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();
std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);
}
private:
aiNode* ReadObject(aiScene* scene)
{
ScopeGuard<aiNode> node(new aiNode());
std::vector<unsigned long> meshIds;
int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));
std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));
std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));
node->mParent = scene->mRootNode;
node->mName.Set(name);
unsigned long meshIdx = meshes.size();
while(ReadToEndElement(D3MF::XmlTag::object))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
{
auto mesh = ReadMesh();
mesh->mName.Set(name);
meshes.push_back(mesh);
meshIds.push_back(meshIdx);
meshIdx++;
}
}
node->mNumMeshes = static_cast<unsigned int>(meshIds.size());
node->mMeshes = new unsigned int[node->mNumMeshes];
std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);
return node.dismiss();
}
aiMesh* ReadMesh()
{
aiMesh* mesh = new aiMesh();
while(ReadToEndElement(D3MF::XmlTag::mesh))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
{
ImportVertices(mesh);
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)
{
ImportTriangles(mesh);
}
}
return mesh;
}
void ImportVertices(aiMesh* mesh)
{
std::vector<aiVector3D> vertices;
while(ReadToEndElement(D3MF::XmlTag::vertices))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
{
vertices.push_back(ReadVertex());
}
}
mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
std::copy(vertices.begin(), vertices.end(), mesh->mVertices);
}
aiVector3D ReadVertex()
{
aiVector3D vertex;
vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
vertex.z = ai_strtof>(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
return vertex;
}
void ImportTriangles(aiMesh* mesh)
{
std::vector<aiFace> faces;
while(ReadToEndElement(D3MF::XmlTag::triangles))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)
{
faces.push_back(ReadTriangle());
}
}
mesh->mNumFaces = static_cast<unsigned int>(faces.size());
mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
std::copy(faces.begin(), faces.end(), mesh->mFaces);
}
aiFace ReadTriangle()
{
aiFace face;
face.mNumIndices = 3;
face.mIndices = new unsigned int[face.mNumIndices];
face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));
return face;
}
private:
bool ReadToStartElement(const std::string& startTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)
{
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&
xmlReader->getNodeName() == startTag)
{
return false;
}
}
//DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
bool ReadToEndElement(const std::string& closeTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END
&& xmlReader->getNodeName() == closeTag)
{
return false;
}
}
DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
private:
std::vector<aiMesh*> meshes;
XmlReader* xmlReader;
};
} //namespace D3MF
static const aiImporterDesc desc = {
"3mf Importer",
"",
"",
"http://3mf.io/",
aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
0,
0,
0,
0,
"3mf"
};
D3MFImporter::D3MFImporter()
{
}
D3MFImporter::~D3MFImporter()
{
}
bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{
const std::string extension = GetExtension(pFile);
if(extension == "3mf")
{
return true;
}
else if(!extension.length() || checkSig)
{
if(!pIOHandler)
return true;
}
return false;
}
void D3MFImporter::SetupProperties(const Importer *pImp)
{
}
const aiImporterDesc *D3MFImporter::GetInfo() const
{
return &desc;
}
void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{
D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));
D3MF::XmlSerializer xmlSerializer(xmlReader.get());
xmlSerializer.ImportXml(pScene);
}
}
#endif // ASSIMP_BUILD_NO_3MF_IMPORTER
<commit_msg>Fixed type in the assimp codebase (this is already fixed in more recent releases of assimp)<commit_after>/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 "D3MFImporter.h"
#include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h"
#include "StringUtils.h"
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>
#include <assimp/ai_assert.h>
#include "D3MFOpcPackage.h"
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
namespace Assimp {
namespace D3MF {
namespace XmlTag {
const std::string model = "model";
const std::string metadata = "metadata";
const std::string resources = "resources";
const std::string object = "object";
const std::string mesh = "mesh";
const std::string vertices = "vertices";
const std::string vertex = "vertex";
const std::string triangles = "triangles";
const std::string triangle = "triangle";
const std::string x = "x";
const std::string y = "y";
const std::string z = "z";
const std::string v1 = "v1";
const std::string v2 = "v2";
const std::string v3 = "v3";
const std::string id = "id";
const std::string name = "name";
const std::string type = "type";
const std::string build = "build";
const std::string item = "item";
const std::string objectid = "objectid";
const std::string transform = "transform";
}
class XmlSerializer
{
public:
XmlSerializer(XmlReader* xmlReader)
: xmlReader(xmlReader)
{
}
void ImportXml(aiScene* scene)
{
scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
scene->mRootNode = new aiNode();
std::vector<aiNode*> children;
while(ReadToEndElement(D3MF::XmlTag::model))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::object)
{
children.push_back(ReadObject(scene));
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::build)
{
}
}
if(scene->mRootNode->mName.length == 0)
scene->mRootNode->mName.Set("3MF");
scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
scene->mMeshes = new aiMesh*[scene->mNumMeshes]();
std::copy(meshes.begin(), meshes.end(), scene->mMeshes);
scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();
std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);
}
private:
aiNode* ReadObject(aiScene* scene)
{
ScopeGuard<aiNode> node(new aiNode());
std::vector<unsigned long> meshIds;
int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));
std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));
std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));
node->mParent = scene->mRootNode;
node->mName.Set(name);
unsigned long meshIdx = meshes.size();
while(ReadToEndElement(D3MF::XmlTag::object))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
{
auto mesh = ReadMesh();
mesh->mName.Set(name);
meshes.push_back(mesh);
meshIds.push_back(meshIdx);
meshIdx++;
}
}
node->mNumMeshes = static_cast<unsigned int>(meshIds.size());
node->mMeshes = new unsigned int[node->mNumMeshes];
std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);
return node.dismiss();
}
aiMesh* ReadMesh()
{
aiMesh* mesh = new aiMesh();
while(ReadToEndElement(D3MF::XmlTag::mesh))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
{
ImportVertices(mesh);
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)
{
ImportTriangles(mesh);
}
}
return mesh;
}
void ImportVertices(aiMesh* mesh)
{
std::vector<aiVector3D> vertices;
while(ReadToEndElement(D3MF::XmlTag::vertices))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
{
vertices.push_back(ReadVertex());
}
}
mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
std::copy(vertices.begin(), vertices.end(), mesh->mVertices);
}
aiVector3D ReadVertex()
{
aiVector3D vertex;
vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
return vertex;
}
void ImportTriangles(aiMesh* mesh)
{
std::vector<aiFace> faces;
while(ReadToEndElement(D3MF::XmlTag::triangles))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)
{
faces.push_back(ReadTriangle());
}
}
mesh->mNumFaces = static_cast<unsigned int>(faces.size());
mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
std::copy(faces.begin(), faces.end(), mesh->mFaces);
}
aiFace ReadTriangle()
{
aiFace face;
face.mNumIndices = 3;
face.mIndices = new unsigned int[face.mNumIndices];
face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));
return face;
}
private:
bool ReadToStartElement(const std::string& startTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)
{
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&
xmlReader->getNodeName() == startTag)
{
return false;
}
}
//DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
bool ReadToEndElement(const std::string& closeTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END
&& xmlReader->getNodeName() == closeTag)
{
return false;
}
}
DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
private:
std::vector<aiMesh*> meshes;
XmlReader* xmlReader;
};
} //namespace D3MF
static const aiImporterDesc desc = {
"3mf Importer",
"",
"",
"http://3mf.io/",
aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
0,
0,
0,
0,
"3mf"
};
D3MFImporter::D3MFImporter()
{
}
D3MFImporter::~D3MFImporter()
{
}
bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{
const std::string extension = GetExtension(pFile);
if(extension == "3mf")
{
return true;
}
else if(!extension.length() || checkSig)
{
if(!pIOHandler)
return true;
}
return false;
}
void D3MFImporter::SetupProperties(const Importer *pImp)
{
}
const aiImporterDesc *D3MFImporter::GetInfo() const
{
return &desc;
}
void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{
D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));
D3MF::XmlSerializer xmlSerializer(xmlReader.get());
xmlSerializer.ImportXml(pScene);
}
}
#endif // ASSIMP_BUILD_NO_3MF_IMPORTER
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* $ Id: $
*
*
* @author <a href="mailto:[email protected]">David N. Bertoni</a>
*/
#include "StdBinInputStream.hpp"
#include <cassert>
#if !defined(XALAN_OLD_STREAMS)
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <istream>
#endif
#endif
#if defined(XALAN_NO_NAMESPACES)
StdBinInputStream::StdBinInputStream(istream& theStream) :
#else
StdBinInputStream::StdBinInputStream(std::istream& theStream) :
#endif
BinInputStream(),
m_stream(theStream)
{
}
StdBinInputStream::~StdBinInputStream()
{
}
unsigned int
StdBinInputStream::curPos() const
{
return m_stream.tellg();
}
unsigned int
StdBinInputStream::readBytes(
XMLByte* const toFill,
const unsigned int maxToRead)
{
assert(sizeof(XMLByte) == sizeof(char));
if (!m_stream)
{
return 0;
}
else
{
unsigned int i = 0;
while(i < maxToRead)
{
const int ch = m_stream.get();
if (ch == EOF)
{
break;
}
else
{
toFill[i] = XMLByte(ch);
++i;
}
}
return i;
}
}
<commit_msg>Read bytes from the stream all at once.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* $ Id: $
*
*
* @author <a href="mailto:[email protected]">David N. Bertoni</a>
*/
#include "StdBinInputStream.hpp"
#include <cassert>
#if !defined(XALAN_OLD_STREAMS)
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <istream>
#endif
#endif
#if defined(XALAN_NO_NAMESPACES)
StdBinInputStream::StdBinInputStream(istream& theStream) :
#else
StdBinInputStream::StdBinInputStream(std::istream& theStream) :
#endif
BinInputStream(),
m_stream(theStream)
{
}
StdBinInputStream::~StdBinInputStream()
{
}
unsigned int
StdBinInputStream::curPos() const
{
return m_stream.tellg();
}
unsigned int
StdBinInputStream::readBytes(
XMLByte* const toFill,
const unsigned int maxToRead)
{
assert(sizeof(XMLByte) == sizeof(char));
if (!m_stream)
{
return 0;
}
else
{
#if defined(XALAN_OLD_STYLE_CASTS)
return m_stream.readsome((char*)toFill, maxToRead);
#else
return m_stream.readsome(reinterpret_cast<char*>(toFill), maxToRead);
#endif
}
}
<|endoftext|> |
<commit_before>/*
* mitkFiberBundleMapper2D.cpp
* mitk-all
*
* Created by HAL9000 on 1/17/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "mitkFiberBundleXMapper2D.h"
#include <mitkBaseRenderer.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>
//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>
//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>
#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>
#include <QCoreApplication>
#include <QFile>
mitk::FiberBundleXMapper2D::FiberBundleXMapper2D()
{
m_lut = vtkLookupTable::New();
m_lut->Build();
}
mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()
{
}
mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()
{
return dynamic_cast< mitk::FiberBundleX * > ( GetData() );
}
void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)
{
if ( !this->IsVisible( renderer ) )
{
return;
}
MITK_INFO << "MapperFBX 2D update: ";
// Calculate time step of the input data for the specified renderer (integer value)
// this method is implemented in mitkMapper
this->CalculateTimeStep( renderer );
//check if updates occured in the node or on the display
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
const DataNode *node = this->GetDataNode();
if ( (localStorage->m_LastUpdateTime < node->GetMTime())
|| (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
|| (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
{
// MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
this->GenerateDataForRenderer( renderer );
}
if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
{
this->UpdateShaderParameter(renderer);
}
}
void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//get information about current position of views
mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();
//generate according cutting planes based on the view position
float sliceN[3], planeOrigin[3];
// since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates
planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
planeOrigin[2] = (float) planeGeo->GetOrigin()[2];
sliceN[0] = planeGeo->GetNormal()[0];
sliceN[1] = planeGeo->GetNormal()[1];
sliceN[2] = planeGeo->GetNormal()[2];
float tmp1 = planeOrigin[0] * sliceN[0];
float tmp2 = planeOrigin[1] * sliceN[1];
float tmp3 = planeOrigin[2] * sliceN[2];
float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector
float plane1[4];
plane1[0] = sliceN[0];
plane1[1] = sliceN[1];
plane1[2] = sliceN[2];
plane1[3] = d1;
float thickness = 2.0;
if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";
bool fiberfading = false;
if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";
int fiberfading_i = 1;
if (!fiberfading)
fiberfading_i = 0;
// set Opacity
float fiberOpacity;
this->GetDataNode()->GetOpacity(fiberOpacity, NULL);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1, &fiberfading_i);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity);
}
// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
//the handler of local storage gets feeded in this method with requested data for related renderwindow
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//this procedure is depricated,
//not needed after initializaton anymore
mitk::DataNode* node = this->GetDataNode();
if ( node == NULL )
{
MITK_INFO << "check DATANODE: ....[Fail] ";
return;
}
///////////////////////////////////
///THIS GET INPUT
mitk::FiberBundleX* fbx = this->GetInput();
localStorage->m_PointMapper->ScalarVisibilityOn();
localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
localStorage->m_PointMapper->SetLookupTable(m_lut); //apply the properties after the slice was set
localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);
// set color
if (fbx->GetCurrentColorCoding() != NULL){
// localStorage->m_PointMapper->SelectColorArray("");
localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());
MITK_DEBUG << "MapperFBX 2D: " << fbx->GetCurrentColorCoding();
if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){
float temprgb[3];
this->GetDataNode()->GetColor( temprgb, NULL );
double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };
localStorage->m_PointActor->GetProperty()->SetColor(trgb);
}
}
localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());
localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
localStorage->m_PointActor->GetProperty()->ShadingOn();
// Applying shading properties
{
mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
}
this->UpdateShaderParameter(renderer);
// We have been modified => save this for next Update()
localStorage->m_LastUpdateTime.Modified();
}
vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{
//MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
this->Update(renderer);
return m_LSH.GetLocalStorage(renderer)->m_PointActor;
}
void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{ //add shader to datano
//####### load shader from file #########
QString applicationDir = QCoreApplication::applicationDirPath();
if (applicationDir.endsWith("bin"))
applicationDir.append("/");
else if (applicationDir.endsWith("MacOS"))
{
//on osx, check if path for installer or MITK development is needed
applicationDir.append("/");
QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" );
if( !f.exists() ) // if file does not exist, then look in MITK development build directory
applicationDir.append("../../../");
}else
applicationDir.append("\\..\\");
mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();
shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));
//####################################################################
node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);
//add other parameters to propertylist
node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
}
}
void mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
if ( this->IsVisible( renderer )==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
if ( this->IsVisible(renderer)==false )
return;
//TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
if ( this->GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
}
void mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
if(IsVisible(renderer)==false)
return;
//TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
if ( GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}
mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()
{
m_PointActor = vtkSmartPointer<vtkActor>::New();
m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
}
<commit_msg>Missed output in a separate branch<commit_after>/*
* mitkFiberBundleMapper2D.cpp
* mitk-all
*
* Created by HAL9000 on 1/17/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "mitkFiberBundleXMapper2D.h"
#include <mitkBaseRenderer.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>
//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>
//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>
#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>
#include <QCoreApplication>
#include <QFile>
mitk::FiberBundleXMapper2D::FiberBundleXMapper2D()
{
m_lut = vtkLookupTable::New();
m_lut->Build();
}
mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()
{
}
mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()
{
return dynamic_cast< mitk::FiberBundleX * > ( GetData() );
}
void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)
{
if ( !this->IsVisible( renderer ) )
{
return;
}
MITK_DEBUG << "MapperFBX 2D update: ";
// Calculate time step of the input data for the specified renderer (integer value)
// this method is implemented in mitkMapper
this->CalculateTimeStep( renderer );
//check if updates occured in the node or on the display
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
const DataNode *node = this->GetDataNode();
if ( (localStorage->m_LastUpdateTime < node->GetMTime())
|| (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
|| (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
{
// MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
this->GenerateDataForRenderer( renderer );
}
if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
{
this->UpdateShaderParameter(renderer);
}
}
void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//get information about current position of views
mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();
//generate according cutting planes based on the view position
float sliceN[3], planeOrigin[3];
// since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates
planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
planeOrigin[2] = (float) planeGeo->GetOrigin()[2];
sliceN[0] = planeGeo->GetNormal()[0];
sliceN[1] = planeGeo->GetNormal()[1];
sliceN[2] = planeGeo->GetNormal()[2];
float tmp1 = planeOrigin[0] * sliceN[0];
float tmp2 = planeOrigin[1] * sliceN[1];
float tmp3 = planeOrigin[2] * sliceN[2];
float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector
float plane1[4];
plane1[0] = sliceN[0];
plane1[1] = sliceN[1];
plane1[2] = sliceN[2];
plane1[3] = d1;
float thickness = 2.0;
if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";
bool fiberfading = false;
if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";
int fiberfading_i = 1;
if (!fiberfading)
fiberfading_i = 0;
// set Opacity
float fiberOpacity;
this->GetDataNode()->GetOpacity(fiberOpacity, NULL);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1, &fiberfading_i);
localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity);
}
// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
//the handler of local storage gets feeded in this method with requested data for related renderwindow
FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
//this procedure is depricated,
//not needed after initializaton anymore
mitk::DataNode* node = this->GetDataNode();
if ( node == NULL )
{
MITK_INFO << "check DATANODE: ....[Fail] ";
return;
}
///////////////////////////////////
///THIS GET INPUT
mitk::FiberBundleX* fbx = this->GetInput();
localStorage->m_PointMapper->ScalarVisibilityOn();
localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
localStorage->m_PointMapper->SetLookupTable(m_lut); //apply the properties after the slice was set
localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);
// set color
if (fbx->GetCurrentColorCoding() != NULL){
// localStorage->m_PointMapper->SelectColorArray("");
localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());
MITK_DEBUG << "MapperFBX 2D: " << fbx->GetCurrentColorCoding();
if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){
float temprgb[3];
this->GetDataNode()->GetColor( temprgb, NULL );
double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };
localStorage->m_PointActor->GetProperty()->SetColor(trgb);
}
}
localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());
localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
localStorage->m_PointActor->GetProperty()->ShadingOn();
// Applying shading properties
{
mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
}
this->UpdateShaderParameter(renderer);
// We have been modified => save this for next Update()
localStorage->m_LastUpdateTime.Modified();
}
vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{
//MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
this->Update(renderer);
return m_LSH.GetLocalStorage(renderer)->m_PointActor;
}
void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{ //add shader to datano
//####### load shader from file #########
QString applicationDir = QCoreApplication::applicationDirPath();
if (applicationDir.endsWith("bin"))
applicationDir.append("/");
else if (applicationDir.endsWith("MacOS"))
{
//on osx, check if path for installer or MITK development is needed
applicationDir.append("/");
QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" );
if( !f.exists() ) // if file does not exist, then look in MITK development build directory
applicationDir.append("../../../");
}else
applicationDir.append("\\..\\");
mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();
shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));
//####################################################################
node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);
//add other parameters to propertylist
node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );
Superclass::SetDefaultProperties(node, renderer, overwrite);
}
// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
if ( this->IsVisible(renderer)==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
{
this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
}
}
void mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
if ( this->IsVisible( renderer )==false )
return;
if ( this->GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
if ( this->IsVisible(renderer)==false )
return;
//TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
if ( this->GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
}
void mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
// MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
if(IsVisible(renderer)==false)
return;
//TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
if ( GetVtkProp(renderer)->GetVisibility() )
this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}
mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()
{
m_PointActor = vtkSmartPointer<vtkActor>::New();
m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
}
<|endoftext|> |
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CmdlineApp.cpp Command line app
//
// includes
#include "stdafx.h"
#include "CmdlineApp.hpp"
#include "Exception.hpp"
#include "CameraException.hpp"
#include "AppCommand.hpp"
#include "AppOptions.hpp"
#include "Event.hpp"
#include "CameraScriptProcessor.hpp"
#include "Instance.hpp"
#include "SourceInfo.hpp"
#include "SourceDevice.hpp"
#include "RemoteReleaseControl.hpp"
#include "ShutterReleaseSettings.hpp"
#include "Filesystem.hpp"
#include "CrashReporter.hpp"
#include "..\version.h"
#include <thread>
CmdlineApp::CmdlineApp()
{
_tprintf(_T("RemotePhotoTool Command-Line %s\n%s\n\n"),
_T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),
_T(VERSIONINFO_COPYRIGHT));
}
void CmdlineApp::InitCrashReporter()
{
CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T("\\RemotePhotoToolCmdline\\");
if (!Directory_Exists(cszFolder))
CreateDirectory(cszFolder, NULL);
cszFolder += _T("crashdumps\\");
if (!Directory_Exists(cszFolder))
CreateDirectory(cszFolder, NULL);
CrashReporter::Init(cszFolder);
}
void CmdlineApp::Run(int argc, TCHAR* argv[])
{
// parse options
AppOptions options(m_vecCommandList);
options.Parse(argc, argv);
if (m_vecCommandList.empty())
{
options.OutputHelp();
return;
}
if (options.IsSelectedHelpOption())
return;
// run command list
std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)
{
try
{
Exec(cmd);
}
catch(const CameraException& ex)
{
_tprintf(_T("CameraException was thrown: \"%s\"\n"), ex.Message().GetString());
}
catch(const Exception& ex)
{
_tprintf(_T("Exception was thrown: \"%s\"\n"), ex.Message().GetString());
}
});
}
void CmdlineApp::Exec(const AppCommand& cmd)
{
switch (cmd.m_enCommand)
{
case AppCommand::showVersion: PrintVersionInfo(); break;
case AppCommand::listDevices: ListDevices(); break;
case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;
case AppCommand::closeDevice:
m_spSourceDevice.reset();
m_spReleaseControl.reset();
break;
case AppCommand::deviceInfo: OutputDeviceInfo(); break;
case AppCommand::deviceProperties: ListDeviceProperties(); break;
case AppCommand::imageProperties: ListImageProperties(); break;
case AppCommand::listenEvents: ListenToEvents(); break;
case AppCommand::releaseShutter: ReleaseShutter(); break;
case AppCommand::runScript: RunScript(cmd.m_cszData); break;
default:
ATLASSERT(false);
break;
}
}
void CmdlineApp::PrintVersionInfo()
{
_tprintf(_T("CanonControl version info\n\n"));
Instance inst = Instance::Get();
CString cszVersionInfo = inst.Version();
_tprintf(_T("%s\n"), cszVersionInfo.GetString());
}
void CmdlineApp::ListDevices()
{
_tprintf(_T("Devices list\n"));
Instance inst = Instance::Get();
std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
inst.EnumerateDevices(vecSourceDevices);
if (vecSourceDevices.empty())
{
_tprintf(_T("No device found.\n"));
}
else
{
for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
{
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
_tprintf(_T("Device %lu: \"%s\"\n"), i+1, spSourceInfo->Name().GetString());
}
}
_tprintf(_T("\n"));
}
void CmdlineApp::OpenByName(const CString& cszName)
{
Instance inst = Instance::Get();
std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
inst.EnumerateDevices(vecSourceDevices);
int iPosOpen = cszName.Find(_T('{'));
int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);
if (iPosOpen != -1 && iPosClose != -1)
{
CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);
size_t iIndex = _tcstoul(cszIndex, nullptr, 10);
if (iIndex >= vecSourceDevices.size())
throw Exception(_T("Invalid index for camera"), __FILE__, __LINE__);
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[iIndex];
_tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());
m_spSourceDevice = spSourceInfo->Open();
return;
}
for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
{
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
if (spSourceInfo->Name() == cszName)
{
_tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());
m_spSourceDevice = spSourceInfo->Open();
return;
}
}
throw Exception(_T("Couldn't find camera model: ") + cszName, __FILE__, __LINE__);
}
void CmdlineApp::OutputDeviceInfo()
{
_tprintf(_T("Device info about \"%s\"\n"), m_spSourceDevice->ModelName().GetString());
_tprintf(_T("Serial number \"%s\"\n"), m_spSourceDevice->SerialNumber().GetString());
// output capabilities
_tprintf(_T("Device capabilities\n"));
bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);
bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);
_tprintf(_T("can release shutter: %s\n"), bCanRelease ? _T("yes") : _T("no"));
_tprintf(_T("can use remote viewfinder: %s\n"), bCanUseViewfinder ? _T("yes") : _T("no"));
_tprintf(_T("\n"));
}
void CmdlineApp::ListDeviceProperties()
{
// output device properties
_tprintf(_T("Device properties\n"));
std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();
for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecProperties[i];
DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);
_tprintf(_T("Property \"%s\" (%04x)%s: %s (%s)\n"),
dp.Name().GetString(),
uiPropertyId,
dp.IsReadOnly() ? _T(" [read-only]") : _T(""),
dp.Value().ToString().GetString(),
dp.AsString().GetString());
std::vector<Variant> vecValidValues = dp.ValidValues();
for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)
{
_tprintf(_T(" Valid value: %s (%s)\n"),
vecValidValues[j].ToString().GetString(),
dp.ValueAsString(vecValidValues[j]).GetString());
}
}
_tprintf(_T("\n"));
}
void CmdlineApp::ListImageProperties()
{
_tprintf(_T("List image properties\n"));
EnsureReleaseControl();
std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();
if (vecImageProperties.empty())
{
_tprintf(_T("no image properties found.\n"));
}
else
for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecImageProperties[i];
ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);
_tprintf(_T("Image property \"%s\" (%04x)%s: %s (%s)\n"),
ip.Name().GetString(),
uiPropertyId,
ip.IsReadOnly() ? _T(" [read-only]") : _T(""),
ip.Value().ToString().GetString(),
ip.AsString().GetString());
std::vector<ImageProperty> vecValues;
m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);
for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)
{
const ImageProperty& ip2 = vecValues[j];
_tprintf(_T(" Valid value: %s (%s)\n"),
ip2.Value().ToString().GetString(),
ip.ValueAsString(ip2.Value()).GetString());
}
}
}
void CmdlineApp::ListenToEvents()
{
_tprintf(_T("Listens for events from camera\n"));
EnsureReleaseControl();
int iPropertyEvent = m_spReleaseControl->AddPropertyEventHandler(
[&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)
{
ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);
_tprintf(_T("Property%s changed: Id=%04x Name=%s Value=%s\n"),
enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T("") : _T(" desc."),
uiValue,
prop.Name().GetString(),
prop.AsString().GetString());
});
int iStateEvent = m_spReleaseControl->AddStateEventHandler(
[&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)
{
_tprintf(_T("State changed: State=%s Value=%u\n"),
enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T("CameraShutdown") :
enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T("RotationAngle") :
enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T("MemoryCardSlotOpen") :
enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T("ReleaseError") :
enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T("BulbExposureTime") :
enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T("InternalError") :
_T("???"),
uiValue);
});
_tprintf(_T("Press any key to exit listening for events...\n\n"));
// wait for key and run OnIdle() in the meantime
Event evtStop(true, false);
std::thread idleThread([&evtStop]()
{
(void)fgetc(stdin);
evtStop.Set();
});
while (!evtStop.Wait(10))
Instance::OnIdle();
idleThread.join();
m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);
m_spReleaseControl->RemoveStateEventHandler(iStateEvent);
}
void CmdlineApp::EnsureReleaseControl()
{
if (m_spReleaseControl != nullptr)
return;
if (m_spSourceDevice == nullptr)
throw Exception(_T("Source device not opened."), __FILE__, __LINE__);
_tprintf(_T("Starting Remote Release Control\n"));
m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();
}
void CmdlineApp::ReleaseShutter()
{
_tprintf(_T("Release shutter\n"));
EnsureReleaseControl();
unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();
_tprintf(_T("Memory for %u images available\n"), uiNumAvailShot);
Event evtPictureTaken(true, false);
ShutterReleaseSettings settings(
ShutterReleaseSettings::saveToHost,
std::bind(&Event::Set, &evtPictureTaken));
m_spReleaseControl->SetReleaseSettings(settings);
m_spReleaseControl->Release();
evtPictureTaken.Wait();
}
void CmdlineApp::RunScript(const CString& cszFilename)
{
_tprintf(_T("Loading script: %s\n"), cszFilename.GetString());
CameraScriptProcessor proc;
proc.SetOutputDebugStringHandler(
[&](const CString& cszText){
_tprintf(_T("%s"), cszText.GetString());
});
proc.LoadScript(cszFilename);
proc.Run();
_tprintf(_T("Press any key to abort running script.\n\n"));
(void)fgetc(stdin);
proc.Stop();
}
<commit_msg>fixed cppcheck message, formatting size_t with wrong format specifier<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CmdlineApp.cpp Command line app
//
// includes
#include "stdafx.h"
#include "CmdlineApp.hpp"
#include "Exception.hpp"
#include "CameraException.hpp"
#include "AppCommand.hpp"
#include "AppOptions.hpp"
#include "Event.hpp"
#include "CameraScriptProcessor.hpp"
#include "Instance.hpp"
#include "SourceInfo.hpp"
#include "SourceDevice.hpp"
#include "RemoteReleaseControl.hpp"
#include "ShutterReleaseSettings.hpp"
#include "Filesystem.hpp"
#include "CrashReporter.hpp"
#include "..\version.h"
#include <thread>
CmdlineApp::CmdlineApp()
{
_tprintf(_T("RemotePhotoTool Command-Line %s\n%s\n\n"),
_T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),
_T(VERSIONINFO_COPYRIGHT));
}
void CmdlineApp::InitCrashReporter()
{
CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T("\\RemotePhotoToolCmdline\\");
if (!Directory_Exists(cszFolder))
CreateDirectory(cszFolder, NULL);
cszFolder += _T("crashdumps\\");
if (!Directory_Exists(cszFolder))
CreateDirectory(cszFolder, NULL);
CrashReporter::Init(cszFolder);
}
void CmdlineApp::Run(int argc, TCHAR* argv[])
{
// parse options
AppOptions options(m_vecCommandList);
options.Parse(argc, argv);
if (m_vecCommandList.empty())
{
options.OutputHelp();
return;
}
if (options.IsSelectedHelpOption())
return;
// run command list
std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)
{
try
{
Exec(cmd);
}
catch(const CameraException& ex)
{
_tprintf(_T("CameraException was thrown: \"%s\"\n"), ex.Message().GetString());
}
catch(const Exception& ex)
{
_tprintf(_T("Exception was thrown: \"%s\"\n"), ex.Message().GetString());
}
});
}
void CmdlineApp::Exec(const AppCommand& cmd)
{
switch (cmd.m_enCommand)
{
case AppCommand::showVersion: PrintVersionInfo(); break;
case AppCommand::listDevices: ListDevices(); break;
case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;
case AppCommand::closeDevice:
m_spSourceDevice.reset();
m_spReleaseControl.reset();
break;
case AppCommand::deviceInfo: OutputDeviceInfo(); break;
case AppCommand::deviceProperties: ListDeviceProperties(); break;
case AppCommand::imageProperties: ListImageProperties(); break;
case AppCommand::listenEvents: ListenToEvents(); break;
case AppCommand::releaseShutter: ReleaseShutter(); break;
case AppCommand::runScript: RunScript(cmd.m_cszData); break;
default:
ATLASSERT(false);
break;
}
}
void CmdlineApp::PrintVersionInfo()
{
_tprintf(_T("CanonControl version info\n\n"));
Instance inst = Instance::Get();
CString cszVersionInfo = inst.Version();
_tprintf(_T("%s\n"), cszVersionInfo.GetString());
}
void CmdlineApp::ListDevices()
{
_tprintf(_T("Devices list\n"));
Instance inst = Instance::Get();
std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
inst.EnumerateDevices(vecSourceDevices);
if (vecSourceDevices.empty())
{
_tprintf(_T("No device found.\n"));
}
else
{
for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
{
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
_tprintf(_T("Device %Iu: \"%s\"\n"), i+1, spSourceInfo->Name().GetString());
}
}
_tprintf(_T("\n"));
}
void CmdlineApp::OpenByName(const CString& cszName)
{
Instance inst = Instance::Get();
std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
inst.EnumerateDevices(vecSourceDevices);
int iPosOpen = cszName.Find(_T('{'));
int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);
if (iPosOpen != -1 && iPosClose != -1)
{
CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);
size_t iIndex = _tcstoul(cszIndex, nullptr, 10);
if (iIndex >= vecSourceDevices.size())
throw Exception(_T("Invalid index for camera"), __FILE__, __LINE__);
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[iIndex];
_tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());
m_spSourceDevice = spSourceInfo->Open();
return;
}
for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
{
std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
if (spSourceInfo->Name() == cszName)
{
_tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());
m_spSourceDevice = spSourceInfo->Open();
return;
}
}
throw Exception(_T("Couldn't find camera model: ") + cszName, __FILE__, __LINE__);
}
void CmdlineApp::OutputDeviceInfo()
{
_tprintf(_T("Device info about \"%s\"\n"), m_spSourceDevice->ModelName().GetString());
_tprintf(_T("Serial number \"%s\"\n"), m_spSourceDevice->SerialNumber().GetString());
// output capabilities
_tprintf(_T("Device capabilities\n"));
bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);
bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);
_tprintf(_T("can release shutter: %s\n"), bCanRelease ? _T("yes") : _T("no"));
_tprintf(_T("can use remote viewfinder: %s\n"), bCanUseViewfinder ? _T("yes") : _T("no"));
_tprintf(_T("\n"));
}
void CmdlineApp::ListDeviceProperties()
{
// output device properties
_tprintf(_T("Device properties\n"));
std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();
for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecProperties[i];
DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);
_tprintf(_T("Property \"%s\" (%04x)%s: %s (%s)\n"),
dp.Name().GetString(),
uiPropertyId,
dp.IsReadOnly() ? _T(" [read-only]") : _T(""),
dp.Value().ToString().GetString(),
dp.AsString().GetString());
std::vector<Variant> vecValidValues = dp.ValidValues();
for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)
{
_tprintf(_T(" Valid value: %s (%s)\n"),
vecValidValues[j].ToString().GetString(),
dp.ValueAsString(vecValidValues[j]).GetString());
}
}
_tprintf(_T("\n"));
}
void CmdlineApp::ListImageProperties()
{
_tprintf(_T("List image properties\n"));
EnsureReleaseControl();
std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();
if (vecImageProperties.empty())
{
_tprintf(_T("no image properties found.\n"));
}
else
for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecImageProperties[i];
ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);
_tprintf(_T("Image property \"%s\" (%04x)%s: %s (%s)\n"),
ip.Name().GetString(),
uiPropertyId,
ip.IsReadOnly() ? _T(" [read-only]") : _T(""),
ip.Value().ToString().GetString(),
ip.AsString().GetString());
std::vector<ImageProperty> vecValues;
m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);
for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)
{
const ImageProperty& ip2 = vecValues[j];
_tprintf(_T(" Valid value: %s (%s)\n"),
ip2.Value().ToString().GetString(),
ip.ValueAsString(ip2.Value()).GetString());
}
}
}
void CmdlineApp::ListenToEvents()
{
_tprintf(_T("Listens for events from camera\n"));
EnsureReleaseControl();
int iPropertyEvent = m_spReleaseControl->AddPropertyEventHandler(
[&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)
{
ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);
_tprintf(_T("Property%s changed: Id=%04x Name=%s Value=%s\n"),
enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T("") : _T(" desc."),
uiValue,
prop.Name().GetString(),
prop.AsString().GetString());
});
int iStateEvent = m_spReleaseControl->AddStateEventHandler(
[&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)
{
_tprintf(_T("State changed: State=%s Value=%u\n"),
enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T("CameraShutdown") :
enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T("RotationAngle") :
enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T("MemoryCardSlotOpen") :
enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T("ReleaseError") :
enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T("BulbExposureTime") :
enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T("InternalError") :
_T("???"),
uiValue);
});
_tprintf(_T("Press any key to exit listening for events...\n\n"));
// wait for key and run OnIdle() in the meantime
Event evtStop(true, false);
std::thread idleThread([&evtStop]()
{
(void)fgetc(stdin);
evtStop.Set();
});
while (!evtStop.Wait(10))
Instance::OnIdle();
idleThread.join();
m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);
m_spReleaseControl->RemoveStateEventHandler(iStateEvent);
}
void CmdlineApp::EnsureReleaseControl()
{
if (m_spReleaseControl != nullptr)
return;
if (m_spSourceDevice == nullptr)
throw Exception(_T("Source device not opened."), __FILE__, __LINE__);
_tprintf(_T("Starting Remote Release Control\n"));
m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();
}
void CmdlineApp::ReleaseShutter()
{
_tprintf(_T("Release shutter\n"));
EnsureReleaseControl();
unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();
_tprintf(_T("Memory for %u images available\n"), uiNumAvailShot);
Event evtPictureTaken(true, false);
ShutterReleaseSettings settings(
ShutterReleaseSettings::saveToHost,
std::bind(&Event::Set, &evtPictureTaken));
m_spReleaseControl->SetReleaseSettings(settings);
m_spReleaseControl->Release();
evtPictureTaken.Wait();
}
void CmdlineApp::RunScript(const CString& cszFilename)
{
_tprintf(_T("Loading script: %s\n"), cszFilename.GetString());
CameraScriptProcessor proc;
proc.SetOutputDebugStringHandler(
[&](const CString& cszText){
_tprintf(_T("%s"), cszText.GetString());
});
proc.LoadScript(cszFilename);
proc.Run();
_tprintf(_T("Press any key to abort running script.\n\n"));
(void)fgetc(stdin);
proc.Stop();
}
<|endoftext|> |
<commit_before><commit_msg>Fix BMC 21651 - [REG] New tab on wrench menu is not working when bookmark manager or download manager is open<commit_after><|endoftext|> |
<commit_before><commit_msg>Looks like the fix I did last time did work. According to the flakiness dashboard this hasn't failed since the day I checked in the fix (Jan 26th).<commit_after><|endoftext|> |
<commit_before><commit_msg>Disable test while investigating. TBR=amit<commit_after><|endoftext|> |
<commit_before>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
namespace {
class OpenMeshReadWriteSTL : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
* Just load a simple mesh file in stla format and count whether
* the right number of entities has been loaded.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {
mesh_.clear();
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl");
EXPECT_TRUE(ok);
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}
/*
* Just load a simple mesh file in stla format and count whether
* the right number of entities has been loaded. Also check facet normals.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {
mesh_.clear();
mesh_.request_face_normals();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::FaceNormal;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl", opt);
EXPECT_TRUE(ok);
EXPECT_TRUE(opt.face_has_normal());
EXPECT_FALSE(opt.vertex_has_normal());
EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
mesh_.release_face_normals();
}
/*
* Just load a simple mesh file in stlb format and count whether
* the right number of entities has been loaded.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {
mesh_.clear();
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");
EXPECT_TRUE(ok);
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}
/*
* Just load a simple mesh file in stlb format and count whether
* the right number of entities has been loaded. Also check facet normals.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {
mesh_.clear();
mesh_.request_face_normals();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::FaceNormal;
opt += OpenMesh::IO::Options::Binary;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);
EXPECT_TRUE(ok);
EXPECT_TRUE(opt.is_binary());
EXPECT_TRUE(opt.face_has_normal());
EXPECT_FALSE(opt.vertex_has_normal());
EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
mesh_.release_face_normals();
}
}
<commit_msg>add write unittest for binary files<commit_after>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
namespace {
class OpenMeshReadWriteSTL : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
* Just load a simple mesh file in stla format and count whether
* the right number of entities has been loaded.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {
mesh_.clear();
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl");
EXPECT_TRUE(ok);
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}
/*
* Just load a simple mesh file in stla format and count whether
* the right number of entities has been loaded. Also check facet normals.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {
mesh_.clear();
mesh_.request_face_normals();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::FaceNormal;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl", opt);
EXPECT_TRUE(ok);
EXPECT_TRUE(opt.face_has_normal());
EXPECT_FALSE(opt.vertex_has_normal());
EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
mesh_.release_face_normals();
}
/*
* Just load a simple mesh file in stlb format and count whether
* the right number of entities has been loaded.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {
mesh_.clear();
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");
EXPECT_TRUE(ok);
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}
/*
* Just load a simple mesh file in stlb format and count whether
* the right number of entities has been loaded. Also check facet normals.
*/
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {
mesh_.clear();
mesh_.request_face_normals();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::FaceNormal;
opt += OpenMesh::IO::Options::Binary;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);
EXPECT_TRUE(ok);
EXPECT_TRUE(opt.is_binary());
EXPECT_TRUE(opt.face_has_normal());
EXPECT_FALSE(opt.vertex_has_normal());
EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
mesh_.release_face_normals();
}
/*
* Read and Write stl binary file
*/
TEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFile) {
mesh_.clear();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::Binary;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");
EXPECT_TRUE(ok);
const char* filename = "cube1Binary_openmeshWriteTestFile.stl";
ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);
EXPECT_TRUE(ok);
ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);
EXPECT_TRUE(ok);
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
remove(filename);
}
/*
* Just load a simple mesh file in stlb format and count whether
* the right number of entities has been loaded. Also check facet normals.
*/
TEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFileWithNormals) {
mesh_.clear();
mesh_.request_face_normals();
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::FaceNormal;
opt += OpenMesh::IO::Options::Binary;
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);
EXPECT_TRUE(ok);
const char* filename = "cube1BinaryNormal_openmeshWriteTestFile.stl";
ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);
EXPECT_TRUE(ok);
ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);
EXPECT_TRUE(ok);
EXPECT_TRUE(opt.is_binary());
EXPECT_TRUE(opt.face_has_normal());
EXPECT_FALSE(opt.vertex_has_normal());
EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";
EXPECT_EQ(7526u , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
mesh_.release_face_normals();
remove(filename);
}
}
<|endoftext|> |
<commit_before><commit_msg>nit: spacing<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkShiftScaleLabelMapFilterTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShiftScaleLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
#include "itkTestingMacros.h"
int itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])
{
if( argc != 6 )
{
std::cerr << "usage: " << argv[0] << " input output shift scale change_bg" << std::endl;
return EXIT_FAILURE;
}
const unsigned int dim = 2;
typedef itk::Image< unsigned char, dim > ImageType;
typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
typedef itk::LabelMap< LabelObjectType > LabelMapType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
I2LType::Pointer i2l = I2LType::New();
i2l->SetInput( reader->GetOutput() );
typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;
ChangeType::Pointer change = ChangeType::New();
change->SetInput( i2l->GetOutput() );
change->SetShift( atof(argv[3]) );
change->SetScale( atof(argv[4]) );
change->SetChangeBackgroundValue( atoi(argv[5]) );
itk::SimpleFilterWatcher watcher6(change, "filter");
typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
L2IType::Pointer l2i = L2IType::New();
l2i->SetInput( change->GetOutput() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( l2i->GetOutput() );
writer->SetFileName( argv[2] );
writer->UseCompressionOn();
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
<commit_msg>BUG: Clarified use of ChangeBackgroundValue as a boolean.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkShiftScaleLabelMapFilterTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShiftScaleLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
#include "itkTestingMacros.h"
int itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])
{
if( argc != 6 )
{
std::cerr << "usage: " << argv[0] << " input output shift scale change_bg" << std::endl;
return EXIT_FAILURE;
}
const unsigned int dim = 2;
typedef itk::Image< unsigned char, dim > ImageType;
typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
typedef itk::LabelMap< LabelObjectType > LabelMapType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
I2LType::Pointer i2l = I2LType::New();
i2l->SetInput( reader->GetOutput() );
typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;
ChangeType::Pointer change = ChangeType::New();
change->SetInput( i2l->GetOutput() );
change->SetShift( atof(argv[3]) );
change->SetScale( atof(argv[4]) );
bool changeBackground = atoi(argv[5]);
change->SetChangeBackgroundValue( changeBackground );
itk::SimpleFilterWatcher watcher6(change, "filter");
typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
L2IType::Pointer l2i = L2IType::New();
l2i->SetInput( change->GetOutput() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( l2i->GetOutput() );
writer->SetFileName( argv[2] );
writer->UseCompressionOn();
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>Revert -r47806 which had negative consequences (failing to handle properly #ifdef at the beginning of an unnamed script and making it much harder to update roottest to work around missing feature in cling)<commit_after><|endoftext|> |
<commit_before>/*
* itkVectorImageRepresenterTest.cpp
*
* Created on: May 3, 2012
* Author: luethi
*/
#include "itkVectorImageRepresenter.h"
#include "genericRepresenterTest.hxx"
typedef itk::Image< itk::Vector<float, 2> ,2 > VectorImageType;
typedef itk::VectorImageRepresenter<float, 2, 2> RepresenterType;
typedef GenericRepresenterTest<RepresenterType> RepresenterTestType;
VectorImageType::Pointer loadVectorImage(const std::string& filename) {
itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();
reader->SetFileName(filename);
reader->Update();
VectorImageType::Pointer img = reader->GetOutput();
img->DisconnectPipeline();
return img;
}
int main(int argc, char** argv) {
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " datadir" << std::endl;
exit(EXIT_FAILURE);
}
std::string datadir = std::string(argv[1]);
const std::string referenceFilename = datadir + "/hand_dfs/df-hand-1.vtk";
const std::string testDatasetFilename = datadir + "/hand_dfs/df-hand-2.vtk";
RepresenterType::Pointer representer = RepresenterType::New();
VectorImageType::Pointer reference = loadVectorImage(referenceFilename);
representer->SetReference(reference);
// choose a test dataset, a point and its associate pixel value
VectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);
VectorImageType::IndexType idx;
idx.Fill(0);
VectorImageType::PointType testPt;
testDataset->TransformIndexToPhysicalPoint(idx, testPt);
VectorImageType::PixelType testValue = testDataset->GetPixel(idx);
RepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));
if (representerTest.runAllTests() == true) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}
}
<commit_msg>fixed bug: testPoint must be taken from reference and not from testData<commit_after>/*
* itkVectorImageRepresenterTest.cpp
*
* Created on: May 3, 2012
* Author: luethi
*/
#include "itkVectorImageRepresenter.h"
#include "genericRepresenterTest.hxx"
typedef itk::Image< itk::Vector<float, 2> ,2 > VectorImageType;
typedef itk::VectorImageRepresenter<float, 2, 2> RepresenterType;
typedef GenericRepresenterTest<RepresenterType> RepresenterTestType;
VectorImageType::Pointer loadVectorImage(const std::string& filename) {
itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();
reader->SetFileName(filename);
reader->Update();
VectorImageType::Pointer img = reader->GetOutput();
img->DisconnectPipeline();
return img;
}
int main(int argc, char** argv) {
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " datadir" << std::endl;
exit(EXIT_FAILURE);
}
std::string datadir = std::string(argv[1]);
const std::string referenceFilename = datadir + "/hand_dfs/df-hand-1.vtk";
const std::string testDatasetFilename = datadir + "/hand_dfs/df-hand-2.vtk";
RepresenterType::Pointer representer = RepresenterType::New();
VectorImageType::Pointer reference = loadVectorImage(referenceFilename);
representer->SetReference(reference);
// choose a test dataset, a point and its associate pixel value
VectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);
VectorImageType::IndexType idx;
idx.Fill(0);
VectorImageType::PointType testPt;
reference->TransformIndexToPhysicalPoint(idx, testPt);
VectorImageType::PixelType testValue = testDataset->GetPixel(idx);
RepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));
if (representerTest.runAllTests() == true) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>#include "decafs_barista.h"
int main (int argc, char *argv[]) {
barista_core_init (argc, argv);
printf ("Barista is initialized.\n");
printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
get_chunk_size());
int port = 0;
if (argc >= MIN_ARGS) {
port = atoi(argv[PORT]);
printf("got port: %d\n", port);
} else {
fprintf(stderr, "port number not specified\n");
exit(-1);
}
BaristaServer *barista_server = BaristaServer::init(port);
barista_server->run();
/* TEST CODE */
/*struct ip_address ip;
struct client default_client = {ip, 1, 1};
int count, fd = open_file ("new_file.txt", O_RDWR, default_client);
char buf[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
char *read_buf = (char *)malloc (1000);
memset (read_buf, '\0', 1000);
printf ("\n\n ------------------------------FIRST WRITE------------------------------\n");
count = write_file (fd, buf, strlen (buf), default_client);
printf ("(\n(BARISTA) wrote %d bytes.\n", count);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------FIRST READ--------------------------------\n");
count = read_file (fd, read_buf, strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDWR | O_APPEND, default_client);
printf ("\n\n ------------------------------SECOND WRITE------------------------------\n");
write_file (fd, buf, strlen (buf), default_client);
close_file (fd, default_client);
fd = open_file ("new_file.txt", O_RDONLY, default_client);
printf ("\n\n ------------------------------SECOND READ--------------------------------\n");
count = read_file (fd, read_buf, 2*strlen (buf), default_client);
printf ("\n(BARISTA) Read %d bytes.\n", count);
printf ("(BARISTA) Buf is:\n%s\n", read_buf);*/
return 0;
}
<commit_msg>added logging to decafs_barista main<commit_after>#include "decafs_barista.h"
int main (int argc, char *argv[]) {
printf("DecafsBarista: initializing barista_core\n");
barista_core_init (argc, argv);
printf ("Barista is initialized.\n");
printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
get_chunk_size());
printf("DecafsBarista: barista_core initialized\n");
int port = 0;
if (argc >= MIN_ARGS) {
port = atoi(argv[PORT]);
printf("got port: %d\n", port);
} else {
fprintf(stderr, "port number not specified\n");
exit(-1);
}
printf("DecafsBarista: initializing BaristaServer\n");
BaristaServer *barista_server = BaristaServer::init(port);
printf("DecafsBarista: BaristaServer initialized, running BaristaServer\n");
barista_server->run();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Export ShapeRec symbols<commit_after><|endoftext|> |
<commit_before>#include "HPACK.h"
#include "gtest/gtest.h"
#include <string.h>
TEST(encode_intTest, NormalTest) {
uint8_t dst[10];
uint8_t expect[][5] = {
{0x01, 0x00},
{0x0f, 0x01},
//{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
};
uint64_t len = encode_int(dst, 1, 1);
EXPECT_EQ(2, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
len = encode_int(dst, 16, 4);
EXPECT_EQ(2, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
/*
len = encode_int(dst, 3000000, 5);
EXPECT_EQ(5, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
*/
}
TEST(decode_intTest, NormalTest) {
uint32_t dst = 0;
uint8_t data[][5] = {
{0x01, 0x00},
{0x0f, 0x01},
};
EXPECT_EQ(1, decode_int(data[0], 1));
EXPECT_EQ(16, decode_int(data[1], 4));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>implement json parser<commit_after>#include "HPACK.h"
#include "hpack_table.h"
#include "gtest/gtest.h"
#include <string.h>
#include "picojson/picojson.h"
#include <fstream>
#include <iostream>
#include <iterator>
TEST(encode_intTest, NormalTest) {
uint8_t dst[10];
uint8_t expect[][5] = {
{0x01, 0x00},
{0x0f, 0x01},
//{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
};
uint64_t len = encode_int(dst, 1, 1);
EXPECT_EQ(2, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
len = encode_int(dst, 16, 4);
EXPECT_EQ(2, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
/*
len = encode_int(dst, 3000000, 5);
EXPECT_EQ(5, len);
EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
*/
}
TEST(decode_intTest, NormalTest) {
uint32_t dst = 0;
uint8_t data[][5] = {
{0x01, 0x00},
{0x0f, 0x01},
};
EXPECT_EQ(1, decode_int(data[0], 1));
EXPECT_EQ(16, decode_int(data[1], 4));
}
TEST(encodeTest, NormalTest) {
std::ifstream ifs("hpack-test-case/haskell-http2-naive/story_00.json");
if (ifs.fail()) {
std::cerr << "fail to open" << std::endl;
}
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
picojson::value v;
std::string err = picojson::parse(v, str);
if (! err.empty()) {
std::cerr << err << std::endl;
}
picojson::object obj = v.get<picojson::object>();
picojson::array arr = obj["cases"].get<picojson::array>();
picojson::array::iterator it_seqno;
for (it_seqno = arr.begin(); it_seqno != arr.end(); it_seqno++) {
picojson::object obj_in = it_seqno->get<picojson::object>();
std::string wire = obj_in["wire"].to_str();
picojson::array json_headers = obj_in["headers"].get<picojson::array>();
picojson::array::iterator it_headers;
std::vector<header> ans_headers;
for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {
picojson::object content = it_headers->get<picojson::object>();
picojson::object::iterator it = content.begin();
ans_headers.push_back(header(it->first, it->second.to_str()));
}
Table* table = new Table();
uint8_t dst[2000];
int64_t len = hpack_encode(dst, ans_headers, false, false, false, table, -1);
//EXPECT_TRUE(0 == std::memcmp(dst, wire, len));
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include <assert.h>
std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;
mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
: m_MitkVtkRenderWindow(NULL), m_Name(name), m_Renderer(renderer)
{
instances.insert(this);
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
}
mitk::RenderWindow::~RenderWindow()
{
instances.erase(this);
m_Renderer = NULL;
m_MitkVtkRenderWindow->Delete(); //xxx
}
void mitk::RenderWindow::MakeCurrent()
{
m_MitkVtkRenderWindow->MakeCurrent();
};
void mitk::RenderWindow::SwapBuffers()
{
m_MitkVtkRenderWindow->Frame();
};
bool mitk::RenderWindow::IsSharing () const
{
return false;
}
void mitk::RenderWindow::Update()
{
m_MitkVtkRenderWindow->MakeCurrent();
m_MitkVtkRenderWindow->Render();
}
void mitk::RenderWindow::Repaint()
{
m_MitkVtkRenderWindow->MakeCurrent();
m_MitkVtkRenderWindow->Render();
}
void mitk::RenderWindow::SetSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
}
void mitk::RenderWindow::InitRenderer()
{
if(m_Renderer.IsNull())
m_Renderer = mitk::OpenGLRenderer::New();
m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);
m_Renderer->InitRenderer(this);
int * size = m_MitkVtkRenderWindow->GetSize();
if((size[0]>10) && (size[1]>10))
m_Renderer->InitSize(size[0], size[1]);
}
void mitk::RenderWindow::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
if (renWin != NULL)
{
m_MitkVtkRenderWindow = renWin;
InitRenderer();
}
}
<commit_msg>FIX: accept NULL as name<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include <assert.h>
std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;
mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
: m_MitkVtkRenderWindow(NULL), m_Renderer(renderer)
{
if(name == NULL)
m_Name = "renderwindow";
else
m_Name = name;
instances.insert(this);
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
}
mitk::RenderWindow::~RenderWindow()
{
instances.erase(this);
m_Renderer = NULL;
m_MitkVtkRenderWindow->Delete(); //xxx
}
void mitk::RenderWindow::MakeCurrent()
{
m_MitkVtkRenderWindow->MakeCurrent();
};
void mitk::RenderWindow::SwapBuffers()
{
m_MitkVtkRenderWindow->Frame();
};
bool mitk::RenderWindow::IsSharing () const
{
return false;
}
void mitk::RenderWindow::Update()
{
m_MitkVtkRenderWindow->MakeCurrent();
m_MitkVtkRenderWindow->Render();
}
void mitk::RenderWindow::Repaint()
{
m_MitkVtkRenderWindow->MakeCurrent();
m_MitkVtkRenderWindow->Render();
}
void mitk::RenderWindow::SetSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
}
void mitk::RenderWindow::InitRenderer()
{
if(m_Renderer.IsNull())
m_Renderer = mitk::OpenGLRenderer::New();
m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);
m_Renderer->InitRenderer(this);
int * size = m_MitkVtkRenderWindow->GetSize();
if((size[0]>10) && (size[1]>10))
m_Renderer->InitSize(size[0], size[1]);
}
void mitk::RenderWindow::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
if (renWin != NULL)
{
m_MitkVtkRenderWindow = renWin;
InitRenderer();
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "localplaingdbadapter.h"
#include "gdbengine.h"
#include "procinterrupt.h"
#include "debuggerstringutils.h"
#include <utils/qtcassert.h>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtGui/QMessageBox>
namespace Debugger {
namespace Internal {
///////////////////////////////////////////////////////////////////////
//
// PlainGdbAdapter
//
///////////////////////////////////////////////////////////////////////
LocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)
: AbstractPlainGdbAdapter(engine, parent)
{
// Output
connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
engine, SLOT(readDebugeeOutput(QByteArray)));
}
AbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const
{
// LD_PRELOAD fails for System-Qt on Mac.
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
return DumperLoadedByGdb;
#else
return DumperLoadedByGdbPreload;
#endif
}
void LocalPlainGdbAdapter::startAdapter()
{
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
showMessage(_("TRYING TO START ADAPTER"));
QStringList gdbArgs;
if (!m_outputCollector.listen()) {
m_engine->handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
.arg(m_outputCollector.errorString()), QString());
return;
}
gdbArgs.append(_("--tty=") + m_outputCollector.serverName());
if (!startParameters().workingDirectory.isEmpty())
m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
if (!startParameters().environment.isEmpty())
m_gdbProc.setEnvironment(startParameters().environment);
if (!m_engine->startGdb(gdbArgs)) {
m_outputCollector.shutdown();
return;
}
checkForReleaseBuild();
m_engine->handleAdapterStarted();
}
void LocalPlainGdbAdapter::setupInferior()
{
AbstractPlainGdbAdapter::setupInferior();
}
void LocalPlainGdbAdapter::runEngine()
{
AbstractPlainGdbAdapter::runEngine();
}
void LocalPlainGdbAdapter::shutdownInferior()
{
m_engine->defaultInferiorShutdown("kill");
}
void LocalPlainGdbAdapter::shutdownAdapter()
{
showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
m_outputCollector.shutdown();
m_engine->notifyAdapterShutdownOk();
}
void LocalPlainGdbAdapter::checkForReleaseBuild()
{
// Quick check for a "release" build
QProcess proc;
QStringList args;
args.append(_("-h"));
args.append(_("-j"));
args.append(_(".debug_info"));
args.append(startParameters().executable);
proc.start(_("objdump"), args);
proc.closeWriteChannel();
QTC_ASSERT(proc.waitForStarted(), qDebug() << "UNABLE TO RUN OBJDUMP");
proc.waitForFinished();
QByteArray ba = proc.readAllStandardOutput();
// This should yield something like
// "debuggertest: file format elf32-i386\n\n"
// "Sections:\nIdx Name Size VMA LMA File off Algn\n"
// "30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\n"
// " CONTENTS, READONLY, DEBUGGING"
if (ba.contains("Sections:") && !ba.contains(".debug_info")) {
m_engine->showMessageBox(QMessageBox::Information, "Warning",
tr("This does not seem to be a \"Debug\" build.\n"
"Setting breakpoints by file name and line number may fail."));
}
}
void LocalPlainGdbAdapter::interruptInferior()
{
const qint64 attachedPID = m_engine->inferiorPid();
if (attachedPID <= 0) {
showMessage(_("TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED"));
return;
}
if (!interruptProcess(attachedPID)) {
showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID));
m_engine->notifyInferiorStopFailed();
}
}
QByteArray LocalPlainGdbAdapter::execFilePath() const
{
return QFileInfo(startParameters().executable)
.absoluteFilePath().toLocal8Bit();
}
bool LocalPlainGdbAdapter::infoTargetNecessary() const
{
#ifdef Q_OS_LINUX
return true;
#else
return false;
#endif
}
QByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const
{
return s.toLocal8Bit();
}
QString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const
{
return QString::fromLocal8Bit(b);
}
} // namespace Internal
} // namespace Debugger
<commit_msg>debugger: skip "release build" check if objdump could not be started<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "localplaingdbadapter.h"
#include "gdbengine.h"
#include "procinterrupt.h"
#include "debuggerstringutils.h"
#include <utils/qtcassert.h>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtGui/QMessageBox>
namespace Debugger {
namespace Internal {
///////////////////////////////////////////////////////////////////////
//
// PlainGdbAdapter
//
///////////////////////////////////////////////////////////////////////
LocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)
: AbstractPlainGdbAdapter(engine, parent)
{
// Output
connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
engine, SLOT(readDebugeeOutput(QByteArray)));
}
AbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const
{
// LD_PRELOAD fails for System-Qt on Mac.
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
return DumperLoadedByGdb;
#else
return DumperLoadedByGdbPreload;
#endif
}
void LocalPlainGdbAdapter::startAdapter()
{
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
showMessage(_("TRYING TO START ADAPTER"));
QStringList gdbArgs;
if (!m_outputCollector.listen()) {
m_engine->handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
.arg(m_outputCollector.errorString()), QString());
return;
}
gdbArgs.append(_("--tty=") + m_outputCollector.serverName());
if (!startParameters().workingDirectory.isEmpty())
m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
if (!startParameters().environment.isEmpty())
m_gdbProc.setEnvironment(startParameters().environment);
if (!m_engine->startGdb(gdbArgs)) {
m_outputCollector.shutdown();
return;
}
checkForReleaseBuild();
m_engine->handleAdapterStarted();
}
void LocalPlainGdbAdapter::setupInferior()
{
AbstractPlainGdbAdapter::setupInferior();
}
void LocalPlainGdbAdapter::runEngine()
{
AbstractPlainGdbAdapter::runEngine();
}
void LocalPlainGdbAdapter::shutdownInferior()
{
m_engine->defaultInferiorShutdown("kill");
}
void LocalPlainGdbAdapter::shutdownAdapter()
{
showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
m_outputCollector.shutdown();
m_engine->notifyAdapterShutdownOk();
}
void LocalPlainGdbAdapter::checkForReleaseBuild()
{
// Quick check for a "release" build
QProcess proc;
QStringList args;
args.append(_("-h"));
args.append(_("-j"));
args.append(_(".debug_info"));
args.append(startParameters().executable);
proc.start(_("objdump"), args);
proc.closeWriteChannel();
if (!proc.waitForStarted()) {
showMessage(_("OBJDUMP PROCESS COULD NOT BE STARTED. "
"RELEASE BUILD CHECK WILL FAIL"));
return;
}
proc.waitForFinished();
QByteArray ba = proc.readAllStandardOutput();
// This should yield something like
// "debuggertest: file format elf32-i386\n\n"
// "Sections:\nIdx Name Size VMA LMA File off Algn\n"
// "30 .debug_info 00087d36 00000000 00000000 0006bbd5 2**0\n"
// " CONTENTS, READONLY, DEBUGGING"
if (ba.contains("Sections:") && !ba.contains(".debug_info")) {
m_engine->showMessageBox(QMessageBox::Information, "Warning",
tr("This does not seem to be a \"Debug\" build.\n"
"Setting breakpoints by file name and line number may fail."));
}
}
void LocalPlainGdbAdapter::interruptInferior()
{
const qint64 attachedPID = m_engine->inferiorPid();
if (attachedPID <= 0) {
showMessage(_("TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED"));
return;
}
if (!interruptProcess(attachedPID)) {
showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID));
m_engine->notifyInferiorStopFailed();
}
}
QByteArray LocalPlainGdbAdapter::execFilePath() const
{
return QFileInfo(startParameters().executable)
.absoluteFilePath().toLocal8Bit();
}
bool LocalPlainGdbAdapter::infoTargetNecessary() const
{
#ifdef Q_OS_LINUX
return true;
#else
return false;
#endif
}
QByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const
{
return s.toLocal8Bit();
}
QString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const
{
return QString::fromLocal8Bit(b);
}
} // namespace Internal
} // namespace Debugger
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "multiplication_process.h"
#include <vistk/pipeline_types/port_types.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <algorithm>
namespace vistk
{
class multiplication_process::priv
{
public:
typedef uint32_t number_t;
priv();
~priv();
edge_ref_t input_edge_factor1;
edge_ref_t input_edge_factor2;
edge_group_t output_edges;
port_info_t factor1_port_info;
port_info_t factor2_port_info;
port_info_t output_port_info;
static port_t const INPUT_FACTOR1_PORT_NAME;
static port_t const INPUT_FACTOR2_PORT_NAME;
static port_t const OUTPUT_PORT_NAME;
};
process::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t("factor1");
process::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t("factor2");
process::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t("product");
multiplication_process
::multiplication_process(config_t const& config)
: process(config)
{
d = boost::shared_ptr<priv>(new priv);
}
multiplication_process
::~multiplication_process()
{
}
void
multiplication_process
::_step()
{
datum_t dat;
stamp_t st;
edge_group_t input_edges;
input_edges.push_back(d->input_edge_factor1);
input_edges.push_back(d->input_edge_factor2);
bool const colored = same_colored_edges(input_edges);
bool const syncd = syncd_edges(input_edges);
if (!colored)
{
st = heartbeat_stamp();
dat = datum::error_datum("The input edges are not colored the same.");
}
else if (!syncd)
{
st = heartbeat_stamp();
dat = datum::error_datum("The input edges are not synchronized.");
}
else
{
edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);
edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);
edge_data_t input_dats;
input_dats.push_back(factor1_dat);
input_dats.push_back(factor2_dat);
st = factor1_dat.get<1>();
datum::datum_type_t const max_type = max_status(input_dats);
switch (max_type)
{
case datum::DATUM_DATA:
{
priv::number_t const factor1 = factor1_dat.get<0>()->get_datum<priv::number_t>();
priv::number_t const factor2 = factor2_dat.get<0>()->get_datum<priv::number_t>();
priv::number_t const product = factor1 * factor2;
dat = datum::new_datum(product);
break;
}
case datum::DATUM_EMPTY:
dat = datum::empty_datum();
break;
case datum::DATUM_COMPLETE:
mark_as_complete();
dat = datum::complete_datum();
break;
case datum::DATUM_ERROR:
dat = datum::error_datum("Error on the input edges.");
break;
case datum::DATUM_INVALID:
default:
dat = datum::error_datum("Unrecognized datum type.");
break;
}
}
edge_datum_t const edat = edge_datum_t(dat, st);
push_to_edges(d->output_edges, edat);
process::_step();
}
void
multiplication_process
::_connect_input_port(port_t const& port, edge_t edge)
{
if (port == priv::INPUT_FACTOR1_PORT_NAME)
{
if (d->input_edge_factor1.use_count())
{
throw port_reconnect_exception(name(), port);
}
d->input_edge_factor1 = edge_ref_t(edge);
return;
}
if (port == priv::INPUT_FACTOR2_PORT_NAME)
{
if (d->input_edge_factor2.use_count())
{
throw port_reconnect_exception(name(), port);
}
d->input_edge_factor2 = edge_ref_t(edge);
return;
}
process::_connect_input_port(port, edge);
}
process::port_info_t
multiplication_process
::_input_port_info(port_t const& port) const
{
if (port == priv::INPUT_FACTOR1_PORT_NAME)
{
return d->factor1_port_info;
}
if (port == priv::INPUT_FACTOR2_PORT_NAME)
{
return d->factor2_port_info;
}
return process::_input_port_info(port);
}
void
multiplication_process
::_connect_output_port(port_t const& port, edge_t edge)
{
if (port == priv::OUTPUT_PORT_NAME)
{
d->output_edges.push_back(edge_ref_t(edge));
return;
}
process::_connect_output_port(port, edge);
}
process::port_info_t
multiplication_process
::_output_port_info(port_t const& port) const
{
if (port == priv::OUTPUT_PORT_NAME)
{
return d->output_port_info;
}
return process::_output_port_info(port);
}
process::ports_t
multiplication_process
::_input_ports() const
{
ports_t ports;
ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);
ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);
return ports;
}
process::ports_t
multiplication_process
::_output_ports() const
{
ports_t ports;
ports.push_back(priv::OUTPUT_PORT_NAME);
return ports;
}
multiplication_process::priv
::priv()
{
port_flags_t required;
required.insert(flag_required);
factor1_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("The first factor to multiply.")));
factor2_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("The second factor to multiply.")));
output_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("Where the product will be available.")));
}
multiplication_process::priv
::~priv()
{
}
}
<commit_msg>Collect all input edges as received<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "multiplication_process.h"
#include <vistk/pipeline_types/port_types.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>
#include <algorithm>
namespace vistk
{
class multiplication_process::priv
{
public:
typedef uint32_t number_t;
priv();
~priv();
edge_ref_t input_edge_factor1;
edge_ref_t input_edge_factor2;
edge_group_t input_edges;
edge_group_t output_edges;
port_info_t factor1_port_info;
port_info_t factor2_port_info;
port_info_t output_port_info;
static port_t const INPUT_FACTOR1_PORT_NAME;
static port_t const INPUT_FACTOR2_PORT_NAME;
static port_t const OUTPUT_PORT_NAME;
};
process::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t("factor1");
process::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t("factor2");
process::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t("product");
multiplication_process
::multiplication_process(config_t const& config)
: process(config)
{
d = boost::shared_ptr<priv>(new priv);
}
multiplication_process
::~multiplication_process()
{
}
void
multiplication_process
::_step()
{
datum_t dat;
stamp_t st;
bool const colored = same_colored_edges(d->input_edges);
bool const syncd = syncd_edges(d->input_edges);
if (!colored)
{
st = heartbeat_stamp();
dat = datum::error_datum("The input edges are not colored the same.");
}
else if (!syncd)
{
st = heartbeat_stamp();
dat = datum::error_datum("The input edges are not synchronized.");
}
else
{
edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);
edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);
edge_data_t input_dats;
input_dats.push_back(factor1_dat);
input_dats.push_back(factor2_dat);
st = factor1_dat.get<1>();
datum::datum_type_t const max_type = max_status(input_dats);
switch (max_type)
{
case datum::DATUM_DATA:
{
priv::number_t const factor1 = factor1_dat.get<0>()->get_datum<priv::number_t>();
priv::number_t const factor2 = factor2_dat.get<0>()->get_datum<priv::number_t>();
priv::number_t const product = factor1 * factor2;
dat = datum::new_datum(product);
break;
}
case datum::DATUM_EMPTY:
dat = datum::empty_datum();
break;
case datum::DATUM_COMPLETE:
mark_as_complete();
dat = datum::complete_datum();
break;
case datum::DATUM_ERROR:
dat = datum::error_datum("Error on the input edges.");
break;
case datum::DATUM_INVALID:
default:
dat = datum::error_datum("Unrecognized datum type.");
break;
}
}
edge_datum_t const edat = edge_datum_t(dat, st);
push_to_edges(d->output_edges, edat);
process::_step();
}
void
multiplication_process
::_connect_input_port(port_t const& port, edge_t edge)
{
if (port == priv::INPUT_FACTOR1_PORT_NAME)
{
if (d->input_edge_factor1.use_count())
{
throw port_reconnect_exception(name(), port);
}
d->input_edge_factor1 = edge_ref_t(edge);
d->input_edges.push_back(d->input_edge_factor1);
return;
}
if (port == priv::INPUT_FACTOR2_PORT_NAME)
{
if (d->input_edge_factor2.use_count())
{
throw port_reconnect_exception(name(), port);
}
d->input_edge_factor2 = edge_ref_t(edge);
d->input_edges.push_back(d->input_edge_factor2);
return;
}
process::_connect_input_port(port, edge);
}
process::port_info_t
multiplication_process
::_input_port_info(port_t const& port) const
{
if (port == priv::INPUT_FACTOR1_PORT_NAME)
{
return d->factor1_port_info;
}
if (port == priv::INPUT_FACTOR2_PORT_NAME)
{
return d->factor2_port_info;
}
return process::_input_port_info(port);
}
void
multiplication_process
::_connect_output_port(port_t const& port, edge_t edge)
{
if (port == priv::OUTPUT_PORT_NAME)
{
d->output_edges.push_back(edge_ref_t(edge));
return;
}
process::_connect_output_port(port, edge);
}
process::port_info_t
multiplication_process
::_output_port_info(port_t const& port) const
{
if (port == priv::OUTPUT_PORT_NAME)
{
return d->output_port_info;
}
return process::_output_port_info(port);
}
process::ports_t
multiplication_process
::_input_ports() const
{
ports_t ports;
ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);
ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);
return ports;
}
process::ports_t
multiplication_process
::_output_ports() const
{
ports_t ports;
ports.push_back(priv::OUTPUT_PORT_NAME);
return ports;
}
multiplication_process::priv
::priv()
{
port_flags_t required;
required.insert(flag_required);
factor1_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("The first factor to multiply.")));
factor2_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("The second factor to multiply.")));
output_port_info = port_info_t(new port_info(
port_types::t_integer,
required,
port_description_t("Where the product will be available.")));
}
multiplication_process::priv
::~priv()
{
}
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(COMPLEXTYPEINFO_HPP)
#define COMPLEXTYPEINFO_HPP
/**
* The class act as a place holder to store complex type information.
*
* The class is intended for internal use.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/RefHash2KeysTableOf.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLContentModel.hpp>
#include <xercesc/validators/schema/SchemaAttDef.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Forward Declarations
// ---------------------------------------------------------------------------
class DatatypeValidator;
class ContentSpecNode;
class SchemaAttDefList;
class SchemaElementDecl;
class XSDLocator;
class VALIDATORS_EXPORT ComplexTypeInfo
{
public:
// -----------------------------------------------------------------------
// Public Constructors/Destructor
// -----------------------------------------------------------------------
ComplexTypeInfo();
~ComplexTypeInfo();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
bool getAbstract() const;
bool getAdoptContentSpec() const;
bool containsAttWithTypeId() const;
bool getPreprocessed() const;
int getDerivedBy() const;
int getBlockSet() const;
int getFinalSet() const;
int getScopeDefined() const;
unsigned int getElementId() const;
int getContentType() const;
unsigned int elementCount() const;
XMLCh* getTypeName() const;
DatatypeValidator* getBaseDatatypeValidator() const;
DatatypeValidator* getDatatypeValidator() const;
ComplexTypeInfo* getBaseComplexTypeInfo() const;
ContentSpecNode* getContentSpec() const;
const SchemaAttDef* getAttWildCard() const;
SchemaAttDef* getAttWildCard();
const SchemaAttDef* getAttDef(const XMLCh* const baseName,
const int uriId) const;
SchemaAttDef* getAttDef(const XMLCh* const baseName,
const int uriId);
XMLAttDefList& getAttDefList() const;
const SchemaElementDecl* elementAt(const unsigned int index) const;
SchemaElementDecl* elementAt(const unsigned int index);
XMLContentModel* getContentModel(const bool checkUPA = false);
const XMLCh* getFormattedContentModel () const;
XSDLocator* getLocator() const;
/**
* returns true if this type is anonymous
**/
bool getAnonymous() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setAbstract(const bool isAbstract);
void setAdoptContentSpec(const bool toAdopt);
void setAttWithTypeId(const bool value);
void setPreprocessed(const bool aValue = true);
void setDerivedBy(const int derivedBy);
void setBlockSet(const int blockSet);
void setFinalSet(const int finalSet);
void setScopeDefined(const int scopeDefined);
void setElementId(const unsigned int elemId);
void setTypeName(const XMLCh* const typeName);
void setContentType(const int contentType);
void setBaseDatatypeValidator(DatatypeValidator* const baseValidator);
void setDatatypeValidator(DatatypeValidator* const validator);
void setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo);
void setContentSpec(ContentSpecNode* const toAdopt);
void setAttWildCard(SchemaAttDef* const toAdopt);
void addAttDef(SchemaAttDef* const toAdd);
void addElement(SchemaElementDecl* const toAdd);
void setContentModel(XMLContentModel* const newModelToAdopt);
void setLocator(XSDLocator* const aLocator);
/**
* sets this type to be anonymous
**/
void setAnonymous();
// -----------------------------------------------------------------------
// Helper methods
// -----------------------------------------------------------------------
bool hasAttDefs() const;
bool contains(const XMLCh* const attName);
XMLAttDef* findAttr
(
const XMLCh* const qName
, const unsigned int uriId
, const XMLCh* const baseName
, const XMLCh* const prefix
, const XMLElementDecl::LookupOpts options
, bool& wasAdded
) const;
bool resetDefs();
void checkUniqueParticleAttribution
(
SchemaGrammar* const pGrammar
, GrammarResolver* const pGrammarResolver
, XMLStringPool* const pStringPool
, XMLValidator* const pValidator
) ;
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
ComplexTypeInfo(const ComplexTypeInfo& elemInfo);
ComplexTypeInfo& operator= (const ComplexTypeInfo& other);
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
void faultInAttDefList() const;
XMLContentModel* createChildModel(ContentSpecNode* specNode, const bool isMixed);
XMLContentModel* makeContentModel(const bool checkUPA = false, ContentSpecNode* const specNode = 0);
XMLCh* formatContentModel () const ;
ContentSpecNode* expandContentModel(ContentSpecNode* const curNode, const int minOccurs, const int maxOccurs);
ContentSpecNode* convertContentSpecTree(ContentSpecNode* const curNode, const bool checkUPA = false);
void resizeContentSpecOrgURI();
// -----------------------------------------------------------------------
// Private data members
// -----------------------------------------------------------------------
bool fAbstract;
bool fAdoptContentSpec;
bool fAttWithTypeId;
bool fPreprocessed;
int fDerivedBy;
int fBlockSet;
int fFinalSet;
int fScopeDefined;
unsigned int fElementId;
int fContentType;
XMLCh* fTypeName;
DatatypeValidator* fBaseDatatypeValidator;
DatatypeValidator* fDatatypeValidator;
ComplexTypeInfo* fBaseComplexTypeInfo;
ContentSpecNode* fContentSpec;
SchemaAttDef* fAttWildCard;
RefHash2KeysTableOf<SchemaAttDef>* fAttDefs;
SchemaAttDefList* fAttList;
RefVectorOf<SchemaElementDecl>* fElements;
XMLContentModel* fContentModel;
XMLCh* fFormattedModel;
unsigned int* fContentSpecOrgURI;
unsigned int fUniqueURI;
unsigned int fContentSpecOrgURISize;
RefVectorOf<ContentSpecNode>* fSpecNodesToDelete;
XSDLocator* fLocator;
bool fAnonymous;
};
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Getter methods
// ---------------------------------------------------------------------------
inline bool ComplexTypeInfo::getAbstract() const {
return fAbstract;
}
inline bool ComplexTypeInfo::getAdoptContentSpec() const {
return fAdoptContentSpec;
}
inline bool ComplexTypeInfo::containsAttWithTypeId() const {
return fAttWithTypeId;
}
inline bool ComplexTypeInfo::getPreprocessed() const {
return fPreprocessed;
}
inline int ComplexTypeInfo::getDerivedBy() const {
return fDerivedBy;
}
inline int ComplexTypeInfo::getBlockSet() const {
return fBlockSet;
}
inline int ComplexTypeInfo::getFinalSet() const {
return fFinalSet;
}
inline int ComplexTypeInfo::getScopeDefined() const {
return fScopeDefined;
}
inline unsigned int ComplexTypeInfo::getElementId() const {
return fElementId;
}
inline int ComplexTypeInfo::getContentType() const {
return fContentType;
}
inline unsigned int ComplexTypeInfo::elementCount() const {
if (fElements) {
return fElements->size();
}
return 0;
}
inline XMLCh* ComplexTypeInfo::getTypeName() const {
return fTypeName;
}
inline DatatypeValidator* ComplexTypeInfo::getBaseDatatypeValidator() const {
return fBaseDatatypeValidator;
}
inline DatatypeValidator* ComplexTypeInfo::getDatatypeValidator() const {
return fDatatypeValidator;
}
inline ComplexTypeInfo* ComplexTypeInfo::getBaseComplexTypeInfo() const {
return fBaseComplexTypeInfo;
}
inline ContentSpecNode* ComplexTypeInfo::getContentSpec() const {
return fContentSpec;
}
inline const SchemaAttDef* ComplexTypeInfo::getAttWildCard() const {
return fAttWildCard;
}
inline SchemaAttDef* ComplexTypeInfo::getAttWildCard() {
return fAttWildCard;
}
inline const SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,
const int uriId) const {
// If no list, then return a null
if (!fAttDefs)
return 0;
return fAttDefs->get(baseName, uriId);
}
inline SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,
const int uriId)
{
// If no list, then return a null
if (!fAttDefs)
return 0;
return fAttDefs->get(baseName, uriId);
}
inline SchemaElementDecl*
ComplexTypeInfo::elementAt(const unsigned int index) {
if (!fElements) {
return 0; // REVISIT - need to throw an exception
}
return fElements->elementAt(index);
}
inline const SchemaElementDecl*
ComplexTypeInfo::elementAt(const unsigned int index) const {
if (!fElements) {
return 0; // REVISIT - need to throw an exception
}
return fElements->elementAt(index);
}
inline XMLContentModel* ComplexTypeInfo::getContentModel(const bool checkUPA)
{
if (!fContentModel)
fContentModel = makeContentModel(checkUPA);
return fContentModel;
}
inline XSDLocator* ComplexTypeInfo::getLocator() const
{
return fLocator;
}
inline bool ComplexTypeInfo::getAnonymous() const {
return fAnonymous;
}
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Setter methods
// ---------------------------------------------------------------------------
inline void ComplexTypeInfo::setAbstract(const bool isAbstract) {
fAbstract = isAbstract;
}
inline void ComplexTypeInfo::setAdoptContentSpec(const bool toAdopt) {
fAdoptContentSpec = toAdopt;
}
inline void ComplexTypeInfo::setAttWithTypeId(const bool value) {
fAttWithTypeId = value;
}
inline void ComplexTypeInfo::setPreprocessed(const bool aValue) {
fPreprocessed = aValue;
}
inline void ComplexTypeInfo::setDerivedBy(const int derivedBy) {
fDerivedBy = derivedBy;
}
inline void ComplexTypeInfo::setBlockSet(const int blockSet) {
fBlockSet = blockSet;
}
inline void ComplexTypeInfo::setFinalSet(const int finalSet) {
fFinalSet = finalSet;
}
inline void ComplexTypeInfo::setScopeDefined(const int scopeDefined) {
fScopeDefined = scopeDefined;
}
inline void ComplexTypeInfo::setElementId(const unsigned int elemId) {
fElementId = elemId;
}
inline void
ComplexTypeInfo::setContentType(const int contentType) {
fContentType = contentType;
}
inline void ComplexTypeInfo::setTypeName(const XMLCh* const typeName) {
if (fTypeName != 0) {
delete [] fTypeName;
}
fTypeName = XMLString::replicate(typeName);
}
inline void
ComplexTypeInfo::setBaseDatatypeValidator(DatatypeValidator* const validator) {
fBaseDatatypeValidator = validator;
}
inline void
ComplexTypeInfo::setDatatypeValidator(DatatypeValidator* const validator) {
fDatatypeValidator = validator;
}
inline void
ComplexTypeInfo::setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo) {
fBaseComplexTypeInfo = typeInfo;
}
inline void ComplexTypeInfo::addElement(SchemaElementDecl* const elem) {
if (!fElements) {
fElements = new RefVectorOf<SchemaElementDecl>(8, false);
}
else if (fElements->containsElement(elem)) {
return;
}
fElements->addElement(elem);
}
inline void ComplexTypeInfo::setAttWildCard(SchemaAttDef* const toAdopt) {
if (fAttWildCard) {
delete fAttWildCard;
}
fAttWildCard = toAdopt;
}
inline void
ComplexTypeInfo::setContentModel(XMLContentModel* const newModelToAdopt)
{
delete fContentModel;
fContentModel = newModelToAdopt;
}
inline void ComplexTypeInfo::setAnonymous() {
fAnonymous = true;
}
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Helper methods
// ---------------------------------------------------------------------------
inline bool ComplexTypeInfo::hasAttDefs() const
{
// If the collection hasn't been faulted in, then no att defs
if (!fAttDefs)
return false;
return !fAttDefs->isEmpty();
}
inline bool ComplexTypeInfo::contains(const XMLCh* const attName) {
if (!fAttDefs) {
return false;
}
RefHash2KeysTableOfEnumerator<SchemaAttDef> enumDefs(fAttDefs);
while (enumDefs.hasMoreElements()) {
if (XMLString::equals(attName, enumDefs.nextElement().getAttName()->getLocalPart())) {
return true;
}
}
return false;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file ComplexTypeInfo.hpp
*/
<commit_msg>Performance: move declaration around can help optimization<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(COMPLEXTYPEINFO_HPP)
#define COMPLEXTYPEINFO_HPP
/**
* The class act as a place holder to store complex type information.
*
* The class is intended for internal use.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/RefHash2KeysTableOf.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLContentModel.hpp>
#include <xercesc/validators/schema/SchemaAttDef.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Forward Declarations
// ---------------------------------------------------------------------------
class DatatypeValidator;
class ContentSpecNode;
class SchemaAttDefList;
class SchemaElementDecl;
class XSDLocator;
class VALIDATORS_EXPORT ComplexTypeInfo
{
public:
// -----------------------------------------------------------------------
// Public Constructors/Destructor
// -----------------------------------------------------------------------
ComplexTypeInfo();
~ComplexTypeInfo();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
bool getAbstract() const;
bool getAdoptContentSpec() const;
bool containsAttWithTypeId() const;
bool getPreprocessed() const;
int getDerivedBy() const;
int getBlockSet() const;
int getFinalSet() const;
int getScopeDefined() const;
unsigned int getElementId() const;
int getContentType() const;
unsigned int elementCount() const;
XMLCh* getTypeName() const;
DatatypeValidator* getBaseDatatypeValidator() const;
DatatypeValidator* getDatatypeValidator() const;
ComplexTypeInfo* getBaseComplexTypeInfo() const;
ContentSpecNode* getContentSpec() const;
const SchemaAttDef* getAttWildCard() const;
SchemaAttDef* getAttWildCard();
const SchemaAttDef* getAttDef(const XMLCh* const baseName,
const int uriId) const;
SchemaAttDef* getAttDef(const XMLCh* const baseName,
const int uriId);
XMLAttDefList& getAttDefList() const;
const SchemaElementDecl* elementAt(const unsigned int index) const;
SchemaElementDecl* elementAt(const unsigned int index);
XMLContentModel* getContentModel(const bool checkUPA = false);
const XMLCh* getFormattedContentModel () const;
XSDLocator* getLocator() const;
/**
* returns true if this type is anonymous
**/
bool getAnonymous() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setAbstract(const bool isAbstract);
void setAdoptContentSpec(const bool toAdopt);
void setAttWithTypeId(const bool value);
void setPreprocessed(const bool aValue = true);
void setDerivedBy(const int derivedBy);
void setBlockSet(const int blockSet);
void setFinalSet(const int finalSet);
void setScopeDefined(const int scopeDefined);
void setElementId(const unsigned int elemId);
void setTypeName(const XMLCh* const typeName);
void setContentType(const int contentType);
void setBaseDatatypeValidator(DatatypeValidator* const baseValidator);
void setDatatypeValidator(DatatypeValidator* const validator);
void setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo);
void setContentSpec(ContentSpecNode* const toAdopt);
void setAttWildCard(SchemaAttDef* const toAdopt);
void addAttDef(SchemaAttDef* const toAdd);
void addElement(SchemaElementDecl* const toAdd);
void setContentModel(XMLContentModel* const newModelToAdopt);
void setLocator(XSDLocator* const aLocator);
/**
* sets this type to be anonymous
**/
void setAnonymous();
// -----------------------------------------------------------------------
// Helper methods
// -----------------------------------------------------------------------
bool hasAttDefs() const;
bool contains(const XMLCh* const attName);
XMLAttDef* findAttr
(
const XMLCh* const qName
, const unsigned int uriId
, const XMLCh* const baseName
, const XMLCh* const prefix
, const XMLElementDecl::LookupOpts options
, bool& wasAdded
) const;
bool resetDefs();
void checkUniqueParticleAttribution
(
SchemaGrammar* const pGrammar
, GrammarResolver* const pGrammarResolver
, XMLStringPool* const pStringPool
, XMLValidator* const pValidator
) ;
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
ComplexTypeInfo(const ComplexTypeInfo& elemInfo);
ComplexTypeInfo& operator= (const ComplexTypeInfo& other);
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
void faultInAttDefList() const;
XMLContentModel* createChildModel(ContentSpecNode* specNode, const bool isMixed);
XMLContentModel* makeContentModel(const bool checkUPA = false, ContentSpecNode* const specNode = 0);
XMLCh* formatContentModel () const ;
ContentSpecNode* expandContentModel(ContentSpecNode* const curNode, const int minOccurs, const int maxOccurs);
ContentSpecNode* convertContentSpecTree(ContentSpecNode* const curNode, const bool checkUPA = false);
void resizeContentSpecOrgURI();
// -----------------------------------------------------------------------
// Private data members
// -----------------------------------------------------------------------
bool fAbstract;
bool fAdoptContentSpec;
bool fAttWithTypeId;
bool fPreprocessed;
int fDerivedBy;
int fBlockSet;
int fFinalSet;
int fScopeDefined;
unsigned int fElementId;
int fContentType;
XMLCh* fTypeName;
DatatypeValidator* fBaseDatatypeValidator;
DatatypeValidator* fDatatypeValidator;
ComplexTypeInfo* fBaseComplexTypeInfo;
ContentSpecNode* fContentSpec;
SchemaAttDef* fAttWildCard;
SchemaAttDefList* fAttList;
RefVectorOf<SchemaElementDecl>* fElements;
RefVectorOf<ContentSpecNode>* fSpecNodesToDelete;
RefHash2KeysTableOf<SchemaAttDef>* fAttDefs;
XMLContentModel* fContentModel;
XMLCh* fFormattedModel;
unsigned int* fContentSpecOrgURI;
unsigned int fUniqueURI;
unsigned int fContentSpecOrgURISize;
XSDLocator* fLocator;
bool fAnonymous;
};
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Getter methods
// ---------------------------------------------------------------------------
inline bool ComplexTypeInfo::getAbstract() const {
return fAbstract;
}
inline bool ComplexTypeInfo::getAdoptContentSpec() const {
return fAdoptContentSpec;
}
inline bool ComplexTypeInfo::containsAttWithTypeId() const {
return fAttWithTypeId;
}
inline bool ComplexTypeInfo::getPreprocessed() const {
return fPreprocessed;
}
inline int ComplexTypeInfo::getDerivedBy() const {
return fDerivedBy;
}
inline int ComplexTypeInfo::getBlockSet() const {
return fBlockSet;
}
inline int ComplexTypeInfo::getFinalSet() const {
return fFinalSet;
}
inline int ComplexTypeInfo::getScopeDefined() const {
return fScopeDefined;
}
inline unsigned int ComplexTypeInfo::getElementId() const {
return fElementId;
}
inline int ComplexTypeInfo::getContentType() const {
return fContentType;
}
inline unsigned int ComplexTypeInfo::elementCount() const {
if (fElements) {
return fElements->size();
}
return 0;
}
inline XMLCh* ComplexTypeInfo::getTypeName() const {
return fTypeName;
}
inline DatatypeValidator* ComplexTypeInfo::getBaseDatatypeValidator() const {
return fBaseDatatypeValidator;
}
inline DatatypeValidator* ComplexTypeInfo::getDatatypeValidator() const {
return fDatatypeValidator;
}
inline ComplexTypeInfo* ComplexTypeInfo::getBaseComplexTypeInfo() const {
return fBaseComplexTypeInfo;
}
inline ContentSpecNode* ComplexTypeInfo::getContentSpec() const {
return fContentSpec;
}
inline const SchemaAttDef* ComplexTypeInfo::getAttWildCard() const {
return fAttWildCard;
}
inline SchemaAttDef* ComplexTypeInfo::getAttWildCard() {
return fAttWildCard;
}
inline const SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,
const int uriId) const {
// If no list, then return a null
if (!fAttDefs)
return 0;
return fAttDefs->get(baseName, uriId);
}
inline SchemaAttDef* ComplexTypeInfo::getAttDef(const XMLCh* const baseName,
const int uriId)
{
// If no list, then return a null
if (!fAttDefs)
return 0;
return fAttDefs->get(baseName, uriId);
}
inline SchemaElementDecl*
ComplexTypeInfo::elementAt(const unsigned int index) {
if (!fElements) {
return 0; // REVISIT - need to throw an exception
}
return fElements->elementAt(index);
}
inline const SchemaElementDecl*
ComplexTypeInfo::elementAt(const unsigned int index) const {
if (!fElements) {
return 0; // REVISIT - need to throw an exception
}
return fElements->elementAt(index);
}
inline XMLContentModel* ComplexTypeInfo::getContentModel(const bool checkUPA)
{
if (!fContentModel)
fContentModel = makeContentModel(checkUPA);
return fContentModel;
}
inline XSDLocator* ComplexTypeInfo::getLocator() const
{
return fLocator;
}
inline bool ComplexTypeInfo::getAnonymous() const {
return fAnonymous;
}
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Setter methods
// ---------------------------------------------------------------------------
inline void ComplexTypeInfo::setAbstract(const bool isAbstract) {
fAbstract = isAbstract;
}
inline void ComplexTypeInfo::setAdoptContentSpec(const bool toAdopt) {
fAdoptContentSpec = toAdopt;
}
inline void ComplexTypeInfo::setAttWithTypeId(const bool value) {
fAttWithTypeId = value;
}
inline void ComplexTypeInfo::setPreprocessed(const bool aValue) {
fPreprocessed = aValue;
}
inline void ComplexTypeInfo::setDerivedBy(const int derivedBy) {
fDerivedBy = derivedBy;
}
inline void ComplexTypeInfo::setBlockSet(const int blockSet) {
fBlockSet = blockSet;
}
inline void ComplexTypeInfo::setFinalSet(const int finalSet) {
fFinalSet = finalSet;
}
inline void ComplexTypeInfo::setScopeDefined(const int scopeDefined) {
fScopeDefined = scopeDefined;
}
inline void ComplexTypeInfo::setElementId(const unsigned int elemId) {
fElementId = elemId;
}
inline void
ComplexTypeInfo::setContentType(const int contentType) {
fContentType = contentType;
}
inline void ComplexTypeInfo::setTypeName(const XMLCh* const typeName) {
if (fTypeName != 0) {
delete [] fTypeName;
}
fTypeName = XMLString::replicate(typeName);
}
inline void
ComplexTypeInfo::setBaseDatatypeValidator(DatatypeValidator* const validator) {
fBaseDatatypeValidator = validator;
}
inline void
ComplexTypeInfo::setDatatypeValidator(DatatypeValidator* const validator) {
fDatatypeValidator = validator;
}
inline void
ComplexTypeInfo::setBaseComplexTypeInfo(ComplexTypeInfo* const typeInfo) {
fBaseComplexTypeInfo = typeInfo;
}
inline void ComplexTypeInfo::addElement(SchemaElementDecl* const elem) {
if (!fElements) {
fElements = new RefVectorOf<SchemaElementDecl>(8, false);
}
else if (fElements->containsElement(elem)) {
return;
}
fElements->addElement(elem);
}
inline void ComplexTypeInfo::setAttWildCard(SchemaAttDef* const toAdopt) {
if (fAttWildCard) {
delete fAttWildCard;
}
fAttWildCard = toAdopt;
}
inline void
ComplexTypeInfo::setContentModel(XMLContentModel* const newModelToAdopt)
{
delete fContentModel;
fContentModel = newModelToAdopt;
}
inline void ComplexTypeInfo::setAnonymous() {
fAnonymous = true;
}
// ---------------------------------------------------------------------------
// ComplexTypeInfo: Helper methods
// ---------------------------------------------------------------------------
inline bool ComplexTypeInfo::hasAttDefs() const
{
// If the collection hasn't been faulted in, then no att defs
if (!fAttDefs)
return false;
return !fAttDefs->isEmpty();
}
inline bool ComplexTypeInfo::contains(const XMLCh* const attName) {
if (!fAttDefs) {
return false;
}
RefHash2KeysTableOfEnumerator<SchemaAttDef> enumDefs(fAttDefs);
while (enumDefs.hasMoreElements()) {
if (XMLString::equals(attName, enumDefs.nextElement().getAttName()->getLocalPart())) {
return true;
}
}
return false;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file ComplexTypeInfo.hpp
*/
<|endoftext|> |
<commit_before>/**
* @file mixGasTransport.cpp
* test problem for mixture transport
*/
// Example
//
// Test case for mixture transport in a gas
// The basic idea is to set up a gradient of some kind.
// Then the resulting transport coefficients out.
// Essentially all of the interface routines should be
// exercised and the results dumped out.
//
// A blessed solution test will make sure that the actual
// solution doesn't change as a function of time or
// further development.
// perhaps, later, an analytical solution could be added
#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
#define MAX(x,y) (( (x) > (y) ) ? (x) : (y))
/*****************************************************************/
/*****************************************************************/
#include "Cantera.h"
#include "transport.h"
#include "IdealGasMix.h"
#include "kernel/TransportFactory.h"
using namespace Cantera;
void printDbl(double val) {
if (fabs(val) < 5.0E-17) {
cout << " nil";
} else {
cout << val;
}
}
int main(int argc, char** argv) {
int k;
string infile = "diamond.xml";
try {
IdealGasMix g("gri30.xml", "gri30_mix");
int nsp = g.nSpecies();
double pres = 1.0E5;
vector_fp Xset(nsp, 0.0);
Xset[0] = 0.269205 ;
Xset[1] = 0.000107082;
Xset[2] = 1.36377e-09 ;
Xset[3] = 4.35475e-10;
Xset[4] = 4.34036e-06 ;
Xset[5] = 0.192249;
Xset[6] = 3.59356e-13;
Xset[7] = 2.78061e-12 ;
Xset[8] = 4.7406e-18 ;
Xset[9] = 4.12955e-17 ;
Xset[10] = 2.58549e-14 ;
Xset[11] = 8.96502e-16 ;
Xset[12] = 6.09056e-11 ;
Xset[13] = 7.56752e-09 ;
Xset[14] = 0.192253;
Xset[15] = 0.0385036;
Xset[16] = 1.49596e-08 ;
Xset[17] = 2.22378e-08 ;
Xset[18] = 1.43096e-13 ;
Xset[19] = 1.45312e-15 ;
Xset[20] = 1.96948e-12 ;
Xset[21] = 8.41937e-19;
Xset[22] = 3.18852e-13 ;
Xset[23] = 7.93625e-18 ;
Xset[24] = 3.20653e-15 ;
Xset[25] = 1.15149e-19 ;
Xset[26] = 1.61189e-18 ;
Xset[27] = 1.4719e-15 ;
Xset[28] = 5.24728e-13 ;
Xset[29] = 6.90582e-17 ;
Xset[30] = 6.37248e-12 ;
Xset[31] =5.93728e-11 ;
Xset[32] = 2.71219e-09 ;
Xset[33] = 2.66645e-06 ;
Xset[34] = 6.57142e-11 ;
Xset[35] = 9.52453e-08 ;
Xset[36] = 1.26006e-14;
Xset[37] = 3.49802e-12;
Xset[38] = 1.19232e-11 ;
Xset[39] = 7.17782e-13 ;
Xset[40] = 1.85347e-07 ;
Xset[41] = 8.25325e-14 ;
Xset[42] = 5.00914e-20 ;
Xset[43] = 1.54407e-16 ;
Xset[44] =3.07176e-11 ;
Xset[45] =4.93198e-08 ;
Xset[46] =4.84792e-12 ;
Xset[47] = 0.307675 ;
Xset[48] =0;
Xset[49] =6.21649e-29;
Xset[50] = 8.42393e-28 ;
Xset[51] = 6.77865e-18;
Xset[52] = 2.19225e-16;
double T1 = 1500.;
double sum = 0.0;
for (k = 0; k < nsp; k++) {
sum += Xset[k];
}
for (k = 0; k < nsp; k++) {
Xset[k] /= sum;
}
vector_fp X2set(nsp, 0.0);
X2set[0] = 0.25 ;
X2set[5] = 0.17;
X2set[14] = 0.15;
X2set[15] = 0.05;
X2set[47] = 0.38 ;
double T2 = 1200.;
double dist = 0.1;
vector_fp X3set(nsp, 0.0);
X3set[0] = 0.27 ;
X3set[5] = 0.15;
X3set[14] = 0.18;
X3set[15] = 0.06;
X3set[47] = 0.36 ;
double T3 = 1400.;
vector_fp grad_T(3, 0.0);
Array2D grad_X(nsp, 2, 0.0);
for( k = 0; k < nsp; k++) {
grad_X(k,0) = (X2set[k] - Xset[k])/dist;
grad_X(k,1) = (X3set[k] - Xset[k])/dist;
}
grad_T[0] = (T2 - T1) / dist;
grad_T[1] = (T3 - T1) / dist;
int log_level = 0;
Transport * tran = newTransportMgr("Mix", &g, log_level=0);
MixTransport * tranMix = dynamic_cast<MixTransport *>(tran);
g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
vector_fp mixDiffs(nsp, 0.0);
tranMix->getMixDiffCoeffs(DATA_PTR(mixDiffs));
printf(" Dump of the mixture Diffusivities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), mixDiffs[k]);
}
vector_fp specVisc(nsp, 0.0);
tranMix->getSpeciesViscosities(DATA_PTR(specVisc));
printf(" Dump of the species viscosities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), specVisc[k]);
}
vector_fp thermDiff(nsp, 0.0);
tranMix->getThermalDiffCoeffs(DATA_PTR(thermDiff));
printf(" Dump of the Thermal Diffusivities :\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), thermDiff[k]);
}
printf("Viscoscity and thermal Cond vs. T\n");
for (k = 0; k < 10; k++) {
T1 = 400. + 100. * k;
g.setState_TPX(T1, pres, DATA_PTR(Xset));
double visc = tran->viscosity();
double cond = tran->thermalConductivity();
printf(" %13g %13.5g %13.5g\n", T1, visc, cond);
}
g.setState_TPX(T1, pres, DATA_PTR(Xset));
Array2D Bdiff(nsp, nsp, 0.0);
printf("Binary Diffusion Coefficients H2 vs species\n");
tranMix->getBinaryDiffCoeffs(nsp, Bdiff.ptrColumn(0));
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" H2 - %15s %13.5g %13.5g\n", sss.c_str(), Bdiff(0,k), Bdiff(k,0));
}
vector_fp specMob(nsp, 0.0);
tranMix->getMobilities(DATA_PTR(specMob));
printf(" Dump of the species mobilities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), specMob[k]);
}
Array2D fluxes(nsp, 2, 0.0);
tranMix->getSpeciesFluxes(2, DATA_PTR(grad_T), nsp,
grad_X.ptrColumn(0), nsp, fluxes.ptrColumn(0));
printf(" Dump of the species fluxes:\n");
double sum1 = 0.0;
double sum2 = 0.0;
double max1 = 0.0;
double max2 = 0.0;
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g %13.5g\n", sss.c_str(), fluxes(k,0), fluxes(k,1));
sum1 += fluxes(k,0);
if (fabs(fluxes(k,0)) > max1) {
max1 = fabs(fluxes(k,0));
}
sum2 += fluxes(k,1);
if (fabs(fluxes(k,1)) > max2) {
max2 = fabs(fluxes(k,0));
}
}
// Make sure roundoff error doesn't interfere with the printout.
// these should be zero.
if (fabs(sum1) * 1.0E14 > max1) {
printf("sum in x direction = %13.5g\n", sum1);
} else {
printf("sum in x direction = 0\n");
}
if (fabs(sum2) * 1.0E14 > max2) {
printf("sum in y direction = %13.5g\n", sum1);
} else {
printf("sum in y direction = 0\n");
}
}
catch (CanteraError) {
showErrors(cout);
}
return 0;
}
/***********************************************************/
<commit_msg>using namespace Cantera_CXX addition<commit_after>/**
* @file mixGasTransport.cpp
* test problem for mixture transport
*/
// Example
//
// Test case for mixture transport in a gas
// The basic idea is to set up a gradient of some kind.
// Then the resulting transport coefficients out.
// Essentially all of the interface routines should be
// exercised and the results dumped out.
//
// A blessed solution test will make sure that the actual
// solution doesn't change as a function of time or
// further development.
// perhaps, later, an analytical solution could be added
#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
#define MAX(x,y) (( (x) > (y) ) ? (x) : (y))
/*****************************************************************/
/*****************************************************************/
#include "Cantera.h"
#include "transport.h"
#include "IdealGasMix.h"
#include "kernel/TransportFactory.h"
using namespace Cantera;
using namespace Cantera_CXX;
void printDbl(double val) {
if (fabs(val) < 5.0E-17) {
cout << " nil";
} else {
cout << val;
}
}
int main(int argc, char** argv) {
int k;
string infile = "diamond.xml";
try {
IdealGasMix g("gri30.xml", "gri30_mix");
int nsp = g.nSpecies();
double pres = 1.0E5;
vector_fp Xset(nsp, 0.0);
Xset[0] = 0.269205 ;
Xset[1] = 0.000107082;
Xset[2] = 1.36377e-09 ;
Xset[3] = 4.35475e-10;
Xset[4] = 4.34036e-06 ;
Xset[5] = 0.192249;
Xset[6] = 3.59356e-13;
Xset[7] = 2.78061e-12 ;
Xset[8] = 4.7406e-18 ;
Xset[9] = 4.12955e-17 ;
Xset[10] = 2.58549e-14 ;
Xset[11] = 8.96502e-16 ;
Xset[12] = 6.09056e-11 ;
Xset[13] = 7.56752e-09 ;
Xset[14] = 0.192253;
Xset[15] = 0.0385036;
Xset[16] = 1.49596e-08 ;
Xset[17] = 2.22378e-08 ;
Xset[18] = 1.43096e-13 ;
Xset[19] = 1.45312e-15 ;
Xset[20] = 1.96948e-12 ;
Xset[21] = 8.41937e-19;
Xset[22] = 3.18852e-13 ;
Xset[23] = 7.93625e-18 ;
Xset[24] = 3.20653e-15 ;
Xset[25] = 1.15149e-19 ;
Xset[26] = 1.61189e-18 ;
Xset[27] = 1.4719e-15 ;
Xset[28] = 5.24728e-13 ;
Xset[29] = 6.90582e-17 ;
Xset[30] = 6.37248e-12 ;
Xset[31] =5.93728e-11 ;
Xset[32] = 2.71219e-09 ;
Xset[33] = 2.66645e-06 ;
Xset[34] = 6.57142e-11 ;
Xset[35] = 9.52453e-08 ;
Xset[36] = 1.26006e-14;
Xset[37] = 3.49802e-12;
Xset[38] = 1.19232e-11 ;
Xset[39] = 7.17782e-13 ;
Xset[40] = 1.85347e-07 ;
Xset[41] = 8.25325e-14 ;
Xset[42] = 5.00914e-20 ;
Xset[43] = 1.54407e-16 ;
Xset[44] =3.07176e-11 ;
Xset[45] =4.93198e-08 ;
Xset[46] =4.84792e-12 ;
Xset[47] = 0.307675 ;
Xset[48] =0;
Xset[49] =6.21649e-29;
Xset[50] = 8.42393e-28 ;
Xset[51] = 6.77865e-18;
Xset[52] = 2.19225e-16;
double T1 = 1500.;
double sum = 0.0;
for (k = 0; k < nsp; k++) {
sum += Xset[k];
}
for (k = 0; k < nsp; k++) {
Xset[k] /= sum;
}
vector_fp X2set(nsp, 0.0);
X2set[0] = 0.25 ;
X2set[5] = 0.17;
X2set[14] = 0.15;
X2set[15] = 0.05;
X2set[47] = 0.38 ;
double T2 = 1200.;
double dist = 0.1;
vector_fp X3set(nsp, 0.0);
X3set[0] = 0.27 ;
X3set[5] = 0.15;
X3set[14] = 0.18;
X3set[15] = 0.06;
X3set[47] = 0.36 ;
double T3 = 1400.;
vector_fp grad_T(3, 0.0);
Array2D grad_X(nsp, 2, 0.0);
for( k = 0; k < nsp; k++) {
grad_X(k,0) = (X2set[k] - Xset[k])/dist;
grad_X(k,1) = (X3set[k] - Xset[k])/dist;
}
grad_T[0] = (T2 - T1) / dist;
grad_T[1] = (T3 - T1) / dist;
int log_level = 0;
Transport * tran = newTransportMgr("Mix", &g, log_level=0);
MixTransport * tranMix = dynamic_cast<MixTransport *>(tran);
g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
vector_fp mixDiffs(nsp, 0.0);
tranMix->getMixDiffCoeffs(DATA_PTR(mixDiffs));
printf(" Dump of the mixture Diffusivities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), mixDiffs[k]);
}
vector_fp specVisc(nsp, 0.0);
tranMix->getSpeciesViscosities(DATA_PTR(specVisc));
printf(" Dump of the species viscosities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), specVisc[k]);
}
vector_fp thermDiff(nsp, 0.0);
tranMix->getThermalDiffCoeffs(DATA_PTR(thermDiff));
printf(" Dump of the Thermal Diffusivities :\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), thermDiff[k]);
}
printf("Viscoscity and thermal Cond vs. T\n");
for (k = 0; k < 10; k++) {
T1 = 400. + 100. * k;
g.setState_TPX(T1, pres, DATA_PTR(Xset));
double visc = tran->viscosity();
double cond = tran->thermalConductivity();
printf(" %13g %13.5g %13.5g\n", T1, visc, cond);
}
g.setState_TPX(T1, pres, DATA_PTR(Xset));
Array2D Bdiff(nsp, nsp, 0.0);
printf("Binary Diffusion Coefficients H2 vs species\n");
tranMix->getBinaryDiffCoeffs(nsp, Bdiff.ptrColumn(0));
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" H2 - %15s %13.5g %13.5g\n", sss.c_str(), Bdiff(0,k), Bdiff(k,0));
}
vector_fp specMob(nsp, 0.0);
tranMix->getMobilities(DATA_PTR(specMob));
printf(" Dump of the species mobilities:\n");
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g\n", sss.c_str(), specMob[k]);
}
Array2D fluxes(nsp, 2, 0.0);
tranMix->getSpeciesFluxes(2, DATA_PTR(grad_T), nsp,
grad_X.ptrColumn(0), nsp, fluxes.ptrColumn(0));
printf(" Dump of the species fluxes:\n");
double sum1 = 0.0;
double sum2 = 0.0;
double max1 = 0.0;
double max2 = 0.0;
for (k = 0; k < nsp; k++) {
string sss = g.speciesName(k);
printf(" %15s %13.5g %13.5g\n", sss.c_str(), fluxes(k,0), fluxes(k,1));
sum1 += fluxes(k,0);
if (fabs(fluxes(k,0)) > max1) {
max1 = fabs(fluxes(k,0));
}
sum2 += fluxes(k,1);
if (fabs(fluxes(k,1)) > max2) {
max2 = fabs(fluxes(k,0));
}
}
// Make sure roundoff error doesn't interfere with the printout.
// these should be zero.
if (fabs(sum1) * 1.0E14 > max1) {
printf("sum in x direction = %13.5g\n", sum1);
} else {
printf("sum in x direction = 0\n");
}
if (fabs(sum2) * 1.0E14 > max2) {
printf("sum in y direction = %13.5g\n", sum1);
} else {
printf("sum in y direction = 0\n");
}
}
catch (CanteraError) {
showErrors(cout);
}
return 0;
}
/***********************************************************/
<|endoftext|> |
<commit_before><commit_msg>Don't consider as danger obstacles moving a least than 2 m/s<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2013 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 "content/browser/web_contents/aura/window_slider.h"
#include "base/bind.h"
#include "base/callback.h"
#include "content/browser/web_contents/aura/shadow_layer_delegate.h"
#include "content/public/browser/overscroll_configuration.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
namespace content {
namespace {
// An animation observer that runs a callback at the end of the animation, and
// destroys itself.
class CallbackAnimationObserver : public ui::ImplicitAnimationObserver {
public:
CallbackAnimationObserver(const base::Closure& closure)
: closure_(closure) {
}
virtual ~CallbackAnimationObserver() {}
private:
// Overridden from ui::ImplicitAnimationObserver:
virtual void OnImplicitAnimationsCompleted() OVERRIDE {
if (!closure_.is_null())
closure_.Run();
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
const base::Closure closure_;
DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
};
} // namespace
WindowSlider::WindowSlider(Delegate* delegate,
aura::Window* event_window,
aura::Window* owner)
: delegate_(delegate),
event_window_(event_window),
owner_(owner),
delta_x_(0.f),
weak_factory_(this),
min_start_threshold_(content::GetOverscrollConfig(
content::OVERSCROLL_CONFIG_MIN_THRESHOLD_START)),
complete_threshold_(content::GetOverscrollConfig(
content::OVERSCROLL_CONFIG_HORIZ_THRESHOLD_COMPLETE)) {
event_window_->AddPreTargetHandler(this);
event_window_->AddObserver(this);
owner_->AddObserver(this);
}
WindowSlider::~WindowSlider() {
delegate_->OnWindowSliderDestroyed();
if (event_window_) {
event_window_->RemovePreTargetHandler(this);
event_window_->RemoveObserver(this);
}
if (owner_)
owner_->RemoveObserver(this);
}
void WindowSlider::ChangeOwner(aura::Window* new_owner) {
if (owner_)
owner_->RemoveObserver(this);
owner_ = new_owner;
if (owner_) {
owner_->AddObserver(this);
UpdateForScroll(0.f, 0.f);
}
}
void WindowSlider::SetupSliderLayer() {
ui::Layer* parent = owner_->layer()->parent();
parent->Add(slider_.get());
if (delta_x_ < 0)
parent->StackAbove(slider_.get(), owner_->layer());
else
parent->StackBelow(slider_.get(), owner_->layer());
slider_->SetBounds(owner_->layer()->bounds());
slider_->SetVisible(true);
}
void WindowSlider::UpdateForScroll(float x_offset, float y_offset) {
float old_delta = delta_x_;
delta_x_ += x_offset;
if (fabs(delta_x_) < min_start_threshold_) {
ResetScroll();
return;
}
if ((old_delta < 0 && delta_x_ > 0) ||
(old_delta > 0 && delta_x_ < 0)) {
slider_.reset();
shadow_.reset();
}
float translate = 0.f;
ui::Layer* translate_layer = NULL;
if (delta_x_ <= -min_start_threshold_) {
if (!slider_.get()) {
slider_.reset(delegate_->CreateFrontLayer());
SetupSliderLayer();
}
translate = event_window_->bounds().width() -
fabs(delta_x_ - min_start_threshold_);
translate_layer = slider_.get();
} else if (delta_x_ >= min_start_threshold_) {
if (!slider_.get()) {
slider_.reset(delegate_->CreateBackLayer());
SetupSliderLayer();
}
translate = delta_x_ - min_start_threshold_;
translate_layer = owner_->layer();
} else {
NOTREACHED();
}
if (!shadow_.get())
shadow_.reset(new ShadowLayerDelegate(translate_layer));
gfx::Transform transform;
transform.Translate(translate, 0);
translate_layer->SetTransform(transform);
}
void WindowSlider::UpdateForFling(float x_velocity, float y_velocity) {
if (fabs(delta_x_) < min_start_threshold_)
return;
int width = owner_->bounds().width();
float ratio = (fabs(delta_x_) - min_start_threshold_) / width;
if (ratio < complete_threshold_) {
ResetScroll();
return;
}
ui::Layer* sliding = delta_x_ < 0 ? slider_.get() : owner_->layer();
ui::ScopedLayerAnimationSettings settings(sliding->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&WindowSlider::CompleteWindowSlideAfterAnimation,
weak_factory_.GetWeakPtr())));
gfx::Transform transform;
transform.Translate(delta_x_ < 0 ? 0 : width, 0);
sliding->SetTransform(transform);
}
void WindowSlider::ResetScroll() {
if (!slider_.get())
return;
// Do not trigger any callbacks if this animation replaces any in-progress
// animation.
weak_factory_.InvalidateWeakPtrs();
// Reset the state of the sliding layer.
if (slider_.get()) {
ui::Layer* layer = slider_.release();
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&base::DeletePointer<ui::Layer>,
base::Unretained(layer))));
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&base::DeletePointer<ShadowLayerDelegate>,
base::Unretained(shadow_.release()))));
gfx::Transform transform;
transform.Translate(delta_x_ < 0 ? layer->bounds().width() : 0, 0);
layer->SetTransform(transform);
}
// Reset the state of the main layer.
{
ui::ScopedLayerAnimationSettings settings(owner_->layer()->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&WindowSlider::AbortWindowSlideAfterAnimation,
weak_factory_.GetWeakPtr())));
owner_->layer()->SetTransform(gfx::Transform());
owner_->layer()->SetLayerBrightness(0.f);
}
delta_x_ = 0.f;
}
void WindowSlider::CancelScroll() {
ResetScroll();
}
void WindowSlider::CompleteWindowSlideAfterAnimation() {
delegate_->OnWindowSlideComplete();
delete this;
}
void WindowSlider::AbortWindowSlideAfterAnimation() {
delegate_->OnWindowSlideAborted();
}
void WindowSlider::OnKeyEvent(ui::KeyEvent* event) {
CancelScroll();
}
void WindowSlider::OnMouseEvent(ui::MouseEvent* event) {
if (!(event->flags() & ui::EF_IS_SYNTHESIZED))
CancelScroll();
}
void WindowSlider::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL)
UpdateForScroll(event->x_offset_ordinal(), event->y_offset_ordinal());
else if (event->type() == ui::ET_SCROLL_FLING_START)
UpdateForFling(event->x_offset_ordinal(), event->y_offset_ordinal());
else
CancelScroll();
event->SetHandled();
}
void WindowSlider::OnGestureEvent(ui::GestureEvent* event) {
const ui::GestureEventDetails& details = event->details();
switch (event->type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
ResetScroll();
break;
case ui::ET_GESTURE_SCROLL_UPDATE:
UpdateForScroll(details.scroll_x(), details.scroll_y());
break;
case ui::ET_GESTURE_SCROLL_END:
UpdateForFling(0.f, 0.f);
break;
case ui::ET_SCROLL_FLING_START:
UpdateForFling(details.velocity_x(), details.velocity_y());
break;
case ui::ET_GESTURE_PINCH_BEGIN:
case ui::ET_GESTURE_PINCH_UPDATE:
case ui::ET_GESTURE_PINCH_END:
CancelScroll();
break;
default:
break;
}
event->SetHandled();
}
void WindowSlider::OnWindowRemovingFromRootWindow(aura::Window* window) {
if (window == event_window_) {
window->RemoveObserver(this);
window->RemovePreTargetHandler(this);
event_window_ = NULL;
} else if (window == owner_) {
window->RemoveObserver(this);
owner_ = NULL;
if (!slider_.get())
delete this;
} else {
NOTREACHED();
}
}
} // namespace content
<commit_msg>aura: Fix a valgrind error in WindowSlider.<commit_after>// Copyright (c) 2013 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 "content/browser/web_contents/aura/window_slider.h"
#include "base/bind.h"
#include "base/callback.h"
#include "content/browser/web_contents/aura/shadow_layer_delegate.h"
#include "content/public/browser/overscroll_configuration.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
namespace content {
namespace {
void DeleteLayerAndShadow(ui::Layer* layer,
ShadowLayerDelegate* shadow) {
delete shadow;
delete layer;
}
// An animation observer that runs a callback at the end of the animation, and
// destroys itself.
class CallbackAnimationObserver : public ui::ImplicitAnimationObserver {
public:
CallbackAnimationObserver(const base::Closure& closure)
: closure_(closure) {
}
virtual ~CallbackAnimationObserver() {}
private:
// Overridden from ui::ImplicitAnimationObserver:
virtual void OnImplicitAnimationsCompleted() OVERRIDE {
if (!closure_.is_null())
closure_.Run();
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
const base::Closure closure_;
DISALLOW_COPY_AND_ASSIGN(CallbackAnimationObserver);
};
} // namespace
WindowSlider::WindowSlider(Delegate* delegate,
aura::Window* event_window,
aura::Window* owner)
: delegate_(delegate),
event_window_(event_window),
owner_(owner),
delta_x_(0.f),
weak_factory_(this),
min_start_threshold_(content::GetOverscrollConfig(
content::OVERSCROLL_CONFIG_MIN_THRESHOLD_START)),
complete_threshold_(content::GetOverscrollConfig(
content::OVERSCROLL_CONFIG_HORIZ_THRESHOLD_COMPLETE)) {
event_window_->AddPreTargetHandler(this);
event_window_->AddObserver(this);
owner_->AddObserver(this);
}
WindowSlider::~WindowSlider() {
delegate_->OnWindowSliderDestroyed();
if (event_window_) {
event_window_->RemovePreTargetHandler(this);
event_window_->RemoveObserver(this);
}
if (owner_)
owner_->RemoveObserver(this);
}
void WindowSlider::ChangeOwner(aura::Window* new_owner) {
if (owner_)
owner_->RemoveObserver(this);
owner_ = new_owner;
if (owner_) {
owner_->AddObserver(this);
UpdateForScroll(0.f, 0.f);
}
}
void WindowSlider::SetupSliderLayer() {
ui::Layer* parent = owner_->layer()->parent();
parent->Add(slider_.get());
if (delta_x_ < 0)
parent->StackAbove(slider_.get(), owner_->layer());
else
parent->StackBelow(slider_.get(), owner_->layer());
slider_->SetBounds(owner_->layer()->bounds());
slider_->SetVisible(true);
}
void WindowSlider::UpdateForScroll(float x_offset, float y_offset) {
float old_delta = delta_x_;
delta_x_ += x_offset;
if (fabs(delta_x_) < min_start_threshold_) {
ResetScroll();
return;
}
if ((old_delta < 0 && delta_x_ > 0) ||
(old_delta > 0 && delta_x_ < 0)) {
slider_.reset();
shadow_.reset();
}
float translate = 0.f;
ui::Layer* translate_layer = NULL;
if (delta_x_ <= -min_start_threshold_) {
if (!slider_.get()) {
slider_.reset(delegate_->CreateFrontLayer());
SetupSliderLayer();
}
translate = event_window_->bounds().width() -
fabs(delta_x_ - min_start_threshold_);
translate_layer = slider_.get();
} else if (delta_x_ >= min_start_threshold_) {
if (!slider_.get()) {
slider_.reset(delegate_->CreateBackLayer());
SetupSliderLayer();
}
translate = delta_x_ - min_start_threshold_;
translate_layer = owner_->layer();
} else {
NOTREACHED();
}
if (!shadow_.get())
shadow_.reset(new ShadowLayerDelegate(translate_layer));
gfx::Transform transform;
transform.Translate(translate, 0);
translate_layer->SetTransform(transform);
}
void WindowSlider::UpdateForFling(float x_velocity, float y_velocity) {
if (fabs(delta_x_) < min_start_threshold_)
return;
int width = owner_->bounds().width();
float ratio = (fabs(delta_x_) - min_start_threshold_) / width;
if (ratio < complete_threshold_) {
ResetScroll();
return;
}
ui::Layer* sliding = delta_x_ < 0 ? slider_.get() : owner_->layer();
ui::ScopedLayerAnimationSettings settings(sliding->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&WindowSlider::CompleteWindowSlideAfterAnimation,
weak_factory_.GetWeakPtr())));
gfx::Transform transform;
transform.Translate(delta_x_ < 0 ? 0 : width, 0);
sliding->SetTransform(transform);
}
void WindowSlider::ResetScroll() {
if (!slider_.get())
return;
// Do not trigger any callbacks if this animation replaces any in-progress
// animation.
weak_factory_.InvalidateWeakPtrs();
// Reset the state of the sliding layer.
if (slider_.get()) {
ui::Layer* layer = slider_.release();
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
// Delete the layer and the shadow at the end of the animation.
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&DeleteLayerAndShadow,
base::Unretained(layer),
base::Unretained(shadow_.release()))));
gfx::Transform transform;
transform.Translate(delta_x_ < 0 ? layer->bounds().width() : 0, 0);
layer->SetTransform(transform);
}
// Reset the state of the main layer.
{
ui::ScopedLayerAnimationSettings settings(owner_->layer()->GetAnimator());
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
settings.SetTweenType(ui::Tween::EASE_OUT);
settings.AddObserver(new CallbackAnimationObserver(
base::Bind(&WindowSlider::AbortWindowSlideAfterAnimation,
weak_factory_.GetWeakPtr())));
owner_->layer()->SetTransform(gfx::Transform());
owner_->layer()->SetLayerBrightness(0.f);
}
delta_x_ = 0.f;
}
void WindowSlider::CancelScroll() {
ResetScroll();
}
void WindowSlider::CompleteWindowSlideAfterAnimation() {
delegate_->OnWindowSlideComplete();
delete this;
}
void WindowSlider::AbortWindowSlideAfterAnimation() {
delegate_->OnWindowSlideAborted();
}
void WindowSlider::OnKeyEvent(ui::KeyEvent* event) {
CancelScroll();
}
void WindowSlider::OnMouseEvent(ui::MouseEvent* event) {
if (!(event->flags() & ui::EF_IS_SYNTHESIZED))
CancelScroll();
}
void WindowSlider::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL)
UpdateForScroll(event->x_offset_ordinal(), event->y_offset_ordinal());
else if (event->type() == ui::ET_SCROLL_FLING_START)
UpdateForFling(event->x_offset_ordinal(), event->y_offset_ordinal());
else
CancelScroll();
event->SetHandled();
}
void WindowSlider::OnGestureEvent(ui::GestureEvent* event) {
const ui::GestureEventDetails& details = event->details();
switch (event->type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
ResetScroll();
break;
case ui::ET_GESTURE_SCROLL_UPDATE:
UpdateForScroll(details.scroll_x(), details.scroll_y());
break;
case ui::ET_GESTURE_SCROLL_END:
UpdateForFling(0.f, 0.f);
break;
case ui::ET_SCROLL_FLING_START:
UpdateForFling(details.velocity_x(), details.velocity_y());
break;
case ui::ET_GESTURE_PINCH_BEGIN:
case ui::ET_GESTURE_PINCH_UPDATE:
case ui::ET_GESTURE_PINCH_END:
CancelScroll();
break;
default:
break;
}
event->SetHandled();
}
void WindowSlider::OnWindowRemovingFromRootWindow(aura::Window* window) {
if (window == event_window_) {
window->RemoveObserver(this);
window->RemovePreTargetHandler(this);
event_window_ = NULL;
} else if (window == owner_) {
window->RemoveObserver(this);
owner_ = NULL;
if (!slider_.get())
delete this;
} else {
NOTREACHED();
}
}
} // namespace content
<|endoftext|> |
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, [email protected]
*/
/*! \file DynamicalSystem.hpp
\brief Abstract class - General interface for all Dynamical Systems.
*/
#ifndef PLUGIN_HPP
#define PLUGIN_HPP
#include "SiconosSharedLibrary.hpp"
class Plugin
{
public:
static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName, std::string& name)
{
SSL::setFunction(f, pluginPath, functionName);
name = pluginPath.substr(0, pluginPath.length() - 3) + ":" + functionName;
return true;
}
static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName)
{
SSL::setFunction(f, pluginPath, functionName);
return true;
}
static bool setFunction(void* f, const std::string& Name)
{
SSL::setFunction(f, SSL::getPluginName(Name), SSL::getPluginFunctionName(Name));
return true;
}
};
#endif
<commit_msg>Plugin: update doc<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, [email protected]
*/
/*! \file Plugin.hpp
\brief Class to deal with functions given as C functions
*/
#ifndef PLUGIN_HPP
#define PLUGIN_HPP
#include "SiconosSharedLibrary.hpp"
class Plugin
{
public:
static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName, std::string& name)
{
SSL::setFunction(f, pluginPath, functionName);
name = pluginPath.substr(0, pluginPath.length() - 3) + ":" + functionName;
return true;
}
static bool setFunction(void* f, const std::string& pluginPath, const std::string& functionName)
{
SSL::setFunction(f, pluginPath, functionName);
return true;
}
static bool setFunction(void* f, const std::string& Name)
{
SSL::setFunction(f, SSL::getPluginName(Name), SSL::getPluginFunctionName(Name));
return true;
}
};
#endif
<|endoftext|> |
<commit_before>// Do not remove the include below
#include "LCD_Experiments.h"
/*
SainSmart GL_ST7735 LCD/microSD module
www.sainsmart.com
Signal Definition TFT LCD):
GND : Power Ground
VCC : 5V power input (3.3V might work)
CS : Chipselect for LCD, (use pin 10)
SDA : LCD Data for SPI (use MOSI, pin 11)
SCL : SCLK for TFT Clock (use SCLK, pin 13)
RS/DC : Command/Data Selection (use pin 9)
RESET : LCD controller reset, active low (use pin 8)
Signal Definition micro-SD):
CS (SD-CS) : Chipselect for TF Card,
CLK (SD-Clock) : SPI Clock
MOSI (SD-DI) : SPI Master out Slave in
MISO (SD-DO) : SPI Master in Slave out
Methods that may be called:
Create an instance:
GL_ST7735(uint8_t CS, uint8_t RS, uint8_t SID,
uint8_t SCLK, uint8_t RST);
GL_ST7735(uint8_t CS, uint8_t RS, uint8_t RST);
Description
The base class for drawing to the GL_ST7735. Use this to create a named
instance of the GL_ST7735 class to refer to in your sketch.
Syntax
GL_ST7735(cs, dc, rst); for using hardware SPI
GL_ST7735(cs, dc, mosi, sclk, rst); for use on any pins
Parameters
cs : int, pin for chip select
dc : int, pin used for data/command
rst : int, pin used for reset
mosi : int, pin used for MOSI communication when not using hardware SPI
sclk : int, pin used for the shared clock, when not using hardware SPI
Returns
none
The screen can be configured for use in two ways. One is to use an Arduino's
hardware SPI interface. The other is to declare all the pins manually. There
is no difference in the functionality of the screen between the two methods,
but using hardware SPI is significantly faster.
If you plan on using the SD card on the TFT module, you must use hardware SPI.
All examples in the library are written for hardware SPI use.
If using hardware SPI with the Uno, you only need to declare the
CS, DC, and RESET pins,
as MOSI (pin 11) and SCLK (pin 13) are already defined.
#define CS 10
#define DC 9
#define RESET 8
GL_ST7735 myScreen = GL_ST7735(CS, DC, RESET);
Initialize an ST7735B:
void initB(void);
Initialize an ST7735R:
void initR(void);
Drawing primitives:
void pushColor(uint16_t color);
void drawPixel(uint8_t x, uint8_t y, uint16_t color);
void drawLine(int16_t x, int16_t y, int16_t x1, int16_t y1, uint16_t color);
void fillScreen(uint16_t color);
void drawVerticalLine(uint8_t x0, uint8_t y0,
uint8_t length, uint16_t color);
void drawHorizontalLine(uint8_t x0, uint8_t y0,
uint8_t length, uint16_t color);
void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,
uint16_t color);
void fillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,
uint16_t color);
void drawCircle(uint8_t x0, uint8_t y0, uint8_t r,
uint16_t color);
void fillCircle(uint8_t x0, uint8_t y0, uint8_t r,
uint16_t color);
void drawString(uint8_t x, uint8_t y, char *c,
uint16_t color, uint8_t size=1);
void drawChar(uint8_t x, uint8_t y, char c,
uint16_t color, uint8_t size=1);
static const uint8_t width = 128;
static const uint8_t height = 160;
Low level:
void setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1);
void writecommand(uint8_t);
void writedata(uint8_t);
void setRotation(uint8_t);
uint8_t getRotation(void);
void drawFastLine(uint8_t x0, uint8_t y0, uint8_t l,
uint16_t color, uint8_t flag);
Commented out:
void dummyclock(void);
x starts on the left and increases to the right.
x goes from 0 to .width - 1
y starts at the top and increases downward.
y goes from 0 to .height - 1
strings are drawn with the stated position being the upper left corner.
circles are drawn with the stated position being the center of the circle.
*/
const byte CS = 10 ;
const byte DC = 9 ;
const byte RESET = 8 ;
GL_ST7735 lcd = GL_ST7735(CS, DC, RESET);
GLBall ball[] = {GLBall(&lcd), GLBall(&lcd), GLBall(&lcd)} ;
const unsigned int xBouncesToRepeat = 33 ;
unsigned int xBouncesRemaining = xBouncesToRepeat ;
//
// This program displays a test pattern on the LCD screen,
// waits two seconds,
// then clears the screen and displays a "ball" that bounces around
// the LCD screen. The ball leaves a trail as it goes.
//
void setup()
{
enum States {
red1, red2, red3,
green1, green2, green3,
blue1, blue2, blue3
} ;
States state = red1 ;
char strResult[17] ;
int offset = 0 ;
unsigned int color = RED ;
lcd.initR() ;
clearScreen(lcd) ; // Clear screen.
Serial.begin(115200) ;
//
// Draw test pattern including string for line number.
//
for (unsigned int i=1; i<=lcd.height; i++) {
const int size = 1 ; // size may be 1, 2, 3, 4, 5, 6, or 7.
// size of 1 is smallest, size of 7 is largest.
//
// Clear space for new data.
// Provides space for 3 digits.
//
lcd.fillRect( 10, 51, 18*size, 8*size, BLACK) ;
//
// Write line number.
//
lcd.drawString(10, 51, itoa(i, strResult, 10), WHITE, size) ;
//
// Draw the line.
//
lcd.drawHorizontalLine(offset, i-1, lcd.width-offset, color) ;
// delay(10) ;
if (i<lcd.width) {
offset++ ;
} else {
offset-- ;
}
//
// Prepare for the next line.
//
switch (state) {
case red1:
state = red2 ;
break ;
case red2:
state = red3 ;
break ;
case red3:
state = green1 ;
color = GREEN ;
break ;
case green1:
state = green2 ;
break ;
case green2:
state = green3 ;
break ;
case green3:
state = blue1 ;
color = BLUE ;
break ;
case blue1:
state = blue2 ;
break ;
case blue2:
state = blue3 ;
break ;
case blue3:
state = red1 ;
color = RED ;
break ;
default:
state = red1 ;
color = RED ;
break ;
}
}
delay(1000) ;
clearScreen(lcd) ;
//
// Draw ellipses.
//
// This ellipse is centered at (60,80),
// has major semi-axis of 50,
// has minor semi-axis that varies,
// and has a rotation angle of 20 degrees.
//
lcd.drawEllipse(60, 80, 50, 10, 90, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, 80, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, 70, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, 60, CYAN ) ;
lcd.drawEllipse(60, 80, 50, 10, 50, RED ) ;
lcd.drawEllipse(60, 80, 50, 10, 40, GREEN ) ;
lcd.drawEllipse(60, 80, 50, 10, 30, BLUE ) ;
lcd.drawEllipse(60, 80, 50, 10, 20, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, 10, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, 0, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, -10, CYAN ) ;
lcd.drawEllipse(60, 80, 50, 10, -20, RED ) ;
lcd.drawEllipse(60, 80, 50, 10, -30, GREEN ) ;
lcd.drawEllipse(60, 80, 50, 10, -40, BLUE ) ;
lcd.drawEllipse(60, 80, 50, 10, -50, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, -60, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, -70, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, -80, CYAN ) ;
delay(2000) ;
clearScreen(lcd) ;
const int delta = 8 ;
int iPrevious = 0 ;
for (int i = 6 ; i <= 54 ; i+=delta ) {
lcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; // Draw new.
if (iPrevious>0) {
lcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK);// Erase previous.
}
iPrevious = i ;
}
for (int i = 46 ; i >= 6 ; i-=delta) {
lcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; // Draw new.
lcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK) ; // Erase previous.
iPrevious = i ;
}
delay(2000) ;
clearScreen(lcd) ;
//
// Set up ball parameters
//
ball[0].setBallColor(YELLOW)
.setTrailColor(RED)
.setRadius(2)
.setXCurrent(50)
.setYCurrent(50)
.setYVel(-ball[0].getYVel())
.begin() ;
ball[1].setBallColor(CYAN)
.setTrailColor(YELLOW)
.begin() ;
ball[2].setBallColor(MAGENTA)
.setTrailColor(GREEN)
.setRadius(8)
.setXCurrent(50)
.setYCurrent(ball[2].getRadius())
.setXVel(-ball[2].getXVel())
.begin() ;
}
void loop() {
//
// Knowing when it is time to switch trail colors
//
int xVelPrevious = ball[1].getXVel();
for (int i = 0; i <= 2; i++) {
if (i != 1) {
ball[i].update();
} else {
if (ball[i].update()) {
int xVelCurrent = ball[i].getXVel();
if (xVelCurrent == -xVelPrevious) {
xBouncesRemaining--;
}
if (xBouncesRemaining == 0) {
for (int j = 0; j <= 2; j++) {
ball[j].setTrailColor(~ball[j].getTrailColor());
ball[j].setBallColor(~ball[j].getBallColor());
}
xBouncesRemaining = xBouncesToRepeat;
}
}
}
}
}
void clearScreen(GL_ST7735 obj) {
obj.fillRect(0, 0, lcd.width, lcd.height, BLACK); // Clear screen.
}
<commit_msg>Make use of new method setInverted(...) to inveert and then non-invert display color of final ellipse.<commit_after>// Do not remove the include below
#include "LCD_Experiments.h"
/*
SainSmart GL_ST7735 LCD/microSD module
www.sainsmart.com
Signal Definition TFT LCD):
GND : Power Ground
VCC : 5V power input (3.3V might work)
CS : Chipselect for LCD, (use pin 10)
SDA : LCD Data for SPI (use MOSI, pin 11)
SCL : SCLK for TFT Clock (use SCLK, pin 13)
RS/DC : Command/Data Selection (use pin 9)
RESET : LCD controller reset, active low (use pin 8)
Signal Definition micro-SD):
CS (SD-CS) : Chipselect for TF Card,
CLK (SD-Clock) : SPI Clock
MOSI (SD-DI) : SPI Master out Slave in
MISO (SD-DO) : SPI Master in Slave out
Methods that may be called:
Create an instance:
GL_ST7735(uint8_t CS, uint8_t RS, uint8_t SID,
uint8_t SCLK, uint8_t RST);
GL_ST7735(uint8_t CS, uint8_t RS, uint8_t RST);
Description
The base class for drawing to the GL_ST7735. Use this to create a named
instance of the GL_ST7735 class to refer to in your sketch.
Syntax
GL_ST7735(cs, dc, rst); for using hardware SPI
GL_ST7735(cs, dc, mosi, sclk, rst); for use on any pins
Parameters
cs : int, pin for chip select
dc : int, pin used for data/command
rst : int, pin used for reset
mosi : int, pin used for MOSI communication when not using hardware SPI
sclk : int, pin used for the shared clock, when not using hardware SPI
Returns
none
The screen can be configured for use in two ways. One is to use an Arduino's
hardware SPI interface. The other is to declare all the pins manually. There
is no difference in the functionality of the screen between the two methods,
but using hardware SPI is significantly faster.
If you plan on using the SD card on the TFT module, you must use hardware SPI.
All examples in the library are written for hardware SPI use.
If using hardware SPI with the Uno, you only need to declare the
CS, DC, and RESET pins,
as MOSI (pin 11) and SCLK (pin 13) are already defined.
#define CS 10
#define DC 9
#define RESET 8
GL_ST7735 myScreen = GL_ST7735(CS, DC, RESET);
Initialize an ST7735B:
void initB(void);
Initialize an ST7735R:
void initR(void);
Drawing primitives:
void pushColor(uint16_t color);
void drawPixel(uint8_t x, uint8_t y, uint16_t color);
void drawLine(int16_t x, int16_t y, int16_t x1, int16_t y1, uint16_t color);
void fillScreen(uint16_t color);
void drawVerticalLine(uint8_t x0, uint8_t y0,
uint8_t length, uint16_t color);
void drawHorizontalLine(uint8_t x0, uint8_t y0,
uint8_t length, uint16_t color);
void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,
uint16_t color);
void fillRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h,
uint16_t color);
void drawCircle(uint8_t x0, uint8_t y0, uint8_t r,
uint16_t color);
void fillCircle(uint8_t x0, uint8_t y0, uint8_t r,
uint16_t color);
void drawString(uint8_t x, uint8_t y, char *c,
uint16_t color, uint8_t size=1);
void drawChar(uint8_t x, uint8_t y, char c,
uint16_t color, uint8_t size=1);
static const uint8_t width = 128;
static const uint8_t height = 160;
Low level:
void setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1);
void writecommand(uint8_t);
void writedata(uint8_t);
void setRotation(uint8_t);
uint8_t getRotation(void);
void drawFastLine(uint8_t x0, uint8_t y0, uint8_t l,
uint16_t color, uint8_t flag);
Commented out:
void dummyclock(void);
x starts on the left and increases to the right.
x goes from 0 to .width - 1
y starts at the top and increases downward.
y goes from 0 to .height - 1
strings are drawn with the stated position being the upper left corner.
circles are drawn with the stated position being the center of the circle.
*/
const byte CS = 10 ;
const byte DC = 9 ;
const byte RESET = 8 ;
GL_ST7735 lcd = GL_ST7735(CS, DC, RESET);
GLBall ball[] = {GLBall(&lcd), GLBall(&lcd), GLBall(&lcd)} ;
const unsigned int xBouncesToRepeat = 33 ;
unsigned int xBouncesRemaining = xBouncesToRepeat ;
//
// This program displays a test pattern on the LCD screen,
// waits two seconds,
// then clears the screen and displays a "ball" that bounces around
// the LCD screen. The ball leaves a trail as it goes.
//
void setup()
{
enum States {
red1, red2, red3,
green1, green2, green3,
blue1, blue2, blue3
} ;
States state = red1 ;
char strResult[17] ;
int offset = 0 ;
unsigned int color = RED ;
lcd.initR() ;
clearScreen(lcd) ; // Clear screen.
Serial.begin(115200) ;
//
// Draw test pattern including string for line number.
//
for (unsigned int i=1; i<=lcd.height; i++) {
const int size = 1 ; // size may be 1, 2, 3, 4, 5, 6, or 7.
// size of 1 is smallest, size of 7 is largest.
//
// Clear space for new data.
// Provides space for 3 digits.
//
lcd.fillRect( 10, 51, 18*size, 8*size, BLACK) ;
//
// Write line number.
//
lcd.drawString(10, 51, itoa(i, strResult, 10), WHITE, size) ;
//
// Draw the line.
//
lcd.drawHorizontalLine(offset, i-1, lcd.width-offset, color) ;
// delay(10) ;
if (i<lcd.width) {
offset++ ;
} else {
offset-- ;
}
//
// Prepare for the next line.
//
switch (state) {
case red1:
state = red2 ;
break ;
case red2:
state = red3 ;
break ;
case red3:
state = green1 ;
color = GREEN ;
break ;
case green1:
state = green2 ;
break ;
case green2:
state = green3 ;
break ;
case green3:
state = blue1 ;
color = BLUE ;
break ;
case blue1:
state = blue2 ;
break ;
case blue2:
state = blue3 ;
break ;
case blue3:
state = red1 ;
color = RED ;
break ;
default:
state = red1 ;
color = RED ;
break ;
}
}
delay(1000) ;
clearScreen(lcd) ;
//
// Draw ellipses.
//
// This ellipse is centered at (60,80),
// has major semi-axis of 50,
// has minor semi-axis that varies,
// and has a rotation angle of 20 degrees.
//
lcd.drawEllipse(60, 80, 50, 10, 90, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, 80, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, 70, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, 60, CYAN ) ;
lcd.drawEllipse(60, 80, 50, 10, 50, RED ) ;
lcd.drawEllipse(60, 80, 50, 10, 40, GREEN ) ;
lcd.drawEllipse(60, 80, 50, 10, 30, BLUE ) ;
lcd.drawEllipse(60, 80, 50, 10, 20, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, 10, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, 0, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, -10, CYAN ) ;
lcd.drawEllipse(60, 80, 50, 10, -20, RED ) ;
lcd.drawEllipse(60, 80, 50, 10, -30, GREEN ) ;
lcd.drawEllipse(60, 80, 50, 10, -40, BLUE ) ;
lcd.drawEllipse(60, 80, 50, 10, -50, WHITE ) ;
lcd.drawEllipse(60, 80, 50, 10, -60, MAGENTA) ;
lcd.drawEllipse(60, 80, 50, 10, -70, YELLOW ) ;
lcd.drawEllipse(60, 80, 50, 10, -80, CYAN ) ;
delay(2000) ;
clearScreen(lcd) ;
const int delta = 8 ;
int iPrevious = 0 ;
for (int i = 6 ; i <= 54 ; i+=delta ) {
lcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; // Draw new.
if (iPrevious>0) {
lcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK);// Erase previous.
}
iPrevious = i ;
}
for (int i = 46 ; i >= 6 ; i-=delta) {
lcd.drawEllipse(60, 80, 54, i, 20, GREEN) ; // Draw new.
lcd.drawEllipse(60, 80, 54, iPrevious, 20, BLACK) ; // Erase previous.
iPrevious = i ;
}
delay(2000) ;
lcd.setInverted(true) ;
delay(2000) ;
lcd.setInverted(false) ;
delay(2000) ;
clearScreen(lcd) ;
//
// Set up ball parameters
//
ball[0].setBallColor(YELLOW)
.setTrailColor(RED)
.setRadius(2)
.setXCurrent(50)
.setYCurrent(50)
.setYVel(-ball[0].getYVel())
.begin() ;
ball[1].setBallColor(CYAN)
.setTrailColor(YELLOW)
.begin() ;
ball[2].setBallColor(MAGENTA)
.setTrailColor(GREEN)
.setRadius(8)
.setXCurrent(50)
.setYCurrent(ball[2].getRadius())
.setXVel(-ball[2].getXVel())
.begin() ;
}
void loop() {
//
// Knowing when it is time to switch trail colors
//
int xVelPrevious = ball[1].getXVel();
for (int i = 0; i <= 2; i++) {
if (i != 1) {
ball[i].update();
} else {
if (ball[i].update()) {
int xVelCurrent = ball[i].getXVel();
if (xVelCurrent == -xVelPrevious) {
xBouncesRemaining--;
}
if (xBouncesRemaining == 0) {
for (int j = 0; j <= 2; j++) {
ball[j].setTrailColor(~ball[j].getTrailColor());
ball[j].setBallColor(~ball[j].getBallColor());
}
xBouncesRemaining = xBouncesToRepeat;
}
}
}
}
}
void clearScreen(GL_ST7735 obj) {
obj.fillRect(0, 0, lcd.width, lcd.height, BLACK); // Clear screen.
}
<|endoftext|> |
<commit_before>/** @file
*
* @ingroup modularLibrary
*
* @brief A Viewer Object.
*
* @details
*
* @authors Théo de la Hogue
*
* @copyright © 2010, Théo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTViewer.h"
#define thisTTClass TTViewer
#define thisTTClassName "Viewer"
#define thisTTClassTags "viewer"
TTObjectBasePtr TTViewer::instantiate (TTSymbol name, TTValue arguments)
{
return new TTViewer(arguments);
}
extern "C" void TTViewer::registerClass()
{
TTClassRegister(TTSymbol("Viewer"), thisTTClassTags, TTViewer::instantiate);
}
TTViewer::TTViewer(const TTValue& arguments) :
TTCallback(arguments),
mAddress(kTTAdrsEmpty),
mDescription(kTTSym_none),
mType(kTTSym_generic),
mTags(kTTSym_none),
mHighlight(NO),
mFreeze(NO),
mDataspace(kTTSym_none),
mDataspaceUnit(kTTSym_none),
mDataspaceConverter("dataspace"),
mActive(YES)
{
addAttributeWithSetter(Address, kTypeSymbol);
addAttribute(Description, kTypeSymbol);
addAttribute(Type, kTypeSymbol);
addAttribute(Tags, kTypeSymbol);
addAttributeWithSetter(Highlight, kTypeBoolean);
addAttributeWithSetter(Freeze, kTypeBoolean);
addAttribute(Dataspace, kTypeSymbol);
addAttributeProperty(Dataspace, readOnly, YES);
addAttributeProperty(Dataspace, hidden, YES);
addAttributeWithSetter(DataspaceUnit, kTypeSymbol);
addAttributeWithSetter(Active, kTypeBoolean);
addAttributeWithSetter(ReturnedValue, kTypeLocalValue);
addAttributeProperty(ReturnedValue, readOnly, YES);
addAttributeProperty(ReturnedValue, hidden, YES);
addMessageWithArguments(Send);
addMessageProperty(Send, hidden, YES);
addMessageWithArguments(Grab);
addMessageProperty(Grab, hidden, YES);
}
TTViewer::~TTViewer()
{
// disable reception to avoid crash
mActive = NO;
}
TTErr TTViewer::setAddress(const TTValue& value)
{
TTBoolean memoActive = mActive;
mAddress = value[0];
// disable reception to avoid crash
mActive = NO;
// if no address : delete sender, receiver and observers
if (mAddress == kTTAdrsEmpty) {
if (mSender.valid()) {
mSender.set(kTTSym_address, kTTAdrsEmpty);
mSender = TTObject();
}
if (mReceiver.valid()) {
mReceiver.set(kTTSym_address, kTTAdrsEmpty);
mReceiver = TTObject();
}
if (mDataspaceObserver.valid()) {
mDataspaceObserver.set(kTTSym_address, kTTAdrsEmpty);
mDataspaceObserver = TTObject();
}
if (mDataspaceUnitObserver.valid()) {
mDataspaceUnitObserver.set(kTTSym_address, kTTAdrsEmpty);
mDataspaceUnitObserver = TTObject();
}
return kTTErrGeneric;
}
// the default attribute to bind is value
if (mAddress.getAttribute() == NO_ATTRIBUTE)
mAddress.appendAttribute(kTTSym_value);
// create sender if needed
if (!mSender.valid())
mSender = TTObject(kTTSym_Sender);
// change sender address
mSender.set(kTTSym_address, mAddress);
// create receiver if needed
if (!mReceiver.valid()) {
TTValue args;
TTObject returnAddressCallback = TTObject("callback");
returnAddressCallback.set(kTTSym_baton, TTObject(this));
returnAddressCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback));
args.append(returnAddressCallback);
TTObject returnValueCallback = TTObject("callback");
returnValueCallback.set(kTTSym_baton, TTObject(this));
returnValueCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback));
args.append(returnValueCallback);
mReceiver = TTObject(kTTSym_Receiver, args);
}
// change receiver address
mReceiver.set(kTTSym_address, mAddress);
// create dataspace observer if needed
if (!mDataspaceObserver.valid()) {
TTValue args;
TTObject empty;
args.append(empty);
TTObject returnDataspaceCallback = TTObject("callback");
returnDataspaceCallback.set(kTTSym_baton, TTObject(this));
returnDataspaceCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceCallback));
args.append(returnDataspaceCallback);
mDataspaceObserver = TTObject(kTTSym_Receiver, args);
}
// change dataspace observer address and get the value
mDataspaceObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspace));
mDataspaceObserver.send(kTTSym_Get);
// create dataspace unit observer if needed
if (!mDataspaceUnitObserver.valid()) {
TTValue args;
TTObject empty;
args.append(empty);
TTObject returnDataspaceUnitCallback = TTObject("callback");
returnDataspaceUnitCallback.set(kTTSym_baton, TTObject(this));
returnDataspaceUnitCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback));
args.append(returnDataspaceUnitCallback);
mDataspaceUnitObserver = TTObject(kTTSym_Receiver, args);
}
// change dataspace unit observer address and get the value
mDataspaceUnitObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspaceUnit));
mDataspaceUnitObserver.send(kTTSym_Get);
// enable reception
mActive = memoActive;
// refresh
return mReceiver.send(kTTSym_Get);
}
TTErr TTViewer::setActive(const TTValue& value)
{
mActive = value;
if (mReceiver.valid()) {
mReceiver.set(kTTSym_active, mActive);
if (mActive)
return mReceiver.send(kTTSym_Get);
else
return kTTErrNone;
}
return kTTErrGeneric;
}
TTErr TTViewer::setHighlight(const TTValue& value)
{
TTAttributePtr anAttribute = NULL;
TTErr err;
mHighlight = value;
err = this->findAttribute(kTTSym_highlight, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, mHighlight); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTViewer::setFreeze(const TTValue& value)
{
mFreeze = value;
if (mReceiver.valid()) {
// update the value if the Viewer is unfreezed
if (!mFreeze)
return mReceiver.send(kTTSym_Get);
else
return kTTErrNone;
}
return kTTErrGeneric;
}
TTErr TTViewer::setReturnedValue(const TTValue& value)
{
TTAttributePtr anAttribute = NULL;
TTErr err;
mReturnedValue = value;
err = this->findAttribute(kTTSym_returnedValue, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, mReturnedValue); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue)
{
if (!mActive)
return kTTErrNone;
TTValue none, valueToSend;
// insert view unit before "ramp" (except for empty value)
if (inputValue.size() > 0 &&
mDataspaceUnit != kTTSym_none &&
mAddress.getAttribute() == kTTSym_value)
{
TTBoolean ramp = false;
for (TTInt32 i = 0; i < inputValue.size(); i++)
{
if (inputValue[i].type() == kTypeSymbol)
{
TTSymbol s = inputValue[i];
if (s == kTTSym_ramp)
{
ramp = true;
valueToSend.append(mDataspaceUnit);
}
}
valueToSend.append(inputValue[i]);
}
if (!ramp)
valueToSend.append(mDataspaceUnit);
}
else
valueToSend = inputValue;
if (mSender.valid())
return mSender.send(kTTSym_Send, valueToSend);
else
return kTTErrGeneric;
}
TTErr TTViewer::Grab(const TTValue& inputValue, TTValue& outputValue)
{
if (mReceiver.valid()) {
return mReceiver.send(kTTSym_Grab, inputValue, outputValue);
}
return kTTErrGeneric;
}
TTErr TTViewer::setDataspaceUnit(const TTValue& value)
{
TTValue n = value; // use new value to protect the attribute
mDataspaceUnit = value;
return mDataspaceConverter.set("outputUnit", mDataspaceUnit);
// TODO : notifyObservers(kTTSym_dataspaceUnit, n);
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTErr TTViewerReceiveAddressCallback(const TTValue& baton, const TTValue& data)
{
return kTTErrNone;
}
TTErr TTViewerReceiveValueCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue converted;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
if (aViewer->mActive) {
if (!aViewer->mFreeze)
// convert data
aViewer->mDataspaceConverter.send("convert", data, converted);
else
// use last data
converted = aViewer->mReturnedValue;
// return value
aViewer->deliver(converted);
aViewer->setReturnedValue(converted);
}
return kTTErrNone;
}
TTErr TTViewerDataspaceCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue v;
TTSymbol dataspace;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
dataspace = data;
// filter repetitions
if (dataspace != aViewer->mDataspace) {
aViewer->mDataspace = data;
return aViewer->mDataspaceConverter.set(kTTSym_dataspace, aViewer->mDataspace);
}
return kTTErrNone;
}
TTErr TTViewerDataspaceUnitCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue v;
TTErr err;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
// set input unit like the data unit
aViewer->mDataspaceConverter.set("inputUnit", data);
// if no unit : set the output unit like the data unit
if (aViewer->mDataspaceUnit == kTTSym_none)
aViewer->mDataspaceUnit = data;
// if the unit is wrong : use the default unit
err = aViewer->mDataspaceConverter.set("outputUnit", aViewer->mDataspaceUnit);
if (err) {
aViewer->mDataspaceConverter.get("outputUnit", v);
aViewer->mDataspaceUnit = v[0];
aViewer->mDataspaceConverter.set("outputUnit", aViewer->mDataspaceUnit);
}
return kTTErrNone;
}
<commit_msg>Fixing #827 even when attibute is kTTSymEmpty<commit_after>/** @file
*
* @ingroup modularLibrary
*
* @brief A Viewer Object.
*
* @details
*
* @authors Théo de la Hogue
*
* @copyright © 2010, Théo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTViewer.h"
#define thisTTClass TTViewer
#define thisTTClassName "Viewer"
#define thisTTClassTags "viewer"
TTObjectBasePtr TTViewer::instantiate (TTSymbol name, TTValue arguments)
{
return new TTViewer(arguments);
}
extern "C" void TTViewer::registerClass()
{
TTClassRegister(TTSymbol("Viewer"), thisTTClassTags, TTViewer::instantiate);
}
TTViewer::TTViewer(const TTValue& arguments) :
TTCallback(arguments),
mAddress(kTTAdrsEmpty),
mDescription(kTTSym_none),
mType(kTTSym_generic),
mTags(kTTSym_none),
mHighlight(NO),
mFreeze(NO),
mDataspace(kTTSym_none),
mDataspaceUnit(kTTSym_none),
mDataspaceConverter("dataspace"),
mActive(YES)
{
addAttributeWithSetter(Address, kTypeSymbol);
addAttribute(Description, kTypeSymbol);
addAttribute(Type, kTypeSymbol);
addAttribute(Tags, kTypeSymbol);
addAttributeWithSetter(Highlight, kTypeBoolean);
addAttributeWithSetter(Freeze, kTypeBoolean);
addAttribute(Dataspace, kTypeSymbol);
addAttributeProperty(Dataspace, readOnly, YES);
addAttributeProperty(Dataspace, hidden, YES);
addAttributeWithSetter(DataspaceUnit, kTypeSymbol);
addAttributeWithSetter(Active, kTypeBoolean);
addAttributeWithSetter(ReturnedValue, kTypeLocalValue);
addAttributeProperty(ReturnedValue, readOnly, YES);
addAttributeProperty(ReturnedValue, hidden, YES);
addMessageWithArguments(Send);
addMessageProperty(Send, hidden, YES);
addMessageWithArguments(Grab);
addMessageProperty(Grab, hidden, YES);
}
TTViewer::~TTViewer()
{
// disable reception to avoid crash
mActive = NO;
}
TTErr TTViewer::setAddress(const TTValue& value)
{
TTBoolean memoActive = mActive;
mAddress = value[0];
// disable reception to avoid crash
mActive = NO;
// if no address : delete sender, receiver and observers
if (mAddress == kTTAdrsEmpty) {
if (mSender.valid()) {
mSender.set(kTTSym_address, kTTAdrsEmpty);
mSender = TTObject();
}
if (mReceiver.valid()) {
mReceiver.set(kTTSym_address, kTTAdrsEmpty);
mReceiver = TTObject();
}
if (mDataspaceObserver.valid()) {
mDataspaceObserver.set(kTTSym_address, kTTAdrsEmpty);
mDataspaceObserver = TTObject();
}
if (mDataspaceUnitObserver.valid()) {
mDataspaceUnitObserver.set(kTTSym_address, kTTAdrsEmpty);
mDataspaceUnitObserver = TTObject();
}
return kTTErrGeneric;
}
// the default attribute to bind is value
if (mAddress.getAttribute() == NO_ATTRIBUTE)
mAddress.appendAttribute(kTTSym_value);
// create sender if needed
if (!mSender.valid())
mSender = TTObject(kTTSym_Sender);
// change sender address
mSender.set(kTTSym_address, mAddress);
// create receiver if needed
if (!mReceiver.valid()) {
TTValue args;
TTObject returnAddressCallback = TTObject("callback");
returnAddressCallback.set(kTTSym_baton, TTObject(this));
returnAddressCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback));
args.append(returnAddressCallback);
TTObject returnValueCallback = TTObject("callback");
returnValueCallback.set(kTTSym_baton, TTObject(this));
returnValueCallback.set(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback));
args.append(returnValueCallback);
mReceiver = TTObject(kTTSym_Receiver, args);
}
// change receiver address
mReceiver.set(kTTSym_address, mAddress);
// create dataspace observer if needed
if (!mDataspaceObserver.valid()) {
TTValue args;
TTObject empty;
args.append(empty);
TTObject returnDataspaceCallback = TTObject("callback");
returnDataspaceCallback.set(kTTSym_baton, TTObject(this));
returnDataspaceCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceCallback));
args.append(returnDataspaceCallback);
mDataspaceObserver = TTObject(kTTSym_Receiver, args);
}
// change dataspace observer address and get the value
mDataspaceObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspace));
mDataspaceObserver.send(kTTSym_Get);
// create dataspace unit observer if needed
if (!mDataspaceUnitObserver.valid()) {
TTValue args;
TTObject empty;
args.append(empty);
TTObject returnDataspaceUnitCallback = TTObject("callback");
returnDataspaceUnitCallback.set(kTTSym_baton, TTObject(this));
returnDataspaceUnitCallback.set(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback));
args.append(returnDataspaceUnitCallback);
mDataspaceUnitObserver = TTObject(kTTSym_Receiver, args);
}
// change dataspace unit observer address and get the value
mDataspaceUnitObserver.set(kTTSym_address, mAddress.appendAttribute(kTTSym_dataspaceUnit));
mDataspaceUnitObserver.send(kTTSym_Get);
// enable reception
mActive = memoActive;
// refresh
return mReceiver.send(kTTSym_Get);
}
TTErr TTViewer::setActive(const TTValue& value)
{
mActive = value;
if (mReceiver.valid()) {
mReceiver.set(kTTSym_active, mActive);
if (mActive)
return mReceiver.send(kTTSym_Get);
else
return kTTErrNone;
}
return kTTErrGeneric;
}
TTErr TTViewer::setHighlight(const TTValue& value)
{
TTAttributePtr anAttribute = NULL;
TTErr err;
mHighlight = value;
err = this->findAttribute(kTTSym_highlight, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, mHighlight); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTViewer::setFreeze(const TTValue& value)
{
mFreeze = value;
if (mReceiver.valid()) {
// update the value if the Viewer is unfreezed
if (!mFreeze)
return mReceiver.send(kTTSym_Get);
else
return kTTErrNone;
}
return kTTErrGeneric;
}
TTErr TTViewer::setReturnedValue(const TTValue& value)
{
TTAttributePtr anAttribute = NULL;
TTErr err;
mReturnedValue = value;
err = this->findAttribute(kTTSym_returnedValue, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, mReturnedValue); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue)
{
if (!mActive)
return kTTErrNone;
TTValue none, valueToSend;
// insert view unit before "ramp" (except for empty value)
if (inputValue.size() > 0 &&
mDataspaceUnit != kTTSym_none &&
(mAddress.getAttribute() == kTTSym_value || mAddress.getAttribute() == kTTSymEmpty))
{
TTBoolean ramp = false;
for (TTInt32 i = 0; i < inputValue.size(); i++)
{
if (inputValue[i].type() == kTypeSymbol)
{
TTSymbol s = inputValue[i];
if (s == kTTSym_ramp)
{
ramp = true;
valueToSend.append(mDataspaceUnit);
}
}
valueToSend.append(inputValue[i]);
}
if (!ramp)
valueToSend.append(mDataspaceUnit);
}
else
valueToSend = inputValue;
if (mSender.valid())
return mSender.send(kTTSym_Send, valueToSend);
else
return kTTErrGeneric;
}
TTErr TTViewer::Grab(const TTValue& inputValue, TTValue& outputValue)
{
if (mReceiver.valid()) {
return mReceiver.send(kTTSym_Grab, inputValue, outputValue);
}
return kTTErrGeneric;
}
TTErr TTViewer::setDataspaceUnit(const TTValue& value)
{
TTValue n = value; // use new value to protect the attribute
mDataspaceUnit = value;
return mDataspaceConverter.set("outputUnit", mDataspaceUnit);
// TODO : notifyObservers(kTTSym_dataspaceUnit, n);
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTErr TTViewerReceiveAddressCallback(const TTValue& baton, const TTValue& data)
{
return kTTErrNone;
}
TTErr TTViewerReceiveValueCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue converted;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
if (aViewer->mActive) {
if (!aViewer->mFreeze)
// convert data
aViewer->mDataspaceConverter.send("convert", data, converted);
else
// use last data
converted = aViewer->mReturnedValue;
// return value
aViewer->deliver(converted);
aViewer->setReturnedValue(converted);
}
return kTTErrNone;
}
TTErr TTViewerDataspaceCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue v;
TTSymbol dataspace;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
dataspace = data;
// filter repetitions
if (dataspace != aViewer->mDataspace) {
aViewer->mDataspace = data;
return aViewer->mDataspaceConverter.set(kTTSym_dataspace, aViewer->mDataspace);
}
return kTTErrNone;
}
TTErr TTViewerDataspaceUnitCallback(const TTValue& baton, const TTValue& data)
{
TTObject o;
TTViewerPtr aViewer;
TTValue v;
TTErr err;
// unpack baton (a #TTViewer)
o = baton[0];
aViewer = (TTViewerPtr)o.instance();
// set input unit like the data unit
aViewer->mDataspaceConverter.set("inputUnit", data);
// if no unit : set the output unit like the data unit
if (aViewer->mDataspaceUnit == kTTSym_none)
aViewer->mDataspaceUnit = data;
// if the unit is wrong : use the default unit
err = aViewer->mDataspaceConverter.set("outputUnit", aViewer->mDataspaceUnit);
if (err) {
aViewer->mDataspaceConverter.get("outputUnit", v);
aViewer->mDataspaceUnit = v[0];
aViewer->mDataspaceConverter.set("outputUnit", aViewer->mDataspaceUnit);
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCLogModule.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCLogModule
// @Desc :
// -------------------------------------------------------------------------
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include <stdarg.h>
#include "NFCLogModule.h"
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP
unsigned int NFCLogModule::idx = 0;
bool NFCLogModule::CheckLogFileExist(const char* filename)
{
std::stringstream stream;
stream << filename << "." << ++idx;
std::fstream file;
file.open(stream.str(), std::ios::in);
if (file)
{
return CheckLogFileExist(filename);
}
return false;
}
void NFCLogModule::rolloutHandler(const char* filename, std::size_t size)
{
std::stringstream stream;
if (!CheckLogFileExist(filename))
{
stream << filename << "." << idx;
rename(filename, stream.str().c_str());
}
}
NFCLogModule::NFCLogModule(NFIPluginManager* p)
{
pPluginManager = p;
}
bool NFCLogModule::Init()
{
mnLogCountTotal = 0;
el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
#if NF_PLATFORM == NF_PLATFORM_WIN
el::Configurations conf("log_win.conf");
#else
el::Configurations conf("log.conf");
#endif
el::Loggers::reconfigureAllLoggers(conf);
el::Helpers::installPreRollOutCallback(rolloutHandler);
return true;
}
bool NFCLogModule::Shut()
{
el::Helpers::uninstallPreRollOutCallback();
return true;
}
bool NFCLogModule::BeforeShut()
{
return true;
}
bool NFCLogModule::AfterInit()
{
return true;
}
bool NFCLogModule::Execute()
{
return true;
}
bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)
{
mnLogCountTotal++;
char szBuffer[1024 * 10] = {0};
va_list args;
va_start(args, format);
vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);
va_end(args);
switch (nll)
{
case NFILogModule::NLL_DEBUG_NORMAL:
LOG(DEBUG) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_INFO_NORMAL:
LOG(INFO) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_WARING_NORMAL:
LOG(WARNING) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_ERROR_NORMAL:
{
LOG(ERROR) << mnLogCountTotal << " " << szBuffer;
//LogStack();
}
break;
case NFILogModule::NLL_FATAL_NORMAL:
LOG(FATAL) << mnLogCountTotal << " " << szBuffer;
break;
default:
LOG(INFO) << mnLogCountTotal << " " << szBuffer;
break;
}
return true;
}
bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[ELEMENT] Indent[%s] Element[%s] %s %s %d", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[ELEMENT] Indent[%s] Element[%s] %s", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[PROPERTY] Indent[%s] Property[%s] %s %s %d", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[PROPERTY] Indent[%s] Property[%s] %s", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s %s %d", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);
}
else
{
Log(nll, "[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[RECORD] Indent[%s] Record[%s] %s %s %d", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[RECORD] Indent[%s] Record[%s] %s", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[OBJECT] Indent[%s] %s %s %d", ident.ToString().c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[OBJECT] Indent[%s] %s", ident.ToString().c_str(), strDesc.c_str());
}
return true;
}
void NFCLogModule::LogStack()
{
//To Add
/*
#ifdef NF_DEBUG_MODE
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
// 创建Dump文件
HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Dump信息
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
//dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// 写入Dump文件内容
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
#endif
*/
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %s %s %d", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s %s", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const int nDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %d %s %d", ident.ToString().c_str(), strInfo.c_str(), nDesc, func, line);
}
else
{
Log(nll, "Indent[%s] %s %d", ident.ToString().c_str(), strInfo.c_str(), nDesc);
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::ostringstream& stream, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %s %d", ident.ToString().c_str(), strInfo.c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s", ident.ToString().c_str(), strInfo.c_str());
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const char* func /*= ""*/, int line /*= 0*/)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %s %d", ident.ToString().c_str(), strInfo.c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s", ident.ToString().c_str(), strInfo.c_str());
}
return true;
}
bool NFCLogModule::LogDebugFunctionDump(const NFGUID ident, const int nMsg, const std::string& strArg, const char* func /*= ""*/, const int line /*= 0*/)
{
//#ifdef NF_DEBUG_MODE
LogNormal(NFILogModule::NLL_WARING_NORMAL, ident, strArg + "MsgID:", nMsg, func, line);
//#endif
return true;
}
bool NFCLogModule::ChangeLogLevel(const std::string& strLevel)
{
el::Level logLevel = el::LevelHelper::convertFromString(strLevel.c_str());
el::Logger* pLogger = el::Loggers::getLogger("default");
if (NULL == pLogger)
{
return false;
}
el::Configurations* pConfigurations = pLogger->configurations();
el::base::TypedConfigurations* pTypeConfigurations = pLogger->typedConfigurations();
if (NULL == pConfigurations)
{
return false;
}
// log级别为debug, info, warning, error, fatal(级别逐渐提高)
// 当传入为info时,则高于(包含)info的级别会输出
// !!!!!! NOTICE:故意没有break,请千万注意 !!!!!!
switch (logLevel)
{
case el::Level::Fatal:
{
el::Configuration errorConfiguration(el::Level::Error, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&errorConfiguration);
}
case el::Level::Error:
{
el::Configuration warnConfiguration(el::Level::Warning, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&warnConfiguration);
}
case el::Level::Warning:
{
el::Configuration infoConfiguration(el::Level::Info, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&infoConfiguration);
}
case el::Level::Info:
{
el::Configuration debugConfiguration(el::Level::Debug, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&debugConfiguration);
}
case el::Level::Debug:
break;
default:
break;
}
el::Loggers::reconfigureAllLoggers(*pConfigurations);
LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), "[Log] Change log level", strLevel, __FUNCTION__, __LINE__);
return true;
}
<commit_msg>fixed for log module<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCLogModule.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCLogModule
// @Desc :
// -------------------------------------------------------------------------
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include <stdarg.h>
#include "NFCLogModule.h"
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP
unsigned int NFCLogModule::idx = 0;
bool NFCLogModule::CheckLogFileExist(const char* filename)
{
std::stringstream stream;
stream << filename << "." << ++idx;
std::fstream file;
file.open(stream.str(), std::ios::in);
if (file)
{
return CheckLogFileExist(filename);
}
return false;
}
void NFCLogModule::rolloutHandler(const char* filename, std::size_t size)
{
std::stringstream stream;
if (!CheckLogFileExist(filename))
{
stream << filename << "." << idx;
rename(filename, stream.str().c_str());
}
}
NFCLogModule::NFCLogModule(NFIPluginManager* p)
{
pPluginManager = p;
}
bool NFCLogModule::Init()
{
mnLogCountTotal = 0;
el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
#if NF_PLATFORM == NF_PLATFORM_WIN
el::Configurations conf("log_win.conf");
#else
el::Configurations conf("log.conf");
#endif
el::Loggers::reconfigureAllLoggers(conf);
el::Helpers::installPreRollOutCallback(rolloutHandler);
return true;
}
bool NFCLogModule::Shut()
{
el::Helpers::uninstallPreRollOutCallback();
return true;
}
bool NFCLogModule::BeforeShut()
{
return true;
}
bool NFCLogModule::AfterInit()
{
return true;
}
bool NFCLogModule::Execute()
{
return true;
}
bool NFCLogModule::Log(const NF_LOG_LEVEL nll, const char* format, ...)
{
mnLogCountTotal++;
char szBuffer[1024 * 10] = {0};
va_list args;
va_start(args, format);
vsnprintf(szBuffer, sizeof(szBuffer) - 1, format, args);
va_end(args);
switch (nll)
{
case NFILogModule::NLL_DEBUG_NORMAL:
LOG(DEBUG) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_INFO_NORMAL:
LOG(INFO) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_WARING_NORMAL:
LOG(WARNING) << mnLogCountTotal << " " << szBuffer;
break;
case NFILogModule::NLL_ERROR_NORMAL:
{
LOG(ERROR) << mnLogCountTotal << " " << szBuffer;
//LogStack();
}
break;
case NFILogModule::NLL_FATAL_NORMAL:
LOG(FATAL) << mnLogCountTotal << " " << szBuffer;
break;
default:
LOG(INFO) << mnLogCountTotal << " " << szBuffer;
break;
}
return true;
}
bool NFCLogModule::LogElement(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strElement, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[ELEMENT] Indent[%s] Element[%s] %s %s %d", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[ELEMENT] Indent[%s] Element[%s] %s", ident.ToString().c_str(), strElement.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogProperty(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strProperty, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[PROPERTY] Indent[%s] Property[%s] %s %s %d", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[PROPERTY] Indent[%s] Property[%s] %s", ident.ToString().c_str(), strProperty.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const int nRow, const int nCol, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s %s %d", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str(), func, line);
}
else
{
Log(nll, "[RECORD] Indent[%s] Record[%s] Row[%d] Col[%d] %s", ident.ToString().c_str(), strRecord.c_str(), nRow, nCol, strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogRecord(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strRecord, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[RECORD] Indent[%s] Record[%s] %s %s %d", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[RECORD] Indent[%s] Record[%s] %s", ident.ToString().c_str(), strRecord.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogObject(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "[OBJECT] Indent[%s] %s %s %d", ident.ToString().c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "[OBJECT] Indent[%s] %s", ident.ToString().c_str(), strDesc.c_str());
}
return true;
}
void NFCLogModule::LogStack()
{
//To Add
/*
#ifdef NF_DEBUG_MODE
time_t t = time(0);
char szDmupName[MAX_PATH];
tm* ptm = localtime(&t);
sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
// 创建Dump文件
HANDLE hDumpFile = CreateFile(szDmupName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Dump信息
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
//dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// 写入Dump文件内容
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
#endif
*/
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const std::string& strDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %s %s %d", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s %s", ident.ToString().c_str(), strInfo.c_str(), strDesc.c_str());
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const int nDesc, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %d %s %d", ident.ToString().c_str(), strInfo.c_str(), nDesc, func, line);
}
else
{
Log(nll, "Indent[%s] %s %d", ident.ToString().c_str(), strInfo.c_str(), nDesc);
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::ostringstream& stream, const char* func, int line)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %d", ident.ToString().c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s", ident.ToString().c_str());
}
return true;
}
bool NFCLogModule::LogNormal(const NF_LOG_LEVEL nll, const NFGUID ident, const std::string& strInfo, const char* func /*= ""*/, int line /*= 0*/)
{
if (line > 0)
{
Log(nll, "Indent[%s] %s %s %d", ident.ToString().c_str(), strInfo.c_str(), func, line);
}
else
{
Log(nll, "Indent[%s] %s", ident.ToString().c_str(), strInfo.c_str());
}
return true;
}
bool NFCLogModule::LogDebugFunctionDump(const NFGUID ident, const int nMsg, const std::string& strArg, const char* func /*= ""*/, const int line /*= 0*/)
{
//#ifdef NF_DEBUG_MODE
LogNormal(NFILogModule::NLL_WARING_NORMAL, ident, strArg + "MsgID:", nMsg, func, line);
//#endif
return true;
}
bool NFCLogModule::ChangeLogLevel(const std::string& strLevel)
{
el::Level logLevel = el::LevelHelper::convertFromString(strLevel.c_str());
el::Logger* pLogger = el::Loggers::getLogger("default");
if (NULL == pLogger)
{
return false;
}
el::Configurations* pConfigurations = pLogger->configurations();
el::base::TypedConfigurations* pTypeConfigurations = pLogger->typedConfigurations();
if (NULL == pConfigurations)
{
return false;
}
// log级别为debug, info, warning, error, fatal(级别逐渐提高)
// 当传入为info时,则高于(包含)info的级别会输出
// !!!!!! NOTICE:故意没有break,请千万注意 !!!!!!
switch (logLevel)
{
case el::Level::Fatal:
{
el::Configuration errorConfiguration(el::Level::Error, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&errorConfiguration);
}
case el::Level::Error:
{
el::Configuration warnConfiguration(el::Level::Warning, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&warnConfiguration);
}
case el::Level::Warning:
{
el::Configuration infoConfiguration(el::Level::Info, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&infoConfiguration);
}
case el::Level::Info:
{
el::Configuration debugConfiguration(el::Level::Debug, el::ConfigurationType::Enabled, "false");
pConfigurations->set(&debugConfiguration);
}
case el::Level::Debug:
break;
default:
break;
}
el::Loggers::reconfigureAllLoggers(*pConfigurations);
LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), "[Log] Change log level", strLevel, __FUNCTION__, __LINE__);
return true;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2008 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
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 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.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgrePrerequisites.h"
#include "OgreMemoryNedAlloc.h"
#include "OgrePlatformInformation.h"
#include "OgreMemoryTracker.h"
#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED
// include ned implementation
#include <nedmalloc.c>
namespace Ogre
{
//---------------------------------------------------------------------
void* NedAllocImpl::allocBytes(size_t count,
const char* file, int line, const char* func)
{
void* ptr = nedalloc::nedmalloc(count);
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
// avoid unused params warning
file;line;func;
#endif
return ptr;
}
//---------------------------------------------------------------------
void NedAllocImpl::deallocBytes(void* ptr)
{
#if OGRE_MEMORY_TRACKER
MemoryTracker::get()._recordDealloc(ptr);
#endif
nedalloc::nedfree(ptr);
}
//---------------------------------------------------------------------
void* NedAllocImpl::allocBytesAligned(size_t align, size_t count,
const char* file, int line, const char* func)
{
// default to platform SIMD alignment if none specified
void* ptr = align ? nedalloc::nedmemalign(align, count)
: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
// avoid unused params warning
file;line;func;
#endif
return ptr;
}
//---------------------------------------------------------------------
void NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)
{
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordDealloc(ptr);
#endif
nedalloc::nedfree(ptr);
}
}
#endif
<commit_msg>Ned deallocator should deal with null pointers<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2008 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
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 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.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgrePrerequisites.h"
#include "OgreMemoryNedAlloc.h"
#include "OgrePlatformInformation.h"
#include "OgreMemoryTracker.h"
#if OGRE_MEMORY_ALLOCATOR == OGRE_MEMORY_ALLOCATOR_NED
// include ned implementation
#include <nedmalloc.c>
namespace Ogre
{
//---------------------------------------------------------------------
void* NedAllocImpl::allocBytes(size_t count,
const char* file, int line, const char* func)
{
void* ptr = nedalloc::nedmalloc(count);
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
// avoid unused params warning
file;line;func;
#endif
return ptr;
}
//---------------------------------------------------------------------
void NedAllocImpl::deallocBytes(void* ptr)
{
// deal with null
if (!ptr)
return;
#if OGRE_MEMORY_TRACKER
MemoryTracker::get()._recordDealloc(ptr);
#endif
nedalloc::nedfree(ptr);
}
//---------------------------------------------------------------------
void* NedAllocImpl::allocBytesAligned(size_t align, size_t count,
const char* file, int line, const char* func)
{
// default to platform SIMD alignment if none specified
void* ptr = align ? nedalloc::nedmemalign(align, count)
: nedalloc::nedmemalign(OGRE_SIMD_ALIGNMENT, count);
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordAlloc(ptr, count, 0, file, line, func);
#else
// avoid unused params warning
file;line;func;
#endif
return ptr;
}
//---------------------------------------------------------------------
void NedAllocImpl::deallocBytesAligned(size_t align, void* ptr)
{
// deal with null
if (!ptr)
return;
#if OGRE_MEMORY_TRACKER
// this alloc policy doesn't do pools (yet, ned can do it)
MemoryTracker::get()._recordDealloc(ptr);
#endif
nedalloc::nedfree(ptr);
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Adding the possibility to select the POI based on pdg (ALICE3 LoI)<commit_after><|endoftext|> |
<commit_before>#include "transactionrecord.h"
#include "wallet/wallet.h"
#include "base58.h"
std::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);
/* Return positive answer if transaction should be shown in list. */
bool TransactionRecord::showTransaction(const CWalletTx &wtx, bool datetime_limit_flag, const int64_t &datetime_limit)
{
// Do not show transactions earlier than the datetime_limit if the flag is set.
if (datetime_limit_flag && (int64_t) wtx.nTime < datetime_limit)
{
return false;
}
std::string ShowOrphans = GetArg("-showorphans", "false");
//R Halford - POS Transactions - If Orphaned follow showorphans directive:
if (wtx.IsCoinStake() && !wtx.IsInMainChain())
{
//Orphaned tx
return (ShowOrphans=="true" ? true : false);
}
if (wtx.IsCoinBase())
{
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain())
{
return false;
}
}
// Suppress OP_RETURN transactions if they did not originate from you.
// This is not "very" taxing but necessary since the transaction is in the wallet already.
if (!wtx.IsFromMe())
{
for (auto const& txout : wtx.vout)
{
if (txout.scriptPubKey == (CScript() << OP_RETURN))
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetTxTime();
int64_t nCredit = wtx.GetCredit(true);
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
size_t wtx_size = wtx.vout.size();
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
bool fContractPresent = false;
NN::ContractType ContractType;
if (!wtx.GetContracts().empty())
{
const auto& contract = wtx.GetContracts().begin();
fContractPresent = true;
ContractType = contract->m_type.Value();
}
// This is legacy CoinBase for PoW, no longer used.
if (wtx.IsCoinBase())
{
for (const auto& txout :wtx.vout)
{
if (wallet->IsMine(txout) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
if (ExtractDestination(txout.scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
// Generated (proof-of-work)
sub.type = TransactionRecord::Generated;
sub.credit = txout.nValue;
parts.append(sub);
}
}
}
// Since we are now separating out the sent sidestake info
// into a separate subtransaction, we need to include the entire
// value of the coinstake transaction here, rather than the previous
// counting of only IsMine outputs.
else if (wtx.IsCoinStake())
{
// We check the first coinstake output (zero is empty) for IsMine to
// determine how to characterize the entire coinstake transaction. The
// sidestakes to other (not mine) addresses are accounted for as negatives
// in a separate subtransaction. The first output is ALWAYS guaranteed to be
// the stake return to the original owner, and so matches the input.
if (wallet->IsMine(wtx.vout[1]) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size();
sub.vout = 1;
sub.type = TransactionRecord::Generated;
// The coinstake HAS to be from an address.
if(ExtractDestination(wtx.vout[1].scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
// Here we add up all of the outputs, whether they are ours (the stake return with
// apportioned reward, or not (sidestake), because the part that is not ours
// will be accounted in the separated sidestake send transaction.
sub.credit = 0;
for (const auto& txout : wtx.vout)
{
sub.credit += txout.nValue;
}
sub.debit = -nDebit;
// Append the subtransaction to the parts QList (transaction record).
parts.append(sub);
}
// We only want outputs > 1 because the zeroth output is always empty,
// and the first output is always the staker's. Output 2 onwards may or
// may not be a sidestake, depending on whether stakesplitting is active,
// or whether sidestaking is even turned on.
// There is no coalescing here. A separate subtransaction is created for each
// sidestake.
for (unsigned int t = 2; t < wtx_size; t++)
{
// If this is not a stake split AND either vout[1] is mine OR
// vout[t] is mine
if (wtx.vout[t].scriptPubKey != wtx.vout[1].scriptPubKey &&
(wallet->IsMine(wtx.vout[1]) != ISMINE_NO ||
wallet->IsMine(wtx.vout[t]) != ISMINE_NO))
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.vout = t;
sub.type = TransactionRecord::Generated;
if (ExtractDestination(wtx.vout[t].scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
int64_t nValue = wtx.vout[t].nValue;
if (wallet->IsMine(wtx.vout[t]) != ISMINE_NO)
{
sub.credit = nValue;
}
else
{
sub.debit = -nValue;
}
parts.append(sub);
}
}
}
else if (nNet > 0)
{
for (const auto& txout : wtx.vout)
{
if (wallet->IsMine(txout) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
if (ExtractDestination(txout.scriptPubKey, address))
{
// Received by Bitcoin Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
sub.credit = txout.nValue;
parts.append(sub);
}
}
}
else // Everything else
{
bool fAllFromMe = true;
for (auto const& txin : wtx.vin)
fAllFromMe = fAllFromMe && (wallet->IsMine(txin) != ISMINE_NO);
bool fAllToMe = true;
for (auto const& txout : wtx.vout)
fAllToMe = fAllToMe && (wallet->IsMine(txout) != ISMINE_NO);
if (fAllFromMe && fAllToMe)
{
// Payment to self
int64_t nChange = wtx.GetChange();
parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "",
-(nDebit - nChange), nCredit - nChange, 0));
}
else if (fAllFromMe)
{
//
// Debit
//
int64_t nTxFee = nDebit - wtx.GetValueOut();
// for tracking message type display
bool fMessageDisplayed = false;
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = parts.size();
if(wallet->IsMine(txout) != ISMINE_NO)
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
// Sent to Bitcoin Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
int64_t nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
// Determine if the transaction is a beacon advertisement or a vote.
// For right now, there should only be one contract in a transaction.
// We will simply select the first and only one. Note that we are
// looping through the outputs one by one in the for loop above this,
// So if we get here, we are not a coinbase or coinstake, and we are on
// an ouput that isn't ours. The worst that can happen from this
// simple approach is to label more than one output with the
// first found contract type. For right now, this is sufficient, because
// the contracts that are sent right now only contain two outputs,
// the burn and the change. We will have to get more sophisticated
// when we allow more than one contract per transaction.
// Notice this doesn't mess with the value or debit, it simply
// overrides the TransactionRecord enum type.
if (fContractPresent)
{
switch (ContractType)
{
case NN::ContractType::BEACON:
sub.type = TransactionRecord::BeaconAdvertisement;
break;
case NN::ContractType::POLL:
sub.type = TransactionRecord::Poll;
break;
case NN::ContractType::VOTE:
sub.type = TransactionRecord::Vote;
break;
case NN::ContractType::MESSAGE:
// Only display the message type for the first not is mine output
if (!fMessageDisplayed && wallet->IsMine(txout) == ISMINE_NO)
{
sub.type = TransactionRecord::Message;
fMessageDisplayed = true;
}
// Do not display the op return output for a send message contract separately.
else if (txout.scriptPubKey[0] == OP_RETURN)
{
continue;
}
break;
default:
break; // Suppress warning
}
}
parts.append(sub);
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0, 0));
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
// Find the block the tx is in
CBlockIndex* pindex = NULL;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = nBestHeight;
if (!IsFinalTx(wtx, nBestHeight + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.nLockTime - nBestHeight;
}
else
{
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
if (wtx.GetBlocksToMaturity() > 0)
{
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain())
{
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
{
status.status = TransactionStatus::NotAccepted;
}
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
else
{
if (status.depth < 0)
{
status.status = TransactionStatus::Conflicted;
}
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
}
else if (status.depth < RecommendedNumConfirmations)
{
status.status = TransactionStatus::Confirming;
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != nBestHeight;
}
std::string TransactionRecord::getTxID()
{
return hash.ToString();
}
<commit_msg>Adjust OP_RETURN filter to only filter version 1 transactions<commit_after>#include "transactionrecord.h"
#include "wallet/wallet.h"
#include "base58.h"
std::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);
/* Return positive answer if transaction should be shown in list. */
bool TransactionRecord::showTransaction(const CWalletTx &wtx, bool datetime_limit_flag, const int64_t &datetime_limit)
{
// Do not show transactions earlier than the datetime_limit if the flag is set.
if (datetime_limit_flag && (int64_t) wtx.nTime < datetime_limit)
{
return false;
}
std::string ShowOrphans = GetArg("-showorphans", "false");
//R Halford - POS Transactions - If Orphaned follow showorphans directive:
if (wtx.IsCoinStake() && !wtx.IsInMainChain())
{
//Orphaned tx
return (ShowOrphans=="true" ? true : false);
}
if (wtx.IsCoinBase())
{
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain())
{
return false;
}
}
// Suppress OP_RETURN transactions if they did not originate from you.
// This is not "very" taxing but necessary since the transaction is in the wallet already.
// We only do this for version 1 transactions, because this legacy error does not occur
// anymore, and we can't filter entire transactions that have OP_RETURNs, since
// some outputs are relevent with the new contract types, such as messages.
if (wtx.nVersion == 1 && !wtx.IsFromMe())
{
for (auto const& txout : wtx.vout)
{
if (txout.scriptPubKey == (CScript() << OP_RETURN))
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetTxTime();
int64_t nCredit = wtx.GetCredit(true);
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
size_t wtx_size = wtx.vout.size();
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
bool fContractPresent = false;
NN::ContractType ContractType;
if (!wtx.GetContracts().empty())
{
const auto& contract = wtx.GetContracts().begin();
fContractPresent = true;
ContractType = contract->m_type.Value();
}
// This is legacy CoinBase for PoW, no longer used.
if (wtx.IsCoinBase())
{
for (const auto& txout :wtx.vout)
{
if (wallet->IsMine(txout) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
if (ExtractDestination(txout.scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
// Generated (proof-of-work)
sub.type = TransactionRecord::Generated;
sub.credit = txout.nValue;
parts.append(sub);
}
}
}
// Since we are now separating out the sent sidestake info
// into a separate subtransaction, we need to include the entire
// value of the coinstake transaction here, rather than the previous
// counting of only IsMine outputs.
else if (wtx.IsCoinStake())
{
// We check the first coinstake output (zero is empty) for IsMine to
// determine how to characterize the entire coinstake transaction. The
// sidestakes to other (not mine) addresses are accounted for as negatives
// in a separate subtransaction. The first output is ALWAYS guaranteed to be
// the stake return to the original owner, and so matches the input.
if (wallet->IsMine(wtx.vout[1]) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size();
sub.vout = 1;
sub.type = TransactionRecord::Generated;
// The coinstake HAS to be from an address.
if(ExtractDestination(wtx.vout[1].scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
// Here we add up all of the outputs, whether they are ours (the stake return with
// apportioned reward, or not (sidestake), because the part that is not ours
// will be accounted in the separated sidestake send transaction.
sub.credit = 0;
for (const auto& txout : wtx.vout)
{
sub.credit += txout.nValue;
}
sub.debit = -nDebit;
// Append the subtransaction to the parts QList (transaction record).
parts.append(sub);
}
// We only want outputs > 1 because the zeroth output is always empty,
// and the first output is always the staker's. Output 2 onwards may or
// may not be a sidestake, depending on whether stakesplitting is active,
// or whether sidestaking is even turned on.
// There is no coalescing here. A separate subtransaction is created for each
// sidestake.
for (unsigned int t = 2; t < wtx_size; t++)
{
// If this is not a stake split AND either vout[1] is mine OR
// vout[t] is mine
if (wtx.vout[t].scriptPubKey != wtx.vout[1].scriptPubKey &&
(wallet->IsMine(wtx.vout[1]) != ISMINE_NO ||
wallet->IsMine(wtx.vout[t]) != ISMINE_NO))
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.vout = t;
sub.type = TransactionRecord::Generated;
if (ExtractDestination(wtx.vout[t].scriptPubKey, address))
{
sub.address = CBitcoinAddress(address).ToString();
}
int64_t nValue = wtx.vout[t].nValue;
if (wallet->IsMine(wtx.vout[t]) != ISMINE_NO)
{
sub.credit = nValue;
}
else
{
sub.debit = -nValue;
}
parts.append(sub);
}
}
}
else if (nNet > 0)
{
for (const auto& txout : wtx.vout)
{
if (wallet->IsMine(txout) != ISMINE_NO)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
if (ExtractDestination(txout.scriptPubKey, address))
{
// Received by Bitcoin Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
if (fContractPresent && ContractType == NN::ContractType::MESSAGE)
{
sub.type = TransactionRecord::Message;
}
sub.credit = txout.nValue;
parts.append(sub);
}
}
}
else // Everything else
{
bool fAllFromMe = true;
for (auto const& txin : wtx.vin)
fAllFromMe = fAllFromMe && (wallet->IsMine(txin) != ISMINE_NO);
bool fAllToMe = true;
for (auto const& txout : wtx.vout)
fAllToMe = fAllToMe && (wallet->IsMine(txout) != ISMINE_NO);
if (fAllFromMe && fAllToMe)
{
// Payment to self
int64_t nChange = wtx.GetChange();
parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "",
-(nDebit - nChange), nCredit - nChange, 0));
}
else if (fAllFromMe)
{
//
// Debit
//
int64_t nTxFee = nDebit - wtx.GetValueOut();
// for tracking message type display
bool fMessageDisplayed = false;
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = parts.size();
if(wallet->IsMine(txout) != ISMINE_NO)
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
// Sent to Bitcoin Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
int64_t nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
// Determine if the transaction is a beacon advertisement or a vote.
// For right now, there should only be one contract in a transaction.
// We will simply select the first and only one. Note that we are
// looping through the outputs one by one in the for loop above this,
// So if we get here, we are not a coinbase or coinstake, and we are on
// an ouput that isn't ours. The worst that can happen from this
// simple approach is to label more than one output with the
// first found contract type. For right now, this is sufficient, because
// the contracts that are sent right now only contain two outputs,
// the burn and the change. We will have to get more sophisticated
// when we allow more than one contract per transaction.
// Notice this doesn't mess with the value or debit, it simply
// overrides the TransactionRecord enum type.
if (fContractPresent)
{
switch (ContractType)
{
case NN::ContractType::BEACON:
sub.type = TransactionRecord::BeaconAdvertisement;
break;
case NN::ContractType::POLL:
sub.type = TransactionRecord::Poll;
break;
case NN::ContractType::VOTE:
sub.type = TransactionRecord::Vote;
break;
case NN::ContractType::MESSAGE:
// Only display the message type for the first not is mine output
if (!fMessageDisplayed && wallet->IsMine(txout) == ISMINE_NO)
{
sub.type = TransactionRecord::Message;
fMessageDisplayed = true;
}
// Do not display the op return output for a send message contract separately.
else if (txout.scriptPubKey[0] == OP_RETURN)
{
continue;
}
break;
default:
break; // Suppress warning
}
}
parts.append(sub);
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0, 0));
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
// Find the block the tx is in
CBlockIndex* pindex = NULL;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = nBestHeight;
if (!IsFinalTx(wtx, nBestHeight + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.nLockTime - nBestHeight;
}
else
{
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
if (wtx.GetBlocksToMaturity() > 0)
{
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain())
{
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
{
status.status = TransactionStatus::NotAccepted;
}
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
else
{
if (status.depth < 0)
{
status.status = TransactionStatus::Conflicted;
}
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
}
else if (status.depth < RecommendedNumConfirmations)
{
status.status = TransactionStatus::Confirming;
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != nBestHeight;
}
std::string TransactionRecord::getTxID()
{
return hash.ToString();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension should result in a new resource being
// created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("one_in_shelf")));
WaitForResourceChange(3);
// Make sure we also recognize extensions with just background pages.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(4);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<commit_msg>Disable crashy TaskManagerBrowserTest.ReloadExtension on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension should result in a new resource being
// created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("one_in_shelf")));
WaitForResourceChange(3);
// Make sure we also recognize extensions with just background pages.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(4);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
#if defined(OS_WIN)
// Crashy, http://crbug.com/42315.
#define MAYBE_ReloadExtension DISABLED_ReloadExtension
#else
#define MAYBE_ReloadExtension ReloadExtension
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<|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/test_suite.h"
#include "chrome/common/chrome_paths.h"
int main(int argc, char** argv) {
TestSuite test_suite(argc, argv);
// Register Chrome Path provider so that we can get test data dir.
chrome::RegisterPathProvider();
return test_suite.Run();
}
<commit_msg>Fix include.<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/test/test_suite.h"
#include "chrome/common/chrome_paths.h"
int main(int argc, char** argv) {
TestSuite test_suite(argc, argv);
// Register Chrome Path provider so that we can get test data dir.
chrome::RegisterPathProvider();
return test_suite.Run();
}
<|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 "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
namespace {
class GpuFeatureTest : public InProcessBrowserTest {
public:
GpuFeatureTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
void SetupBlacklist(const std::string& json_blacklist) {
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0 unknown");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);
}
void RunTest(const FilePath& url, bool expect_gpu_process) {
using namespace trace_analyzer;
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
test_path = test_path.Append(url);
ASSERT_TRUE(file_util::PathExists(test_path))
<< "Missing test file: " << test_path.value();
ASSERT_TRUE(tracing::BeginTracing("test_gpu"));
ui_test_utils::DOMMessageQueue message_queue;
// Have to use a new tab for the blacklist to work.
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
// Wait for message indicating the test has finished running.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::string json_events;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("GpuProcessLaunched")) != NULL);
}
};
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_compositing\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define WebGLAllowed FLAKY_WebGLAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
#if defined(OS_MACOSX)
// TODO(zmo): enabling Mac when skia backend is enabled.
const bool expect_gpu_process = false;
#else
const bool expect_gpu_process = true;
#endif
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_2d_canvas\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
} // namespace anonymous
<commit_msg>Marking GpuFeatureTest.Canvas2DAllowed flaky on Linux.<commit_after>// 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 "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
namespace {
class GpuFeatureTest : public InProcessBrowserTest {
public:
GpuFeatureTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
void SetupBlacklist(const std::string& json_blacklist) {
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0 unknown");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);
}
void RunTest(const FilePath& url, bool expect_gpu_process) {
using namespace trace_analyzer;
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
test_path = test_path.Append(url);
ASSERT_TRUE(file_util::PathExists(test_path))
<< "Missing test file: " << test_path.value();
ASSERT_TRUE(tracing::BeginTracing("test_gpu"));
ui_test_utils::DOMMessageQueue message_queue;
// Have to use a new tab for the blacklist to work.
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
// Wait for message indicating the test has finished running.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::string json_events;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("GpuProcessLaunched")) != NULL);
}
};
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_compositing\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define WebGLAllowed FLAKY_WebGLAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define Canvas2DAllowed FLAKY_Canvas2DAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
#if defined(OS_MACOSX)
// TODO(zmo): enabling Mac when skia backend is enabled.
const bool expect_gpu_process = false;
#else
const bool expect_gpu_process = true;
#endif
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_2d_canvas\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
} // namespace anonymous
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/test/net/fake_external_tab.h"
#include <exdisp.h>
#include "app/app_paths.h"
#include "app/resource_bundle.h"
#include "app/win_util.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/path_service.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/net/dialog_watchdog.h"
#include "chrome_frame/test/net/test_automation_resource_message_filter.h"
namespace {
// A special command line switch to allow developers to manually launch the
// browser and debug CF inside the browser.
const wchar_t kManualBrowserLaunch[] = L"manual-browser";
// Pops up a message box after the test environment has been set up
// and before tearing it down. Useful for when debugging tests and not
// the test environment that's been set up.
const wchar_t kPromptAfterSetup[] = L"prompt-after-setup";
const int kTestServerPort = 4666;
// The test HTML we use to initialize Chrome Frame.
// Note that there's a little trick in there to avoid an extra URL request
// that the browser will otherwise make for the site's favicon.
// If we don't do this the browser will create a new URL request after
// the CF page has been initialized and that URL request will confuse the
// global URL instance counter in the unit tests and subsequently trip
// some DCHECKs.
const char kChromeFrameHtml[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"<link rel=\"shortcut icon\" href=\"file://c:\\favicon.ico\"/>"
"</head><body>Chrome Frame should now be loaded</body></html>";
bool ShouldLaunchBrowser() {
return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);
}
bool PromptAfterSetup() {
return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);
}
} // end namespace
FakeExternalTab::FakeExternalTab() {
PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);
GetProfilePath(&user_data_dir_);
PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);
process_singleton_.reset(new ProcessSingleton(user_data_dir_));
}
FakeExternalTab::~FakeExternalTab() {
if (!overridden_user_dir_.empty()) {
PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);
}
}
std::wstring FakeExternalTab::GetProfileName() {
return L"iexplore";
}
bool FakeExternalTab::GetProfilePath(FilePath* path) {
if (!chrome::GetChromeFrameUserDataDirectory(path))
return false;
*path = path->Append(GetProfileName());
return true;
}
void FakeExternalTab::Initialize() {
DCHECK(g_browser_process == NULL);
SystemMonitor system_monitor;
// The gears plugin causes the PluginRequestInterceptor to kick in and it
// will cause problems when it tries to intercept URL requests.
PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());
icu_util::Initialize();
chrome::RegisterPathProvider();
app::RegisterPathProvider();
// Load Chrome.dll as our resource dll.
FilePath dll;
PathService::Get(base::DIR_MODULE, &dll);
dll = dll.Append(chrome::kBrowserResourcesDll);
HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),
NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
DCHECK(res_mod);
_AtlBaseModule.SetResourceInstance(res_mod);
ResourceBundle::InitSharedInstance(L"en-US");
CommandLine* cmd = CommandLine::ForCurrentProcess();
cmd->AppendSwitch(switches::kDisableWebResources);
cmd->AppendSwitch(switches::kSingleProcess);
browser_process_.reset(new BrowserProcessImpl(*cmd));
// BrowserProcessImpl's constructor should set g_browser_process.
DCHECK(g_browser_process);
// Set the app locale and create the child threads.
g_browser_process->set_application_locale("en-US");
g_browser_process->db_thread();
g_browser_process->file_thread();
g_browser_process->io_thread();
RenderProcessHost::set_run_renderer_in_process(true);
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(FilePath(user_data()));
PrefService* prefs = profile->GetPrefs();
DCHECK(prefs != NULL);
WebCacheManager::RegisterPrefs(prefs);
PrefService* local_state = browser_process_->local_state();
local_state->RegisterStringPref(prefs::kApplicationLocale, L"");
local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);
browser::RegisterLocalState(local_state);
// Override some settings to avoid hitting some preferences that have not
// been registered.
prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
profile->InitExtensions();
}
void FakeExternalTab::Shutdown() {
browser_process_.reset();
g_browser_process = NULL;
process_singleton_.reset();
ResourceBundle::CleanupSharedInstance();
}
CFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)
: NetTestSuite(argc, argv),
chrome_frame_html_("/chrome_frame", kChromeFrameHtml) {
// Register the main thread by instantiating it, but don't call any methods.
main_thread_.reset(new ChromeThread(ChromeThread::UI,
MessageLoop::current()));
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
fake_chrome_.Initialize();
pss_subclass_.reset(new ProcessSingletonSubclass(this));
EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));
StartChromeFrameInHostBrowser();
}
CFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {
fake_chrome_.Shutdown();
}
void CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {
if (!ShouldLaunchBrowser())
return;
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));
test_http_server_->AddResponse(&chrome_frame_html_);
std::wstring url(StringPrintf(L"http://localhost:%i/chrome_frame",
kTestServerPort).c_str());
// Launch IE. This launches IE correctly on Vista too.
ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));
EXPECT_TRUE(ie_process.IsValid());
// NOTE: If you're running IE8 and CF is not being loaded, you need to
// disable IE8's prebinding until CF properly handles that situation.
//
// HKCU\Software\Microsoft\Internet Explorer\Main
// Value name: EnablePreBinding (REG_DWORD)
// Value: 0
}
void CFUrlRequestUnittestRunner::ShutDownHostBrowser() {
if (ShouldLaunchBrowser()) {
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
}
}
// Override virtual void Initialize to not call icu initialize
void CFUrlRequestUnittestRunner::Initialize() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
// Start by replicating some of the steps that would otherwise be
// done by TestSuite::Initialize. We can't call the base class
// directly because it will attempt to initialize some things such as
// ICU that have already been initialized for this process.
InitializeLogging();
base::Time::UseHighResolutionTimer(true);
#if !defined(PURIFY) && defined(OS_WIN)
logging::SetLogAssertHandler(UnitTestAssertHandler);
#endif // !defined(PURIFY)
// Next, do some initialization for NetTestSuite.
NetTestSuite::InitializeTestThread();
}
void CFUrlRequestUnittestRunner::Shutdown() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
NetTestSuite::Shutdown();
}
void CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(
const std::string& channel_id) {
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(fake_chrome_.user_data());
AutomationProviderList* list =
g_browser_process->InitAutomationProviderList();
DCHECK(list);
list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,
channel_id, this));
}
void CFUrlRequestUnittestRunner::OnInitialTabLoaded() {
test_http_server_.reset();
StartTests();
}
void CFUrlRequestUnittestRunner::RunMainUIThread() {
DCHECK(MessageLoop::current());
DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);
MessageLoop::current()->Run();
}
void CFUrlRequestUnittestRunner::StartTests() {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to run", "", MB_OK);
DCHECK_EQ(test_thread_.IsValid(), false);
test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,
&test_thread_id_));
DCHECK(test_thread_.IsValid());
}
// static
DWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {
PlatformThread::SetName("CFUrlRequestUnittestRunner");
// Needed for some url request tests like the intercept job tests, etc.
NotificationService service;
CFUrlRequestUnittestRunner* me =
reinterpret_cast<CFUrlRequestUnittestRunner*>(param);
me->Run();
me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,
NewRunnableFunction(TakeDownBrowser, me));
return 0;
}
// static
void CFUrlRequestUnittestRunner::TakeDownBrowser(
CFUrlRequestUnittestRunner* me) {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to exit", "", MB_OK);
me->ShutDownHostBrowser();
}
void CFUrlRequestUnittestRunner::InitializeLogging() {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
logging::InitLogging(log_filename.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::DELETE_OLD_LOG_FILE);
// We want process and thread IDs because we may have multiple processes.
// Note: temporarily enabled timestamps in an effort to catch bug 6361.
logging::SetLogItems(true, true, true, true);
}
void FilterDisabledTests() {
if (::testing::FLAGS_gtest_filter.length() &&
::testing::FLAGS_gtest_filter.Compare("*") != 0) {
// Don't override user specified filters.
return;
}
const char* disabled_tests[] = {
// Tests disabled since they're testing the same functionality used
// by the TestAutomationProvider.
"URLRequestTest.Intercept",
"URLRequestTest.InterceptNetworkError",
"URLRequestTest.InterceptRestartRequired",
"URLRequestTest.InterceptRespectsCancelMain",
"URLRequestTest.InterceptRespectsCancelRedirect",
"URLRequestTest.InterceptRespectsCancelFinal",
"URLRequestTest.InterceptRespectsCancelInRestart",
"URLRequestTest.InterceptRedirect",
"URLRequestTest.InterceptServerError",
"URLRequestTestFTP.*",
// Tests that are currently not working:
// Temporarily disabled because they needs user input (login dialog).
"URLRequestTestHTTP.BasicAuth",
"URLRequestTestHTTP.BasicAuthWithCookies",
// HTTPS tests temporarily disabled due to the certificate error dialog.
// TODO(tommi): The tests currently fail though, so need to fix.
"HTTPSRequestTest.HTTPSMismatchedTest",
"HTTPSRequestTest.HTTPSExpiredTest",
// Tests chrome's network stack's cache (might not apply to CF).
"URLRequestTestHTTP.VaryHeader",
// I suspect we can only get this one to work (if at all) on IE8 and
// later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags
// See http://msdn.microsoft.com/en-us/library/aa385328(VS.85).aspx
"URLRequestTest.DoNotSaveCookies",
// TODO(ananta): This test has been consistently failing. Disabling it for
// now.
"URLRequestTestHTTP.GetTest_NoCache",
// These tests have been disabled as the Chrome cookie policies don't make
// sense for the host network stack.
"URLRequestTest.DoNotSaveCookies_ViaPolicy",
"URLRequestTest.DoNotSendCookies_ViaPolicy",
"URLRequestTest.DoNotSaveCookies_ViaPolicy_Async",
"URLRequestTest.CookiePolicy_ForceSession",
};
std::string filter("-"); // All following filters will be negative.
for (int i = 0; i < arraysize(disabled_tests); ++i) {
if (i > 0)
filter += ":";
filter += disabled_tests[i];
}
::testing::FLAGS_gtest_filter = filter;
}
int main(int argc, char** argv) {
DialogWatchdog watchdog;
// See url_request_unittest.cc for these credentials.
SupplyProxyCredentials credentials("user", "secret");
watchdog.AddObserver(&credentials);
testing::InitGoogleTest(&argc, argv);
FilterDisabledTests();
PluginService::EnableChromePlugins(false);
CFUrlRequestUnittestRunner test_suite(argc, argv);
test_suite.RunMainUIThread();
return 0;
}
<commit_msg>Disabling the following net tests for ChromeFrame as this functionality does not exist there.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/test/net/fake_external_tab.h"
#include <exdisp.h>
#include "app/app_paths.h"
#include "app/resource_bundle.h"
#include "app/win_util.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/path_service.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "chrome_frame/test/net/dialog_watchdog.h"
#include "chrome_frame/test/net/test_automation_resource_message_filter.h"
namespace {
// A special command line switch to allow developers to manually launch the
// browser and debug CF inside the browser.
const wchar_t kManualBrowserLaunch[] = L"manual-browser";
// Pops up a message box after the test environment has been set up
// and before tearing it down. Useful for when debugging tests and not
// the test environment that's been set up.
const wchar_t kPromptAfterSetup[] = L"prompt-after-setup";
const int kTestServerPort = 4666;
// The test HTML we use to initialize Chrome Frame.
// Note that there's a little trick in there to avoid an extra URL request
// that the browser will otherwise make for the site's favicon.
// If we don't do this the browser will create a new URL request after
// the CF page has been initialized and that URL request will confuse the
// global URL instance counter in the unit tests and subsequently trip
// some DCHECKs.
const char kChromeFrameHtml[] = "<html><head>"
"<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"
"<link rel=\"shortcut icon\" href=\"file://c:\\favicon.ico\"/>"
"</head><body>Chrome Frame should now be loaded</body></html>";
bool ShouldLaunchBrowser() {
return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);
}
bool PromptAfterSetup() {
return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);
}
} // end namespace
FakeExternalTab::FakeExternalTab() {
PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);
GetProfilePath(&user_data_dir_);
PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);
process_singleton_.reset(new ProcessSingleton(user_data_dir_));
}
FakeExternalTab::~FakeExternalTab() {
if (!overridden_user_dir_.empty()) {
PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);
}
}
std::wstring FakeExternalTab::GetProfileName() {
return L"iexplore";
}
bool FakeExternalTab::GetProfilePath(FilePath* path) {
if (!chrome::GetChromeFrameUserDataDirectory(path))
return false;
*path = path->Append(GetProfileName());
return true;
}
void FakeExternalTab::Initialize() {
DCHECK(g_browser_process == NULL);
SystemMonitor system_monitor;
// The gears plugin causes the PluginRequestInterceptor to kick in and it
// will cause problems when it tries to intercept URL requests.
PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());
icu_util::Initialize();
chrome::RegisterPathProvider();
app::RegisterPathProvider();
// Load Chrome.dll as our resource dll.
FilePath dll;
PathService::Get(base::DIR_MODULE, &dll);
dll = dll.Append(chrome::kBrowserResourcesDll);
HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),
NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
DCHECK(res_mod);
_AtlBaseModule.SetResourceInstance(res_mod);
ResourceBundle::InitSharedInstance(L"en-US");
CommandLine* cmd = CommandLine::ForCurrentProcess();
cmd->AppendSwitch(switches::kDisableWebResources);
cmd->AppendSwitch(switches::kSingleProcess);
browser_process_.reset(new BrowserProcessImpl(*cmd));
// BrowserProcessImpl's constructor should set g_browser_process.
DCHECK(g_browser_process);
// Set the app locale and create the child threads.
g_browser_process->set_application_locale("en-US");
g_browser_process->db_thread();
g_browser_process->file_thread();
g_browser_process->io_thread();
RenderProcessHost::set_run_renderer_in_process(true);
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(FilePath(user_data()));
PrefService* prefs = profile->GetPrefs();
DCHECK(prefs != NULL);
WebCacheManager::RegisterPrefs(prefs);
PrefService* local_state = browser_process_->local_state();
local_state->RegisterStringPref(prefs::kApplicationLocale, L"");
local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);
browser::RegisterLocalState(local_state);
// Override some settings to avoid hitting some preferences that have not
// been registered.
prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);
prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);
prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);
profile->InitExtensions();
}
void FakeExternalTab::Shutdown() {
browser_process_.reset();
g_browser_process = NULL;
process_singleton_.reset();
ResourceBundle::CleanupSharedInstance();
}
CFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)
: NetTestSuite(argc, argv),
chrome_frame_html_("/chrome_frame", kChromeFrameHtml) {
// Register the main thread by instantiating it, but don't call any methods.
main_thread_.reset(new ChromeThread(ChromeThread::UI,
MessageLoop::current()));
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
fake_chrome_.Initialize();
pss_subclass_.reset(new ProcessSingletonSubclass(this));
EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));
StartChromeFrameInHostBrowser();
}
CFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {
fake_chrome_.Shutdown();
}
void CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {
if (!ShouldLaunchBrowser())
return;
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));
test_http_server_->AddResponse(&chrome_frame_html_);
std::wstring url(StringPrintf(L"http://localhost:%i/chrome_frame",
kTestServerPort).c_str());
// Launch IE. This launches IE correctly on Vista too.
ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));
EXPECT_TRUE(ie_process.IsValid());
// NOTE: If you're running IE8 and CF is not being loaded, you need to
// disable IE8's prebinding until CF properly handles that situation.
//
// HKCU\Software\Microsoft\Internet Explorer\Main
// Value name: EnablePreBinding (REG_DWORD)
// Value: 0
}
void CFUrlRequestUnittestRunner::ShutDownHostBrowser() {
if (ShouldLaunchBrowser()) {
win_util::ScopedCOMInitializer com;
chrome_frame_test::CloseAllIEWindows();
}
}
// Override virtual void Initialize to not call icu initialize
void CFUrlRequestUnittestRunner::Initialize() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
// Start by replicating some of the steps that would otherwise be
// done by TestSuite::Initialize. We can't call the base class
// directly because it will attempt to initialize some things such as
// ICU that have already been initialized for this process.
InitializeLogging();
base::Time::UseHighResolutionTimer(true);
#if !defined(PURIFY) && defined(OS_WIN)
logging::SetLogAssertHandler(UnitTestAssertHandler);
#endif // !defined(PURIFY)
// Next, do some initialization for NetTestSuite.
NetTestSuite::InitializeTestThread();
}
void CFUrlRequestUnittestRunner::Shutdown() {
DCHECK(::GetCurrentThreadId() == test_thread_id_);
NetTestSuite::Shutdown();
}
void CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(
const std::string& channel_id) {
Profile* profile = g_browser_process->profile_manager()->
GetDefaultProfile(fake_chrome_.user_data());
AutomationProviderList* list =
g_browser_process->InitAutomationProviderList();
DCHECK(list);
list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,
channel_id, this));
}
void CFUrlRequestUnittestRunner::OnInitialTabLoaded() {
test_http_server_.reset();
StartTests();
}
void CFUrlRequestUnittestRunner::RunMainUIThread() {
DCHECK(MessageLoop::current());
DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);
MessageLoop::current()->Run();
}
void CFUrlRequestUnittestRunner::StartTests() {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to run", "", MB_OK);
DCHECK_EQ(test_thread_.IsValid(), false);
test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,
&test_thread_id_));
DCHECK(test_thread_.IsValid());
}
// static
DWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {
PlatformThread::SetName("CFUrlRequestUnittestRunner");
// Needed for some url request tests like the intercept job tests, etc.
NotificationService service;
CFUrlRequestUnittestRunner* me =
reinterpret_cast<CFUrlRequestUnittestRunner*>(param);
me->Run();
me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,
NewRunnableFunction(TakeDownBrowser, me));
return 0;
}
// static
void CFUrlRequestUnittestRunner::TakeDownBrowser(
CFUrlRequestUnittestRunner* me) {
if (PromptAfterSetup())
MessageBoxA(NULL, "click ok to exit", "", MB_OK);
me->ShutDownHostBrowser();
}
void CFUrlRequestUnittestRunner::InitializeLogging() {
FilePath exe;
PathService::Get(base::FILE_EXE, &exe);
FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
logging::InitLogging(log_filename.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::DELETE_OLD_LOG_FILE);
// We want process and thread IDs because we may have multiple processes.
// Note: temporarily enabled timestamps in an effort to catch bug 6361.
logging::SetLogItems(true, true, true, true);
}
void FilterDisabledTests() {
if (::testing::FLAGS_gtest_filter.length() &&
::testing::FLAGS_gtest_filter.Compare("*") != 0) {
// Don't override user specified filters.
return;
}
const char* disabled_tests[] = {
// Tests disabled since they're testing the same functionality used
// by the TestAutomationProvider.
"URLRequestTest.Intercept",
"URLRequestTest.InterceptNetworkError",
"URLRequestTest.InterceptRestartRequired",
"URLRequestTest.InterceptRespectsCancelMain",
"URLRequestTest.InterceptRespectsCancelRedirect",
"URLRequestTest.InterceptRespectsCancelFinal",
"URLRequestTest.InterceptRespectsCancelInRestart",
"URLRequestTest.InterceptRedirect",
"URLRequestTest.InterceptServerError",
"URLRequestTestFTP.*",
// Tests that are currently not working:
// Temporarily disabled because they needs user input (login dialog).
"URLRequestTestHTTP.BasicAuth",
"URLRequestTestHTTP.BasicAuthWithCookies",
// HTTPS tests temporarily disabled due to the certificate error dialog.
// TODO(tommi): The tests currently fail though, so need to fix.
"HTTPSRequestTest.HTTPSMismatchedTest",
"HTTPSRequestTest.HTTPSExpiredTest",
// Tests chrome's network stack's cache (might not apply to CF).
"URLRequestTestHTTP.VaryHeader",
// I suspect we can only get this one to work (if at all) on IE8 and
// later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags
// See http://msdn.microsoft.com/en-us/library/aa385328(VS.85).aspx
"URLRequestTest.DoNotSaveCookies",
// TODO(ananta): This test has been consistently failing. Disabling it for
// now.
"URLRequestTestHTTP.GetTest_NoCache",
// These tests have been disabled as the Chrome cookie policies don't make
// sense or have not been implemented for the host network stack.
"URLRequestTest.DoNotSaveCookies_ViaPolicy",
"URLRequestTest.DoNotSendCookies_ViaPolicy",
"URLRequestTest.DoNotSaveCookies_ViaPolicy_Async",
"URLRequestTest.CookiePolicy_ForceSession",
"URLRequestTest.DoNotSendCookies",
"URLRequestTest.DoNotSendCookies_ViaPolicy_Async",
"URLRequestTest.CancelTest_During_OnGetCookiesBlocked",
"URLRequestTest.CancelTest_During_OnSetCookieBlocked",
};
std::string filter("-"); // All following filters will be negative.
for (int i = 0; i < arraysize(disabled_tests); ++i) {
if (i > 0)
filter += ":";
filter += disabled_tests[i];
}
::testing::FLAGS_gtest_filter = filter;
}
int main(int argc, char** argv) {
DialogWatchdog watchdog;
// See url_request_unittest.cc for these credentials.
SupplyProxyCredentials credentials("user", "secret");
watchdog.AddObserver(&credentials);
testing::InitGoogleTest(&argc, argv);
FilterDisabledTests();
PluginService::EnableChromePlugins(false);
CFUrlRequestUnittestRunner test_suite(argc, argv);
test_suite.RunMainUIThread();
return 0;
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** rtspconnectionclient.cpp
**
** Interface to an RTSP client connection
**
** -------------------------------------------------------------------------*/
#include "rtspconnectionclient.h"
RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback)
: MediaSink(env)
, m_buffer(NULL)
, m_bufferSize(0)
, m_callback(callback)
, m_markerSize(0)
{
allocate(1024*1024);
}
RTSPConnection::SessionSink::~SessionSink()
{
delete [] m_buffer;
}
void RTSPConnection::SessionSink::allocate(ssize_t bufferSize)
{
m_bufferSize = bufferSize;
m_buffer = new u_int8_t[m_bufferSize];
if (m_callback)
{
m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize);
envir() << "markerSize:" << (int)m_markerSize << "\n";
}
}
void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)
{
if (numTruncatedBytes != 0)
{
delete [] m_buffer;
envir() << "buffer too small " << (int)m_bufferSize << " allocate bigger one\n";
allocate(m_bufferSize*2);
}
else if (m_callback)
{
if (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize, presentationTime))
{
envir() << "NOTIFY failed\n";
}
}
this->continuePlaying();
}
Boolean RTSPConnection::SessionSink::continuePlaying()
{
Boolean ret = False;
if (source() != NULL)
{
source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize,
afterGettingFrame, this,
onSourceClosure, this);
ret = True;
}
return ret;
}
RTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel)
: m_startCallbackTask(NULL)
, m_env(env)
, m_callback(callback)
, m_url(rtspURL)
, m_timeout(timeout)
, m_rtpovertcp(rtpovertcp)
, m_verbosity(verbosityLevel)
, m_rtspClient(NULL)
{
this->start();
}
void RTSPConnection::start(unsigned int delay)
{
m_startCallbackTask = m_env.taskScheduler().scheduleDelayedTask(delay*1000000, TaskstartCallback, this);
}
void RTSPConnection::TaskstartCallback()
{
if (m_rtspClient)
{
Medium::close(m_rtspClient);
}
m_rtspClient = new RTSPClientConnection(*this, m_env, m_callback, m_url.c_str(), m_timeout, m_rtpovertcp, m_verbosity);
}
RTSPConnection::~RTSPConnection()
{
m_env.taskScheduler().unscheduleDelayedTask(m_startCallbackTask);
Medium::close(m_rtspClient);
}
RTSPConnection::RTSPClientConnection::RTSPClientConnection(RTSPConnection& connection, Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel)
: RTSPClientConstrutor(env, rtspURL, verbosityLevel, NULL, 0)
, m_connection(connection)
, m_timeout(timeout)
, m_rtpovertcp(rtpovertcp)
, m_session(NULL)
, m_subSessionIter(NULL)
, m_callback(callback)
, m_nbPacket(0)
{
// start tasks
m_ConnectionTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskConnectionTimeout, this);
// initiate connection process
this->sendNextCommand();
}
RTSPConnection::RTSPClientConnection::~RTSPClientConnection()
{
envir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);
envir().taskScheduler().unscheduleDelayedTask(m_DataArrivalTimeoutTask);
delete m_subSessionIter;
// free subsession
if (m_session != NULL)
{
MediaSubsessionIterator iter(*m_session);
MediaSubsession* subsession;
while ((subsession = iter.next()) != NULL)
{
if (subsession->sink)
{
envir() << "Close session: " << subsession->mediumName() << "/" << subsession->codecName() << "\n";
Medium::close(subsession->sink);
subsession->sink = NULL;
}
}
Medium::close(m_session);
}
}
void RTSPConnection::RTSPClientConnection::sendNextCommand()
{
if (m_subSessionIter == NULL)
{
// no SDP, send DESCRIBE
this->sendDescribeCommand(continueAfterDESCRIBE);
}
else
{
m_subSession = m_subSessionIter->next();
if (m_subSession != NULL)
{
// still subsession to SETUP
if (!m_subSession->initiate())
{
envir() << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n";
this->sendNextCommand();
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession" << "\n";
}
}
this->sendSetupCommand(*m_subSession, continueAfterSETUP, false, m_rtpovertcp);
}
else
{
// no more subsession to SETUP, send PLAY
this->sendPlayCommand(*m_session, continueAfterPLAY);
}
}
}
void RTSPConnection::RTSPClientConnection::continueAfterDESCRIBE(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to DESCRIBE: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "Got SDP:\n" << resultString << "\n";
}
m_session = MediaSession::createNew(envir(), resultString);
m_subSessionIter = new MediaSubsessionIterator(*m_session);
this->sendNextCommand();
}
delete[] resultString;
}
void RTSPConnection::RTSPClientConnection::continueAfterSETUP(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to SETUP: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
m_subSession->sink = SessionSink::createNew(envir(), m_callback);
if (m_subSession->sink == NULL)
{
envir() << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n";
}
else if (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines()))
{
envir() << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession" << "\n";
m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL);
}
}
delete[] resultString;
this->sendNextCommand();
}
void RTSPConnection::RTSPClientConnection::continueAfterPLAY(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to PLAY: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "PLAY OK" << "\n";
}
m_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);
}
envir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);
delete[] resultString;
}
void RTSPConnection::RTSPClientConnection::TaskConnectionTimeout()
{
m_callback->onConnectionTimeout(m_connection);
}
void RTSPConnection::RTSPClientConnection::TaskDataArrivalTimeout()
{
unsigned int newTotNumPacketsReceived = 0;
MediaSubsessionIterator iter(*m_session);
MediaSubsession* subsession;
while ((subsession = iter.next()) != NULL)
{
RTPSource* src = subsession->rtpSource();
if (src != NULL)
{
newTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived();
}
}
if (newTotNumPacketsReceived == m_nbPacket)
{
m_callback->onDataTimeout(m_connection);
}
else
{
m_nbPacket = newTotNumPacketsReceived;
m_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);
}
}
<commit_msg>run onNewSession callback, before onNewBuffer<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** rtspconnectionclient.cpp
**
** Interface to an RTSP client connection
**
** -------------------------------------------------------------------------*/
#include "rtspconnectionclient.h"
RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback)
: MediaSink(env)
, m_buffer(NULL)
, m_bufferSize(0)
, m_callback(callback)
, m_markerSize(0)
{
allocate(1024*1024);
}
RTSPConnection::SessionSink::~SessionSink()
{
delete [] m_buffer;
}
void RTSPConnection::SessionSink::allocate(ssize_t bufferSize)
{
m_bufferSize = bufferSize;
m_buffer = new u_int8_t[m_bufferSize];
if (m_callback)
{
m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize);
envir() << "markerSize:" << (int)m_markerSize << "\n";
}
}
void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)
{
if (numTruncatedBytes != 0)
{
delete [] m_buffer;
envir() << "buffer too small " << (int)m_bufferSize << " allocate bigger one\n";
allocate(m_bufferSize*2);
}
else if (m_callback)
{
if (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize, presentationTime))
{
envir() << "NOTIFY failed\n";
}
}
this->continuePlaying();
}
Boolean RTSPConnection::SessionSink::continuePlaying()
{
Boolean ret = False;
if (source() != NULL)
{
source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize,
afterGettingFrame, this,
onSourceClosure, this);
ret = True;
}
return ret;
}
RTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel)
: m_startCallbackTask(NULL)
, m_env(env)
, m_callback(callback)
, m_url(rtspURL)
, m_timeout(timeout)
, m_rtpovertcp(rtpovertcp)
, m_verbosity(verbosityLevel)
, m_rtspClient(NULL)
{
this->start();
}
void RTSPConnection::start(unsigned int delay)
{
m_startCallbackTask = m_env.taskScheduler().scheduleDelayedTask(delay*1000000, TaskstartCallback, this);
}
void RTSPConnection::TaskstartCallback()
{
if (m_rtspClient)
{
Medium::close(m_rtspClient);
}
m_rtspClient = new RTSPClientConnection(*this, m_env, m_callback, m_url.c_str(), m_timeout, m_rtpovertcp, m_verbosity);
}
RTSPConnection::~RTSPConnection()
{
m_env.taskScheduler().unscheduleDelayedTask(m_startCallbackTask);
Medium::close(m_rtspClient);
}
RTSPConnection::RTSPClientConnection::RTSPClientConnection(RTSPConnection& connection, Environment& env, Callback* callback, const char* rtspURL, int timeout, bool rtpovertcp, int verbosityLevel)
: RTSPClientConstrutor(env, rtspURL, verbosityLevel, NULL, 0)
, m_connection(connection)
, m_timeout(timeout)
, m_rtpovertcp(rtpovertcp)
, m_session(NULL)
, m_subSessionIter(NULL)
, m_callback(callback)
, m_nbPacket(0)
{
// start tasks
m_ConnectionTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskConnectionTimeout, this);
// initiate connection process
this->sendNextCommand();
}
RTSPConnection::RTSPClientConnection::~RTSPClientConnection()
{
envir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);
envir().taskScheduler().unscheduleDelayedTask(m_DataArrivalTimeoutTask);
delete m_subSessionIter;
// free subsession
if (m_session != NULL)
{
MediaSubsessionIterator iter(*m_session);
MediaSubsession* subsession;
while ((subsession = iter.next()) != NULL)
{
if (subsession->sink)
{
envir() << "Close session: " << subsession->mediumName() << "/" << subsession->codecName() << "\n";
Medium::close(subsession->sink);
subsession->sink = NULL;
}
}
Medium::close(m_session);
}
}
void RTSPConnection::RTSPClientConnection::sendNextCommand()
{
if (m_subSessionIter == NULL)
{
// no SDP, send DESCRIBE
this->sendDescribeCommand(continueAfterDESCRIBE);
}
else
{
m_subSession = m_subSessionIter->next();
if (m_subSession != NULL)
{
// still subsession to SETUP
if (!m_subSession->initiate())
{
envir() << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n";
this->sendNextCommand();
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession" << "\n";
}
}
this->sendSetupCommand(*m_subSession, continueAfterSETUP, false, m_rtpovertcp);
}
else
{
// no more subsession to SETUP, send PLAY
this->sendPlayCommand(*m_session, continueAfterPLAY);
}
}
}
void RTSPConnection::RTSPClientConnection::continueAfterDESCRIBE(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to DESCRIBE: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "Got SDP:\n" << resultString << "\n";
}
m_session = MediaSession::createNew(envir(), resultString);
m_subSessionIter = new MediaSubsessionIterator(*m_session);
this->sendNextCommand();
}
delete[] resultString;
}
void RTSPConnection::RTSPClientConnection::continueAfterSETUP(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to SETUP: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
if (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines()))
{
envir() << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession" << "\n";
m_subSession->sink = SessionSink::createNew(envir(), m_callback);
if (m_subSession->sink == NULL)
{
envir() << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n";
} else {
m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL);
}
}
}
delete[] resultString;
this->sendNextCommand();
}
void RTSPConnection::RTSPClientConnection::continueAfterPLAY(int resultCode, char* resultString)
{
if (resultCode != 0)
{
envir() << "Failed to PLAY: " << resultString << "\n";
m_callback->onError(m_connection, resultString);
}
else
{
if (fVerbosityLevel > 1)
{
envir() << "PLAY OK" << "\n";
}
m_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);
}
envir().taskScheduler().unscheduleDelayedTask(m_ConnectionTimeoutTask);
delete[] resultString;
}
void RTSPConnection::RTSPClientConnection::TaskConnectionTimeout()
{
m_callback->onConnectionTimeout(m_connection);
}
void RTSPConnection::RTSPClientConnection::TaskDataArrivalTimeout()
{
unsigned int newTotNumPacketsReceived = 0;
MediaSubsessionIterator iter(*m_session);
MediaSubsession* subsession;
while ((subsession = iter.next()) != NULL)
{
RTPSource* src = subsession->rtpSource();
if (src != NULL)
{
newTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived();
}
}
if (newTotNumPacketsReceived == m_nbPacket)
{
m_callback->onDataTimeout(m_connection);
}
else
{
m_nbPacket = newTotNumPacketsReceived;
m_DataArrivalTimeoutTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this);
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
//
// webcam.cpp --a part of libdecodeqr
//
// Copyright(C) 2007 NISHI Takao <[email protected]>
// JMA (Japan Medical Association)
// NaCl (Network Applied Communication Laboratory Ltd.)
//
// This is free software with ABSOLUTELY NO WARRANTY.
// You can redistribute and/or modify it under the terms of LGPL.
//
// $Id$
//
#include <stdio.h>
#include <highgui.h>
#include "../../libdecodeqr/decodeqr.h"
int main(int argc,char *argv[])
{
//
// start camera
//
CvCapture *capture=cvCaptureFromCAM(0);
if(!capture)
return(-1);
//
// initialize qr decoder
//
QrDecoderHandle decoder=qr_decoder_open();
printf("libdecodeqr version %s\n",qr_decoder_version());
cvNamedWindow("src",1);
cvNamedWindow("bin",1);
puts("Hit [SPACE] key to grab, or any key to end.");
puts("");
//
// 1 shot grabing
//
//
// allocate grabed buffer to decoder
//
int key=-1;
IplImage *camera=cvQueryFrame(capture);
IplImage *src=NULL;
if(camera){
src=cvCloneImage(camera);
qr_decoder_set_image_buffer(decoder,src);
}
else
key=1;
unsigned char *text=NULL;
int text_size=0;
while(key<=0){
cvShowImage("src",camera);
key=cvWaitKey(150);
//
// when [SPACE] key pressed, do decode.
//
if(key==0x20&&!qr_decoder_is_busy(decoder)){
key=-1;
//
// if left-bottom origin (MS-Windows style) format,
// it must be converted to left-top origin.
//
if(camera->origin)
cvConvertImage(camera,src,CV_CVTIMG_FLIP);
else
cvCopy(camera,src);
//
// While decoding is a failure, decrease the
// adaptive_th_size parameter.
// Note that the adaptive_th_size must be odd.
//
short sz,stat;
for(sz=25,stat=0;
(sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);
sz-=2)
stat=qr_decoder_decode(decoder,sz);
//
// for debug, show binarized image.
//
cvShowImage("bin",
qr_decoder_get_binarized_image_buffer(decoder));
printf("adaptive_th_size=%d, status=%04x\n",sz,stat);
//
// on suceed decoding, print decoded text.
//
QrCodeHeader header;
if(qr_decoder_get_header(decoder,&header)){
if(text_size<header.byte_size+1){
if(text)
delete text;
text_size=header.byte_size+1;
text=new unsigned char[text_size];
}
qr_decoder_get_body(decoder,text,text_size);
printf("%s\n\n",text);
//
// draw found code region with green line
//
CvPoint *vertexes=qr_decoder_get_coderegion_vertexes(decoder);
CvPoint pt=vertexes[3];
int i;
for(i=0;i<4;i++){
cvLine(src,pt,vertexes[i],CV_RGB(0,255,0),3);
pt=vertexes[i];
}
//
// draw found finder patterns with green ellipse
//
CvBox2D *boxes=qr_decoder_get_finderpattern_boxes(decoder);
for(i=0;i<3;i++){
CvSize sz=cvSize((int)boxes[i].size.width/2,
(int)boxes[i].size.height/2);
cvEllipse(src,
cvPointFrom32f(boxes[i].center),
sz,
boxes[i].angle,
0,360,
CV_RGB(0,255,0),2);
}
if(src->origin)
cvConvertImage(src,src,CV_CVTIMG_FLIP);
cvShowImage("src",src);
//
// wait 1500msec.
//
key=cvWaitKey(1500);
}
}
camera=cvQueryFrame(capture);
if(!camera)
break;
}
if(text)
delete text;
qr_decoder_close(decoder);
if(src)
cvReleaseImage(&src);
cvReleaseCapture(&capture);
return(0);
}
<commit_msg>src/sample/webcam/webcam.cpp: * dumps core bug fixed?<commit_after>/////////////////////////////////////////////////////////////////////////
//
// webcam.cpp --a part of libdecodeqr
//
// Copyright(C) 2007 NISHI Takao <[email protected]>
// JMA (Japan Medical Association)
// NaCl (Network Applied Communication Laboratory Ltd.)
//
// This is free software with ABSOLUTELY NO WARRANTY.
// You can redistribute and/or modify it under the terms of LGPL.
//
// $Id$
//
#include <stdio.h>
#include <highgui.h>
#include "../../libdecodeqr/decodeqr.h"
int main(int argc,char *argv[])
{
//
// start camera
//
CvCapture *capture=cvCaptureFromCAM(0);
if(!capture)
return(-1);
//
// initialize qr decoder
//
QrDecoderHandle decoder=qr_decoder_open();
printf("libdecodeqr version %s\n",qr_decoder_version());
cvNamedWindow("src",1);
cvNamedWindow("bin",1);
puts("Hit [SPACE] key to grab, or any key to end.");
puts("");
//
// 1 shot grabing
//
//
// allocate grabed buffer to decoder
//
int key=-1;
IplImage *camera=cvQueryFrame(capture);
IplImage *src=NULL,*bin=NULL;
if(camera){
src=cvCloneImage(camera);
qr_decoder_set_image_buffer(decoder,src);
}
else
key=1;
unsigned char *text=NULL;
int text_size=0;
while(key<=0){
cvShowImage("src",camera);
key=cvWaitKey(150);
//
// when [SPACE] key pressed, do decode.
//
if(key==0x20&&!qr_decoder_is_busy(decoder)){
key=-1;
//
// if left-bottom origin (MS-Windows style) format,
// it must be converted to left-top origin.
//
if(camera->origin)
cvConvertImage(camera,src,CV_CVTIMG_FLIP);
else
cvCopy(camera,src);
//
// While decoding is a failure, decrease the
// adaptive_th_size parameter.
// Note that the adaptive_th_size must be odd.
//
short sz,stat;
for(sz=25,stat=0;
(sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);
sz-=2)
stat=qr_decoder_decode(decoder,sz);
//
// for debug, show binarized image.
//
if(bin)
cvReleaseImage(&bin);
bin=cvCloneImage(qr_decoder_get_binarized_image_buffer(decoder));
cvShowImage("bin",bin);
printf("adaptive_th_size=%d, status=%04x\n",sz,stat);
//
// on suceed decoding, print decoded text.
//
QrCodeHeader header;
if(qr_decoder_get_header(decoder,&header)){
if(text_size<header.byte_size+1){
if(text)
delete text;
text_size=header.byte_size+1;
text=new unsigned char[text_size];
}
qr_decoder_get_body(decoder,text,text_size);
printf("%s\n\n",text);
//
// draw found code region with green line
//
CvPoint *vertexes=qr_decoder_get_coderegion_vertexes(decoder);
CvPoint pt=vertexes[3];
int i;
for(i=0;i<4;i++){
cvLine(src,pt,vertexes[i],CV_RGB(0,255,0),3);
pt=vertexes[i];
}
//
// draw found finder patterns with green ellipse
//
CvBox2D *boxes=qr_decoder_get_finderpattern_boxes(decoder);
for(i=0;i<3;i++){
CvSize sz=cvSize((int)boxes[i].size.width/2,
(int)boxes[i].size.height/2);
cvEllipse(src,
cvPointFrom32f(boxes[i].center),
sz,
boxes[i].angle,
0,360,
CV_RGB(0,255,0),2);
}
if(src->origin)
cvConvertImage(src,src,CV_CVTIMG_FLIP);
cvShowImage("src",src);
//
// wait 1500msec.
//
key=cvWaitKey(1500);
}
}
camera=cvQueryFrame(capture);
if(!camera)
break;
}
if(text)
delete text;
qr_decoder_close(decoder);
if(bin)
cvReleaseImage(&bin);
if(src)
cvReleaseImage(&src);
cvReleaseCapture(&capture);
return(0);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../Util/GitDescription.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/TimingUtil.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#ifdef __linux__
#include <malloc.h>
#endif
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <numeric>
#include <vector>
const unsigned number_of_elements = 268435456;
struct Statistics
{
double min, max, med, mean, dev;
};
void RunStatistics(std::vector<double> &timings_vector, Statistics &stats)
{
std::sort(timings_vector.begin(), timings_vector.end());
stats.min = timings_vector.front();
stats.max = timings_vector.back();
stats.med = timings_vector[timings_vector.size() / 2];
double primary_sum = std::accumulate(timings_vector.begin(), timings_vector.end(), 0.0);
stats.mean = primary_sum / timings_vector.size();
double primary_sq_sum = std::inner_product(
timings_vector.begin(), timings_vector.end(), timings_vector.begin(), 0.0);
stats.dev = std::sqrt(primary_sq_sum / timings_vector.size() - (stats.mean * stats.mean));
}
int main(int argc, char *argv[])
{
LogPolicy::GetInstance().Unmute();
SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", "
<< "compiled at " << __DATE__ << ", " __TIME__;
#ifdef __FreeBSD__
SimpleLogger().Write() << "Not supported on FreeBSD";
return 0;
#endif
if (1 == argc)
{
SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device";
return -1;
}
boost::filesystem::path test_path = boost::filesystem::path(argv[1]);
test_path /= "osrm.tst";
SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string();
try
{
// create files for testing
if (2 == argc)
{
// create file to test
if (boost::filesystem::exists(test_path))
{
throw OSRMException("Data file already exists");
}
int *random_array = new int[number_of_elements];
std::generate(random_array, random_array + number_of_elements, std::rand);
#ifdef __APPLE__
FILE *fd = fopen(test_path.string().c_str(), "w");
fcntl(fileno(fd), F_NOCACHE, 1);
fcntl(fileno(fd), F_RDAHEAD, 0);
TIMER_START(write_1gb);
write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned));
TIMER_STOP(write_1gb);
fclose(fd);
#endif
#ifdef __linux__
int f =
open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU);
if (-1 == f)
{
throw OSRMException("Could not open random data file");
}
TIMER_START(write_1gb);
int ret = write(f, random_array, number_of_elements * sizeof(unsigned));
if (0 > ret)
{
throw OSRMException("could not write random data file");
}
TIMER_STOP(write_1gb);
close(f);
#endif
delete[] random_array;
SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb)
<< "s";
SimpleLogger().Write() << "raw write performance: " << std::setprecision(5)
<< std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb)
<< "MB/sec";
SimpleLogger().Write(logDEBUG)
<< "finished creation of random data. Flush disk cache now!";
}
else
{
// Run Non-Cached I/O benchmarks
if (!boost::filesystem::exists(test_path))
{
throw OSRMException("data file does not exist");
}
// volatiles do not get optimized
Statistics stats;
#ifdef __APPLE__
volatile unsigned single_block[1024];
char *raw_array = new char[number_of_elements * sizeof(unsigned)];
FILE *fd = fopen(test_path.string().c_str(), "r");
fcntl(fileno(fd), F_NOCACHE, 1);
fcntl(fileno(fd), F_RDAHEAD, 0);
#endif
#ifdef __linux__
char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned));
int f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
if (-1 == f)
{
SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
return -1;
}
char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned));
#endif
TIMER_START(read_1gb);
#ifdef __APPLE__
read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned));
close(fileno(fd));
fd = fopen(test_path.string().c_str(), "r");
#endif
#ifdef __linux__
int ret = read(f, raw_array, number_of_elements * sizeof(unsigned));
SimpleLogger().Write(logDEBUG) << "read " << ret
<< " bytes, error: " << strerror(errno);
close(f);
f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
#endif
TIMER_STOP(read_1gb);
SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb)
<< "s";
SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed
<< 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec";
std::vector<double> timing_results_raw_random;
SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB";
#ifdef __APPLE__
fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
lseek(f, 0, SEEK_SET);
#endif
// make 1000 random access, time each I/O seperately
unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) / 4096;
for (unsigned i = 0; i < 1000; ++i)
{
unsigned block_to_read = std::rand() % number_of_blocks;
off_t current_offset = block_to_read * 4096;
TIMER_START(random_access);
#ifdef __APPLE__
int ret1 = fseek(fd, current_offset, SEEK_SET);
int ret2 = read(fileno(fd), (char *)&single_block[0], 4096);
#endif
#ifdef __FreeBSD__
int ret1 = 0;
int ret2 = 0;
#endif
#ifdef __linux__
int ret1 = lseek(f, current_offset, SEEK_SET);
int ret2 = read(f, (char *)single_block, 4096);
#endif
TIMER_STOP(random_access);
if (((off_t) - 1) == ret1)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
throw OSRMException("seek error");
}
if (-1 == ret2)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
throw OSRMException("read error");
}
timing_results_raw_random.push_back(TIMER_SEC(random_access));
}
// Do statistics
SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics";
std::ofstream random_csv("random.csv", std::ios::trunc);
for (unsigned i = 0; i < timing_results_raw_random.size(); ++i)
{
random_csv << i << ", " << timing_results_raw_random[i] << std::endl;
}
random_csv.close();
RunStatistics(timing_results_raw_random, stats);
SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed
<< "min: " << stats.min << "ms, "
<< "mean: " << stats.mean << "ms, "
<< "med: " << stats.med << "ms, "
<< "max: " << stats.max << "ms, "
<< "dev: " << stats.dev << "ms";
std::vector<double> timing_results_raw_seq;
#ifdef __APPLE__
fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
lseek(f, 0, SEEK_SET);
#endif
// read every 100th block
for (unsigned i = 0; i < 1000; ++i)
{
off_t current_offset = i * 4096;
TIMER_START(read_every_100);
#ifdef __APPLE__
int ret1 = fseek(fd, current_offset, SEEK_SET);
int ret2 = read(fileno(fd), (char *)&single_block, 4096);
#endif
#ifdef __FreeBSD__
int ret1 = 0;
int ret2 = 0;
#endif
#ifdef __linux__
int ret1 = lseek(f, current_offset, SEEK_SET);
int ret2 = read(f, (char *)single_block, 4096);
#endif
TIMER_STOP(read_every_100);
if (((off_t) - 1) == ret1)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
throw OSRMException("seek error");
}
if (-1 == ret2)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
throw OSRMException("read error");
}
timing_results_raw_seq.push_back(TIMER_SEC(read_every_100));
}
#ifdef __APPLE__
fclose(fd);
// free(single_element);
free(raw_array);
// free(single_block);
#endif
#ifdef __linux__
close(f);
#endif
// Do statistics
SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics";
// print simple statistics: min, max, median, variance
std::ofstream seq_csv("sequential.csv", std::ios::trunc);
for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i)
{
seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl;
}
seq_csv.close();
RunStatistics(timing_results_raw_seq, stats);
SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed
<< "min: " << stats.min << "ms, "
<< "mean: " << stats.mean << "ms, "
<< "med: " << stats.med << "ms, "
<< "max: " << stats.max << "ms, "
<< "dev: " << stats.dev << "ms";
if (boost::filesystem::exists(test_path))
{
boost::filesystem::remove(test_path);
SimpleLogger().Write(logDEBUG) << "removing temporary files";
}
}
}
catch (const std::exception &e)
{
SimpleLogger().Write(logWARNING) << "caught exception: " << e.what();
SimpleLogger().Write(logWARNING) << "cleaning up, and exiting";
if (boost::filesystem::exists(test_path))
{
boost::filesystem::remove(test_path);
SimpleLogger().Write(logWARNING) << "removing temporary files";
}
return -1;
}
return 0;
}
<commit_msg>disable io-benchmark on Windows<commit_after>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../Util/GitDescription.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/TimingUtil.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#ifdef __linux__
#include <malloc.h>
#endif
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <numeric>
#include <vector>
const unsigned number_of_elements = 268435456;
struct Statistics
{
double min, max, med, mean, dev;
};
void RunStatistics(std::vector<double> &timings_vector, Statistics &stats)
{
std::sort(timings_vector.begin(), timings_vector.end());
stats.min = timings_vector.front();
stats.max = timings_vector.back();
stats.med = timings_vector[timings_vector.size() / 2];
double primary_sum = std::accumulate(timings_vector.begin(), timings_vector.end(), 0.0);
stats.mean = primary_sum / timings_vector.size();
double primary_sq_sum = std::inner_product(
timings_vector.begin(), timings_vector.end(), timings_vector.begin(), 0.0);
stats.dev = std::sqrt(primary_sq_sum / timings_vector.size() - (stats.mean * stats.mean));
}
int main(int argc, char *argv[])
{
LogPolicy::GetInstance().Unmute();
SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", "
<< "compiled at " << __DATE__ << ", " __TIME__;
#ifdef __FreeBSD__
SimpleLogger().Write() << "Not supported on FreeBSD";
return 0;
#endif
#ifdef WIN32
SimpleLogger().Write() << "Not supported on Windows";
return 0;
#else
if (1 == argc)
{
SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device";
return -1;
}
boost::filesystem::path test_path = boost::filesystem::path(argv[1]);
test_path /= "osrm.tst";
SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string();
try
{
// create files for testing
if (2 == argc)
{
// create file to test
if (boost::filesystem::exists(test_path))
{
throw OSRMException("Data file already exists");
}
int *random_array = new int[number_of_elements];
std::generate(random_array, random_array + number_of_elements, std::rand);
#ifdef __APPLE__
FILE *fd = fopen(test_path.string().c_str(), "w");
fcntl(fileno(fd), F_NOCACHE, 1);
fcntl(fileno(fd), F_RDAHEAD, 0);
TIMER_START(write_1gb);
write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned));
TIMER_STOP(write_1gb);
fclose(fd);
#endif
#ifdef __linux__
int f =
open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU);
if (-1 == f)
{
throw OSRMException("Could not open random data file");
}
TIMER_START(write_1gb);
int ret = write(f, random_array, number_of_elements * sizeof(unsigned));
if (0 > ret)
{
throw OSRMException("could not write random data file");
}
TIMER_STOP(write_1gb);
close(f);
#endif
delete[] random_array;
SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb)
<< "s";
SimpleLogger().Write() << "raw write performance: " << std::setprecision(5)
<< std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb)
<< "MB/sec";
SimpleLogger().Write(logDEBUG)
<< "finished creation of random data. Flush disk cache now!";
}
else
{
// Run Non-Cached I/O benchmarks
if (!boost::filesystem::exists(test_path))
{
throw OSRMException("data file does not exist");
}
// volatiles do not get optimized
Statistics stats;
#ifdef __APPLE__
volatile unsigned single_block[1024];
char *raw_array = new char[number_of_elements * sizeof(unsigned)];
FILE *fd = fopen(test_path.string().c_str(), "r");
fcntl(fileno(fd), F_NOCACHE, 1);
fcntl(fileno(fd), F_RDAHEAD, 0);
#endif
#ifdef __linux__
char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned));
int f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
if (-1 == f)
{
SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
return -1;
}
char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned));
#endif
TIMER_START(read_1gb);
#ifdef __APPLE__
read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned));
close(fileno(fd));
fd = fopen(test_path.string().c_str(), "r");
#endif
#ifdef __linux__
int ret = read(f, raw_array, number_of_elements * sizeof(unsigned));
SimpleLogger().Write(logDEBUG) << "read " << ret
<< " bytes, error: " << strerror(errno);
close(f);
f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
#endif
TIMER_STOP(read_1gb);
SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb)
<< "s";
SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed
<< 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec";
std::vector<double> timing_results_raw_random;
SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB";
#ifdef __APPLE__
fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
lseek(f, 0, SEEK_SET);
#endif
// make 1000 random access, time each I/O seperately
unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) / 4096;
for (unsigned i = 0; i < 1000; ++i)
{
unsigned block_to_read = std::rand() % number_of_blocks;
off_t current_offset = block_to_read * 4096;
TIMER_START(random_access);
#ifdef __APPLE__
int ret1 = fseek(fd, current_offset, SEEK_SET);
int ret2 = read(fileno(fd), (char *)&single_block[0], 4096);
#endif
#ifdef __FreeBSD__
int ret1 = 0;
int ret2 = 0;
#endif
#ifdef __linux__
int ret1 = lseek(f, current_offset, SEEK_SET);
int ret2 = read(f, (char *)single_block, 4096);
#endif
TIMER_STOP(random_access);
if (((off_t) - 1) == ret1)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
throw OSRMException("seek error");
}
if (-1 == ret2)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
throw OSRMException("read error");
}
timing_results_raw_random.push_back(TIMER_SEC(random_access));
}
// Do statistics
SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics";
std::ofstream random_csv("random.csv", std::ios::trunc);
for (unsigned i = 0; i < timing_results_raw_random.size(); ++i)
{
random_csv << i << ", " << timing_results_raw_random[i] << std::endl;
}
random_csv.close();
RunStatistics(timing_results_raw_random, stats);
SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed
<< "min: " << stats.min << "ms, "
<< "mean: " << stats.mean << "ms, "
<< "med: " << stats.med << "ms, "
<< "max: " << stats.max << "ms, "
<< "dev: " << stats.dev << "ms";
std::vector<double> timing_results_raw_seq;
#ifdef __APPLE__
fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
lseek(f, 0, SEEK_SET);
#endif
// read every 100th block
for (unsigned i = 0; i < 1000; ++i)
{
off_t current_offset = i * 4096;
TIMER_START(read_every_100);
#ifdef __APPLE__
int ret1 = fseek(fd, current_offset, SEEK_SET);
int ret2 = read(fileno(fd), (char *)&single_block, 4096);
#endif
#ifdef __FreeBSD__
int ret1 = 0;
int ret2 = 0;
#endif
#ifdef __linux__
int ret1 = lseek(f, current_offset, SEEK_SET);
int ret2 = read(f, (char *)single_block, 4096);
#endif
TIMER_STOP(read_every_100);
if (((off_t) - 1) == ret1)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
throw OSRMException("seek error");
}
if (-1 == ret2)
{
SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
throw OSRMException("read error");
}
timing_results_raw_seq.push_back(TIMER_SEC(read_every_100));
}
#ifdef __APPLE__
fclose(fd);
// free(single_element);
free(raw_array);
// free(single_block);
#endif
#ifdef __linux__
close(f);
#endif
// Do statistics
SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics";
// print simple statistics: min, max, median, variance
std::ofstream seq_csv("sequential.csv", std::ios::trunc);
for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i)
{
seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl;
}
seq_csv.close();
RunStatistics(timing_results_raw_seq, stats);
SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed
<< "min: " << stats.min << "ms, "
<< "mean: " << stats.mean << "ms, "
<< "med: " << stats.med << "ms, "
<< "max: " << stats.max << "ms, "
<< "dev: " << stats.dev << "ms";
if (boost::filesystem::exists(test_path))
{
boost::filesystem::remove(test_path);
SimpleLogger().Write(logDEBUG) << "removing temporary files";
}
}
}
catch (const std::exception &e)
{
SimpleLogger().Write(logWARNING) << "caught exception: " << e.what();
SimpleLogger().Write(logWARNING) << "cleaning up, and exiting";
if (boost::filesystem::exists(test_path))
{
boost::filesystem::remove(test_path);
SimpleLogger().Write(logWARNING) << "removing temporary files";
}
return -1;
}
return 0;
#endif
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLog10ImageFilterAndAdaptorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <itkImage.h>
#include <itkLog10ImageFilter.h>
#include <itkLog10ImageAdaptor.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkSubtractImageFilter.h>
int itkLog10ImageFilterAndAdaptorTest(int, char* [] )
{
// Define the dimension of the images
const unsigned int ImageDimension = 3;
// Declare the types of the images
typedef itk::Image<float, ImageDimension> InputImageType;
typedef itk::Image<float, ImageDimension> OutputImageType;
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex<
InputImageType> InputIteratorType;
typedef itk::ImageRegionIteratorWithIndex<
OutputImageType> OutputIteratorType;
// Declare the type of the index to access images
typedef itk::Index<ImageDimension> IndexType;
// Declare the type of the size
typedef itk::Size<ImageDimension> SizeType;
// Declare the type of the Region
typedef itk::ImageRegion<ImageDimension> RegionType;
// Create two images
InputImageType::Pointer inputImage = InputImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->SetRequestedRegion( region );
inputImage->Allocate();
// Create one iterator for the Input Image (this is a light object)
InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );
// Initialize the content of Image A
const double value = vnl_math::pi / 6.0;
std::cout << "Content of the Input " << std::endl;
it.GoToBegin();
while( !it.IsAtEnd() )
{
it.Set( value );
std::cout << it.Get() << std::endl;
++it;
}
// Declare the type for the Log10 filter
typedef itk::Log10ImageFilter< InputImageType,
OutputImageType > FilterType;
// Create an ADD Filter
FilterType::Pointer filter = FilterType::New();
// Connect the input images
filter->SetInput( inputImage );
// Get the Smart Pointer to the Filter Output
OutputImageType::Pointer outputImage = filter->GetOutput();
// Execute the filter
filter->Update();
filter->SetFunctor(filter->GetFunctor());
// Create an iterator for going through the image output
OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion());
// Check the content of the result image
std::cout << "Verification of the output " << std::endl;
const OutputImageType::PixelType epsilon = 1e-6;
ot.GoToBegin();
it.GoToBegin();
while( !ot.IsAtEnd() )
{
std::cout << ot.Get() << " = ";
std::cout << log10( it.Get() ) << std::endl;
const InputImageType::PixelType input = it.Get();
const OutputImageType::PixelType output = ot.Get();
const OutputImageType::PixelType naturallog = log10(input);
if( vcl_fabs( naturallog - output ) > epsilon )
{
std::cerr << "Error in itkLog10ImageFilterTest " << std::endl;
std::cerr << " log10( " << input << ") = " << naturallog << std::endl;
std::cerr << " differs from " << output;
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++ot;
++it;
}
//---------------------------------------
// This section tests for Log10ImageAdaptor
//---------------------------------------
typedef itk::Log10ImageAdaptor<InputImageType,
OutputImageType::PixelType> AdaptorType;
AdaptorType::Pointer log10Adaptor = AdaptorType::New();
log10Adaptor->SetImage( inputImage );
typedef itk::SubtractImageFilter<
OutputImageType,
AdaptorType,
OutputImageType > DiffFilterType;
DiffFilterType::Pointer diffFilter = DiffFilterType::New();
diffFilter->SetInput1( outputImage );
diffFilter->SetInput2( log10Adaptor );
diffFilter->Update();
// Get the Smart Pointer to the Diff filter Output
OutputImageType::Pointer diffImage = diffFilter->GetOutput();
// Check the content of the diff image
std::cout << "Comparing the results with those of an Adaptor" << std::endl;
std::cout << "Verification of the output " << std::endl;
// Create an iterator for going through the image output
OutputIteratorType dt(diffImage, diffImage->GetRequestedRegion());
dt.GoToBegin();
while( !dt.IsAtEnd() )
{
std::cout << dt.Get() << std::endl;
const OutputImageType::PixelType diff = dt.Get();
if( vcl_fabs( diff ) > epsilon )
{
std::cerr << "Error in itkLog10ImageFilterTest " << std::endl;
std::cerr << "Comparing results with Adaptors" << std::endl;
std::cerr << " difference = " << diff << std::endl;
std::cerr << " differs from 0 ";
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++dt;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: Replacing "log10" with "vcl_log10" in order to support Sun-CC and -stlport4.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLog10ImageFilterAndAdaptorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkLog10ImageFilter.h"
#include "itkLog10ImageAdaptor.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkSubtractImageFilter.h"
int itkLog10ImageFilterAndAdaptorTest(int, char* [] )
{
// Define the dimension of the images
const unsigned int ImageDimension = 3;
// Declare the types of the images
typedef itk::Image<float, ImageDimension> InputImageType;
typedef itk::Image<float, ImageDimension> OutputImageType;
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex<
InputImageType> InputIteratorType;
typedef itk::ImageRegionIteratorWithIndex<
OutputImageType> OutputIteratorType;
// Declare the type of the index to access images
typedef itk::Index<ImageDimension> IndexType;
// Declare the type of the size
typedef itk::Size<ImageDimension> SizeType;
// Declare the type of the Region
typedef itk::ImageRegion<ImageDimension> RegionType;
// Create two images
InputImageType::Pointer inputImage = InputImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->SetRequestedRegion( region );
inputImage->Allocate();
// Create one iterator for the Input Image (this is a light object)
InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );
// Initialize the content of Image A
const double value = vnl_math::pi / 6.0;
std::cout << "Content of the Input " << std::endl;
it.GoToBegin();
while( !it.IsAtEnd() )
{
it.Set( value );
std::cout << it.Get() << std::endl;
++it;
}
// Declare the type for the Log10 filter
typedef itk::Log10ImageFilter< InputImageType,
OutputImageType > FilterType;
// Create an ADD Filter
FilterType::Pointer filter = FilterType::New();
// Connect the input images
filter->SetInput( inputImage );
// Get the Smart Pointer to the Filter Output
OutputImageType::Pointer outputImage = filter->GetOutput();
// Execute the filter
filter->Update();
filter->SetFunctor(filter->GetFunctor());
// Create an iterator for going through the image output
OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion());
// Check the content of the result image
std::cout << "Verification of the output " << std::endl;
const OutputImageType::PixelType epsilon = 1e-6;
ot.GoToBegin();
it.GoToBegin();
while( !ot.IsAtEnd() )
{
std::cout << ot.Get() << " = ";
std::cout << vcl_log10( it.Get() ) << std::endl;
const InputImageType::PixelType input = it.Get();
const OutputImageType::PixelType output = ot.Get();
const OutputImageType::PixelType naturallog = vcl_log10(input);
if( vcl_fabs( naturallog - output ) > epsilon )
{
std::cerr << "Error in itkLog10ImageFilterTest " << std::endl;
std::cerr << " vcl_log10( " << input << ") = " << naturallog << std::endl;
std::cerr << " differs from " << output;
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++ot;
++it;
}
//---------------------------------------
// This section tests for Log10ImageAdaptor
//---------------------------------------
typedef itk::Log10ImageAdaptor<InputImageType,
OutputImageType::PixelType> AdaptorType;
AdaptorType::Pointer log10Adaptor = AdaptorType::New();
log10Adaptor->SetImage( inputImage );
typedef itk::SubtractImageFilter<
OutputImageType,
AdaptorType,
OutputImageType > DiffFilterType;
DiffFilterType::Pointer diffFilter = DiffFilterType::New();
diffFilter->SetInput1( outputImage );
diffFilter->SetInput2( log10Adaptor );
diffFilter->Update();
// Get the Smart Pointer to the Diff filter Output
OutputImageType::Pointer diffImage = diffFilter->GetOutput();
// Check the content of the diff image
std::cout << "Comparing the results with those of an Adaptor" << std::endl;
std::cout << "Verification of the output " << std::endl;
// Create an iterator for going through the image output
OutputIteratorType dt(diffImage, diffImage->GetRequestedRegion());
dt.GoToBegin();
while( !dt.IsAtEnd() )
{
std::cout << dt.Get() << std::endl;
const OutputImageType::PixelType diff = dt.Get();
if( vcl_fabs( diff ) > epsilon )
{
std::cerr << "Error in itkLog10ImageFilterTest " << std::endl;
std::cerr << "Comparing results with Adaptors" << std::endl;
std::cerr << " difference = " << diff << std::endl;
std::cerr << " differs from 0 ";
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++dt;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, Ӱ
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "stdafx.h"
#include "IkhWinLib2/COpenGLWnd.h"
BEGIN_IKHWINLIB2()
BEGIN_MSGMAP(COpenGLWnd, CWindow)
MSGMAP_WM_CREATE(OnCreate)
MSGMAP_WM_SIZE(OnSize)
MSGMAP_WM_DESTROY(OnDestroy)
END_MSGMAP(COpenGLWnd, CWindow)
COpenGLWnd::COpenGLWnd(BYTE cDepthBits /* = 24 */, BYTE cStencilBits /* = 8 */)
: m_cDepthBits(cDepthBits), m_cStencilBits(cStencilBits),
, m_fps(0), m_hdc(nullptr)
, m_count(0), m_gap(0), m_PrevTime(0), m_bCalced(false)
{
}
BOOL COpenGLWnd::OnCreate(LPCREATESTRUCT lpcs)
{
if (!MSG_FORWARD_WM_CREATE(CWindow, lpcs))
return FALSE;
PIXELFORMATDESCRIPTOR pfd;
int nPixelFormat;
m_hdc = GetDC(*this);
RECT rt;
GetClientRect(*this, &rt);
m_cx = rt.right;
m_cy = rt.bottom;
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = m_cDepthBits;
pfd.cStencilBits = m_cStencilBits;
pfd.iLayerType = PFD_MAIN_PLANE;
nPixelFormat = ChoosePixelFormat(m_hdc, &pfd);
if (nPixelFormat != 0)
{
if (SetPixelFormat(m_hdc, nPixelFormat, &pfd))
{
return TRUE;
}
}
return FALSE;
}
void COpenGLWnd::OnSize(UINT state, int cx, int cy)
{
MSG_FORWARD_WM_SIZE(CWindow, state, cx, cy);
m_cx = cx;
m_cy = cy;
}
void COpenGLWnd::OnDestroy()
{
wglMakeCurrent(m_hdc, nullptr);
MSG_FORWARD_WM_DESTROY(CWindow);
}
HGLRC COpenGLWnd::InitGL()
{
assert(this != nullptr);
HGLRC hrc = wglCreateContext(m_hdc);
wglMakeCurrent(m_hdc, hrc);
return hrc;
}
void COpenGLWnd::DestroyGL(HGLRC hrc)
{
assert(this != nullptr);
wglDeleteContext(hrc);
}
void COpenGLWnd::SizeChangeProc()
{
glViewport(0, 0, m_cx, m_cy);
}
unsigned COpenGLWnd::CalcFPS()
{
assert(this != nullptr);
DWORD now = GetTickCount();
if (!m_bCalced)
{
m_PrevTime = now;
m_bCalced = true;
}
m_gap = now - m_PrevTime;
m_count++;
if (m_gap >= 1000)
{
m_PrevTime = now;
m_gap -= 1000;
m_fps = m_count;
m_count = 0;
}
return m_fps;
}
END_IKHWINLIB2()
<commit_msg>minor change (fix) (#9) (#10)<commit_after>// Copyright (c) 2014, Ӱ
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "stdafx.h"
#include "IkhWinLib2/COpenGLWnd.h"
BEGIN_IKHWINLIB2()
BEGIN_MSGMAP(COpenGLWnd, CWindow)
MSGMAP_WM_CREATE(OnCreate)
MSGMAP_WM_SIZE(OnSize)
MSGMAP_WM_DESTROY(OnDestroy)
END_MSGMAP(COpenGLWnd, CWindow)
COpenGLWnd::COpenGLWnd(BYTE cDepthBits /* = 24 */, BYTE cStencilBits /* = 8 */)
: m_cDepthBits(cDepthBits), m_cStencilBits(cStencilBits)
, m_fps(0), m_hdc(nullptr)
, m_count(0), m_gap(0), m_PrevTime(0), m_bCalced(false)
{
}
BOOL COpenGLWnd::OnCreate(LPCREATESTRUCT lpcs)
{
if (!MSG_FORWARD_WM_CREATE(CWindow, lpcs))
return FALSE;
PIXELFORMATDESCRIPTOR pfd;
int nPixelFormat;
m_hdc = GetDC(*this);
RECT rt;
GetClientRect(*this, &rt);
m_cx = rt.right;
m_cy = rt.bottom;
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = m_cDepthBits;
pfd.cStencilBits = m_cStencilBits;
pfd.iLayerType = PFD_MAIN_PLANE;
nPixelFormat = ChoosePixelFormat(m_hdc, &pfd);
if (nPixelFormat != 0)
{
if (SetPixelFormat(m_hdc, nPixelFormat, &pfd))
{
return TRUE;
}
}
return FALSE;
}
void COpenGLWnd::OnSize(UINT state, int cx, int cy)
{
MSG_FORWARD_WM_SIZE(CWindow, state, cx, cy);
m_cx = cx;
m_cy = cy;
}
void COpenGLWnd::OnDestroy()
{
wglMakeCurrent(m_hdc, nullptr);
MSG_FORWARD_WM_DESTROY(CWindow);
}
HGLRC COpenGLWnd::InitGL()
{
assert(this != nullptr);
HGLRC hrc = wglCreateContext(m_hdc);
wglMakeCurrent(m_hdc, hrc);
return hrc;
}
void COpenGLWnd::DestroyGL(HGLRC hrc)
{
assert(this != nullptr);
wglDeleteContext(hrc);
}
void COpenGLWnd::SizeChangeProc()
{
glViewport(0, 0, m_cx, m_cy);
}
unsigned COpenGLWnd::CalcFPS()
{
assert(this != nullptr);
DWORD now = GetTickCount();
if (!m_bCalced)
{
m_PrevTime = now;
m_bCalced = true;
}
m_gap = now - m_PrevTime;
m_count++;
if (m_gap >= 1000)
{
m_PrevTime = now;
m_gap -= 1000;
m_fps = m_count;
m_count = 0;
}
return m_fps;
}
END_IKHWINLIB2()
<|endoftext|> |
<commit_before>#include "sp/sp.h"
#include "sp/system/FileSystem.h"
#include "sp/system/Memory.h"
#include <Windows.h>
namespace sp {
static int64 GetFileSizeInternal(HANDLE file)
{
LARGE_INTEGER size;
GetFileSizeEx(file, &size);
return size.QuadPart;
}
void CALLBACK FileIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
}
bool FileSystem::FileExists(const String& path)
{
DWORD result = GetFileAttributes(path.c_str());
return !(result == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND);
}
int64 FileSystem::GetFileSize(const String& path)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (file == INVALID_HANDLE_VALUE)
return -1;
return GetFileSizeInternal(file);
}
bool FileSystem::ReadFile(const String& path, void* buffer, int64 size)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (file == INVALID_HANDLE_VALUE)
return false;
if (size < 0)
size = GetFileSizeInternal(file);
OVERLAPPED ol = { 0 };
bool result = ReadFileEx(file, buffer, size, &ol, FileIOCompletionRoutine);
CloseHandle(file);
return result;
}
byte* FileSystem::ReadFile(const String& path)
{
int64 size = GetFileSize(path);
byte* buffer = spnew byte[size];
if (!ReadFile(path, buffer, size))
{
spdel buffer;
return nullptr;
}
return buffer;
}
String FileSystem::ReadTextFile(const String& path)
{
int64 size = GetFileSize(path);
String result(size, 0);
if (!ReadFile(path, &result[0]))
return String();
// Strip carriage returns
result.erase(std::remove(result.begin(), result.end(), '\r'), result.end());
return result;
}
bool FileSystem::WriteFile(const String& path, byte* buffer)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, NULL, NULL, CREATE_NEW | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
return false;
int64 size = GetFileSizeInternal(file);
DWORD written;
bool result = ::WriteFile(file, buffer, size, &written, NULL);
CloseHandle(file);
return result;
}
bool FileSystem::WriteTextFile(const String& path, const String& text)
{
return WriteFile(path, (byte*)&text[0]);
}
}<commit_msg>Fixed Win32FileSystem file handle not being closed.<commit_after>#include "sp/sp.h"
#include "sp/system/FileSystem.h"
#include "sp/system/Memory.h"
#include <Windows.h>
namespace sp {
static int64 GetFileSizeInternal(HANDLE file)
{
LARGE_INTEGER size;
GetFileSizeEx(file, &size);
return size.QuadPart;
}
void CALLBACK FileIOCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
}
bool FileSystem::FileExists(const String& path)
{
DWORD result = GetFileAttributes(path.c_str());
return !(result == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND);
}
int64 FileSystem::GetFileSize(const String& path)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (file == INVALID_HANDLE_VALUE)
return -1;
int64 result = GetFileSizeInternal(file);
CloseHandle(file);
return result;
}
bool FileSystem::ReadFile(const String& path, void* buffer, int64 size)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (file == INVALID_HANDLE_VALUE)
return false;
if (size < 0)
size = GetFileSizeInternal(file);
OVERLAPPED ol = { 0 };
bool result = ReadFileEx(file, buffer, size, &ol, FileIOCompletionRoutine);
CloseHandle(file);
return result;
}
byte* FileSystem::ReadFile(const String& path)
{
int64 size = GetFileSize(path);
byte* buffer = spnew byte[size];
if (!ReadFile(path, buffer, size))
{
spdel buffer;
return nullptr;
}
return buffer;
}
String FileSystem::ReadTextFile(const String& path)
{
int64 size = GetFileSize(path);
String result(size, 0);
if (!ReadFile(path, &result[0]))
return String();
// Strip carriage returns
result.erase(std::remove(result.begin(), result.end(), '\r'), result.end());
return result;
}
bool FileSystem::WriteFile(const String& path, byte* buffer)
{
HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, NULL, NULL, CREATE_NEW | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
return false;
int64 size = GetFileSizeInternal(file);
DWORD written;
bool result = ::WriteFile(file, buffer, size, &written, NULL);
CloseHandle(file);
return result;
}
bool FileSystem::WriteTextFile(const String& path, const String& text)
{
return WriteFile(path, (byte*)&text[0]);
}
}<|endoftext|> |
<commit_before>#include "ColorGradientLabel.h"
#include <cassert>
#include <algorithm>
#include <limits>
#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include "ColorGradientModel.h"
#include "util.hpp"
namespace
{
const QBrush TransparencyBackgroundBrush()
{
const int size = 12;
QImage backgroundImage(size, size, QImage::Format_ARGB32);
unsigned char *bits = backgroundImage.bits();
int color, i;
for(unsigned short x = 0; x < size; ++x)
for(unsigned short y = 0; y < size; ++y)
{
i = (x * size + y) * 4;
color = (x <= 5 && y <= 5) || (x > 5 && y > 5) ? 255 : 224;
bits[i + 2] = color;
bits[i + 1] = color;
bits[i + 0] = color;
bits[i + 3] = 255;
}
return QBrush(backgroundImage);
};
} // namespace
namespace widgetzeug
{
ColorGradientLabel::ColorGradientLabel(QWidget * parent)
: QGLWidget{parent}
, m_model{nullptr}
, m_backgroundBrush{TransparencyBackgroundBrush()}
{
setMinimumSize(1u, 30);
}
ColorGradientLabel::ColorGradientLabel(
ColorGradientModel * model,
QWidget * parent)
: ColorGradientLabel{parent}
{
setModel(model);
}
ColorGradientLabel::~ColorGradientLabel()
{
if (m_model)
m_model->disconnect(m_modelConnection);
}
void ColorGradientLabel::setModel(widgetzeug::ColorGradientModel * model)
{
if (m_model)
m_model->disconnect(m_modelConnection);
m_model = model;
updatePixmap();
update();
m_modelConnection = connect(model, &ColorGradientModel::changed,
[this] ()
{
updatePixmap();
update();
});
}
void ColorGradientLabel::setHistogram(const QList<uint> & histogram)
{
m_histogram = histogram;
updateHistogram();
update();
}
void ColorGradientLabel::resizeEvent(QResizeEvent * event)
{
if (!m_model)
return;
updateHistogram();
updatePixmap();
update();
}
void ColorGradientLabel::paintEvent(QPaintEvent * event)
{
QPainter painter{this};
paintGradient(event->rect(), painter);
paintHistogram(painter);
}
void ColorGradientLabel::paintGradient(const QRect & paintRect, QPainter & painter)
{
painter.save();
painter.setPen(Qt::NoPen);
painter.setBrush(m_backgroundBrush);
painter.drawRect(paintRect);
painter.drawPixmap(paintRect, m_gradientPixmap);
painter.restore();
}
void ColorGradientLabel::paintHistogram(QPainter & painter)
{
if (m_histogram.empty())
return;
const auto width = this->width();
const auto widthScale = width / static_cast<qreal>(m_numBuckets * m_actualBucketSize);
painter.save();
auto pen = QPen{QColor{0, 0, 0, 100}};
pen.setWidthF(1.0 / devicePixelRatio());
painter.setPen(pen);
painter.setBrush(QColor{255, 255, 255, 70});
painter.scale(widthScale, 1.0);
painter.drawPath(m_histogramPath);
painter.restore();
}
QList<qreal> ColorGradientLabel::generateBuckets(uint numBuckets)
{
auto buckets = QList<qreal>{};
if (numBuckets < m_histogram.size())
{
const auto invNumBuckets = 1.0 / numBuckets;
auto histogram_index = 0;
for (auto bucket_i = 0u; bucket_i < numBuckets; ++bucket_i)
{
const auto norm_bucket_i = static_cast<qreal>(bucket_i) / numBuckets;
auto value = 0u, count = 0u;
while (static_cast<qreal>(histogram_index) / m_histogram.size() < (norm_bucket_i + invNumBuckets))
{
count += 1;
value += m_histogram[histogram_index++];
}
buckets << value / count;
}
assert(histogram_index == m_histogram.size());
}
else
{
std::copy(
m_histogram.begin(),
m_histogram.end(),
std::back_inserter(buckets));
}
auto min = std::numeric_limits<qreal>::max(), max = 0.0;
for (const auto & value : buckets)
{
min = std::min(min, value);
max = std::max(max, value);
}
const auto diff = (max - min);
for (auto & value : buckets)
{
value = static_cast<qreal>(value - min) / diff;
assert(value >= 0.0 && value <= 1.0);
}
for (auto i = 0; i < buckets.size(); ++i)
{
const auto prev = std::max(0, i - 1);
const auto next = std::min(buckets.size() - 1, i + 1);
buckets[i] = (buckets[prev] + buckets[i] + buckets[next]) / 3.0;
}
return buckets;
}
void ColorGradientLabel::updateHistogram()
{
if (m_histogram.empty())
{
m_histogramPath = QPainterPath{};
return;
}
const auto buckets = generateBuckets(width() / s_bucketSize);
m_numBuckets = buckets.size();
m_actualBucketSize = width() / m_numBuckets;
static const auto offset = 2u;
const auto height = this->height();
const auto paddingTop = static_cast<uint>(height * 0.2);
const auto maxRange = static_cast<uint>(height * 0.7);
const auto initialX = 0.0;
auto currentX = initialX;
m_histogramPath = QPainterPath{};
m_histogramPath.moveTo(currentX, height + offset);
for (const auto & value : buckets)
{
const auto y = paddingTop + (1.0 - value) * maxRange;
m_histogramPath.lineTo(currentX, y);
currentX += m_actualBucketSize;
m_histogramPath.lineTo(currentX, y);
}
m_histogramPath.lineTo(currentX, height + offset);
m_histogramPath.lineTo(initialX, height + offset);
}
void ColorGradientLabel::updatePixmap()
{
auto image = m_model->image(width() * devicePixelRatio());
m_gradientPixmap = QPixmap::fromImage(image);
m_gradientPixmap.setDevicePixelRatio(devicePixelRatio());
}
} // namespace widgetzeug
<commit_msg>Fix unsigned warning<commit_after>#include "ColorGradientLabel.h"
#include <cassert>
#include <algorithm>
#include <limits>
#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include "ColorGradientModel.h"
#include "util.hpp"
namespace
{
const QBrush TransparencyBackgroundBrush()
{
const int size = 12;
QImage backgroundImage(size, size, QImage::Format_ARGB32);
unsigned char *bits = backgroundImage.bits();
int color, i;
for(unsigned short x = 0; x < size; ++x)
for(unsigned short y = 0; y < size; ++y)
{
i = (x * size + y) * 4;
color = (x <= 5 && y <= 5) || (x > 5 && y > 5) ? 255 : 224;
bits[i + 2] = color;
bits[i + 1] = color;
bits[i + 0] = color;
bits[i + 3] = 255;
}
return QBrush(backgroundImage);
};
} // namespace
namespace widgetzeug
{
ColorGradientLabel::ColorGradientLabel(QWidget * parent)
: QGLWidget{parent}
, m_model{nullptr}
, m_backgroundBrush{TransparencyBackgroundBrush()}
{
setMinimumSize(1u, 30);
}
ColorGradientLabel::ColorGradientLabel(
ColorGradientModel * model,
QWidget * parent)
: ColorGradientLabel{parent}
{
setModel(model);
}
ColorGradientLabel::~ColorGradientLabel()
{
if (m_model)
m_model->disconnect(m_modelConnection);
}
void ColorGradientLabel::setModel(widgetzeug::ColorGradientModel * model)
{
if (m_model)
m_model->disconnect(m_modelConnection);
m_model = model;
updatePixmap();
update();
m_modelConnection = connect(model, &ColorGradientModel::changed,
[this] ()
{
updatePixmap();
update();
});
}
void ColorGradientLabel::setHistogram(const QList<uint> & histogram)
{
m_histogram = histogram;
updateHistogram();
update();
}
void ColorGradientLabel::resizeEvent(QResizeEvent * event)
{
if (!m_model)
return;
updateHistogram();
updatePixmap();
update();
}
void ColorGradientLabel::paintEvent(QPaintEvent * event)
{
QPainter painter{this};
paintGradient(event->rect(), painter);
paintHistogram(painter);
}
void ColorGradientLabel::paintGradient(const QRect & paintRect, QPainter & painter)
{
painter.save();
painter.setPen(Qt::NoPen);
painter.setBrush(m_backgroundBrush);
painter.drawRect(paintRect);
painter.drawPixmap(paintRect, m_gradientPixmap);
painter.restore();
}
void ColorGradientLabel::paintHistogram(QPainter & painter)
{
if (m_histogram.empty())
return;
const auto width = this->width();
const auto widthScale = width / static_cast<qreal>(m_numBuckets * m_actualBucketSize);
painter.save();
auto pen = QPen{QColor{0, 0, 0, 100}};
pen.setWidthF(1.0 / devicePixelRatio());
painter.setPen(pen);
painter.setBrush(QColor{255, 255, 255, 70});
painter.scale(widthScale, 1.0);
painter.drawPath(m_histogramPath);
painter.restore();
}
QList<qreal> ColorGradientLabel::generateBuckets(uint numBuckets)
{
auto buckets = QList<qreal>{};
if (numBuckets < static_cast<unsigned int>(m_histogram.size()))
{
const auto invNumBuckets = 1.0 / numBuckets;
auto histogram_index = 0;
for (auto bucket_i = 0u; bucket_i < numBuckets; ++bucket_i)
{
const auto norm_bucket_i = static_cast<qreal>(bucket_i) / numBuckets;
auto value = 0u, count = 0u;
while (static_cast<qreal>(histogram_index) / m_histogram.size() < (norm_bucket_i + invNumBuckets))
{
count += 1;
value += m_histogram[histogram_index++];
}
buckets << value / count;
}
assert(histogram_index == m_histogram.size());
}
else
{
std::copy(
m_histogram.begin(),
m_histogram.end(),
std::back_inserter(buckets));
}
auto min = std::numeric_limits<qreal>::max(), max = 0.0;
for (const auto & value : buckets)
{
min = std::min(min, value);
max = std::max(max, value);
}
const auto diff = (max - min);
for (auto & value : buckets)
{
value = static_cast<qreal>(value - min) / diff;
assert(value >= 0.0 && value <= 1.0);
}
for (auto i = 0; i < buckets.size(); ++i)
{
const auto prev = std::max(0, i - 1);
const auto next = std::min(buckets.size() - 1, i + 1);
buckets[i] = (buckets[prev] + buckets[i] + buckets[next]) / 3.0;
}
return buckets;
}
void ColorGradientLabel::updateHistogram()
{
if (m_histogram.empty())
{
m_histogramPath = QPainterPath{};
return;
}
const auto buckets = generateBuckets(width() / s_bucketSize);
m_numBuckets = buckets.size();
m_actualBucketSize = width() / m_numBuckets;
static const auto offset = 2u;
const auto height = this->height();
const auto paddingTop = static_cast<uint>(height * 0.2);
const auto maxRange = static_cast<uint>(height * 0.7);
const auto initialX = 0.0;
auto currentX = initialX;
m_histogramPath = QPainterPath{};
m_histogramPath.moveTo(currentX, height + offset);
for (const auto & value : buckets)
{
const auto y = paddingTop + (1.0 - value) * maxRange;
m_histogramPath.lineTo(currentX, y);
currentX += m_actualBucketSize;
m_histogramPath.lineTo(currentX, y);
}
m_histogramPath.lineTo(currentX, height + offset);
m_histogramPath.lineTo(initialX, height + offset);
}
void ColorGradientLabel::updatePixmap()
{
auto image = m_model->image(width() * devicePixelRatio());
m_gradientPixmap = QPixmap::fromImage(image);
m_gradientPixmap.setDevicePixelRatio(devicePixelRatio());
}
} // namespace widgetzeug
<|endoftext|> |
<commit_before>/********************************** SIGNATURE *********************************\
| ,, |
| db `7MM |
| ;MM: MM |
| ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 |
| ,M `MM 8I `" MM MM ,M' Yb MM' "' |
| AbmmmqMA `YMMMa. MM MM 8M"""""" MM |
| A' VML L. I8 MM MM YM. , MM |
| .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. |
| |
| |
| ,, ,, |
| .g8"""bgd `7MM db `7MM |
| .dP' `M MM MM |
| dM' ` MM `7MM ,p6"bo MM ,MP' |
| MM MM MM 6M' OO MM ;Y |
| MM. `7MMF' MM MM 8M MM;Mm |
| `Mb. MM MM MM YM. , MM `Mb. |
| `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. |
| |
\******************************************************************************/
/*********************************** LICENSE **********************************\
| Copyright (c) 2013, Asher Glick |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| * Redistributions of source code must retain the above copyright notice, |
| this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| POSSIBILITY OF SUCH DAMAGE. |
\******************************************************************************/
#include <openssl/sha.h>
#include <unistd.h>
#include <math.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
#define HASHSIZE 32
//////////////////////////////////////////////////////////////////////////////
//////////////////////// BASE MODIFICATION FUNCTIONS /////////////////////////
//////////////////////////////////////////////////////////////////////////////
int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) {
double logOldBase = log(oldBase);
double logNewBase = log(newBase);
double newBaseLength = oldBaseLength * (logOldBase/logNewBase);
int intNewBaseLength = newBaseLength;
if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up
return intNewBaseLength;
}
// Trims all of the preceding zeros off a function
vector<int> trimNumber(vector<int> v) {
vector<int>::iterator i = v.begin();
while (i != v.end()-1) {
if (*i != 0) {
break;
}
i++;
}
return vector<int>(i, v.end());
}
// creats a new base number of the old base value of 10
vector<int> tenInOldBase(int oldBase, int newBase) {
// int ten[] = {1,0};
int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase);
int maxLength = newBaseLength>2?newBaseLength:2;
vector <int> newNumber(maxLength, 0);
int currentNumber = oldBase;
for (int i = maxLength-1; i >=0; i--) {
newNumber[i] = currentNumber % newBase;
currentNumber = currentNumber / newBase;
}
newNumber = trimNumber(newNumber);
// return calculateNewBase(oldBase, 2, newBase, ten);
return newNumber;
}
// Multiplies two base n numbers together
vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) {
int resultLength = firstNumber.size() + secondNumber.size();
vector<int> resultNumber(resultLength, 0);
for (int i = firstNumber.size() - 1 ; i >= 0; i--) {
for (int j = secondNumber.size() - 1; j >= 0; j--) {
resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j];
}
}
for (int i = resultNumber.size() -1; i > 0; i--) {
if (resultNumber[i] >= base) {
resultNumber[i-1] += resultNumber[i]/base;
resultNumber[i] = resultNumber[i] % base;
}
}
return trimNumber(resultNumber);
}
vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) {
int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase);
vector<int> newNumber(newNumberLength, 0);
vector<int> conversionFactor(1, 1); // a single digit of 1
for (int i = oldNumber.size()-1; i >= 0; i--) {
vector<int> difference(conversionFactor);
// size the vector
for (unsigned int j = 0; j < difference.size(); j++) {
difference[j] *= oldNumber[i];
}
// add the vector
for (unsigned int j = 0; j < difference.size(); j++) {
int newNumberIndex = j + newNumberLength - difference.size();
newNumber[newNumberIndex] += difference[j];
}
// increment the conversion factor by oldbase 10
conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase));
}
// Flatten number to base
for (int i = newNumber.size()-1; i >=0; i--) {
if (newNumber[i] >= newBase) {
newNumber[i-1] += newNumber[i]/newBase;
newNumber[i] = newNumber[i]%newBase;
}
}
return trimNumber(newNumber);
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// READ SETTINGS ////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
struct settingWrapper {
string domain;
string allowedCharacters;
uint maxCharacters;
string regex;
};
settingWrapper getSettings(string domain) {
string hexCharacters = "0123456789abcdef";
settingWrapper settings;
// open ~/.passcodes/config
ifstream configFile;
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
string configPath = string(homedir) + "/.passcodes/";
string subscriptionPath = string(homedir) + "/.passcodes/subscriptions";
configFile.open(subscriptionPath.c_str());
if (!configFile.is_open()) {
cout << "File does not exist" << endl;
#if defined(_WIN32)
_mkdir(strPath.c_str());
#else
mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777
#endif
ofstream testFile;
testFile.open(subscriptionPath.c_str());
testFile << "http://passcod.es/global.chanel" << endl;
testFile << "http://asherglick.github.io/Passcodes" << endl;
testFile.close();
configFile.open(subscriptionPath.c_str());
}
cout << "opening file" << endl;
//configFile.open(subscriptionPath.c_str());
string subscription = "";
if (configFile.is_open()) {
cout << "File is open" << endl;
while (getline(configFile, subscription)) {
cout << "LINE" << endl;
unsigned char hash[20];
SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash);
string cashedSubscriptionName = "";
for (int i = 0; i < 4; i++) {
cashedSubscriptionName += hexCharacters[hash[i]&0x0F];
cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F];
}
cout << cashedSubscriptionName << endl;
}
}
// look for 'subscriptions' section
// open each file in the subscriptions list in order
// ~/.passcodes/<subscription>/<domain>
// add any non-blank entry to the settings, latter entries overriding former
return settings;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////// GENERATE PASSWORD FUNCTIONS /////////////////////////
//////////////////////////////////////////////////////////////////////////////
#define ITERATIONCOUNT 100000
/****************************** GENERATE PASSWORD *****************************\
| The generate password function takes in the domain and the master password |
| then returns the 16 character long base64 password based off of the sha256 |
| hash |
\******************************************************************************/
string generatePassword(string masterpass, string domain) {
settingWrapper settings = getSettings(domain);
string prehash = masterpass+domain;
unsigned char hash[HASHSIZE];
string output = "";
for (int i = 0; i < ITERATIONCOUNT; i++) {
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
prehash = "";
for (int j = 0; j < HASHSIZE; j++) {
prehash += hash[j];
}
}
vector<int> hashedValues(32);
for (int j = 0; j < HASHSIZE; j++) {
hashedValues[j] = static_cast<int>(hash[j]);
}
vector<int> newValues = calculateNewBase(256, 64, hashedValues);
for (int val : newValues) {
cout << val << ", ";
}
return "Failed";
}
/************************************ HELP ************************************\
| The help fucntion displays the help text to the user, it is called if the |
| help flag is present or if the user has used the program incorrectly |
\******************************************************************************/
void help() {
cout <<
"Welcome to the command line application for passcod.es\n"
"written by Asher Glick ([email protected])\n"
"\n"
"Usage\n"
" passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n"
"\n"
"Commands\n"
" -d Any text that comes after this flag is set as the domain\n"
" If no domain is given it is prompted for\n"
" -p Any text that comes after this flag is set as the password\n"
" If this flag is set a warning will be displayed\n"
" If this flag is not set the user is prompted for a password\n"
" -h Display the help menu\n"
" No other functions will be run if this flag is present\n"
" -s Suppress warnings\n"
" No warning messages will appear from using the -p flag\n"
<< endl;
}
/************************************ MAIN ************************************\
| The main function handles all of the arguments, parsing them into the |
| correct locations. Then prompts the user to enter the domain and password |
| if they have not been specified in the arguments. Finaly it outputs the |
| generated password to the user |
\******************************************************************************/
int main(int argc, char* argv[]) {
bool silent = false;
string domain = "";
string password = "";
string *pointer = NULL;
// Parse the arguments
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
} else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
} else if (string(argv[i]) == "-s") { // silent flag
silent = true;
} else if (string(argv[i]) == "-h") { // help flag
help();
return 0;
} else {
if (pointer == NULL) {
help();
return 0;
} else {
*pointer += argv[i];
}
}
}
// If there is no domain given, prompt the user for a domain
if (domain == "") {
cout << "Enter Domain: ";
getline(cin, domain);
}
// If there is a password given and the silent flag is not present
// give the user a warning telling them that the password flag is insecure
if (password != "" && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
// If there is not a password given, prompt the user for a password securly
else if (password == "") {
password = string(getpass("Enter Password: "));
}
// Output the generated Password to the user
cout << generatePassword(domain, password) << endl;
}
<commit_msg>fixed a bug with password and updated config reading<commit_after>/********************************** SIGNATURE *********************************\
| ,, |
| db `7MM |
| ;MM: MM |
| ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 |
| ,M `MM 8I `" MM MM ,M' Yb MM' "' |
| AbmmmqMA `YMMMa. MM MM 8M"""""" MM |
| A' VML L. I8 MM MM YM. , MM |
| .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. |
| |
| |
| ,, ,, |
| .g8"""bgd `7MM db `7MM |
| .dP' `M MM MM |
| dM' ` MM `7MM ,p6"bo MM ,MP' |
| MM MM MM 6M' OO MM ;Y |
| MM. `7MMF' MM MM 8M MM;Mm |
| `Mb. MM MM MM YM. , MM `Mb. |
| `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. |
| |
\******************************************************************************/
/*********************************** LICENSE **********************************\
| Copyright (c) 2013, Asher Glick |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| * Redistributions of source code must retain the above copyright notice, |
| this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| POSSIBILITY OF SUCH DAMAGE. |
\******************************************************************************/
#include <openssl/sha.h>
#include <unistd.h>
#include <math.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
#define HASHSIZE 32
//////////////////////////////////////////////////////////////////////////////
//////////////////////// BASE MODIFICATION FUNCTIONS /////////////////////////
//////////////////////////////////////////////////////////////////////////////
int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) {
double logOldBase = log(oldBase);
double logNewBase = log(newBase);
double newBaseLength = oldBaseLength * (logOldBase/logNewBase);
int intNewBaseLength = newBaseLength;
if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up
return intNewBaseLength;
}
// Trims all of the preceding zeros off a function
vector<int> trimNumber(vector<int> v) {
vector<int>::iterator i = v.begin();
while (i != v.end()-1) {
if (*i != 0) {
break;
}
i++;
}
return vector<int>(i, v.end());
}
// creats a new base number of the old base value of 10
vector<int> tenInOldBase(int oldBase, int newBase) {
// int ten[] = {1,0};
int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase);
int maxLength = newBaseLength>2?newBaseLength:2;
vector <int> newNumber(maxLength, 0);
int currentNumber = oldBase;
for (int i = maxLength-1; i >=0; i--) {
newNumber[i] = currentNumber % newBase;
currentNumber = currentNumber / newBase;
}
newNumber = trimNumber(newNumber);
// return calculateNewBase(oldBase, 2, newBase, ten);
return newNumber;
}
// Multiplies two base n numbers together
vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) {
int resultLength = firstNumber.size() + secondNumber.size();
vector<int> resultNumber(resultLength, 0);
for (int i = firstNumber.size() - 1 ; i >= 0; i--) {
for (int j = secondNumber.size() - 1; j >= 0; j--) {
resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j];
}
}
for (int i = resultNumber.size() -1; i > 0; i--) {
if (resultNumber[i] >= base) {
resultNumber[i-1] += resultNumber[i]/base;
resultNumber[i] = resultNumber[i] % base;
}
}
return trimNumber(resultNumber);
}
vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) {
int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase);
vector<int> newNumber(newNumberLength, 0);
vector<int> conversionFactor(1, 1); // a single digit of 1
for (int i = oldNumber.size()-1; i >= 0; i--) {
vector<int> difference(conversionFactor);
// size the vector
for (unsigned int j = 0; j < difference.size(); j++) {
difference[j] *= oldNumber[i];
}
// add the vector
for (unsigned int j = 0; j < difference.size(); j++) {
int newNumberIndex = j + newNumberLength - difference.size();
newNumber[newNumberIndex] += difference[j];
}
// increment the conversion factor by oldbase 10
conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase));
}
// Flatten number to base
for (int i = newNumber.size()-1; i >=0; i--) {
if (newNumber[i] >= newBase) {
newNumber[i-1] += newNumber[i]/newBase;
newNumber[i] = newNumber[i]%newBase;
}
}
return trimNumber(newNumber);
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// READ SETTINGS ////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
struct settingWrapper {
string domain;
string allowedCharacters;
uint maxCharacters;
string regex;
};
settingWrapper getSettings(string domain) {
string hexCharacters = "0123456789abcdef";
settingWrapper settings;
// open ~/.passcodes/config
ifstream configFile;
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
string configPath = string(homedir) + "/.passcodes/";
string subscriptionPath = string(homedir) + "/.passcodes/subscriptions";
configFile.open(subscriptionPath.c_str());
if (!configFile.is_open()) {
cout << "File does not exist" << endl;
#if defined(_WIN32)
_mkdir(strPath.c_str());
#else
mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777
#endif
ofstream testFile;
testFile.open(subscriptionPath.c_str());
testFile << "http://passcod.es/global.chanel" << endl;
testFile << "http://asherglick.github.io/Passcodes" << endl;
testFile.close();
configFile.open(subscriptionPath.c_str());
}
cout << "opening file" << endl;
//configFile.open(subscriptionPath.c_str());
string subscription = "";
if (configFile.is_open()) {
cout << "File is open" << endl;
while (getline(configFile, subscription)) {
unsigned char hash[20];
SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash);
string cashedSubscriptionName = "";
for (int i = 0; i < 4; i++) {
cashedSubscriptionName += hexCharacters[hash[i]&0x0F];
cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F];
}
ifstream subscription;
string subscriptionPath = configPath + "cashe/" + cashedSubscriptionName + "/" + domain;
subscription.open(subscriptionPath);
string maxLength
cout << subscriptionPath << endl;
}
}
// look for 'subscriptions' section
// open each file in the subscriptions list in order
// ~/.passcodes/<subscription>/<domain>
// add any non-blank entry to the settings, latter entries overriding former
return settings;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////// GENERATE PASSWORD FUNCTIONS /////////////////////////
//////////////////////////////////////////////////////////////////////////////
#define ITERATIONCOUNT 100000
/****************************** GENERATE PASSWORD *****************************\
| The generate password function takes in the domain and the master password |
| then returns the 16 character long base64 password based off of the sha256 |
| hash |
\******************************************************************************/
string generatePassword(string domain, string masterpass ) {
settingWrapper settings = getSettings(domain);
string prehash = domain+masterpass;
unsigned char hash[HASHSIZE];
string output = "";
for (int i = 0; i < ITERATIONCOUNT; i++) {
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
prehash = "";
for (int j = 0; j < HASHSIZE; j++) {
prehash += hash[j];
}
}
vector<int> hashedValues(32);
for (int j = 0; j < HASHSIZE; j++) {
hashedValues[j] = static_cast<int>(hash[j]);
}
vector<int> newValues = calculateNewBase(256, 64, hashedValues);
for (int val : newValues) {
cout << val << ", ";
}
return "Failed";
}
/************************************ HELP ************************************\
| The help fucntion displays the help text to the user, it is called if the |
| help flag is present or if the user has used the program incorrectly |
\******************************************************************************/
void help() {
cout <<
"Welcome to the command line application for passcod.es\n"
"written by Asher Glick ([email protected])\n"
"\n"
"Usage\n"
" passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n"
"\n"
"Commands\n"
" -d Any text that comes after this flag is set as the domain\n"
" If no domain is given it is prompted for\n"
" -p Any text that comes after this flag is set as the password\n"
" If this flag is set a warning will be displayed\n"
" If this flag is not set the user is prompted for a password\n"
" -h Display the help menu\n"
" No other functions will be run if this flag is present\n"
" -s Suppress warnings\n"
" No warning messages will appear from using the -p flag\n"
<< endl;
}
/************************************ MAIN ************************************\
| The main function handles all of the arguments, parsing them into the |
| correct locations. Then prompts the user to enter the domain and password |
| if they have not been specified in the arguments. Finaly it outputs the |
| generated password to the user |
\******************************************************************************/
int main(int argc, char* argv[]) {
bool silent = false;
string domain = "";
string password = "";
string *pointer = NULL;
// Parse the arguments
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
} else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
} else if (string(argv[i]) == "-s") { // silent flag
silent = true;
} else if (string(argv[i]) == "-h") { // help flag
help();
return 0;
} else {
if (pointer == NULL) {
help();
return 0;
} else {
*pointer += argv[i];
}
}
}
// If there is no domain given, prompt the user for a domain
if (domain == "") {
cout << "Enter Domain: ";
getline(cin, domain);
}
// If there is a password given and the silent flag is not present
// give the user a warning telling them that the password flag is insecure
if (password != "" && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
// If there is not a password given, prompt the user for a password securly
else if (password == "") {
password = string(getpass("Enter Password: "));
}
// Output the generated Password to the user
cout << generatePassword(domain, password) << endl;
}
<|endoftext|> |
<commit_before>/**
\file innerintegral.hh
**/
#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
// dune-common
#include <dune/common/densematrix.hh>
// dune-geometry
#include <dune/geometry/quadraturerules.hh>
// dune-stuff
#include <dune/stuff/common/matrix.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteOperator {
namespace Local {
namespace Codim1 {
/**
\brief Local operator for inner intersections, i.e. those who have an inner codim 0 entity (Entity or En) and an
outer codim 0 Neighboring entity (Neighbor or Ne).
**/
template <class LocalEvaluationImp>
class InnerIntegral
{
public:
typedef LocalEvaluationImp LocalEvaluationType;
typedef InnerIntegral<LocalEvaluationType> ThisType;
typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;
// template< class InducingDiscreteFunctionType >
// class LocalFunctional
// {
// public:
// typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,
// InducingDiscreteFunctionType >
// Type;
// };
InnerIntegral(const LocalEvaluationType& localEvaluation)
: localEvaluation_(localEvaluation)
{
}
const LocalEvaluationType& localEvaluation() const
{
return localEvaluation_;
}
// template< class InducingDiscreteFunctionType >
// typename LocalFunctional< InducingDiscreteFunctionType >::Type
// localFunctional( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const
// {
// typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,
// InducingDiscreteFunctionType >
// LocalFunctionalType;
// return LocalFunctionalType( *this, inducingDiscreteFunction );
// } // end method localFunctional
unsigned int numTmpObjectsRequired() const
{
return 4;
}
/**
\todo Rename Entity -> En, Neighbor -> Ne
**/
template <class LocalAnsatzBaseFunctionSetEntityType, class LocalAnsatzBaseFunctionSetNeighborType,
class LocalTestBaseFunctionSetEntityType, class LocalTestBaseFunctionSetNeighborType,
class IntersectionType, class LocalMatrixType>
void applyLocal(const LocalAnsatzBaseFunctionSetEntityType& localAnsatzBaseFunctionSetEntity,
const LocalAnsatzBaseFunctionSetNeighborType& localAnsatzBaseFunctionSetNeighbor,
const LocalTestBaseFunctionSetEntityType& localTestBaseFunctionSetEntity,
const LocalTestBaseFunctionSetNeighborType& localTestBaseFunctionSetNeighbor,
const IntersectionType& intersection, LocalMatrixType& localMatrixEnEn,
LocalMatrixType& localMatrixEnNe, LocalMatrixType& localMatrixNeEn, LocalMatrixType& localMatrixNeNe,
std::vector<LocalMatrixType>& tmpLocalMatrices) const
{
// preparations
const unsigned int rowsEn = localAnsatzBaseFunctionSetEntity.size();
const unsigned int rowsNe = localAnsatzBaseFunctionSetNeighbor.size();
const unsigned int colsEn = localTestBaseFunctionSetEntity.size();
const unsigned int colsNe = localTestBaseFunctionSetNeighbor.size();
// make sure, that the target matrices are big enough
assert(localMatrixEnEn.rows() >= rowsEn);
assert(localMatrixEnEn.cols() >= colsEn);
assert(localMatrixEnNe.rows() >= rowsEn);
assert(localMatrixEnNe.cols() >= colsNe);
assert(localMatrixNeEn.rows() >= rowsNe);
assert(localMatrixNeEn.cols() >= colsEn);
assert(localMatrixNeNe.rows() >= rowsNe);
assert(localMatrixNeNe.cols() >= colsNe);
// clear target matrices
Dune::Stuff::Common::Matrix::clear(localMatrixEnEn);
Dune::Stuff::Common::Matrix::clear(localMatrixEnNe);
Dune::Stuff::Common::Matrix::clear(localMatrixNeEn);
Dune::Stuff::Common::Matrix::clear(localMatrixNeNe);
// check tmp local matrices
if (tmpLocalMatrices.size() < numTmpObjectsRequired()) {
tmpLocalMatrices.resize(
numTmpObjectsRequired(),
LocalMatrixType(std::max(localAnsatzBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),
localAnsatzBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),
std::max(localTestBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),
localTestBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),
RangeFieldType(0.0)));
} // check tmp local matrices
// quadrature
const unsigned int quadratureOrder =
localEvaluation_.order()
+ std::max(localAnsatzBaseFunctionSetEntity.order(), localAnsatzBaseFunctionSetNeighbor.order())
+ std::max(localTestBaseFunctionSetEntity.order(), localTestBaseFunctionSetNeighbor.order());
typedef Dune::QuadratureRules<DomainFieldType, IntersectionType::mydimension> FaceQuadratureRules;
typedef Dune::QuadratureRule<DomainFieldType, IntersectionType::mydimension> FaceQuadratureType;
const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), 2 * quadratureOrder + 1);
// do loop over all quadrature points
const typename FaceQuadratureType::const_iterator quadratureEnd = faceQuadrature.end();
for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin(); quadPoint != quadratureEnd;
++quadPoint) {
// local coordinates
typedef typename IntersectionType::LocalCoordinate LocalCoordinateType;
const LocalCoordinateType x = quadPoint->position();
// integration factors
const double integrationFactor = intersection.geometry().integrationElement(x);
const double quadratureWeight = quadPoint->weight();
// evaluate the local operation
localEvaluation_.evaluateLocal(localAnsatzBaseFunctionSetEntity,
localTestBaseFunctionSetEntity,
localAnsatzBaseFunctionSetNeighbor,
localTestBaseFunctionSetNeighbor,
intersection,
x,
tmpLocalMatrices[0], /*EnEn*/
tmpLocalMatrices[1], /*EnNe*/
tmpLocalMatrices[2], /*NeEn*/
tmpLocalMatrices[3]); /*NeNe*/
// compute integral (see below)
addToIntegral(tmpLocalMatrices[0], integrationFactor, quadratureWeight, rowsEn, colsEn, localMatrixEnEn);
addToIntegral(tmpLocalMatrices[1], integrationFactor, quadratureWeight, rowsEn, colsNe, localMatrixEnNe);
addToIntegral(tmpLocalMatrices[2], integrationFactor, quadratureWeight, rowsNe, colsEn, localMatrixNeEn);
addToIntegral(tmpLocalMatrices[3], integrationFactor, quadratureWeight, rowsNe, colsNe, localMatrixNeNe);
} // done loop over all quadrature points
} // void applyLocal
private:
InnerIntegral(const ThisType& other);
ThisType& operator=(const ThisType&);
template <class MatrixImp, class RangeFieldType>
void addToIntegral(const Dune::DenseMatrix<MatrixImp>& localMatrix, const RangeFieldType& integrationFactor,
const RangeFieldType& quadratureWeight, const unsigned int rows, const unsigned int cols,
Dune::DenseMatrix<MatrixImp>& ret) const
{
// loop over all rows
for (unsigned int i = 0; i < rows; ++i) {
// get row
const typename Dune::DenseMatrix<MatrixImp>::const_row_reference localMatrixRow = localMatrix[i];
typename Dune::DenseMatrix<MatrixImp>::row_reference retRow = ret[i];
// loop over all cols
for (unsigned int j = 0; j < cols; ++j) {
retRow[j] += localMatrixRow[j] * integrationFactor * quadratureWeight;
} // loop over all cols
} // loop over all rows
} // end method addToIntegral
const LocalEvaluationType& localEvaluation_;
}; // end class InnerIntegral
} // end namespace Codim1
} // end namespace Local
} // end namespace DiscreteOperator
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
<commit_msg>[discreteoperator.local.codim1.innerintegral] minor change in argument reordering<commit_after>/**
\file innerintegral.hh
**/
#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
// dune-common
#include <dune/common/densematrix.hh>
// dune-geometry
#include <dune/geometry/quadraturerules.hh>
// dune-stuff
#include <dune/stuff/common/matrix.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteOperator {
namespace Local {
namespace Codim1 {
/**
\brief Local operator for inner intersections, i.e. those who have an inner codim 0 entity (Entity or En) and an
outer codim 0 Neighboring entity (Neighbor or Ne).
**/
template <class LocalEvaluationImp>
class InnerIntegral
{
public:
typedef LocalEvaluationImp LocalEvaluationType;
typedef InnerIntegral<LocalEvaluationType> ThisType;
typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;
// template< class InducingDiscreteFunctionType >
// class LocalFunctional
// {
// public:
// typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,
// InducingDiscreteFunctionType >
// Type;
// };
InnerIntegral(const LocalEvaluationType& localEvaluation)
: localEvaluation_(localEvaluation)
{
}
const LocalEvaluationType& localEvaluation() const
{
return localEvaluation_;
}
// template< class InducingDiscreteFunctionType >
// typename LocalFunctional< InducingDiscreteFunctionType >::Type
// localFunctional( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const
// {
// typedef Dune::Functionals::DiscreteFunctional::Local::Codim0::IntegralInduced< ThisType,
// InducingDiscreteFunctionType >
// LocalFunctionalType;
// return LocalFunctionalType( *this, inducingDiscreteFunction );
// } // end method localFunctional
unsigned int numTmpObjectsRequired() const
{
return 4;
}
/**
\todo Rename Entity -> En, Neighbor -> Ne
**/
template <class LocalAnsatzBaseFunctionSetEntityType, class LocalTestBaseFunctionSetEntityType,
class LocalAnsatzBaseFunctionSetNeighborType, class LocalTestBaseFunctionSetNeighborType,
class IntersectionType, class LocalMatrixType>
void applyLocal(const LocalAnsatzBaseFunctionSetEntityType& localAnsatzBaseFunctionSetEntity,
const LocalTestBaseFunctionSetEntityType& localTestBaseFunctionSetEntity,
const LocalAnsatzBaseFunctionSetNeighborType& localAnsatzBaseFunctionSetNeighbor,
const LocalTestBaseFunctionSetNeighborType& localTestBaseFunctionSetNeighbor,
const IntersectionType& intersection, LocalMatrixType& localMatrixEnEn,
LocalMatrixType& localMatrixEnNe, LocalMatrixType& localMatrixNeEn, LocalMatrixType& localMatrixNeNe,
std::vector<LocalMatrixType>& tmpLocalMatrices) const
{
// preparations
const unsigned int rowsEn = localAnsatzBaseFunctionSetEntity.size();
const unsigned int rowsNe = localAnsatzBaseFunctionSetNeighbor.size();
const unsigned int colsEn = localTestBaseFunctionSetEntity.size();
const unsigned int colsNe = localTestBaseFunctionSetNeighbor.size();
// make sure, that the target matrices are big enough
assert(localMatrixEnEn.rows() >= rowsEn);
assert(localMatrixEnEn.cols() >= colsEn);
assert(localMatrixEnNe.rows() >= rowsEn);
assert(localMatrixEnNe.cols() >= colsNe);
assert(localMatrixNeEn.rows() >= rowsNe);
assert(localMatrixNeEn.cols() >= colsEn);
assert(localMatrixNeNe.rows() >= rowsNe);
assert(localMatrixNeNe.cols() >= colsNe);
// clear target matrices
Dune::Stuff::Common::Matrix::clear(localMatrixEnEn);
Dune::Stuff::Common::Matrix::clear(localMatrixEnNe);
Dune::Stuff::Common::Matrix::clear(localMatrixNeEn);
Dune::Stuff::Common::Matrix::clear(localMatrixNeNe);
// check tmp local matrices
if (tmpLocalMatrices.size() < numTmpObjectsRequired()) {
tmpLocalMatrices.resize(
numTmpObjectsRequired(),
LocalMatrixType(std::max(localAnsatzBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),
localAnsatzBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),
std::max(localTestBaseFunctionSetEntity.baseFunctionSet().space().map().maxLocalSize(),
localTestBaseFunctionSetNeighbor.baseFunctionSet().space().map().maxLocalSize()),
RangeFieldType(0.0)));
} // check tmp local matrices
// quadrature
const unsigned int quadratureOrder =
localEvaluation_.order()
+ std::max(localAnsatzBaseFunctionSetEntity.order(), localAnsatzBaseFunctionSetNeighbor.order())
+ std::max(localTestBaseFunctionSetEntity.order(), localTestBaseFunctionSetNeighbor.order());
typedef Dune::QuadratureRules<DomainFieldType, IntersectionType::mydimension> FaceQuadratureRules;
typedef Dune::QuadratureRule<DomainFieldType, IntersectionType::mydimension> FaceQuadratureType;
const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), 2 * quadratureOrder + 1);
// do loop over all quadrature points
for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin();
quadPoint != faceQuadrature.end();
++quadPoint) {
// local coordinates
typedef typename IntersectionType::LocalCoordinate LocalCoordinateType;
const LocalCoordinateType x = quadPoint->position();
// integration factors
const double integrationFactor = intersection.geometry().integrationElement(x);
const double quadratureWeight = quadPoint->weight();
// evaluate the local operation
localEvaluation_.evaluateLocal(localAnsatzBaseFunctionSetEntity,
localTestBaseFunctionSetEntity,
localAnsatzBaseFunctionSetNeighbor,
localTestBaseFunctionSetNeighbor,
intersection,
x,
tmpLocalMatrices[0], /*EnEn*/
tmpLocalMatrices[1], /*EnNe*/
tmpLocalMatrices[2], /*NeEn*/
tmpLocalMatrices[3]); /*NeNe*/
// compute integral (see below)
addToIntegral(tmpLocalMatrices[0], integrationFactor, quadratureWeight, rowsEn, colsEn, localMatrixEnEn);
addToIntegral(tmpLocalMatrices[1], integrationFactor, quadratureWeight, rowsEn, colsNe, localMatrixEnNe);
addToIntegral(tmpLocalMatrices[2], integrationFactor, quadratureWeight, rowsNe, colsEn, localMatrixNeEn);
addToIntegral(tmpLocalMatrices[3], integrationFactor, quadratureWeight, rowsNe, colsNe, localMatrixNeNe);
} // done loop over all quadrature points
} // void applyLocal
private:
InnerIntegral(const ThisType& other);
ThisType& operator=(const ThisType&);
template <class MatrixImp, class RangeFieldType>
void addToIntegral(const Dune::DenseMatrix<MatrixImp>& localMatrix, const RangeFieldType& integrationFactor,
const RangeFieldType& quadratureWeight, const unsigned int rows, const unsigned int cols,
Dune::DenseMatrix<MatrixImp>& ret) const
{
// loop over all rows
for (unsigned int i = 0; i < rows; ++i) {
// get row
const typename Dune::DenseMatrix<MatrixImp>::const_row_reference localMatrixRow = localMatrix[i];
typename Dune::DenseMatrix<MatrixImp>::row_reference retRow = ret[i];
// loop over all cols
for (unsigned int j = 0; j < cols; ++j) {
retRow[j] += localMatrixRow[j] * integrationFactor * quadratureWeight;
} // loop over all cols
} // loop over all rows
} // end method addToIntegral
const LocalEvaluationType& localEvaluation_;
}; // end class InnerIntegral
} // end namespace Codim1
} // end namespace Local
} // end namespace DiscreteOperator
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEOPERATOR_LOCAL_CODIM1_INNERINTEGRAL_HH
<|endoftext|> |
<commit_before>// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.
#include <QHashFunctions>
#include "Note.h"
#include "Utils/Utils.h"
Note::Note(Note::Pitch pitch, int octave)
: pitch_(pitch)
, octave_(octave)
{
}
Note Note::noteFromKey(int key)
{
Note note;
note.setPitch((Note::Pitch)(key % 12));
note.setOctave(-1 + key / 12);
return note;
}
QString Note::pitchName(Note::Pitch pitch)
{
switch (pitch) {
case Pitch::C: return "do";
case Pitch::Cis: return "di";
case Pitch::D: return "re";
case Pitch::Ees: return "me";
case Pitch::E: return "mi";
case Pitch::F: return "fa";
case Pitch::Fis: return "fi";
case Pitch::G: return "so";
case Pitch::Aes: return "lu";
case Pitch::A: return "la";
case Pitch::Bes: return "se";
case Pitch::B: return "si";
default: break;
}
return "?";
}
QString Note::pitchName() const
{
return pitchName(pitch_);
}
bool Note::isFilled() const
{
switch (pitch_) {
case Pitch::C:
case Pitch::D:
case Pitch::E:
case Pitch::Fis:
case Pitch::Aes:
case Pitch::Bes:
return true;
default:
break;
}
return false;
}
Note::Pitch Note::pitch() const
{
return pitch_;
}
void Note::setPitch(const Pitch &pitch)
{
pitch_ = pitch;
}
int Note::octave() const
{
return octave_;
}
void Note::setOctave(int octave)
{
octave_ = octave;
}
bool Note::operator==(const Note &other) const
{
return pitch_ == other.pitch_ && octave_ == other.octave_;
}
bool Note::operator<(const Note &other) const
{
return octave_ < other.octave_ ||
(octave_ == other.octave_ && pitch_ < other.pitch_);
}
uint qHash(Note note)
{
return ::qHash((int)note.pitch()) ^ ::qHash(note.octave());
}
QTextStream &operator<<(QTextStream &s, const Note ¬e)
{
return s << "{ octave: " << (int)note.octave() << ", pitch: " << (int)note.pitch() << " }";
}
<commit_msg>Change QHashFunctions include to backwards-compatible QHash<commit_after>// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.
#include <QHash>
#include "Note.h"
#include "Utils/Utils.h"
Note::Note(Note::Pitch pitch, int octave)
: pitch_(pitch)
, octave_(octave)
{
}
Note Note::noteFromKey(int key)
{
Note note;
note.setPitch((Note::Pitch)(key % 12));
note.setOctave(-1 + key / 12);
return note;
}
QString Note::pitchName(Note::Pitch pitch)
{
switch (pitch) {
case Pitch::C: return "do";
case Pitch::Cis: return "di";
case Pitch::D: return "re";
case Pitch::Ees: return "me";
case Pitch::E: return "mi";
case Pitch::F: return "fa";
case Pitch::Fis: return "fi";
case Pitch::G: return "so";
case Pitch::Aes: return "lu";
case Pitch::A: return "la";
case Pitch::Bes: return "se";
case Pitch::B: return "si";
default: break;
}
return "?";
}
QString Note::pitchName() const
{
return pitchName(pitch_);
}
bool Note::isFilled() const
{
switch (pitch_) {
case Pitch::C:
case Pitch::D:
case Pitch::E:
case Pitch::Fis:
case Pitch::Aes:
case Pitch::Bes:
return true;
default:
break;
}
return false;
}
Note::Pitch Note::pitch() const
{
return pitch_;
}
void Note::setPitch(const Pitch &pitch)
{
pitch_ = pitch;
}
int Note::octave() const
{
return octave_;
}
void Note::setOctave(int octave)
{
octave_ = octave;
}
bool Note::operator==(const Note &other) const
{
return pitch_ == other.pitch_ && octave_ == other.octave_;
}
bool Note::operator<(const Note &other) const
{
return octave_ < other.octave_ ||
(octave_ == other.octave_ && pitch_ < other.pitch_);
}
uint qHash(Note note)
{
return ::qHash((int)note.pitch()) ^ ::qHash(note.octave());
}
QTextStream &operator<<(QTextStream &s, const Note ¬e)
{
return s << "{ octave: " << (int)note.octave() << ", pitch: " << (int)note.pitch() << " }";
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "wrapping_paper_functions.hpp"
void run_part_one() {
unsigned int area_sum = 0;
std::string dimensions;
while (std::cin >> dimensions) {
Present present(dimensions);
unsigned int area = calculate_wrapping_paper_area(present);
std::cout << area << std::endl;
area_sum += area;
}
std::cout << area_sum << std::endl;
}
void run_part_two() {
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day2 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<commit_msg>added calculation of ribbon length to main function<commit_after>#include <iostream>
#include <string>
#include "wrapping_paper_functions.hpp"
void run_part_one() {
unsigned int area_sum = 0;
std::string dimensions;
while (std::cin >> dimensions) {
Present present(dimensions);
unsigned int area = calculate_wrapping_paper_area(present);
std::cout << area << std::endl;
area_sum += area;
}
std::cout << area_sum << std::endl;
}
void run_part_two() {
unsigned int total_length = 0;
std::string dimensions;
while (std::cin >> dimensions) {
Present present(dimensions);
unsigned int length = calculate_ribbon_length(present);
std::cout << length << std::endl;
total_length += length;
}
std::cout << total_length << std::endl;
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day2 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) , Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 <ctype.h>
#include "nsapi_types.h"
#include "ATHandler.h"
#include "EventQueue.h"
#include "ATHandler_stub.h"
using namespace mbed;
using namespace events;
#include "CellularLog.h"
const int DEFAULT_AT_TIMEOUT = 1000; // at default timeout in milliseconds
nsapi_error_t ATHandler_stub::nsapi_error_value = 0;
uint8_t ATHandler_stub::nsapi_error_ok_counter = 0;
int ATHandler_stub::int_value = -1;
int ATHandler_stub::ref_count = 0;
int ATHandler_stub::timeout = 0;
bool ATHandler_stub::default_timeout = 0;
bool ATHandler_stub::debug_on = 0;
ssize_t ATHandler_stub::ssize_value = 0;
const char *ATHandler_stub::read_string_value = NULL;
size_t ATHandler_stub::size_value = 0;
size_t ATHandler_stub::return_given_size = false;
bool ATHandler_stub::bool_value = false;
uint8_t ATHandler_stub::uint8_value = 0;
FileHandle_stub *ATHandler_stub::fh_value = NULL;
device_err_t ATHandler_stub::device_err_value;
bool ATHandler_stub::call_immediately = false;
uint8_t ATHandler_stub::resp_info_true_counter = false;
uint8_t ATHandler_stub::info_elem_true_counter = false;
int ATHandler_stub::int_valid_count_table[kRead_int_table_size];
int ATHandler_stub::int_count = kRead_int_table_size;
bool ATHandler_stub::process_oob_urc = false;
int ATHandler_stub::read_string_index = kRead_string_table_size;
const char *ATHandler_stub::read_string_table[kRead_string_table_size];
int ATHandler_stub::resp_stop_success_count = kResp_stop_count_default;
int ATHandler_stub::urc_amount = 0;
mbed::Callback<void()> ATHandler_stub::callback[kATHandler_urc_table_max_size];
char *ATHandler_stub::urc_string_table[kATHandler_urc_table_max_size];
ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) :
_nextATHandler(0),
_fileHandle(fh),
_queue(queue)
{
ATHandler_stub::ref_count = 1;
ATHandler_stub::process_oob_urc = false;
ATHandler_stub::urc_amount = 0;
int i=0;
while (i < kATHandler_urc_table_max_size) {
ATHandler_stub::callback[i] = NULL;
ATHandler_stub::urc_string_table[i++] = NULL;
}
}
void ATHandler::set_debug(bool debug_on)
{
ATHandler_stub::debug_on = debug_on;
}
ATHandler::~ATHandler()
{
ATHandler_stub::ref_count = kATHandler_destructor_ref_ount;
int i=0;
while (i < kATHandler_urc_table_max_size) {
if (ATHandler_stub::urc_string_table[i]) {
delete [] ATHandler_stub::urc_string_table[i];
i++;
} else {
break;
}
}
}
void ATHandler::inc_ref_count()
{
ATHandler_stub::ref_count++;
}
void ATHandler::dec_ref_count()
{
ATHandler_stub::ref_count--;
}
int ATHandler::get_ref_count()
{
return ATHandler_stub::ref_count;
}
FileHandle *ATHandler::get_file_handle()
{
return ATHandler_stub::fh_value;
}
void ATHandler::set_file_handle(FileHandle *fh)
{
}
nsapi_error_t ATHandler::set_urc_handler(const char *urc, mbed::Callback<void()> cb)
{
if (ATHandler_stub::urc_amount < kATHandler_urc_table_max_size) {
ATHandler_stub::callback[ATHandler_stub::urc_amount] = cb;
ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount] = new char[kATHandler_urc_string_max_size];
if (urc) {
int bytes_to_copy = strlen(urc) < kATHandler_urc_string_max_size ? strlen(urc) : kATHandler_urc_string_max_size;
memcpy(ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount], urc, bytes_to_copy);
}
ATHandler_stub::urc_amount++;
} else {
ATHandler_stub::callback[0] = cb;
MBED_ASSERT("ATHandler URC amount limit reached");
}
if (ATHandler_stub::call_immediately) {
cb();
}
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::remove_urc_handler(const char *prefix)
{
}
nsapi_error_t ATHandler::get_last_error() const
{
if (ATHandler_stub::nsapi_error_ok_counter) {
ATHandler_stub::nsapi_error_ok_counter--;
return NSAPI_ERROR_OK;
}
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::lock()
{
}
void ATHandler::unlock()
{
}
nsapi_error_t ATHandler::unlock_return_error()
{
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout)
{
ATHandler_stub::timeout = timeout_milliseconds;
ATHandler_stub::default_timeout = default_timeout;
}
void ATHandler::restore_at_timeout()
{
}
void ATHandler::process_oob()
{
if (ATHandler_stub::process_oob_urc) {
int i = 0;
while (i < ATHandler_stub::urc_amount) {
if (ATHandler_stub::read_string_index >= 0) {
if (!memcmp(ATHandler_stub::urc_string_table[i],
ATHandler_stub::read_string_table[ATHandler_stub::read_string_index],
strlen(ATHandler_stub::urc_string_table[i]))) {
ATHandler_stub::callback[i]();
break;
}
}
i++;
}
}
}
void ATHandler::clear_error()
{
ATHandler_stub::nsapi_error_ok_counter++;
}
void ATHandler::skip_param(uint32_t count)
{
}
void ATHandler::skip_param(ssize_t len, uint32_t count)
{
}
ssize_t ATHandler::read_bytes(uint8_t *buf, size_t len)
{
return ATHandler_stub::ssize_value;
}
ssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag)
{
if (ATHandler_stub::read_string_index == kRead_string_table_size) {
if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) {
memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value + 1);
buf[ATHandler_stub::ssize_value] = '\0';
}
return ATHandler_stub::ssize_value;
}
ATHandler_stub::read_string_index--;
if (ATHandler_stub::read_string_index >= 0) {
const char *tmp = ATHandler_stub::read_string_table[ATHandler_stub::read_string_index];
ssize_t len = strlen(tmp);
memcpy(buf, tmp, len + 1);
buf[len] = '\0';
return len;
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
return -1;
}
int32_t ATHandler::read_int()
{
if (ATHandler_stub::nsapi_error_value != NSAPI_ERROR_OK) {
return -1;
}
if (ATHandler_stub::int_count == kRead_int_table_size) {
return ATHandler_stub::int_value;
}
//printf("ATHandler_stub::int_count: %d", ATHandler_stub::int_count);
ATHandler_stub::int_count--;
if (ATHandler_stub::int_count < kRead_int_table_size && ATHandler_stub::int_count >= 0) {
return ATHandler_stub::int_valid_count_table[ATHandler_stub::int_count];
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
return -1;
}
void ATHandler::set_delimiter(char delimiter)
{
}
void ATHandler::set_default_delimiter()
{
}
void ATHandler::set_stop_tag(const char *stop_tag_seq)
{
}
int ATHandler::get_3gpp_error()
{
return ATHandler_stub::int_value;
}
void ATHandler::resp_start(const char *prefix, bool stop)
{
}
bool ATHandler::info_resp()
{
if (ATHandler_stub::resp_info_true_counter) {
ATHandler_stub::resp_info_true_counter--;
return true;
}
return ATHandler_stub::bool_value;
}
bool ATHandler::info_elem(char start_tag)
{
if (ATHandler_stub::info_elem_true_counter) {
ATHandler_stub::info_elem_true_counter--;
return true;
}
return ATHandler_stub::bool_value;
}
bool ATHandler::consume_to_stop_tag()
{
return ATHandler_stub::bool_value;
}
void ATHandler::resp_stop()
{
if (ATHandler_stub::resp_stop_success_count > 0) {
ATHandler_stub::resp_stop_success_count--;
return;
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
}
void ATHandler::cmd_start(const char *cmd)
{
}
void ATHandler::write_int(int32_t param)
{
}
void ATHandler::write_string(const char *param, bool useQuotations)
{
}
size_t ATHandler::write_bytes(const uint8_t *param, size_t len)
{
if (ATHandler_stub::return_given_size) {
return len;
}
return ATHandler_stub::size_value;
}
void ATHandler::cmd_stop()
{
}
void ATHandler::cmd_stop_read_resp()
{
cmd_stop();
resp_start();
resp_stop();
}
device_err_t ATHandler::get_last_device_error() const
{
return ATHandler_stub::device_err_value;
}
void ATHandler::flush()
{
}
<commit_msg>cellular: registration status change astyle fix<commit_after>/*
* Copyright (c) , Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 <ctype.h>
#include "nsapi_types.h"
#include "ATHandler.h"
#include "EventQueue.h"
#include "ATHandler_stub.h"
using namespace mbed;
using namespace events;
#include "CellularLog.h"
const int DEFAULT_AT_TIMEOUT = 1000; // at default timeout in milliseconds
nsapi_error_t ATHandler_stub::nsapi_error_value = 0;
uint8_t ATHandler_stub::nsapi_error_ok_counter = 0;
int ATHandler_stub::int_value = -1;
int ATHandler_stub::ref_count = 0;
int ATHandler_stub::timeout = 0;
bool ATHandler_stub::default_timeout = 0;
bool ATHandler_stub::debug_on = 0;
ssize_t ATHandler_stub::ssize_value = 0;
const char *ATHandler_stub::read_string_value = NULL;
size_t ATHandler_stub::size_value = 0;
size_t ATHandler_stub::return_given_size = false;
bool ATHandler_stub::bool_value = false;
uint8_t ATHandler_stub::uint8_value = 0;
FileHandle_stub *ATHandler_stub::fh_value = NULL;
device_err_t ATHandler_stub::device_err_value;
bool ATHandler_stub::call_immediately = false;
uint8_t ATHandler_stub::resp_info_true_counter = false;
uint8_t ATHandler_stub::info_elem_true_counter = false;
int ATHandler_stub::int_valid_count_table[kRead_int_table_size];
int ATHandler_stub::int_count = kRead_int_table_size;
bool ATHandler_stub::process_oob_urc = false;
int ATHandler_stub::read_string_index = kRead_string_table_size;
const char *ATHandler_stub::read_string_table[kRead_string_table_size];
int ATHandler_stub::resp_stop_success_count = kResp_stop_count_default;
int ATHandler_stub::urc_amount = 0;
mbed::Callback<void()> ATHandler_stub::callback[kATHandler_urc_table_max_size];
char *ATHandler_stub::urc_string_table[kATHandler_urc_table_max_size];
ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, int timeout, const char *output_delimiter, uint16_t send_delay) :
_nextATHandler(0),
_fileHandle(fh),
_queue(queue)
{
ATHandler_stub::ref_count = 1;
ATHandler_stub::process_oob_urc = false;
ATHandler_stub::urc_amount = 0;
int i = 0;
while (i < kATHandler_urc_table_max_size) {
ATHandler_stub::callback[i] = NULL;
ATHandler_stub::urc_string_table[i++] = NULL;
}
}
void ATHandler::set_debug(bool debug_on)
{
ATHandler_stub::debug_on = debug_on;
}
ATHandler::~ATHandler()
{
ATHandler_stub::ref_count = kATHandler_destructor_ref_ount;
int i = 0;
while (i < kATHandler_urc_table_max_size) {
if (ATHandler_stub::urc_string_table[i]) {
delete [] ATHandler_stub::urc_string_table[i];
i++;
} else {
break;
}
}
}
void ATHandler::inc_ref_count()
{
ATHandler_stub::ref_count++;
}
void ATHandler::dec_ref_count()
{
ATHandler_stub::ref_count--;
}
int ATHandler::get_ref_count()
{
return ATHandler_stub::ref_count;
}
FileHandle *ATHandler::get_file_handle()
{
return ATHandler_stub::fh_value;
}
void ATHandler::set_file_handle(FileHandle *fh)
{
}
nsapi_error_t ATHandler::set_urc_handler(const char *urc, mbed::Callback<void()> cb)
{
if (ATHandler_stub::urc_amount < kATHandler_urc_table_max_size) {
ATHandler_stub::callback[ATHandler_stub::urc_amount] = cb;
ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount] = new char[kATHandler_urc_string_max_size];
if (urc) {
int bytes_to_copy = strlen(urc) < kATHandler_urc_string_max_size ? strlen(urc) : kATHandler_urc_string_max_size;
memcpy(ATHandler_stub::urc_string_table[ATHandler_stub::urc_amount], urc, bytes_to_copy);
}
ATHandler_stub::urc_amount++;
} else {
ATHandler_stub::callback[0] = cb;
MBED_ASSERT("ATHandler URC amount limit reached");
}
if (ATHandler_stub::call_immediately) {
cb();
}
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::remove_urc_handler(const char *prefix)
{
}
nsapi_error_t ATHandler::get_last_error() const
{
if (ATHandler_stub::nsapi_error_ok_counter) {
ATHandler_stub::nsapi_error_ok_counter--;
return NSAPI_ERROR_OK;
}
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::lock()
{
}
void ATHandler::unlock()
{
}
nsapi_error_t ATHandler::unlock_return_error()
{
return ATHandler_stub::nsapi_error_value;
}
void ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout)
{
ATHandler_stub::timeout = timeout_milliseconds;
ATHandler_stub::default_timeout = default_timeout;
}
void ATHandler::restore_at_timeout()
{
}
void ATHandler::process_oob()
{
if (ATHandler_stub::process_oob_urc) {
int i = 0;
while (i < ATHandler_stub::urc_amount) {
if (ATHandler_stub::read_string_index >= 0) {
if (!memcmp(ATHandler_stub::urc_string_table[i],
ATHandler_stub::read_string_table[ATHandler_stub::read_string_index],
strlen(ATHandler_stub::urc_string_table[i]))) {
ATHandler_stub::callback[i]();
break;
}
}
i++;
}
}
}
void ATHandler::clear_error()
{
ATHandler_stub::nsapi_error_ok_counter++;
}
void ATHandler::skip_param(uint32_t count)
{
}
void ATHandler::skip_param(ssize_t len, uint32_t count)
{
}
ssize_t ATHandler::read_bytes(uint8_t *buf, size_t len)
{
return ATHandler_stub::ssize_value;
}
ssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag)
{
if (ATHandler_stub::read_string_index == kRead_string_table_size) {
if (ATHandler_stub::read_string_value && ATHandler_stub::ssize_value >= 0) {
memcpy(buf, ATHandler_stub::read_string_value, ATHandler_stub::ssize_value + 1);
buf[ATHandler_stub::ssize_value] = '\0';
}
return ATHandler_stub::ssize_value;
}
ATHandler_stub::read_string_index--;
if (ATHandler_stub::read_string_index >= 0) {
const char *tmp = ATHandler_stub::read_string_table[ATHandler_stub::read_string_index];
ssize_t len = strlen(tmp);
memcpy(buf, tmp, len + 1);
buf[len] = '\0';
return len;
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
return -1;
}
int32_t ATHandler::read_int()
{
if (ATHandler_stub::nsapi_error_value != NSAPI_ERROR_OK) {
return -1;
}
if (ATHandler_stub::int_count == kRead_int_table_size) {
return ATHandler_stub::int_value;
}
//printf("ATHandler_stub::int_count: %d", ATHandler_stub::int_count);
ATHandler_stub::int_count--;
if (ATHandler_stub::int_count < kRead_int_table_size && ATHandler_stub::int_count >= 0) {
return ATHandler_stub::int_valid_count_table[ATHandler_stub::int_count];
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
return -1;
}
void ATHandler::set_delimiter(char delimiter)
{
}
void ATHandler::set_default_delimiter()
{
}
void ATHandler::set_stop_tag(const char *stop_tag_seq)
{
}
int ATHandler::get_3gpp_error()
{
return ATHandler_stub::int_value;
}
void ATHandler::resp_start(const char *prefix, bool stop)
{
}
bool ATHandler::info_resp()
{
if (ATHandler_stub::resp_info_true_counter) {
ATHandler_stub::resp_info_true_counter--;
return true;
}
return ATHandler_stub::bool_value;
}
bool ATHandler::info_elem(char start_tag)
{
if (ATHandler_stub::info_elem_true_counter) {
ATHandler_stub::info_elem_true_counter--;
return true;
}
return ATHandler_stub::bool_value;
}
bool ATHandler::consume_to_stop_tag()
{
return ATHandler_stub::bool_value;
}
void ATHandler::resp_stop()
{
if (ATHandler_stub::resp_stop_success_count > 0) {
ATHandler_stub::resp_stop_success_count--;
return;
}
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_DEVICE_ERROR;
}
void ATHandler::cmd_start(const char *cmd)
{
}
void ATHandler::write_int(int32_t param)
{
}
void ATHandler::write_string(const char *param, bool useQuotations)
{
}
size_t ATHandler::write_bytes(const uint8_t *param, size_t len)
{
if (ATHandler_stub::return_given_size) {
return len;
}
return ATHandler_stub::size_value;
}
void ATHandler::cmd_stop()
{
}
void ATHandler::cmd_stop_read_resp()
{
cmd_stop();
resp_start();
resp_stop();
}
device_err_t ATHandler::get_last_device_error() const
{
return ATHandler_stub::device_err_value;
}
void ATHandler::flush()
{
}
<|endoftext|> |
<commit_before>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
#include <functional>
#include <type_traits>
#include <memory>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
}
template <typename Container, typename AccumulateFunc>
impl::Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
template <typename T, typename AccumulateFunc>
impl::Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T>, AccumulateFunc);
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator iter::accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
template <typename T, typename AF>
friend Accumulator<std::initializer_list<T>, AF> iter::accumulate(
std::initializer_list<T>, AF);
using AccumVal = std::remove_reference_t<std::result_of_t<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>>;
Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)
: container(std::forward<Container>(in_container)),
accumulate_func(in_accumulate_func) {}
public:
Accumulator(Accumulator&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
AccumulateFunc* accumulate_func;
std::unique_ptr<AccumVal> acc_val;
public:
Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
AccumulateFunc& in_accumulate_fun)
: sub_iter{std::move(iter)},
sub_end{std::move(end)},
accumulate_func(&in_accumulate_fun),
// only get first value if not an end iterator
acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}
Iterator(const Iterator& other)
: sub_iter{other.sub_iter},
sub_end{other.sub_end},
accumulate_func{other.accumulate_func},
acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) { return *this; }
this->sub_iter = other.sub_iter;
this->sub_end = other.sub_end;
this->accumulate_func = other.accumulate_func;
this->acc_val.reset(
other.acc_val ? new AccumVal(*other.acc_val) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *this->acc_val;
}
const AccumVal* operator->() const {
return this->acc_val.get();
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
*this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
this->accumulate_func};
}
};
template <typename Container, typename AccumulateFunc>
iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate(
Container&& container, AccumulateFunc accumulate_func) {
return {std::forward<Container>(container), accumulate_func};
}
template <typename T, typename AccumulateFunc>
iter::impl::Accumulator<std::initializer_list<T>, AccumulateFunc>
iter::accumulate(std::initializer_list<T> il, AccumulateFunc accumulate_func) {
return {std::move(il), accumulate_func};
}
namespace iter {
template <typename Container>
auto accumulate(Container&& container) -> decltype(accumulate(
std::forward<Container>(container),
std::plus<std::remove_reference_t<impl::iterator_deref<Container>>>{})) {
return accumulate(std::forward<Container>(container),
std::plus<std::remove_reference_t<impl::iterator_deref<Container>>>{});
}
template <typename T>
auto accumulate(std::initializer_list<T> il)
-> decltype(accumulate(std::move(il), std::plus<T>{})) {
return accumulate(std::move(il), std::plus<T>{});
}
}
#endif
<commit_msg>drops init list support from accumulate<commit_after>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterbase.hpp"
#include <utility>
#include <iterator>
#include <functional>
#include <type_traits>
#include <memory>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
}
template <typename Container, typename AccumulateFunc>
impl::Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator iter::accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
using AccumVal = std::remove_reference_t<std::result_of_t<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>>;
Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func)
: container(std::forward<Container>(in_container)),
accumulate_func(in_accumulate_func) {}
public:
Accumulator(Accumulator&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
AccumulateFunc* accumulate_func;
std::unique_ptr<AccumVal> acc_val;
public:
Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
AccumulateFunc& in_accumulate_fun)
: sub_iter{std::move(iter)},
sub_end{std::move(end)},
accumulate_func(&in_accumulate_fun),
// only get first value if not an end iterator
acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {}
Iterator(const Iterator& other)
: sub_iter{other.sub_iter},
sub_end{other.sub_end},
accumulate_func{other.accumulate_func},
acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) { return *this; }
this->sub_iter = other.sub_iter;
this->sub_end = other.sub_end;
this->accumulate_func = other.accumulate_func;
this->acc_val.reset(
other.acc_val ? new AccumVal(*other.acc_val) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *this->acc_val;
}
const AccumVal* operator->() const {
return this->acc_val.get();
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
*this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
this->accumulate_func};
}
};
template <typename Container, typename AccumulateFunc>
iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate(
Container&& container, AccumulateFunc accumulate_func) {
return {std::forward<Container>(container), accumulate_func};
}
namespace iter {
template <typename Container>
auto accumulate(Container&& container) -> decltype(accumulate(
std::forward<Container>(container),
std::plus<std::remove_reference_t<impl::iterator_deref<Container>>>{})) {
return accumulate(std::forward<Container>(container),
std::plus<std::remove_reference_t<impl::iterator_deref<Container>>>{});
}
}
#endif
<|endoftext|> |
<commit_before>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"
//#define DISABLE_IMPORT
#ifndef DISABLE_IMPORT
#include "curl.h"
#endif
#include "errors.h"
#include "patternsContainers.h"
#include "WebssonUtils/constants.h"
#include "WebssonUtils/utilsWebss.h"
using namespace std;
using namespace webss;
const char ERROR_INPUT_DICTIONARY[] = "dictionary can only have key-values";
const char ERROR_INPUT_LIST[] = "list can only have concrete value-onlys";
const char ERROR_INPUT_TUPLE[] = "tuple can only have concrete value-onlys or key-values";
const char ERROR_INPUT_NAMESPACE[] = "namespace can only have entity definitions";
const char ERROR_INPUT_ENUM[] = "enum can only have key-onlys";
const char ERROR_INPUT_DOCUMENT[] = "document can only have concrete value-onlys or key-values";
string getItPosition(SmartIterator& it)
{
return "[ln " + to_string(it.getLine()) + ", ch " + to_string(it.getCharCount()) + "]";
}
string getItCurrentChar(SmartIterator& it)
{
if (!it)
return string("");
string out;
out += " '";
if (*it == '\'' || *it == '\\')
out += '\\';
out = out + *it + "' ";
switch (*it)
{
case '~': out += "(using namespace)"; break;
case '!': out += "(entity declaration)"; break;
case '@': out += "(import)"; break;
case '#': out += "(option)"; break;
case '&': out += "(self)"; break;
case ':': out += "(line string)"; break;
case '"': out += "(cstring)"; break;
case '?': out += "(entity declaration)"; break;
case '.': out += "(scope)"; break;
case '(': case ')':out += "(parenthesis / round bracket)"; break;
case '{': case '}': out += "(brace / curly bracket)"; break;
case '[': case ']': out += "(square bracket)"; break;
case '<': case '>': out += "(angle bracket / chevron)"; break;
default:
break;
}
return out;
}
Dictionary Parser::parseDictionary()
{
return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
{
if (nextTag == Tag::C_STRING)
addJsonKeyvalue(dict);
else
parseOtherValue(
CaseKeyValue{ dict.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_DICTIONARY),
ErrorValueOnly(ERROR_INPUT_DICTIONARY),
ErrorAbstractEntity(ERROR_INPUT_DICTIONARY));
});
}
List Parser::parseList()
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
list.add(parseValueOnly());
});
}
Tuple Parser::parseTuple()
{
return parseContainer<Tuple, ConType::TUPLE>(Tuple(), [&](Tuple& tuple)
{
parseOtherValue(
CaseKeyValue{ tuple.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_TUPLE),
CaseValueOnly{ tuple.add(move(value)); },
ErrorAbstractEntity(ERROR_INPUT_TUPLE));
});
}
List Parser::parseListText()
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
list.add(parseLineString());
});
}
Tuple Parser::parseTupleText()
{
return parseContainer<Tuple, ConType::TUPLE>(Tuple(), [&](Tuple& tuple)
{
tuple.add(parseLineString());
});
}
Namespace Parser::parseNamespace(const string& name, const Namespace& previousNamespace)
{
return parseContainer<Namespace, ConType::DICTIONARY>(Namespace(name, previousNamespace), [&](Namespace& nspace)
{
switch (*it)
{
case CHAR_ABSTRACT_ENTITY:
++it;
nspace.addSafe(parseAbstractEntity(nspace));
break;
case CHAR_CONCRETE_ENTITY:
++it;
nspace.addSafe(parseConcreteEntity());
break;
case CHAR_SELF:
skipJunkToTag(++it, Tag::START_TEMPLATE);
nspace.addSafe(Entity(string(name), parseTemplateHead()));
break;
default:
throw runtime_error(ERROR_INPUT_NAMESPACE);
}
});
}
Enum Parser::parseEnum(const string& name)
{
return parseContainer<Enum, ConType::LIST>(Enum(name), [&](Enum& tEnum)
{
parseOtherValue(
ErrorKeyValue(ERROR_INPUT_ENUM),
CaseKeyOnly{ tEnum.add(move(key)); },
ErrorValueOnly(ERROR_INPUT_ENUM),
ErrorAbstractEntity(ERROR_INPUT_ENUM));
});
}
Document Parser::parseDocument()
{
try
{
Document doc;
if (!containerEmpty() && !parseDocumentHead(doc.getHead(), Namespace::getEmptyInstance()))
{
do
parseOtherValue(
CaseKeyValue{ doc.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_DOCUMENT),
CaseValueOnly{ doc.add(move(value)); },
ErrorAbstractEntity(ERROR_INPUT_DOCUMENT));
while (checkNextElement());
}
return doc;
}
catch (const exception& e)
{
throw runtime_error(string(getItPosition(it) + ' ' + e.what() + getItCurrentChar(it)).c_str());
}
}
bool Parser::parseDocumentHead(vector<ParamDocument>& docHead, const Namespace& nspace)
{
assert(it);
do
{
switch (*it)
{
case CHAR_ABSTRACT_ENTITY:
{
++it;
auto ent = parseAbstractEntity(nspace);
docHead.push_back(ParamDocument::makeEntityAbstract(ent));
ents.addLocalSafe(move(ent));
break;
}
case CHAR_CONCRETE_ENTITY:
{
++it;
auto ent = parseConcreteEntity();
docHead.push_back(ParamDocument::makeEntityConcrete(ent));
ents.addLocalSafe(move(ent));
break;
}
case CHAR_IMPORT:
{
++it;
auto import = parseImport();
docHead.push_back(move(import));
break;
}
case CHAR_SCOPED_DOCUMENT:
++it;
parseScopedDocument(docHead);
break;
default:
return false;
}
} while (checkNextElement());
return true;
}
void Parser::parseScopedDocument(vector<ParamDocument>& docHead)
{
if (*skipJunkToValid(it) == OPEN_TEMPLATE)
{
ContainerSwitcher switcher1(*this, ConType::TEMPLATE_HEAD, false);
if (containerEmpty())
throw runtime_error("can't have empty scoped document head");
auto head = parseTemplateHeadScoped();
skipJunkToTag(it, Tag::START_DICTIONARY);
DocumentHead body;
ContainerSwitcher switcher2(*this, ConType::DICTIONARY, false);
if (!containerEmpty())
{
ParamDocumentIncluder includer(ents, head.getParameters());
if (!parseDocumentHead(body, Namespace::getEmptyInstance()))
throw runtime_error(ERROR_UNEXPECTED);
}
docHead.push_back(ScopedDocument{ move(head), move(body) });
}
else
{
const auto& nspace = parseUsingNamespaceStatic();
//first check the namespace entity is accessible; if so it has to be removed since
//it'll no longer be necessary and an entity with the same name could be inside
if (ParamDocumentIncluder::namespacePresentScope(ents, nspace))
ents.removeLocal(ents[nspace.getName()]);
for (const auto& ent : nspace)
ents.addLocalSafe(ent);
}
}
ImportedDocument Parser::parseImport()
{
#ifdef DISABLE_IMPORT
throw runtime_error("this parser cannot import documents");
#else
nextTag = getTag(it);
auto importName = parseValueOnly();
if (!importName.isString())
throw runtime_error("import must reference a string");
ImportedDocument import(move(importName));
const auto& link = import.getLink();
if (!importedDocuments.hasEntity(link))
{
try
{
importedDocuments.addLocalSafe(link, 0);
ImportSwitcher switcher(*this, SmartIterator(Curl().readWebDocument(link)));
DocumentHead docHead;
if (!containerEmpty() && !parseDocumentHead(docHead, Namespace::getEmptyInstance()))
throw runtime_error(ERROR_UNEXPECTED);
}
catch (const exception& e)
{ throw runtime_error(string("while parsing import, ") + e.what()); }
}
return import;
#endif
}
const Namespace& Parser::parseUsingNamespaceStatic()
{
skipJunkToTag(it, Tag::NAME_START);
auto nameType = parseNameType();
if (nameType.type != NameType::ENTITY_ABSTRACT || !nameType.entity.getContent().isNamespace())
throw runtime_error("expected namespace");
return nameType.entity.getContent().getNamespaceSafe();
}<commit_msg>Scoped names for namespace and enum<commit_after>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"
//#define DISABLE_IMPORT
#ifndef DISABLE_IMPORT
#include "curl.h"
#endif
#include "errors.h"
#include "patternsContainers.h"
#include "WebssonUtils/constants.h"
#include "WebssonUtils/utilsWebss.h"
using namespace std;
using namespace webss;
const char ERROR_INPUT_DICTIONARY[] = "dictionary can only have key-values";
const char ERROR_INPUT_LIST[] = "list can only have concrete value-onlys";
const char ERROR_INPUT_TUPLE[] = "tuple can only have concrete value-onlys or key-values";
const char ERROR_INPUT_NAMESPACE[] = "namespace can only have entity definitions";
const char ERROR_INPUT_ENUM[] = "enum can only have key-onlys";
const char ERROR_INPUT_DOCUMENT[] = "document can only have concrete value-onlys or key-values";
string getItPosition(SmartIterator& it)
{
return "[ln " + to_string(it.getLine()) + ", ch " + to_string(it.getCharCount()) + "]";
}
string getItCurrentChar(SmartIterator& it)
{
if (!it)
return string("");
string out;
out += " '";
if (*it == '\'' || *it == '\\')
out += '\\';
out = out + *it + "' ";
switch (*it)
{
case '~': out += "(using namespace)"; break;
case '!': out += "(entity declaration)"; break;
case '@': out += "(import)"; break;
case '#': out += "(option)"; break;
case '&': out += "(self)"; break;
case ':': out += "(line string)"; break;
case '"': out += "(cstring)"; break;
case '?': out += "(entity declaration)"; break;
case '.': out += "(scope)"; break;
case '(': case ')':out += "(parenthesis / round bracket)"; break;
case '{': case '}': out += "(brace / curly bracket)"; break;
case '[': case ']': out += "(square bracket)"; break;
case '<': case '>': out += "(angle bracket / chevron)"; break;
default:
break;
}
return out;
}
Dictionary Parser::parseDictionary()
{
return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
{
if (nextTag == Tag::C_STRING)
addJsonKeyvalue(dict);
else
parseOtherValue(
CaseKeyValue{ dict.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_DICTIONARY),
ErrorValueOnly(ERROR_INPUT_DICTIONARY),
ErrorAbstractEntity(ERROR_INPUT_DICTIONARY));
});
}
List Parser::parseList()
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
list.add(parseValueOnly());
});
}
Tuple Parser::parseTuple()
{
return parseContainer<Tuple, ConType::TUPLE>(Tuple(), [&](Tuple& tuple)
{
parseOtherValue(
CaseKeyValue{ tuple.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_TUPLE),
CaseValueOnly{ tuple.add(move(value)); },
ErrorAbstractEntity(ERROR_INPUT_TUPLE));
});
}
List Parser::parseListText()
{
return parseContainer<List, ConType::LIST>(List(), [&](List& list)
{
list.add(parseLineString());
});
}
Tuple Parser::parseTupleText()
{
return parseContainer<Tuple, ConType::TUPLE>(Tuple(), [&](Tuple& tuple)
{
tuple.add(parseLineString());
});
}
Namespace Parser::parseNamespace(const string& name, const Namespace& previousNamespace)
{
return parseContainer<Namespace, ConType::DICTIONARY>(Namespace(name, previousNamespace), [&](Namespace& nspace)
{
switch (*it)
{
case CHAR_ABSTRACT_ENTITY:
++it;
nspace.addSafe(parseAbstractEntity(nspace));
break;
case CHAR_CONCRETE_ENTITY:
++it;
nspace.addSafe(parseConcreteEntity());
break;
case CHAR_SELF:
skipJunkToTag(++it, Tag::START_TEMPLATE);
nspace.addSafe(Entity(string(name), parseTemplateHead()));
break;
default:
throw runtime_error(ERROR_INPUT_NAMESPACE);
}
});
}
Enum Parser::parseEnum(const string& name)
{
return parseContainer<Enum, ConType::LIST>(Enum(name), [&](Enum& tEnum)
{
if (nextTag != Tag::NAME_START)
throw runtime_error(ERROR_UNEXPECTED);
auto name = parseName(it);
if (isKeyword(name))
throw runtime_error("enum name can't be a keyword");
tEnum.addSafe(move(name));
});
}
Document Parser::parseDocument()
{
try
{
Document doc;
if (!containerEmpty() && !parseDocumentHead(doc.getHead(), Namespace::getEmptyInstance()))
{
do
parseOtherValue(
CaseKeyValue{ doc.addSafe(move(key), move(value)); },
ErrorKeyOnly(ERROR_INPUT_DOCUMENT),
CaseValueOnly{ doc.add(move(value)); },
ErrorAbstractEntity(ERROR_INPUT_DOCUMENT));
while (checkNextElement());
}
return doc;
}
catch (const exception& e)
{
throw runtime_error(string(getItPosition(it) + ' ' + e.what() + getItCurrentChar(it)).c_str());
}
}
bool Parser::parseDocumentHead(vector<ParamDocument>& docHead, const Namespace& nspace)
{
assert(it);
do
{
switch (*it)
{
case CHAR_ABSTRACT_ENTITY:
{
++it;
auto ent = parseAbstractEntity(nspace);
docHead.push_back(ParamDocument::makeEntityAbstract(ent));
ents.addLocalSafe(move(ent));
break;
}
case CHAR_CONCRETE_ENTITY:
{
++it;
auto ent = parseConcreteEntity();
docHead.push_back(ParamDocument::makeEntityConcrete(ent));
ents.addLocalSafe(move(ent));
break;
}
case CHAR_IMPORT:
{
++it;
auto import = parseImport();
docHead.push_back(move(import));
break;
}
case CHAR_SCOPED_DOCUMENT:
++it;
parseScopedDocument(docHead);
break;
default:
return false;
}
} while (checkNextElement());
return true;
}
void Parser::parseScopedDocument(vector<ParamDocument>& docHead)
{
if (*skipJunkToValid(it) == OPEN_TEMPLATE)
{
ContainerSwitcher switcher1(*this, ConType::TEMPLATE_HEAD, false);
if (containerEmpty())
throw runtime_error("can't have empty scoped document head");
auto head = parseTemplateHeadScoped();
skipJunkToTag(it, Tag::START_DICTIONARY);
DocumentHead body;
ContainerSwitcher switcher2(*this, ConType::DICTIONARY, false);
if (!containerEmpty())
{
ParamDocumentIncluder includer(ents, head.getParameters());
if (!parseDocumentHead(body, Namespace::getEmptyInstance()))
throw runtime_error(ERROR_UNEXPECTED);
}
docHead.push_back(ScopedDocument{ move(head), move(body) });
}
else
{
const auto& nspace = parseUsingNamespaceStatic();
//first check the namespace entity is accessible; if so it has to be removed since
//it'll no longer be necessary and an entity with the same name could be inside
if (ParamDocumentIncluder::namespacePresentScope(ents, nspace))
ents.removeLocal(ents[nspace.getName()]);
for (const auto& ent : nspace)
ents.addLocalSafe(ent);
}
}
ImportedDocument Parser::parseImport()
{
#ifdef DISABLE_IMPORT
throw runtime_error("this parser cannot import documents");
#else
nextTag = getTag(it);
auto importName = parseValueOnly();
if (!importName.isString())
throw runtime_error("import must reference a string");
ImportedDocument import(move(importName));
const auto& link = import.getLink();
if (!importedDocuments.hasEntity(link))
{
try
{
importedDocuments.addLocalSafe(link, 0);
ImportSwitcher switcher(*this, SmartIterator(Curl().readWebDocument(link)));
DocumentHead docHead;
if (!containerEmpty() && !parseDocumentHead(docHead, Namespace::getEmptyInstance()))
throw runtime_error(ERROR_UNEXPECTED);
}
catch (const exception& e)
{ throw runtime_error(string("while parsing import, ") + e.what()); }
}
return import;
#endif
}
const Namespace& Parser::parseUsingNamespaceStatic()
{
skipJunkToTag(it, Tag::NAME_START);
auto nameType = parseNameType();
if (nameType.type != NameType::ENTITY_ABSTRACT || !nameType.entity.getContent().isNamespace())
throw runtime_error("expected namespace");
return nameType.entity.getContent().getNamespaceSafe();
}<|endoftext|> |
<commit_before><commit_msg>Fixing a possible error source<commit_after><|endoftext|> |
<commit_before>#include "pch.h"
#include "WASAPIDevice.h"
using namespace LibAudio;
WASAPIDevice::WASAPIDevice() : m_initialized(false)
{
}
void WASAPIDevice::StopAsync()
{
if (Capture != nullptr)
{
Capture->StopCaptureAsync();
}
}
void WASAPIDevice::InitCaptureDevice(size_t id, DataCollector^ collector)
{
Number = id;
if (Capture)
{
Capture = nullptr;
}
Capture = Make<WASAPICapture>();
StateChangedEvent = Capture->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
Capture->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::InitRendererDevice(size_t id, DataCollector^ collector)
{
HRESULT hr = S_OK;
if (Renderer)
{
Renderer = nullptr;
}
Renderer = Make<WASAPIRenderer>();
StateChangedEvent = Renderer->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
DEVICEPROPS props;
props.IsTonePlayback = true;
props.Frequency = static_cast<DWORD>(440);
/*
switch (m_ContentType)
{
case ContentType::ContentTypeTone:
props.IsTonePlayback = true;
props.Frequency = static_cast<DWORD>(sliderFrequency->Value);
break;
case ContentType::ContentTypeFile:
props.IsTonePlayback = false;
props.ContentStream = m_ContentStream;
break;
}
m_IsMinimumLatency = static_cast<Platform::Boolean>(toggleMinimumLatency->IsOn);
props.IsLowLatency = m_IsMinimumLatency;
props.IsHWOffload = false;
props.IsBackground = false;
props.IsRawChosen = static_cast<Platform::Boolean>(toggleRawAudio->IsOn);
props.IsRawSupported = m_deviceSupportsRawMode;
*/
Renderer->SetProperties(props);
Renderer->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)
{
// Get the current time for messages
auto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
calendar->SetToNow();
// Handle state specific messages
switch (e->State)
{
case DeviceState::DeviceStateInitialized:
{
String^ str = String::Concat(ID, "-DeviceStateInitialized\n");
OutputDebugString(str->Data());
if (Capture != nullptr)
{
Capture->StartCaptureAsync();
}
if (Renderer != nullptr)
{
Renderer->StartPlaybackAsync();
}
break;
}
case DeviceState::DeviceStateCapturing:
{
String^ str = String::Concat(ID, "-DeviceStateCapturing\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateDiscontinuity:
{
String^ str = String::Concat(ID, "-DeviceStateDiscontinuity\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateInError:
{
String^ str = String::Concat(ID, "-DeviceStateInError\n");
OutputDebugString(str->Data());
break;
}
}
}
<commit_msg>12052016 - 12:53<commit_after>#include "pch.h"
#include "WASAPIDevice.h"
using namespace LibAudio;
WASAPIDevice::WASAPIDevice() : m_initialized(false)
{
}
void WASAPIDevice::StopAsync()
{
if (Capture != nullptr)
{
Capture->StopCaptureAsync();
}
}
void WASAPIDevice::InitCaptureDevice(size_t id, DataCollector^ collector)
{
Number = id;
if (Capture)
{
Capture = nullptr;
}
Capture = Make<WASAPICapture>();
StateChangedEvent = Capture->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
Capture->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::InitRendererDevice(size_t id, DataCollector^ collector)
{
HRESULT hr = S_OK;
if (Renderer)
{
Renderer = nullptr;
}
Renderer = Make<WASAPIRenderer>();
StateChangedEvent = Renderer->GetDeviceStateEvent();
DeviceStateChangeToken = StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &WASAPIDevice::OnDeviceStateChange);
DEVICEPROPS props;
props.IsTonePlayback = true;
props.Frequency = static_cast<DWORD>(440);
/*
switch (m_ContentType)
{
case ContentType::ContentTypeTone:
props.IsTonePlayback = true;
props.Frequency = static_cast<DWORD>(sliderFrequency->Value);
break;
case ContentType::ContentTypeFile:
props.IsTonePlayback = false;
props.ContentStream = m_ContentStream;
break;
}
m_IsMinimumLatency = static_cast<Platform::Boolean>(toggleMinimumLatency->IsOn);
props.IsLowLatency = m_IsMinimumLatency;
props.IsHWOffload = false;
props.IsBackground = false;
props.IsRawChosen = static_cast<Platform::Boolean>(toggleRawAudio->IsOn);
props.IsRawSupported = m_deviceSupportsRawMode;
*/
Renderer->SetProperties(props);
Renderer->InitializeAudioDeviceAsync(ID, Number, collector);
m_initialized = true;
}
void WASAPIDevice::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)
{
// Get the current time for messages
auto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
calendar->SetToNow();
// Handle state specific messages
switch (e->State)
{
case DeviceState::DeviceStateActivated:
{
String^ str = String::Concat(ID, "-DeviceStateActivated\n");
OutputDebugString(str->Data());
if (Renderer != nullptr)
{
Renderer->StartPlaybackAsync();
}
break;
}
case DeviceState::DeviceStateInitialized:
{
String^ str = String::Concat(ID, "-DeviceStateInitialized\n");
OutputDebugString(str->Data());
if (Capture != nullptr)
{
Capture->StartCaptureAsync();
}
break;
}
case DeviceState::DeviceStateCapturing:
{
String^ str = String::Concat(ID, "-DeviceStateCapturing\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateDiscontinuity:
{
String^ str = String::Concat(ID, "-DeviceStateDiscontinuity\n");
OutputDebugString(str->Data());
break;
}
case DeviceState::DeviceStateInError:
{
String^ str = String::Concat(ID, "-DeviceStateInError\n");
OutputDebugString(str->Data());
break;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/network_configuration_updater.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/policy/mock_configuration_policy_provider.h"
#include "chrome/browser/policy/policy_map.h"
#include "chrome/browser/policy/policy_service_impl.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::Mock;
using testing::Return;
using testing::_;
namespace policy {
static const char kFakeONC[] = "{ \"GUID\": \"1234\" }";
class NetworkConfigurationUpdaterTest
: public testing::TestWithParam<const char*> {
protected:
virtual void SetUp() OVERRIDE {
EXPECT_CALL(network_library_, LoadOncNetworks(_, "", _, _, _))
.WillRepeatedly(Return(true));
EXPECT_CALL(provider_, IsInitializationComplete())
.WillRepeatedly(Return(true));
PolicyServiceImpl::Providers providers;
providers.push_back(&provider_);
policy_service_.reset(new PolicyServiceImpl(providers));
}
// Maps configuration policy name to corresponding ONC source.
static chromeos::NetworkUIData::ONCSource NameToONCSource(
const std::string& name) {
if (name == key::kDeviceOpenNetworkConfiguration)
return chromeos::NetworkUIData::ONC_SOURCE_DEVICE_POLICY;
if (name == key::kOpenNetworkConfiguration)
return chromeos::NetworkUIData::ONC_SOURCE_USER_POLICY;
return chromeos::NetworkUIData::ONC_SOURCE_NONE;
}
chromeos::MockNetworkLibrary network_library_;
MockConfigurationPolicyProvider provider_;
scoped_ptr<PolicyServiceImpl> policy_service_;
};
TEST_P(NetworkConfigurationUpdaterTest, InitialUpdate) {
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.WillOnce(Return(true));
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
Mock::VerifyAndClearExpectations(&network_library_);
}
TEST_P(NetworkConfigurationUpdaterTest, AllowWebTrust) {
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
updater.set_allow_web_trust(true);
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
true, _))
.WillOnce(Return(true));
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
}
TEST_P(NetworkConfigurationUpdaterTest, PolicyChange) {
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
// We should update if policy changes.
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.WillOnce(Return(true));
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
// No update if the set the same value again.
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.Times(0);
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
// Another update is expected if the policy goes away.
EXPECT_CALL(network_library_,
LoadOncNetworks(NetworkConfigurationUpdater::kEmptyConfiguration,
"", NameToONCSource(GetParam()), false, _))
.WillOnce(Return(true));
policy.Erase(GetParam());
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
}
INSTANTIATE_TEST_CASE_P(
NetworkConfigurationUpdaterTestInstance,
NetworkConfigurationUpdaterTest,
testing::Values(key::kDeviceOpenNetworkConfiguration,
key::kOpenNetworkConfiguration));
} // namespace policy
<commit_msg>Update unit_test that broke after http://crrev.com/162481<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 "chrome/browser/policy/network_configuration_updater.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/policy/mock_configuration_policy_provider.h"
#include "chrome/browser/policy/policy_map.h"
#include "chrome/browser/policy/policy_service_impl.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::Mock;
using testing::Return;
using testing::_;
namespace policy {
static const char kFakeONC[] = "{ \"GUID\": \"1234\" }";
class NetworkConfigurationUpdaterTest
: public testing::TestWithParam<const char*> {
protected:
virtual void SetUp() OVERRIDE {
EXPECT_CALL(network_library_, LoadOncNetworks(_, "", _, _, _))
.WillRepeatedly(Return(true));
EXPECT_CALL(provider_, IsInitializationComplete())
.WillRepeatedly(Return(true));
provider_.Init();
PolicyServiceImpl::Providers providers;
providers.push_back(&provider_);
policy_service_.reset(new PolicyServiceImpl(providers));
}
virtual void TearDown() OVERRIDE {
provider_.Shutdown();
}
// Maps configuration policy name to corresponding ONC source.
static chromeos::NetworkUIData::ONCSource NameToONCSource(
const std::string& name) {
if (name == key::kDeviceOpenNetworkConfiguration)
return chromeos::NetworkUIData::ONC_SOURCE_DEVICE_POLICY;
if (name == key::kOpenNetworkConfiguration)
return chromeos::NetworkUIData::ONC_SOURCE_USER_POLICY;
return chromeos::NetworkUIData::ONC_SOURCE_NONE;
}
chromeos::MockNetworkLibrary network_library_;
MockConfigurationPolicyProvider provider_;
scoped_ptr<PolicyServiceImpl> policy_service_;
};
TEST_P(NetworkConfigurationUpdaterTest, InitialUpdate) {
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.WillOnce(Return(true));
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
Mock::VerifyAndClearExpectations(&network_library_);
}
TEST_P(NetworkConfigurationUpdaterTest, AllowWebTrust) {
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
updater.set_allow_web_trust(true);
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
true, _))
.WillOnce(Return(true));
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
}
TEST_P(NetworkConfigurationUpdaterTest, PolicyChange) {
NetworkConfigurationUpdater updater(policy_service_.get(), &network_library_);
// We should update if policy changes.
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.WillOnce(Return(true));
PolicyMap policy;
policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Value::CreateStringValue(kFakeONC));
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
// No update if the set the same value again.
EXPECT_CALL(network_library_,
LoadOncNetworks(kFakeONC, "", NameToONCSource(GetParam()),
false, _))
.Times(0);
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
// Another update is expected if the policy goes away.
EXPECT_CALL(network_library_,
LoadOncNetworks(NetworkConfigurationUpdater::kEmptyConfiguration,
"", NameToONCSource(GetParam()), false, _))
.WillOnce(Return(true));
policy.Erase(GetParam());
provider_.UpdateChromePolicy(policy);
Mock::VerifyAndClearExpectations(&network_library_);
}
INSTANTIATE_TEST_CASE_P(
NetworkConfigurationUpdaterTestInstance,
NetworkConfigurationUpdaterTest,
testing::Values(key::kDeviceOpenNetworkConfiguration,
key::kOpenNetworkConfiguration));
} // namespace policy
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
int route_id,
Profile* profile,
SiteInstance* site,
GURL opener_url,
const string16& frame_name) {
ExtensionsService* extensions_service = profile->GetExtensionsService();
if (!opener_url.is_valid() ||
frame_name.empty() ||
!extensions_service ||
!extensions_service->is_ready())
return NULL;
Extension* extension = extensions_service->GetExtensionByURL(opener_url);
if (!extension)
extension = extensions_service->GetExtensionByWebExtent(opener_url);
if (!extension ||
!extension->HasApiPermission(Extension::kBackgroundPermission))
return NULL;
// Only allow a single background contents per app.
if (!profile->GetBackgroundContentsService() ||
profile->GetBackgroundContentsService()->GetAppBackgroundContents(
ASCIIToUTF16(extension->id())))
return NULL;
// Ensure that we're trying to open this from the extension's process.
ExtensionProcessManager* process_manager =
profile->GetExtensionProcessManager();
if (!site->GetProcess() || !process_manager ||
site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
return NULL;
// Passed all the checks, so this should be created as a BackgroundContents.
BackgroundContents* contents = new BackgroundContents(site, route_id);
string16 appid = ASCIIToUTF16(extension->id());
BackgroundContentsOpenedDetails details = { contents, frame_name, appid };
NotificationService::current()->Notify(
NotificationType::BACKGROUND_CONTENTS_OPENED,
Source<Profile>(profile),
Details<BackgroundContentsOpenedDetails>(&details));
return contents;
}
TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
int route_id,
Profile* profile,
SiteInstance* site,
DOMUITypeID domui_type,
RenderViewHostDelegate* opener,
WindowContainerType window_container_type,
const string16& frame_name) {
if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
BackgroundContents* contents = MaybeCreateBackgroundContents(
route_id,
profile,
site,
opener->GetURL(),
frame_name);
if (contents) {
pending_contents_[route_id] = contents->render_view_host();
return NULL;
}
}
// Create the new web contents. This will automatically create the new
// TabContentsView. In the future, we may want to create the view separately.
TabContents* new_contents =
new TabContents(profile,
site,
route_id,
opener->GetAsTabContents());
new_contents->set_opener_dom_ui_type(domui_type);
TabContentsView* new_view = new_contents->view();
// TODO(brettw) it seems bogus that we have to call this function on the
// newly created object and give it one of its own member variables.
new_view->CreateViewForWidget(new_contents->render_view_host());
// Save the created window associated with the route so we can show it later.
pending_contents_[route_id] = new_contents->render_view_host();
return new_contents;
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
RenderWidgetHost* widget_host =
new RenderWidgetHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(widget_host);
// Popups should not get activated.
widget_view->set_popup_type(popup_type);
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
PendingContents::iterator iter = pending_contents_.find(route_id);
if (iter == pending_contents_.end()) {
DCHECK(false);
return NULL;
}
RenderViewHost* new_rvh = iter->second;
pending_contents_.erase(route_id);
// The renderer crashed or it is a TabContents and has no view.
if (!new_rvh->process()->HasConnection() ||
(new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
return NULL;
// TODO(brettw) this seems bogus to reach into here and initialize the host.
new_rvh->Init();
return new_rvh->delegate()->GetAsTabContents();
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
int route_id) {
PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
if (iter == pending_widget_views_.end()) {
DCHECK(false);
return NULL;
}
RenderWidgetHostView* widget_host_view = iter->second;
pending_widget_views_.erase(route_id);
RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
if (!widget_host->process()->HasConnection()) {
// The view has gone away or the renderer crashed. Nothing to do.
return NULL;
}
return widget_host_view;
}
void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
RenderWidgetHost* host) {
for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
i != pending_widget_views_.end(); ++i) {
if (host->view() == i->second) {
pending_widget_views_.erase(i);
return;
}
}
}
// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
Profile* profile, bool is_dom_ui) {
PrefService* prefs = profile->GetPrefs();
WebPreferences web_prefs;
web_prefs.fixed_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));
web_prefs.serif_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));
web_prefs.sans_serif_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))
web_prefs.standard_font_family = web_prefs.serif_font_family;
else
web_prefs.standard_font_family = web_prefs.sans_serif_font_family;
web_prefs.cursive_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));
web_prefs.fantasy_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));
web_prefs.default_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFontSize);
web_prefs.default_fixed_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
web_prefs.minimum_font_size =
prefs->GetInteger(prefs::kWebKitMinimumFontSize);
web_prefs.minimum_logical_font_size =
prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
web_prefs.javascript_can_open_windows_automatically =
prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
web_prefs.dom_paste_enabled =
prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
web_prefs.shrinks_standalone_images_to_fit =
prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
const DictionaryValue* inspector_settings =
prefs->GetDictionary(prefs::kWebKitInspectorSettings);
if (inspector_settings) {
for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
iter != inspector_settings->end_keys(); ++iter) {
std::string value;
if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
web_prefs.inspector_settings.push_back(
std::make_pair(WideToUTF8(*iter), value));
}
}
web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
{ // Command line switches are used for preferences with no user interface.
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
web_prefs.developer_extras_enabled =
!command_line.HasSwitch(switches::kDisableDevTools);
web_prefs.javascript_enabled =
!command_line.HasSwitch(switches::kDisableJavaScript) &&
prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
web_prefs.web_security_enabled =
!command_line.HasSwitch(switches::kDisableWebSecurity) &&
prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
web_prefs.plugins_enabled =
!command_line.HasSwitch(switches::kDisablePlugins) &&
prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
web_prefs.java_enabled =
!command_line.HasSwitch(switches::kDisableJava) &&
prefs->GetBoolean(prefs::kWebKitJavaEnabled);
web_prefs.loads_images_automatically =
prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
web_prefs.uses_page_cache =
command_line.HasSwitch(switches::kEnableFastback);
web_prefs.remote_fonts_enabled =
!command_line.HasSwitch(switches::kDisableRemoteFonts);
web_prefs.xss_auditor_enabled =
command_line.HasSwitch(switches::kEnableXSSAuditor);
web_prefs.application_cache_enabled =
!command_line.HasSwitch(switches::kDisableApplicationCache);
web_prefs.local_storage_enabled =
!command_line.HasSwitch(switches::kDisableLocalStorage);
web_prefs.databases_enabled =
!command_line.HasSwitch(switches::kDisableDatabases);
web_prefs.experimental_webgl_enabled =
command_line.HasSwitch(switches::kEnableExperimentalWebGL);
web_prefs.site_specific_quirks_enabled =
!command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
web_prefs.allow_file_access_from_file_urls =
command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
web_prefs.show_composited_layer_borders =
command_line.HasSwitch(switches::kShowCompositedLayerBorders);
web_prefs.accelerated_compositing_enabled =
command_line.HasSwitch(switches::kEnableAcceleratedCompositing);
web_prefs.accelerated_2d_canvas_enabled =
command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
web_prefs.memory_info_enabled =
command_line.HasSwitch(switches::kEnableMemoryInfo);
// The user stylesheet watcher may not exist in a testing profile.
if (profile->GetUserStyleSheetWatcher()) {
web_prefs.user_style_sheet_enabled = true;
web_prefs.user_style_sheet_location =
profile->GetUserStyleSheetWatcher()->user_style_sheet();
} else {
web_prefs.user_style_sheet_enabled = false;
}
}
web_prefs.uses_universal_detector =
prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
web_prefs.text_areas_are_resizable =
prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
// Make sure we will set the default_encoding with canonical encoding name.
web_prefs.default_encoding =
CharacterEncoding::GetCanonicalEncodingNameByAliasName(
web_prefs.default_encoding);
if (web_prefs.default_encoding.empty()) {
prefs->ClearPref(prefs::kDefaultCharset);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
}
DCHECK(!web_prefs.default_encoding.empty());
if (is_dom_ui) {
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
}
return web_prefs;
}
<commit_msg>Remove unneeded browser.h include from RVHDelegateHelper.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/render_view_host_delegate_helper.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
int route_id,
Profile* profile,
SiteInstance* site,
GURL opener_url,
const string16& frame_name) {
ExtensionsService* extensions_service = profile->GetExtensionsService();
if (!opener_url.is_valid() ||
frame_name.empty() ||
!extensions_service ||
!extensions_service->is_ready())
return NULL;
Extension* extension = extensions_service->GetExtensionByURL(opener_url);
if (!extension)
extension = extensions_service->GetExtensionByWebExtent(opener_url);
if (!extension ||
!extension->HasApiPermission(Extension::kBackgroundPermission))
return NULL;
// Only allow a single background contents per app.
if (!profile->GetBackgroundContentsService() ||
profile->GetBackgroundContentsService()->GetAppBackgroundContents(
ASCIIToUTF16(extension->id())))
return NULL;
// Ensure that we're trying to open this from the extension's process.
ExtensionProcessManager* process_manager =
profile->GetExtensionProcessManager();
if (!site->GetProcess() || !process_manager ||
site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
return NULL;
// Passed all the checks, so this should be created as a BackgroundContents.
BackgroundContents* contents = new BackgroundContents(site, route_id);
string16 appid = ASCIIToUTF16(extension->id());
BackgroundContentsOpenedDetails details = { contents, frame_name, appid };
NotificationService::current()->Notify(
NotificationType::BACKGROUND_CONTENTS_OPENED,
Source<Profile>(profile),
Details<BackgroundContentsOpenedDetails>(&details));
return contents;
}
TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
int route_id,
Profile* profile,
SiteInstance* site,
DOMUITypeID domui_type,
RenderViewHostDelegate* opener,
WindowContainerType window_container_type,
const string16& frame_name) {
if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
BackgroundContents* contents = MaybeCreateBackgroundContents(
route_id,
profile,
site,
opener->GetURL(),
frame_name);
if (contents) {
pending_contents_[route_id] = contents->render_view_host();
return NULL;
}
}
// Create the new web contents. This will automatically create the new
// TabContentsView. In the future, we may want to create the view separately.
TabContents* new_contents =
new TabContents(profile,
site,
route_id,
opener->GetAsTabContents());
new_contents->set_opener_dom_ui_type(domui_type);
TabContentsView* new_view = new_contents->view();
// TODO(brettw) it seems bogus that we have to call this function on the
// newly created object and give it one of its own member variables.
new_view->CreateViewForWidget(new_contents->render_view_host());
// Save the created window associated with the route so we can show it later.
pending_contents_[route_id] = new_contents->render_view_host();
return new_contents;
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
RenderWidgetHost* widget_host =
new RenderWidgetHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(widget_host);
// Popups should not get activated.
widget_view->set_popup_type(popup_type);
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
PendingContents::iterator iter = pending_contents_.find(route_id);
if (iter == pending_contents_.end()) {
DCHECK(false);
return NULL;
}
RenderViewHost* new_rvh = iter->second;
pending_contents_.erase(route_id);
// The renderer crashed or it is a TabContents and has no view.
if (!new_rvh->process()->HasConnection() ||
(new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
return NULL;
// TODO(brettw) this seems bogus to reach into here and initialize the host.
new_rvh->Init();
return new_rvh->delegate()->GetAsTabContents();
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
int route_id) {
PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
if (iter == pending_widget_views_.end()) {
DCHECK(false);
return NULL;
}
RenderWidgetHostView* widget_host_view = iter->second;
pending_widget_views_.erase(route_id);
RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
if (!widget_host->process()->HasConnection()) {
// The view has gone away or the renderer crashed. Nothing to do.
return NULL;
}
return widget_host_view;
}
void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
RenderWidgetHost* host) {
for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
i != pending_widget_views_.end(); ++i) {
if (host->view() == i->second) {
pending_widget_views_.erase(i);
return;
}
}
}
// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
Profile* profile, bool is_dom_ui) {
PrefService* prefs = profile->GetPrefs();
WebPreferences web_prefs;
web_prefs.fixed_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily));
web_prefs.serif_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily));
web_prefs.sans_serif_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))
web_prefs.standard_font_family = web_prefs.serif_font_family;
else
web_prefs.standard_font_family = web_prefs.sans_serif_font_family;
web_prefs.cursive_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily));
web_prefs.fantasy_font_family =
UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily));
web_prefs.default_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFontSize);
web_prefs.default_fixed_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
web_prefs.minimum_font_size =
prefs->GetInteger(prefs::kWebKitMinimumFontSize);
web_prefs.minimum_logical_font_size =
prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
web_prefs.javascript_can_open_windows_automatically =
prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
web_prefs.dom_paste_enabled =
prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
web_prefs.shrinks_standalone_images_to_fit =
prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
const DictionaryValue* inspector_settings =
prefs->GetDictionary(prefs::kWebKitInspectorSettings);
if (inspector_settings) {
for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
iter != inspector_settings->end_keys(); ++iter) {
std::string value;
if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
web_prefs.inspector_settings.push_back(
std::make_pair(WideToUTF8(*iter), value));
}
}
web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
{ // Command line switches are used for preferences with no user interface.
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
web_prefs.developer_extras_enabled =
!command_line.HasSwitch(switches::kDisableDevTools);
web_prefs.javascript_enabled =
!command_line.HasSwitch(switches::kDisableJavaScript) &&
prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
web_prefs.web_security_enabled =
!command_line.HasSwitch(switches::kDisableWebSecurity) &&
prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
web_prefs.plugins_enabled =
!command_line.HasSwitch(switches::kDisablePlugins) &&
prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
web_prefs.java_enabled =
!command_line.HasSwitch(switches::kDisableJava) &&
prefs->GetBoolean(prefs::kWebKitJavaEnabled);
web_prefs.loads_images_automatically =
prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
web_prefs.uses_page_cache =
command_line.HasSwitch(switches::kEnableFastback);
web_prefs.remote_fonts_enabled =
!command_line.HasSwitch(switches::kDisableRemoteFonts);
web_prefs.xss_auditor_enabled =
command_line.HasSwitch(switches::kEnableXSSAuditor);
web_prefs.application_cache_enabled =
!command_line.HasSwitch(switches::kDisableApplicationCache);
web_prefs.local_storage_enabled =
!command_line.HasSwitch(switches::kDisableLocalStorage);
web_prefs.databases_enabled =
!command_line.HasSwitch(switches::kDisableDatabases);
web_prefs.experimental_webgl_enabled =
command_line.HasSwitch(switches::kEnableExperimentalWebGL);
web_prefs.site_specific_quirks_enabled =
!command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
web_prefs.allow_file_access_from_file_urls =
command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
web_prefs.show_composited_layer_borders =
command_line.HasSwitch(switches::kShowCompositedLayerBorders);
web_prefs.accelerated_compositing_enabled =
command_line.HasSwitch(switches::kEnableAcceleratedCompositing);
web_prefs.accelerated_2d_canvas_enabled =
command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
web_prefs.memory_info_enabled =
command_line.HasSwitch(switches::kEnableMemoryInfo);
// The user stylesheet watcher may not exist in a testing profile.
if (profile->GetUserStyleSheetWatcher()) {
web_prefs.user_style_sheet_enabled = true;
web_prefs.user_style_sheet_location =
profile->GetUserStyleSheetWatcher()->user_style_sheet();
} else {
web_prefs.user_style_sheet_enabled = false;
}
}
web_prefs.uses_universal_detector =
prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
web_prefs.text_areas_are_resizable =
prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
// Make sure we will set the default_encoding with canonical encoding name.
web_prefs.default_encoding =
CharacterEncoding::GetCanonicalEncodingNameByAliasName(
web_prefs.default_encoding);
if (web_prefs.default_encoding.empty()) {
prefs->ClearPref(prefs::kDefaultCharset);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
}
DCHECK(!web_prefs.default_encoding.empty());
if (is_dom_ui) {
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
}
return web_prefs;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <limits>
#include <fstream>
#include <sstream>
#include <vector>
#include <stb/stb_image.h>
#include <stb/stb_image_resize.h>
#include <stb/stb_image_write.h>
#include "ImageUtils.h"
#include "PaletteWindow.h"
#include "SummaryView.h"
SummaryView::SummaryView(int size, int tileCount, int offsetX, int offsetY, int visibleSideCount, int reductionFactor)
: isAlive(false), size(size), tileId(tileCount), selectedTile(2955),
topographicSummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, "../ContourTiler/rasters/summary/", "summary.png"),
overlaySummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, "../ContourTiler/rasters/summary/", "overlay.png"),
windowSelf(nullptr), offsetX(offsetX), offsetY(offsetY), visibleSideCount(visibleSideCount)
{
}
void SummaryView::RemapToTile(double* x, double* y)
{
int tileX, tileY;
tileId.GetPositionFromId(selectedTile, &tileX, &tileY);
(*x) *= ((double)1000 * tileId.GetTileCount());
(*y) *= ((double)1000 * tileId.GetTileCount());
(*x) -= (tileX * 1000);
(*y) -= (tileY * 1000);
}
void SummaryView::MoveSelectedTile(Direction direction)
{
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
switch (direction)
{
case UP: ++y; break;
case DOWN: --y; break;
case LEFT: --x; break;
case RIGHT: ++x; break;
}
if (topographicSummarizer.IsTileValid(x, y))
{
selectedTile = tileId.GetTileId(x, y);
UpdateSelectedTileRectangle();
// TODO this doesn't apply on startup, and should be fixed to not pass around the window pointer.
if (windowSelf != nullptr)
{
std::stringstream titleString;
titleString << "Summary (" << x << ", " << y << ")" << std::endl;
windowSelf->setTitle(titleString.str());
}
}
}
void SummaryView::LoadSelectedTile(unsigned char** data, int offsetX, int offsetY)
{
if (*data != nullptr)
{
// We could also do topographic, but we (for now) don't support elevation changes with this program.
ImageUtils::FreeImage(*data);
*data = nullptr;
}
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
x += offsetX;
y += offsetY;
// Ensure we read a valid image.
x = std::max(0, x);
y = std::max(0, y);
x = std::min(x, tileId.GetTileCount() - 1);
y = std::min(y, tileId.GetTileCount() - 1);
std::stringstream imageTile;
imageTile << "../ContourTiler/rasters/" << y << "/" << x << ".png";
int width, height;
if (!ImageUtils::LoadImage(imageTile.str().c_str(), &width, &height, data))
{
std::cout << "Failed to load " << imageTile.str() << std::endl;
}
}
void SummaryView::LoadSelectedTile(bool loadEdges, unsigned char** centerData, unsigned char** leftData, unsigned char** rightData, unsigned char** topData, unsigned char** bottomData)
{
LoadSelectedTile(centerData, 0, 0);
// Don't reload the edges if we aren't saving when moving to speed up drawing
if (loadEdges)
{
LoadSelectedTile(leftData, -1, 0);
LoadSelectedTile(rightData, 1, 0);
LoadSelectedTile(topData, 0, 1);
LoadSelectedTile(bottomData, 0, -1);
}
}
// We know that only the topographic data is what really matters. We do need to indicate a reload to both topographic and overlay layers though.
void SummaryView::UpdateSelectedTile(unsigned char* newData)
{
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
topographicSummarizer.UpdateSummaryForTile(newData, x, y, true);
overlaySummarizer.UpdateSummaryForTile(newData, x, y, false);
}
void SummaryView::UpdateSelectedTileRectangle()
{
int motionScale = size / visibleSideCount;
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
selectedTileRectangle.setPosition(sf::Vector2f((float)((x - offsetX) * motionScale), (float)(size - (y - offsetY + 1) * motionScale)));
}
void SummaryView::HandleEvents(sf::RenderWindow& window)
{
// Handle all events.
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
// Ignore -- we only close if the main map editor closes.
}
}
}
void SummaryView::Render(sf::RenderWindow& window)
{
window.draw(topographicSummarizer.GetSummarizedSprite());
window.draw(overlaySummarizer.GetSummarizedSprite());
window.draw(selectedTileRectangle);
}
void SummaryView::ThreadStart()
{
topographicSummarizer.Initialize(
[](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float
{
return ((float)((unsigned short)r + (((unsigned short)g) << 8))) / (float)std::numeric_limits<unsigned short>::max();
},
[](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void
{
unsigned short averageValue = (unsigned short)(value * (float)std::numeric_limits<unsigned short>::max());
unsigned char actualValue = (unsigned char)(averageValue / 256);
*r = actualValue;
*g = actualValue;
*b = actualValue;
*a = 255;
});
overlaySummarizer.Initialize(
[](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float
{
return (float)b;
},
[](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void
{
// This will probably look odd but it's the best I can do.
unsigned char averageValue = (unsigned char)value;
PaletteWindow::TerrainType type = PaletteWindow::GetNearestTerrainType(averageValue);
sf::Color color = PaletteWindow::GetTerrainColor(type);
*r = color.r;
*g = color.g;
*b = color.b;
*a = 110;
});
selectedTileRectangle = sf::RectangleShape(sf::Vector2f((float)(size / visibleSideCount), (float)(size / visibleSideCount)));
selectedTileRectangle.setFillColor(sf::Color(0, 0, 0, 0));
selectedTileRectangle.setOutlineThickness(1.0f);
selectedTileRectangle.setOutlineColor(sf::Color::Green);
UpdateSelectedTileRectangle();
// 24 depth bits, 8 stencil bits, 8x AA, major version 4.
sf::ContextSettings contextSettings = sf::ContextSettings(24, 8, 8, 4, 0);
sf::Uint32 style = sf::Style::Titlebar;
sf::RenderWindow window(sf::VideoMode(size, size), "Summary", style, contextSettings);
window.setFramerateLimit(60);
// TODO
windowSelf = &window;
// Start the main loop
isAlive = true;
while (isAlive)
{
HandleEvents(window);
Render(window);
// Display what we rendered.
window.display();
}
}
void SummaryView::Start()
{
executionThread = new std::thread(&SummaryView::ThreadStart, this);
while (!isAlive)
{
sf::sleep(sf::milliseconds(50));
}
}
void SummaryView::Stop()
{
isAlive = false;
executionThread->join();
delete executionThread;
}<commit_msg>Fudge factor necessary for the summary to be correct. Going to take a whil e to draw in all the tiles.<commit_after>#include <iostream>
#include <limits>
#include <fstream>
#include <sstream>
#include <vector>
#include <stb/stb_image.h>
#include <stb/stb_image_resize.h>
#include <stb/stb_image_write.h>
#include "ImageUtils.h"
#include "PaletteWindow.h"
#include "SummaryView.h"
SummaryView::SummaryView(int size, int tileCount, int offsetX, int offsetY, int visibleSideCount, int reductionFactor)
: isAlive(false), size(size), tileId(tileCount), selectedTile(2955),
topographicSummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, "../ContourTiler/rasters/summary/", "summary.png"),
overlaySummarizer(size, tileCount, offsetX, offsetY, visibleSideCount, reductionFactor, "../ContourTiler/rasters/summary/", "overlay.png"),
windowSelf(nullptr), offsetX(offsetX), offsetY(offsetY), visibleSideCount(visibleSideCount)
{
}
void SummaryView::RemapToTile(double* x, double* y)
{
int tileX, tileY;
tileId.GetPositionFromId(selectedTile, &tileX, &tileY);
(*x) *= ((double)1000 * tileId.GetTileCount());
(*y) *= ((double)1000 * tileId.GetTileCount());
(*x) -= (tileX * 1000);
(*y) -= (tileY * 1000);
}
void SummaryView::MoveSelectedTile(Direction direction)
{
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
switch (direction)
{
case UP: ++y; break;
case DOWN: --y; break;
case LEFT: --x; break;
case RIGHT: ++x; break;
}
if (topographicSummarizer.IsTileValid(x, y))
{
selectedTile = tileId.GetTileId(x, y);
UpdateSelectedTileRectangle();
// TODO this doesn't apply on startup, and should be fixed to not pass around the window pointer.
if (windowSelf != nullptr)
{
std::stringstream titleString;
titleString << "Summary (" << x << ", " << y << ")" << std::endl;
windowSelf->setTitle(titleString.str());
}
}
}
void SummaryView::LoadSelectedTile(unsigned char** data, int offsetX, int offsetY)
{
if (*data != nullptr)
{
// We could also do topographic, but we (for now) don't support elevation changes with this program.
ImageUtils::FreeImage(*data);
*data = nullptr;
}
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
x += offsetX;
y += offsetY;
// Ensure we read a valid image.
x = std::max(0, x);
y = std::max(0, y);
x = std::min(x, tileId.GetTileCount() - 1);
y = std::min(y, tileId.GetTileCount() - 1);
std::stringstream imageTile;
imageTile << "../ContourTiler/rasters/" << y << "/" << x << ".png";
int width, height;
if (!ImageUtils::LoadImage(imageTile.str().c_str(), &width, &height, data))
{
std::cout << "Failed to load " << imageTile.str() << std::endl;
}
}
void SummaryView::LoadSelectedTile(bool loadEdges, unsigned char** centerData, unsigned char** leftData, unsigned char** rightData, unsigned char** topData, unsigned char** bottomData)
{
LoadSelectedTile(centerData, 0, 0);
// Don't reload the edges if we aren't saving when moving to speed up drawing
if (loadEdges)
{
LoadSelectedTile(leftData, -1, 0);
LoadSelectedTile(rightData, 1, 0);
LoadSelectedTile(topData, 0, 1);
LoadSelectedTile(bottomData, 0, -1);
}
}
// We know that only the topographic data is what really matters. We do need to indicate a reload to both topographic and overlay layers though.
void SummaryView::UpdateSelectedTile(unsigned char* newData)
{
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
topographicSummarizer.UpdateSummaryForTile(newData, x, y, true);
overlaySummarizer.UpdateSummaryForTile(newData, x, y, false);
}
void SummaryView::UpdateSelectedTileRectangle()
{
int motionScale = size / visibleSideCount;
int x, y;
tileId.GetPositionFromId(selectedTile, &x, &y);
selectedTileRectangle.setPosition(sf::Vector2f((float)((x - offsetX) * motionScale), (float)(size - (y - offsetY + 1) * motionScale)));
}
void SummaryView::HandleEvents(sf::RenderWindow& window)
{
// Handle all events.
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
// Ignore -- we only close if the main map editor closes.
}
}
}
void SummaryView::Render(sf::RenderWindow& window)
{
window.draw(topographicSummarizer.GetSummarizedSprite());
window.draw(overlaySummarizer.GetSummarizedSprite());
window.draw(selectedTileRectangle);
}
void SummaryView::ThreadStart()
{
topographicSummarizer.Initialize(
[](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float
{
return ((float)((unsigned short)r + (((unsigned short)g) << 8))) / (float)std::numeric_limits<unsigned short>::max();
},
[](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void
{
unsigned short averageValue = (unsigned short)(value * (float)std::numeric_limits<unsigned short>::max());
unsigned char actualValue = (unsigned char)(averageValue / 256);
*r = actualValue;
*g = actualValue;
*b = actualValue;
*a = 255;
});
overlaySummarizer.Initialize(
[](unsigned char r, unsigned char g, unsigned char b, unsigned char a) -> float
{
return (float)b;
},
[](float value, unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a) -> void
{
// This will probably look odd but it's the best I can do.
unsigned char averageValue = (unsigned char)value;
PaletteWindow::TerrainType type = PaletteWindow::GetNearestTerrainType(averageValue > 250 ? averageValue : averageValue + 10);
sf::Color color = PaletteWindow::GetTerrainColor(type);
*r = color.r;
*g = color.g;
*b = color.b;
*a = 110;
});
selectedTileRectangle = sf::RectangleShape(sf::Vector2f((float)(size / visibleSideCount), (float)(size / visibleSideCount)));
selectedTileRectangle.setFillColor(sf::Color(0, 0, 0, 0));
selectedTileRectangle.setOutlineThickness(1.0f);
selectedTileRectangle.setOutlineColor(sf::Color::Green);
UpdateSelectedTileRectangle();
// 24 depth bits, 8 stencil bits, 8x AA, major version 4.
sf::ContextSettings contextSettings = sf::ContextSettings(24, 8, 8, 4, 0);
sf::Uint32 style = sf::Style::Titlebar;
sf::RenderWindow window(sf::VideoMode(size, size), "Summary", style, contextSettings);
window.setFramerateLimit(60);
// TODO
windowSelf = &window;
// Start the main loop
isAlive = true;
while (isAlive)
{
HandleEvents(window);
Render(window);
// Display what we rendered.
window.display();
}
}
void SummaryView::Start()
{
executionThread = new std::thread(&SummaryView::ThreadStart, this);
while (!isAlive)
{
sf::sleep(sf::milliseconds(50));
}
}
void SummaryView::Stop()
{
isAlive = false;
executionThread->join();
delete executionThread;
}<|endoftext|> |
<commit_before>/*
This file is part of the E_Rendering library.
Copyright (C) 2018 Sascha Brandt <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_VertexAccessor.h"
#include "E_Mesh.h"
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Util/StringIdentifier.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Vec4.h>
#include <E_Util/Graphics/E_Color.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
namespace E_Rendering{
using namespace Rendering;
// ----------------------------------------
// E_VertexAccessor
//! (static)
EScript::Type * E_VertexAccessor::getTypeObject() {
// E_VertexAccessor ---|> Object
static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
return typeObject.get();
}
//! (static) init members
void E_VertexAccessor::init(EScript::Namespace & lib) {
EScript::Type * typeObject = E_VertexAccessor::getTypeObject();
declareConstant(&lib,getClassName(),typeObject);
//! [ESMF] new Rendering.VertexAccessor( Mesh )
ES_CTOR(typeObject, 1, 1, new VertexAccessor(parameter[0].to<Mesh*>(rt)->openVertexData()))
//! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute])
ES_MFUN(typeObject,const VertexAccessor,"getPosition",1,2,thisObj->getPosition(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::POSITION.toString())))
//! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute])
ES_MFUN(typeObject,VertexAccessor,"setPosition",2,3,(thisObj->setPosition(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())),thisEObj))
//! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute])
ES_MFUN(typeObject,const VertexAccessor,"getNormal",1,2,thisObj->getNormal(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::NORMAL.toString())))
//! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute])
ES_MFUN(typeObject,VertexAccessor,"setNormal",2,3,(thisObj->setPosition(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())),thisEObj))
//! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute])
ES_MFUN(typeObject,const VertexAccessor,"getColor4f",1,2,thisObj->getColor4f(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::COLOR.toString())))
//! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color, [String attribute])
ES_MFUN(typeObject,VertexAccessor,"setColor",2,3,(thisObj->setColor(parameter[0].to<uint32_t>(rt), parameter[1].to<Util::Color4f>(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())),thisEObj))
//! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute])
ES_MFUN(typeObject,const VertexAccessor,"getTexCoord",1,2,thisObj->getTexCoord(parameter[0].to<uint32_t>(rt), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())))
//! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute])
ES_MFUN(typeObject,VertexAccessor,"setTexCoord",2,3,(thisObj->setTexCoord(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec2>(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())),thisEObj))
//! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getVec4",2,2,thisObj->getVec4(parameter[0].to<uint32_t>(rt), parameter[1].toString()))
//! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute)
ES_MFUN(typeObject,VertexAccessor,"setVec4",3,3,(thisObj->setVec4(parameter[0].to<uint32_t>(rt), parameter[1].to<Geometry::Vec4>(rt), parameter[2].toString()),thisEObj))
//! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getFloat",2,2,thisObj->getFloat(parameter[0].to<uint32_t>(rt), parameter[1].toString()))
//! [ESMF] Array VertexAccessor.getFloats(Number index, String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getFloats",2,2,EScript::Array::create(thisObj->getFloats(parameter[0].to<uint32_t>(rt), parameter[1].toString())))
//! [ESMF] thisEObj VertexAccessor.setFloat(Number index, Number value, String attribute)
ES_MFUN(typeObject,VertexAccessor,"setFloat",3,3,(thisObj->setFloat(parameter[0].to<uint32_t>(rt), parameter[1].toFloat(), parameter[2].toString()),thisEObj))
//! [ESMF] thisEObj VertexAccessor.setFloats(Number index, Array values, String attribute)
ES_MFUNCTION(typeObject,VertexAccessor,"setFloats",3,3,{
EScript::Array * a=parameter[1].to<EScript::Array*>(rt);
std::vector<float> values;
for(auto v : *a)
values.push_back(v.toFloat());
thisObj->setFloats(parameter[0].to<uint32_t>(rt), values, parameter[2].toString());
return thisEObj;
})
//! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getUInt",2,2,thisObj->getUInt(parameter[0].to<uint32_t>(rt), parameter[1].toString()))
//! [ESMF] Array VertexAccessor.getUInts(Number index, String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getUInts",2,2,EScript::Array::create(thisObj->getUInts(parameter[0].to<uint32_t>(rt), parameter[1].toString())))
//! [ESMF] thisEObj VertexAccessor.setUInt(Number index, Number value, String attribute)
ES_MFUN(typeObject,VertexAccessor,"setUInt",3,3,(thisObj->setUInt(parameter[0].to<uint32_t>(rt), parameter[1].toUInt(), parameter[2].toString()),thisEObj))
//! [ESMF] thisEObj VertexAccessor.setUInts(Number index, Array values, String attribute)
ES_MFUNCTION(typeObject,VertexAccessor,"setUInts",3,3,{
EScript::Array * a=parameter[1].to<EScript::Array*>(rt);
std::vector<uint32_t> values;
for(auto v : *a)
values.push_back(v.toUInt());
thisObj->setUInts(parameter[0].to<uint32_t>(rt), values, parameter[2].toString());
return thisEObj;
})
}
}
<commit_msg>Changed bindings for VertexAccessor<commit_after>/*
This file is part of the E_Rendering library.
Copyright (C) 2018 Sascha Brandt <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_VertexAccessor.h"
#include "E_Mesh.h"
#include <Rendering/Mesh/VertexAttributeIds.h>
#include <Util/StringIdentifier.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Geometry/E_Vec3.h>
#include <E_Geometry/E_Vec4.h>
#include <E_Util/Graphics/E_Color.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
namespace E_Rendering{
using namespace Rendering;
// ----------------------------------------
// E_VertexAccessor
//! (static)
EScript::Type * E_VertexAccessor::getTypeObject() {
// E_VertexAccessor ---|> Object
static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
return typeObject.get();
}
//! (static) init members
void E_VertexAccessor::init(EScript::Namespace & lib) {
EScript::Type * typeObject = E_VertexAccessor::getTypeObject();
declareConstant(&lib,getClassName(),typeObject);
//! [ESMF] new Rendering.VertexAccessor( Mesh )
ES_CTOR(typeObject, 1, 1, VertexAccessor::create(parameter[0].to<Mesh*>(rt)))
//! [ESMF] Number VertexAccessor.getAttributeLocation(String attribute)
ES_MFUN(typeObject,const VertexAccessor,"getAttributeLocation",1,1,thisObj->getAttributeLocation(parameter[0].toString()))
//! [ESMF] Geometry.Vec3 VertexAccessor.getPosition(Number index, [String attribute | Number location])
ES_MFUN(typeObject,const VertexAccessor,"getPosition",1,2,
parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->getPosition(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::POSITION.toString())) :
thisObj->getPosition(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] thisEObj VertexAccessor.setPosition(Number index, Geometry.Vec3, [String attribute | Number location])
ES_MFUN(typeObject,VertexAccessor,"setPosition",2,3,(
parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
thisObj->setPosition(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::POSITION.toString())) :
thisObj->setPosition(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].to<uint16_t>(rt))
,thisEObj))
//! [ESMF] Geometry.Vec3 VertexAccessor.getNormal(Number index, [String attribute | Number location])
ES_MFUN(typeObject,const VertexAccessor,"getNormal",1,2,
parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->getNormal(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::NORMAL.toString())) :
thisObj->getNormal(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] thisEObj VertexAccessor.setNormal(Number index, Geometry.Vec3, [String attribute | Number location])
ES_MFUN(typeObject,VertexAccessor,"setNormal",2,3,(
parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
thisObj->setNormal(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].toString(VertexAttributeIds::NORMAL.toString())) :
thisObj->setNormal(parameter[0].toUInt(), parameter[1].to<Geometry::Vec3>(rt), parameter[2].to<uint16_t>(rt))
,thisEObj))
//! [ESMF] Util.Color4f VertexAccessor.getColor4f(Number index, [String attribute | Number location])
ES_MFUN(typeObject,const VertexAccessor,"getColor4f",1,2,
parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->getColor4f(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::COLOR.toString())) :
thisObj->getColor4f(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] thisEObj VertexAccessor.setColor(Number index, Util.Color4f, [String attribute | Number location])
ES_MFUN(typeObject,VertexAccessor,"setColor",2,3,(
parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
thisObj->setColor(parameter[0].toUInt(), parameter[1].to<Util::Color4f>(rt), parameter[2].toString(VertexAttributeIds::COLOR.toString())) :
thisObj->setColor(parameter[0].toUInt(), parameter[1].to<Util::Color4f>(rt), parameter[2].to<uint16_t>(rt))
,thisEObj))
//! [ESMF] Geometry.Vec2 VertexAccessor.getTexCoord(Number index, [String attribute | Number location])
ES_MFUN(typeObject,const VertexAccessor,"getTexCoord",1,2,
parameter[1].isNull() || parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->getTexCoord(parameter[0].toUInt(), parameter[1].toString(VertexAttributeIds::TEXCOORD0.toString())) :
thisObj->getTexCoord(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] thisEObj VertexAccessor.setTexCoord(Number index, Geometry.Vec2, [String attribute | Number location])
ES_MFUN(typeObject,VertexAccessor,"setTexCoord",2,3,(
parameter[2].isNull() || parameter[2]->isA(EScript::String::getTypeObject()) ?
thisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to<Geometry::Vec2>(rt), parameter[2].toString(VertexAttributeIds::TEXCOORD0.toString())) :
thisObj->setTexCoord(parameter[0].toUInt(), parameter[1].to<Geometry::Vec2>(rt), parameter[2].to<uint16_t>(rt))
,thisEObj))
//! [ESMF] Geometry.Vec4 VertexAccessor.getVec4(Number index, String attribute | Number location)
ES_MFUN(typeObject,const VertexAccessor,"getVec4",2,2,
parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->getVec4(parameter[0].toUInt(), parameter[1].toString()) :
thisObj->getVec4(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] thisEObj VertexAccessor.setVec4(Number index, Geometry.Vec4, String attribute | Number location)
ES_MFUN(typeObject,VertexAccessor,"setVec4",3,3,(
parameter[2]->isA(EScript::String::getTypeObject()) ?
thisObj->setVec4(parameter[0].toUInt(), parameter[1].to<Geometry::Vec4>(rt), parameter[2].toString()) :
thisObj->setVec4(parameter[0].toUInt(), parameter[1].to<Geometry::Vec4>(rt), parameter[2].to<uint16_t>(rt))
,thisEObj))
//! [ESMF] Number VertexAccessor.getFloat(Number index, String attribute | Number location)
ES_MFUN(typeObject,const VertexAccessor,"getFloat",2,2,
parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->readValue<float>(parameter[0].toUInt(), parameter[1].toString()) :
thisObj->readValue<float>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] Number VertexAccessor.getFloats(Number index, String attribute | Number location, Number count)
ES_MFUN(typeObject,const VertexAccessor,"getFloats",3,3,
EScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->readValues<float>(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
thisObj->readValues<float>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt()))
)
//! [ESMF] thisEObj VertexAccessor.setFloat(Number index, String attribute | Number location, Number value)
ES_MFUN(typeObject,VertexAccessor,"setFloat",3,3,(
parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toFloat()) :
thisObj->writeValue(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toFloat())
,thisEObj))
//! [ESMF] thisEObj VertexAccessor.setFloats(Number index, String attribute, Array values)
ES_MFUNCTION(typeObject,VertexAccessor,"setFloats",3,3,{
EScript::Array * a=parameter[2].to<EScript::Array*>(rt);
std::vector<float> values;
for(auto v : *a)
values.push_back(v.toFloat());
if(parameter[1]->isA(EScript::String::getTypeObject()))
thisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);
else
thisObj->writeValues(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), values);
return thisEObj;
})
//! [ESMF] Number VertexAccessor.getUInt(Number index, String attribute | Number location)
ES_MFUN(typeObject,const VertexAccessor,"getUInt",2,2,
parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->readValue<uint32_t>(parameter[0].toUInt(), parameter[1].toString()) :
thisObj->readValue<uint32_t>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt))
)
//! [ESMF] Number VertexAccessor.getUInts(Number index, String attribute | Number location, Number count)
ES_MFUN(typeObject,const VertexAccessor,"getUInts",3,3,
EScript::Array::create(parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->readValues<uint32_t>(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
thisObj->readValues<uint32_t>(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt()))
)
//! [ESMF] thisEObj VertexAccessor.setUInt(Number index, String attribute | Number location, Number value)
ES_MFUN(typeObject,VertexAccessor,"setUInt",3,3,(
parameter[1]->isA(EScript::String::getTypeObject()) ?
thisObj->writeValue(parameter[0].toUInt(), parameter[1].toString(), parameter[2].toUInt()) :
thisObj->writeValue(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), parameter[2].toUInt())
,thisEObj))
//! [ESMF] thisEObj VertexAccessor.setUInts(Number index, String attribute, Array values)
ES_MFUNCTION(typeObject,VertexAccessor,"setUInts",3,3,{
EScript::Array * a=parameter[2].to<EScript::Array*>(rt);
std::vector<uint32_t> values;
for(auto v : *a)
values.push_back(v.toUInt());
if(parameter[1]->isA(EScript::String::getTypeObject()))
thisObj->writeValues(parameter[0].toUInt(), parameter[1].toString(), values);
else
thisObj->writeValues(parameter[0].toUInt(), parameter[1].to<uint16_t>(rt), values);
return thisEObj;
})
}
}
<|endoftext|> |
<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "Core.h"
#include "OrbitModule.h"
#include "Serialization.h"
#include "Pdb.h"
#include <string>
#ifndef WIN32
#include "LinuxUtils.h"
#include "Capture.h"
#include "ScopeTimer.h"
#include "OrbitUnreal.h"
#include "Params.h"
#include "OrbitProcess.h"
#include "Path.h"
#endif
//-----------------------------------------------------------------------------
Module::Module()
{
}
//-----------------------------------------------------------------------------
std::wstring Module::GetPrettyName()
{
if( m_PrettyName.size() == 0 )
{
#ifdef WIN32
m_PrettyName = Format( "%s [%I64x - %I64x] %s\r\n", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );
m_AddressRange = Format( "[%I64x - %I64x]", m_AddressStart, m_AddressEnd );
#else
m_PrettyName = m_FullName;
m_AddressRange = Format( "[%016llx - %016llx]", m_AddressStart, m_AddressEnd );
m_PdbName = m_FullName;
m_FoundPdb = true;
#endif
}
return s2ws(m_PrettyName);
}
//-----------------------------------------------------------------------------
bool Module::IsDll() const
{
return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L".dll" ) ||
Contains(m_Name, ".so" );
}
//-----------------------------------------------------------------------------
bool Module::LoadDebugInfo()
{
std::wstring pdbName = s2ws(m_PdbName);
m_Pdb = std::make_shared<Pdb>( pdbName.c_str() );
m_Pdb->SetMainModule( (HMODULE)m_AddressStart );
PRINT_VAR(m_FoundPdb);
if( m_FoundPdb )
{
return m_Pdb->LoadDataFromPdb();
}
return false;
}
//-----------------------------------------------------------------------------
uint64_t Module::ValidateAddress( uint64_t a_Address )
{
if( ContainsAddress(a_Address ) )
return a_Address;
// Treat input address as RVA
uint64_t newAddress = m_AddressStart + a_Address;
if( ContainsAddress(newAddress) )
return newAddress;
return 0xbadadd;
}
//-----------------------------------------------------------------------------
void Module::SetLoaded(bool a_Value)
{
m_Loaded = a_Value;
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( Module, 0 )
{
ORBIT_NVP_VAL( 0, m_Name );
ORBIT_NVP_VAL( 0, m_FullName );
ORBIT_NVP_VAL( 0, m_PdbName );
ORBIT_NVP_VAL( 0, m_Directory );
ORBIT_NVP_VAL( 0, m_PrettyName );
ORBIT_NVP_VAL( 0, m_AddressRange );
ORBIT_NVP_VAL( 0, m_DebugSignature );
ORBIT_NVP_VAL( 0, m_AddressStart );
ORBIT_NVP_VAL( 0, m_AddressEnd );
ORBIT_NVP_VAL( 0, m_EntryPoint );
ORBIT_NVP_VAL( 0, m_FoundPdb );
ORBIT_NVP_VAL( 0, m_Selected );
ORBIT_NVP_VAL( 0, m_Loaded );
ORBIT_NVP_VAL( 0, m_PdbSize );
}
#ifndef WIN32
//-----------------------------------------------------------------------------
Function* Pdb::FunctionFromName( const std::string& a_Name )
{
uint64_t hash = StringHash(a_Name);
auto iter = m_StringFunctionMap.find(hash);
return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;
}
//-----------------------------------------------------------------------------
void Pdb::LoadPdb( const wchar_t* a_PdbName )
{
m_FileName = a_PdbName;
m_Name = Path::GetFileName(m_FileName);
{
SCOPE_TIMER_LOG(L"nm");
// nm
std::string nmCommand = std::string("nm ") + ws2s(a_PdbName) + std::string(" -n -l");
std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());
std::stringstream nmStream(nmResult);
std::string line;
while (std::getline(nmStream, line, '\n'))
{
std::vector<std::string> tokens = Tokenize(line, " \t");
if (tokens.size() > 2) // nm
{
Function func;
func.m_Name = tokens[2];
func.m_Address = std::stoull(tokens[0], nullptr, 16);
func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());
func.m_Module = ws2s(Path::GetFileName(a_PdbName));
func.m_Pdb = this;
this->AddFunction(func);
// Debug - Temporary
if (Contains(func.m_PrettyName, "btCollisionDispatcher::needsCollision"))
{
PRINT_VAR(func.m_PrettyName);
}
}
}
}
ProcessData();
{
SCOPE_TIMER_LOG(L"bpftrace -l");
// find functions that can receive bpftrace uprobes
std::string bpfCommand = std::string("bpftrace -l 'uprobe: ") + ws2s(a_PdbName) + std::string("'");
std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());
std::stringstream bpfStream(bpfResult);
std::string line;
while (std::getline(bpfStream, line, '\n'))
{
std::vector<std::string> tokens = Tokenize(line);
if (tokens.size() == 2) // bpftrace
{
Function func;
auto probeTokens = Tokenize(tokens[1], ":");
if (probeTokens.size() == 2)
{
std::string mangled = probeTokens[1];
std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());
// Debug - Temporary
if (Contains(demangled, "btCollisionDispatcher::needsCollision"))
PRINT_VAR(demangled);
Function* func = FunctionFromName(demangled);
if (func && func->m_Probe.empty())
{
std::string probe = Replace(tokens[1], ".", "*");
func->m_Probe = probe;
}
}
}
}
}
}
//-----------------------------------------------------------------------------
void Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback )
{
m_LoadingCompleteCallback = a_CompletionCallback;
LoadPdb(a_PdbName);
a_CompletionCallback();
}
//-----------------------------------------------------------------------------
void Pdb::ProcessData()
{
SCOPE_TIMER_LOG( L"ProcessData" );
ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );
auto & functions = Capture::GTargetProcess->GetFunctions();
auto & globals = Capture::GTargetProcess->GetGlobals();
functions.reserve( functions.size() + m_Functions.size() );
for( Function & func : m_Functions )
{
func.m_Pdb = this;
functions.push_back( &func );
GOrbitUnreal.OnFunctionAdded( &func );
}
if( GParams.m_FindFileAndLineInfo )
{
SCOPE_TIMER_LOG(L"Find File and Line info");
for( Function & func : m_Functions )
{
func.FindFile();
}
}
for( Type & type : m_Types )
{
type.m_Pdb = this;
Capture::GTargetProcess->AddType( type );
GOrbitUnreal.OnTypeAdded( &type );
}
for( Variable & var : m_Globals )
{
var.m_Pdb = this;
globals.push_back( &var );
}
for( auto & it : m_TypeMap )
{
it.second.m_Pdb = this;
}
PopulateFunctionMap();
PopulateStringFunctionMap();
}
//-----------------------------------------------------------------------------
void Pdb::PopulateFunctionMap()
{
m_IsPopulatingFunctionMap = true;
SCOPE_TIMER_LOG( L"Pdb::PopulateFunctionMap" );
uint64_t baseAddress = (uint64_t)GetHModule();
bool rvaAddresses = false;
// It seems nm can return addresses as VA or RVA
// TODO: investigate, use simple test to detect RVA
for( Function & function : m_Functions )
{
if( function.m_Address > 0 && function.m_Address < baseAddress )
{
rvaAddresses = true;
break;
}
}
for( Function & Function : m_Functions )
{
uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();
m_FunctionMap.insert( std::make_pair( RVA, &Function ) );
}
m_IsPopulatingFunctionMap = false;
}
//-----------------------------------------------------------------------------
void Pdb::PopulateStringFunctionMap()
{
m_IsPopulatingFunctionStringMap = true;
{
//SCOPE_TIMER_LOG( L"Reserving map" );
m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );
}
{
//SCOPE_TIMER_LOG( L"Hash" );
for( Function & Function : m_Functions )
{
Function.Hash();
}
}
{
//SCOPE_TIMER_LOG( L"Map inserts" );
for( Function & Function : m_Functions )
{
m_StringFunctionMap[Function.m_NameHash] = &Function;
}
}
m_IsPopulatingFunctionStringMap = false;
}
//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )
{
uint64_t RVA = a_Address - (uint64_t)GetHModule();
auto iter = m_FunctionMap.find(RVA);
return (iter != m_FunctionMap.end()) ? iter->second : nullptr;
}
//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )
{
uint64_t RVA = a_Address - (uint64_t)GetHModule();
auto it = m_FunctionMap.upper_bound( RVA );
if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())
{
--it;
Function* func = it->second;
return func;
}
return nullptr;
}
#endif
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(ModuleDebugInfo, 0)
{
ORBIT_NVP_VAL(0, m_Pid);
ORBIT_NVP_VAL(0, m_Name);
ORBIT_NVP_VAL(0, m_Functions);
}<commit_msg>Fix Linux build.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "Core.h"
#include "OrbitModule.h"
#include "Serialization.h"
#include "Pdb.h"
#include <string>
#ifndef WIN32
#include "LinuxUtils.h"
#include "Capture.h"
#include "ScopeTimer.h"
#include "OrbitUnreal.h"
#include "Params.h"
#include "OrbitProcess.h"
#include "Path.h"
#endif
//-----------------------------------------------------------------------------
Module::Module()
{
}
//-----------------------------------------------------------------------------
std::wstring Module::GetPrettyName()
{
if( m_PrettyName.size() == 0 )
{
#ifdef WIN32
m_PrettyName = Format( "%s [%I64x - %I64x] %s\r\n", m_Name.c_str(), m_AddressStart, m_AddressEnd, m_FullName.c_str() );
m_AddressRange = Format( "[%I64x - %I64x]", m_AddressStart, m_AddressEnd );
#else
m_PrettyName = m_FullName;
m_AddressRange = Format( "[%016llx - %016llx]", m_AddressStart, m_AddressEnd );
m_PdbName = m_FullName;
m_FoundPdb = true;
#endif
}
return s2ws(m_PrettyName);
}
//-----------------------------------------------------------------------------
bool Module::IsDll() const
{
return ToLower( Path::GetExtension( s2ws(m_FullName) ) ) == std::wstring( L".dll" ) ||
Contains(m_Name, ".so" );
}
//-----------------------------------------------------------------------------
bool Module::LoadDebugInfo()
{
std::wstring pdbName = s2ws(m_PdbName);
m_Pdb = std::make_shared<Pdb>( pdbName.c_str() );
m_Pdb->SetMainModule( (HMODULE)m_AddressStart );
PRINT_VAR(m_FoundPdb);
if( m_FoundPdb )
{
return m_Pdb->LoadDataFromPdb();
}
return false;
}
//-----------------------------------------------------------------------------
uint64_t Module::ValidateAddress( uint64_t a_Address )
{
if( ContainsAddress(a_Address ) )
return a_Address;
// Treat input address as RVA
uint64_t newAddress = m_AddressStart + a_Address;
if( ContainsAddress(newAddress) )
return newAddress;
return 0xbadadd;
}
//-----------------------------------------------------------------------------
void Module::SetLoaded(bool a_Value)
{
m_Loaded = a_Value;
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( Module, 0 )
{
ORBIT_NVP_VAL( 0, m_Name );
ORBIT_NVP_VAL( 0, m_FullName );
ORBIT_NVP_VAL( 0, m_PdbName );
ORBIT_NVP_VAL( 0, m_Directory );
ORBIT_NVP_VAL( 0, m_PrettyName );
ORBIT_NVP_VAL( 0, m_AddressRange );
ORBIT_NVP_VAL( 0, m_DebugSignature );
ORBIT_NVP_VAL( 0, m_AddressStart );
ORBIT_NVP_VAL( 0, m_AddressEnd );
ORBIT_NVP_VAL( 0, m_EntryPoint );
ORBIT_NVP_VAL( 0, m_FoundPdb );
ORBIT_NVP_VAL( 0, m_Selected );
ORBIT_NVP_VAL( 0, m_Loaded );
ORBIT_NVP_VAL( 0, m_PdbSize );
}
#ifndef WIN32
//-----------------------------------------------------------------------------
Function* Pdb::FunctionFromName( const std::string& a_Name )
{
uint64_t hash = StringHash(a_Name);
auto iter = m_StringFunctionMap.find(hash);
return (iter == m_StringFunctionMap.end()) ? nullptr : iter->second;
}
//-----------------------------------------------------------------------------
bool Pdb::LoadPdb( const wchar_t* a_PdbName )
{
m_FileName = a_PdbName;
m_Name = Path::GetFileName(m_FileName);
{
SCOPE_TIMER_LOG(L"nm");
// nm
std::string nmCommand = std::string("nm ") + ws2s(a_PdbName) + std::string(" -n -l");
std::string nmResult = LinuxUtils::ExecuteCommand(nmCommand.c_str());
std::stringstream nmStream(nmResult);
std::string line;
while (std::getline(nmStream, line, '\n'))
{
std::vector<std::string> tokens = Tokenize(line, " \t");
if (tokens.size() > 2) // nm
{
Function func;
func.m_Name = tokens[2];
func.m_Address = std::stoull(tokens[0], nullptr, 16);
func.m_PrettyName = LinuxUtils::Demangle(tokens[2].c_str());
func.m_Module = ws2s(Path::GetFileName(a_PdbName));
func.m_Pdb = this;
this->AddFunction(func);
// Debug - Temporary
if (Contains(func.m_PrettyName, "btCollisionDispatcher::needsCollision"))
{
PRINT_VAR(func.m_PrettyName);
}
}
}
}
ProcessData();
{
SCOPE_TIMER_LOG(L"bpftrace -l");
// find functions that can receive bpftrace uprobes
std::string bpfCommand = std::string("bpftrace -l 'uprobe: ") + ws2s(a_PdbName) + std::string("'");
std::string bpfResult = LinuxUtils::ExecuteCommand(bpfCommand.c_str());
std::stringstream bpfStream(bpfResult);
std::string line;
while (std::getline(bpfStream, line, '\n'))
{
std::vector<std::string> tokens = Tokenize(line);
if (tokens.size() == 2) // bpftrace
{
Function func;
auto probeTokens = Tokenize(tokens[1], ":");
if (probeTokens.size() == 2)
{
std::string mangled = probeTokens[1];
std::string demangled = LinuxUtils::Demangle(probeTokens[1].c_str());
// Debug - Temporary
if (Contains(demangled, "btCollisionDispatcher::needsCollision"))
PRINT_VAR(demangled);
Function* func = FunctionFromName(demangled);
if (func && func->m_Probe.empty())
{
std::string probe = Replace(tokens[1], ".", "*");
func->m_Probe = probe;
}
}
}
}
}
return true;
}
//-----------------------------------------------------------------------------
void Pdb::LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback )
{
m_LoadingCompleteCallback = a_CompletionCallback;
LoadPdb(a_PdbName);
a_CompletionCallback();
}
//-----------------------------------------------------------------------------
void Pdb::ProcessData()
{
SCOPE_TIMER_LOG( L"ProcessData" );
ScopeLock lock( Capture::GTargetProcess->GetDataMutex() );
auto & functions = Capture::GTargetProcess->GetFunctions();
auto & globals = Capture::GTargetProcess->GetGlobals();
functions.reserve( functions.size() + m_Functions.size() );
for( Function & func : m_Functions )
{
func.m_Pdb = this;
functions.push_back( &func );
GOrbitUnreal.OnFunctionAdded( &func );
}
if( GParams.m_FindFileAndLineInfo )
{
SCOPE_TIMER_LOG(L"Find File and Line info");
for( Function & func : m_Functions )
{
func.FindFile();
}
}
for( Type & type : m_Types )
{
type.m_Pdb = this;
Capture::GTargetProcess->AddType( type );
GOrbitUnreal.OnTypeAdded( &type );
}
for( Variable & var : m_Globals )
{
var.m_Pdb = this;
globals.push_back( &var );
}
for( auto & it : m_TypeMap )
{
it.second.m_Pdb = this;
}
PopulateFunctionMap();
PopulateStringFunctionMap();
}
//-----------------------------------------------------------------------------
void Pdb::PopulateFunctionMap()
{
m_IsPopulatingFunctionMap = true;
SCOPE_TIMER_LOG( L"Pdb::PopulateFunctionMap" );
uint64_t baseAddress = (uint64_t)GetHModule();
bool rvaAddresses = false;
// It seems nm can return addresses as VA or RVA
// TODO: investigate, use simple test to detect RVA
for( Function & function : m_Functions )
{
if( function.m_Address > 0 && function.m_Address < baseAddress )
{
rvaAddresses = true;
break;
}
}
for( Function & Function : m_Functions )
{
uint64_t RVA = rvaAddresses ? Function.m_Address : Function.m_Address - (uint64_t)GetHModule();
m_FunctionMap.insert( std::make_pair( RVA, &Function ) );
}
m_IsPopulatingFunctionMap = false;
}
//-----------------------------------------------------------------------------
void Pdb::PopulateStringFunctionMap()
{
m_IsPopulatingFunctionStringMap = true;
{
//SCOPE_TIMER_LOG( L"Reserving map" );
m_StringFunctionMap.reserve( unsigned ( 1.5f * (float)m_Functions.size() ) );
}
{
//SCOPE_TIMER_LOG( L"Hash" );
for( Function & Function : m_Functions )
{
Function.Hash();
}
}
{
//SCOPE_TIMER_LOG( L"Map inserts" );
for( Function & Function : m_Functions )
{
m_StringFunctionMap[Function.m_NameHash] = &Function;
}
}
m_IsPopulatingFunctionStringMap = false;
}
//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromExactAddress( uint64_t a_Address )
{
uint64_t RVA = a_Address - (uint64_t)GetHModule();
auto iter = m_FunctionMap.find(RVA);
return (iter != m_FunctionMap.end()) ? iter->second : nullptr;
}
//-----------------------------------------------------------------------------
Function* Pdb::GetFunctionFromProgramCounter( uint64_t a_Address )
{
uint64_t RVA = a_Address - (uint64_t)GetHModule();
auto it = m_FunctionMap.upper_bound( RVA );
if (!m_FunctionMap.empty() && it != m_FunctionMap.begin())
{
--it;
Function* func = it->second;
return func;
}
return nullptr;
}
#endif
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE(ModuleDebugInfo, 0)
{
ORBIT_NVP_VAL(0, m_Pid);
ORBIT_NVP_VAL(0, m_Name);
ORBIT_NVP_VAL(0, m_Functions);
}<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>
int main(int argc, char * argv[])
{
return 0;
}
<commit_msg>added basic adobe example on which i will begin working<commit_after>#include <iostream>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <memory>
#include <string>
#include <vector>
using namespace std;
#if 0
class object_t
{
public:
virtual ~object_t() {}
virtual void draw(ostream&, size_t) const = 0;
};
using document_t = vector<shared_ptr<object_t>>;
void draw(const document_t& x, ostream& out, size_t position)
{
out << string(position, ' ') << "<document>" << endl;
for (const auto& e : x )
e->draw(out, position + 2);
out << string(position, ' ') << "</document>" << endl;
}
class my_class_t : public object_t
{
public:
void draw(ostream &out, size_t position) const
{
out << string(position, ' ') << "my_class_t" << endl;
}
};
int main(int argc, char * argv[])
{
document_t document;
document.emplace_back(new my_class_t{});
draw(document,cout, 1);
return 0;
}
#else
class object_t
{
public:
template<typename T>
object_t(T x) : self_(make_shared<model<T>>(move(x))) {}
void draw(ostream& out, size_t position) const
{
self_->draw_(out,position);
}
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual void draw_(ostream&, size_t) const = 0;
};
template<typename T>
struct model : concept_t
{
model(T x) : data_(move(x)) {}
void draw_(ostream& out, size_t position) const
{
data_.draw(out,position);
}
T data_;
};
shared_ptr<const concept_t> self_;
};
using document_t = vector<object_t>;
void draw(const document_t& x, ostream& out, size_t position)
{
out << string(position, ' ') << "<document>" << endl;
for (const auto& e : x )
e.draw(out, position + 2);
out << string(position, ' ') << "</document>" << endl;
}
class my_class_t
{
public:
void draw(ostream& out, size_t position) const
{
out << string(position, ' ') << "my_class_t" << endl;
}
};
int main()
{
document_t document;
document.emplace_back(my_class_t{});
draw(document,cout,0);
}
#endif
<|endoftext|> |
<commit_before>// SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.
// @author Florian Dahlitz
#include "stdafx.h"
#include "SmallGames.h"
void ISmallGames::HangingMan::setupGame()
{
wordlist = getWordlist();
word = getRandomWord(wordlist);
boost::to_upper(word);
userWord = "_";
for (unsigned int i = 0; i < word.size() - 1; ++i)
userWord += "_";
return;
}
void ISmallGames::HangingMan::buildWindow()
{
system("cls");
std::cout << "THE HANGING MAN" << std::endl;
for (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)
if (it->first == m_efforts)
std::cout << it->second << std::endl << std::endl;
for (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)
std::cout << "\n";
std::cout << "" << std::endl << std::endl; // clean buffer + better overview
for (int i = 0; i < userWord.length(); i++)
std::cout << userWord[i] << " ";
std::cout << std::endl; // clean buffer
return;
}
std::map<unsigned int, std::string> ISmallGames::HangingMan::getWordlist()
{
unsigned int i = 0;
std::string strWord;
std::map<unsigned int, std::string> wordlist;
std::ifstream worldlistFile(m_path);
if (worldlistFile.fail())
std::cout << m_path << std::endl;
// TODO: change reading file w/ vectors -> read something about
while (std::getline(worldlistFile, strWord))
{
wordlist[i] = strWord;
std::cout << ++i << " - " << strWord << std::endl;
}
return wordlist;
}
std::string ISmallGames::HangingMan::getRandomWord(std::map<unsigned int, std::string> wordlist)
{
std::string randomWord;
auto iter = wordlist.begin();
srand(time(NULL));
std::advance(iter, rand() % wordlist.size());
randomWord = iter->second;
wordlist.erase(iter);
return randomWord;
}
void ISmallGames::HangingMan::playGame()
{
do {
buildWindow();
char userChar = getUserChar();
addToUserWord(userChar);
} while (userWord.compare(word) && (m_efforts != 6));
return;
}
char ISmallGames::HangingMan::getUserChar()
{
char userChar;
do {
std::cout << "Type in a character: ";
std::cin >> userChar;
userChar = toupper(userChar);
} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));
usedChars[userChar] = userChar;
return userChar;
}
void ISmallGames::HangingMan::addToUserWord(char userChar)
{
size_t found = word.find(userChar);
if (found == std::string::npos)
m_efforts++;
while (found != std::string::npos)
{
userWord[found] = userChar;
found = word.find(userChar, found+1);
}
return;
}
<commit_msg>fixed issue #2 -> multiple chars at one input<commit_after>// SmallGames.cpp : Definiert die exportierten Funktionen fr die DLL-Anwendung.
// @author Florian Dahlitz
#include "stdafx.h"
#include "SmallGames.h"
void ISmallGames::HangingMan::setupGame()
{
wordlist = getWordlist();
word = getRandomWord(wordlist);
boost::to_upper(word);
userWord = "_";
for (unsigned int i = 0; i < word.size() - 1; ++i)
userWord += "_";
return;
}
void ISmallGames::HangingMan::buildWindow()
{
system("cls");
std::cout << "THE HANGING MAN" << std::endl;
for (it = hangingManParts.begin(); it != hangingManParts.end(); ++it)
if (it->first == m_efforts)
std::cout << it->second << std::endl << std::endl;
for (int i = 0; i < (m_hangingMan - manHeight[m_efforts]); ++i)
std::cout << "\n";
std::cout << "" << std::endl << std::endl; // clean buffer + better overview
for (int i = 0; i < userWord.length(); i++)
std::cout << userWord[i] << " ";
std::cout << std::endl; // clean buffer
return;
}
std::map<unsigned int, std::string> ISmallGames::HangingMan::getWordlist()
{
unsigned int i = 0;
std::string strWord;
std::map<unsigned int, std::string> wordlist;
std::ifstream worldlistFile(m_path);
if (worldlistFile.fail())
std::cout << m_path << std::endl;
// TODO: change reading file w/ vectors -> read something about
while (std::getline(worldlistFile, strWord))
{
wordlist[i] = strWord;
std::cout << ++i << " - " << strWord << std::endl;
}
return wordlist;
}
std::string ISmallGames::HangingMan::getRandomWord(std::map<unsigned int, std::string> wordlist)
{
std::string randomWord;
auto iter = wordlist.begin();
srand(time(NULL));
std::advance(iter, rand() % wordlist.size());
randomWord = iter->second;
wordlist.erase(iter);
return randomWord;
}
void ISmallGames::HangingMan::playGame()
{
do {
buildWindow();
char userChar = getUserChar();
addToUserWord(userChar);
} while (userWord.compare(word) && (m_efforts != 6));
return;
}
char ISmallGames::HangingMan::getUserChar()
{
std::string userInput;
char userChar;
do {
std::cout << "Type in a character: ";
std::cin >> userInput;
userChar = userInput[0];
userChar = toupper(userChar);
} while ((usedChars.count(userChar) == 1) || (allowedChars.count(userChar) != 1));
usedChars[userChar] = userChar;
return userChar;
}
void ISmallGames::HangingMan::addToUserWord(char userChar)
{
size_t found = word.find(userChar);
if (found == std::string::npos)
m_efforts++;
while (found != std::string::npos)
{
userWord[found] = userChar;
found = word.find(userChar, found+1);
}
return;
}
<|endoftext|> |
<commit_before>#include "Iop_Sysmem.h"
#include "../Log.h"
#include "Iop_SifMan.h"
using namespace Iop;
#define LOG_NAME ("iop_sysmem")
#define FUNCTION_ALLOCATEMEMORY "AllocateMemory"
#define FUNCTION_FREEMEMORY "FreeMemory"
#define FUNCTION_PRINTF "printf"
#define FUNCTION_QUERYMEMSIZE "QueryMemSize"
#define FUNCTION_QUERYMAXFREEMEMSIZE "QueryMaxFreeMemSize"
#define MIN_BLOCK_SIZE 0x20
CSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)
: m_iopRam(ram)
, m_memoryBegin(memoryBegin)
, m_memoryEnd(memoryEnd)
, m_stdio(stdio)
, m_ioman(ioman)
, m_memorySize(memoryEnd - memoryBegin)
, m_blocks(reinterpret_cast<BLOCK*>(&ram[blockBase]), 1, MAX_BLOCKS)
{
//Initialize block map
m_headBlockId = m_blocks.Allocate();
BLOCK* block = m_blocks[m_headBlockId];
block->address = m_memorySize;
block->size = 0;
block->nextBlock = 0;
//Register sif module
sifMan.RegisterModule(MODULE_ID, this);
}
CSysmem::~CSysmem()
{
}
std::string CSysmem::GetId() const
{
return "sysmem";
}
std::string CSysmem::GetFunctionName(unsigned int functionId) const
{
switch(functionId)
{
case 4:
return FUNCTION_ALLOCATEMEMORY;
break;
case 5:
return FUNCTION_FREEMEMORY;
break;
case 6:
return FUNCTION_QUERYMEMSIZE;
break;
case 7:
return FUNCTION_QUERYMAXFREEMEMSIZE;
break;
case 14:
return FUNCTION_PRINTF;
break;
default:
return "unknown";
break;
}
}
void CSysmem::Invoke(CMIPS& context, unsigned int functionId)
{
switch(functionId)
{
case 4:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(AllocateMemory(
context.m_State.nGPR[CMIPS::A1].nV[0],
context.m_State.nGPR[CMIPS::A0].nV[0],
context.m_State.nGPR[CMIPS::A2].nV[0]
));
break;
case 5:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(FreeMemory(
context.m_State.nGPR[CMIPS::A0].nV[0]
));
break;
case 6:
context.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;
break;
case 7:
context.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();
break;
case 14:
m_stdio.__printf(context);
break;
default:
CLog::GetInstance().Print(LOG_NAME, "%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId);
break;
}
}
bool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
switch(method)
{
case 0x01:
assert(retSize == 4);
ret[0] = SifAllocate(args[0]);
break;
case 0x02:
assert(argsSize == 4);
ret[0] = SifFreeMemory(args[0]);
break;
case 0x03:
assert(argsSize >= 4);
assert(retSize == 4);
ret[0] = SifLoadMemory(args[0], reinterpret_cast<const char*>(args) + 4);
break;
case 0x04:
assert(retSize == 4);
ret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);
break;
case 0x06:
ret[0] = m_memorySize;
break;
case 0x07:
ret[0] = QueryMaxFreeMemSize();
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Unknown method invoked (0x%0.8X).\r\n", method);
break;
}
return true;
}
uint32 CSysmem::QueryMaxFreeMemSize()
{
uint32 maxSize = 0;
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while (nextBlock != NULL)
{
uint32 end = nextBlock->address;
if ((end - begin) >= maxSize)
{
maxSize = end - begin;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
return maxSize;
}
uint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)
{
CLog::GetInstance().Print(LOG_NAME, "AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\r\n",
size, flags, wantedAddress);
const uint32 blockSize = MIN_BLOCK_SIZE;
size = ((size + (blockSize - 1)) / blockSize) * blockSize;
if(flags == 0 || flags == 1)
{
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
uint32 end = nextBlock->address;
if((end - begin) >= size)
{
break;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
uint32 newBlockId = m_blocks.Allocate();
assert(newBlockId != 0);
if(newBlockId == 0)
{
return 0;
}
BLOCK* newBlock = m_blocks[newBlockId];
newBlock->address = begin;
newBlock->size = size;
newBlock->nextBlock = *nextBlockId;
*nextBlockId = newBlockId;
return begin + m_memoryBegin;
}
}
else if(flags == 2)
{
assert(wantedAddress != 0);
wantedAddress -= m_memoryBegin;
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
uint32 end = nextBlock->address;
if(begin > wantedAddress)
{
//Couldn't find suitable space
nextBlock = NULL;
break;
}
if(
(begin <= wantedAddress) &&
((end - begin) >= size)
)
{
break;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
uint32 newBlockId = m_blocks.Allocate();
assert(newBlockId != 0);
if(newBlockId == 0)
{
return 0;
}
BLOCK* newBlock = m_blocks[newBlockId];
newBlock->address = wantedAddress;
newBlock->size = size;
newBlock->nextBlock = *nextBlockId;
*nextBlockId = newBlockId;
return wantedAddress + m_memoryBegin;
}
}
else
{
assert(0);
}
assert(0);
return NULL;
}
uint32 CSysmem::FreeMemory(uint32 address)
{
CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
address -= m_memoryBegin;
//Search for block pointing at the address
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
if(nextBlock->address == address)
{
break;
}
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
m_blocks.Free(*nextBlockId);
*nextBlockId = nextBlock->nextBlock;
}
else
{
CLog::GetInstance().Print(LOG_NAME, "%s: Trying to unallocate an unexisting memory block (0x%0.8X).\r\n", __FUNCTION__, address);
}
return 0;
}
uint32 CSysmem::SifAllocate(uint32 nSize)
{
uint32 result = AllocateMemory(nSize, 0, 0);
CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = Allocate(size = 0x%0.8X);\r\n",
result, nSize);
return result;
}
uint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)
{
uint32 result = AllocateMemory(nSize, nFlags, nPtr);
CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\r\n",
result, nFlags, nSize, nPtr);
return result;
}
uint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)
{
CLog::GetInstance().Print(LOG_NAME, "LoadMemory(address = 0x%0.8X, filePath = '%s');\r\n",
address, filePath);
auto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);
if(static_cast<int32>(fd) < 0)
{
return fd;
}
uint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);
m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);
m_ioman.Read(fd, fileSize, m_iopRam + address);
m_ioman.Close(fd);
return 0;
}
uint32 CSysmem::SifFreeMemory(uint32 address)
{
CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
FreeMemory(address);
return 0;
}
<commit_msg>Changed minimum memory alloc block size to 256 bytes.<commit_after>#include "Iop_Sysmem.h"
#include "../Log.h"
#include "Iop_SifMan.h"
using namespace Iop;
#define LOG_NAME ("iop_sysmem")
#define FUNCTION_ALLOCATEMEMORY "AllocateMemory"
#define FUNCTION_FREEMEMORY "FreeMemory"
#define FUNCTION_PRINTF "printf"
#define FUNCTION_QUERYMEMSIZE "QueryMemSize"
#define FUNCTION_QUERYMAXFREEMEMSIZE "QueryMaxFreeMemSize"
#define MIN_BLOCK_SIZE 0x100
CSysmem::CSysmem(uint8* ram, uint32 memoryBegin, uint32 memoryEnd, uint32 blockBase, CStdio& stdio, CIoman& ioman, CSifMan& sifMan)
: m_iopRam(ram)
, m_memoryBegin(memoryBegin)
, m_memoryEnd(memoryEnd)
, m_stdio(stdio)
, m_ioman(ioman)
, m_memorySize(memoryEnd - memoryBegin)
, m_blocks(reinterpret_cast<BLOCK*>(&ram[blockBase]), 1, MAX_BLOCKS)
{
//Initialize block map
m_headBlockId = m_blocks.Allocate();
BLOCK* block = m_blocks[m_headBlockId];
block->address = m_memorySize;
block->size = 0;
block->nextBlock = 0;
//Register sif module
sifMan.RegisterModule(MODULE_ID, this);
}
CSysmem::~CSysmem()
{
}
std::string CSysmem::GetId() const
{
return "sysmem";
}
std::string CSysmem::GetFunctionName(unsigned int functionId) const
{
switch(functionId)
{
case 4:
return FUNCTION_ALLOCATEMEMORY;
break;
case 5:
return FUNCTION_FREEMEMORY;
break;
case 6:
return FUNCTION_QUERYMEMSIZE;
break;
case 7:
return FUNCTION_QUERYMAXFREEMEMSIZE;
break;
case 14:
return FUNCTION_PRINTF;
break;
default:
return "unknown";
break;
}
}
void CSysmem::Invoke(CMIPS& context, unsigned int functionId)
{
switch(functionId)
{
case 4:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(AllocateMemory(
context.m_State.nGPR[CMIPS::A1].nV[0],
context.m_State.nGPR[CMIPS::A0].nV[0],
context.m_State.nGPR[CMIPS::A2].nV[0]
));
break;
case 5:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(FreeMemory(
context.m_State.nGPR[CMIPS::A0].nV[0]
));
break;
case 6:
context.m_State.nGPR[CMIPS::V0].nD0 = m_memorySize;
break;
case 7:
context.m_State.nGPR[CMIPS::V0].nD0 = QueryMaxFreeMemSize();
break;
case 14:
m_stdio.__printf(context);
break;
default:
CLog::GetInstance().Print(LOG_NAME, "%s(%0.8X): Unknown function (%d) called.\r\n", __FUNCTION__, context.m_State.nPC, functionId);
break;
}
}
bool CSysmem::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
switch(method)
{
case 0x01:
assert(retSize == 4);
ret[0] = SifAllocate(args[0]);
break;
case 0x02:
assert(argsSize == 4);
ret[0] = SifFreeMemory(args[0]);
break;
case 0x03:
assert(argsSize >= 4);
assert(retSize == 4);
ret[0] = SifLoadMemory(args[0], reinterpret_cast<const char*>(args) + 4);
break;
case 0x04:
assert(retSize == 4);
ret[0] = SifAllocateSystemMemory(args[0], args[1], args[2]);
break;
case 0x06:
ret[0] = m_memorySize;
break;
case 0x07:
ret[0] = QueryMaxFreeMemSize();
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Unknown method invoked (0x%0.8X).\r\n", method);
break;
}
return true;
}
uint32 CSysmem::QueryMaxFreeMemSize()
{
uint32 maxSize = 0;
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while (nextBlock != NULL)
{
uint32 end = nextBlock->address;
if ((end - begin) >= maxSize)
{
maxSize = end - begin;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
return maxSize;
}
uint32 CSysmem::AllocateMemory(uint32 size, uint32 flags, uint32 wantedAddress)
{
CLog::GetInstance().Print(LOG_NAME, "AllocateMemory(size = 0x%0.8X, flags = 0x%0.8X, wantedAddress = 0x%0.8X);\r\n",
size, flags, wantedAddress);
const uint32 blockSize = MIN_BLOCK_SIZE;
size = ((size + (blockSize - 1)) / blockSize) * blockSize;
if(flags == 0 || flags == 1)
{
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
uint32 end = nextBlock->address;
if((end - begin) >= size)
{
break;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
uint32 newBlockId = m_blocks.Allocate();
assert(newBlockId != 0);
if(newBlockId == 0)
{
return 0;
}
BLOCK* newBlock = m_blocks[newBlockId];
newBlock->address = begin;
newBlock->size = size;
newBlock->nextBlock = *nextBlockId;
*nextBlockId = newBlockId;
return begin + m_memoryBegin;
}
}
else if(flags == 2)
{
assert(wantedAddress != 0);
wantedAddress -= m_memoryBegin;
uint32 begin = 0;
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
uint32 end = nextBlock->address;
if(begin > wantedAddress)
{
//Couldn't find suitable space
nextBlock = NULL;
break;
}
if(
(begin <= wantedAddress) &&
((end - begin) >= size)
)
{
break;
}
begin = nextBlock->address + nextBlock->size;
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
uint32 newBlockId = m_blocks.Allocate();
assert(newBlockId != 0);
if(newBlockId == 0)
{
return 0;
}
BLOCK* newBlock = m_blocks[newBlockId];
newBlock->address = wantedAddress;
newBlock->size = size;
newBlock->nextBlock = *nextBlockId;
*nextBlockId = newBlockId;
return wantedAddress + m_memoryBegin;
}
}
else
{
assert(0);
}
assert(0);
return NULL;
}
uint32 CSysmem::FreeMemory(uint32 address)
{
CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
address -= m_memoryBegin;
//Search for block pointing at the address
uint32* nextBlockId = &m_headBlockId;
BLOCK* nextBlock = m_blocks[*nextBlockId];
while(nextBlock != NULL)
{
if(nextBlock->address == address)
{
break;
}
nextBlockId = &nextBlock->nextBlock;
nextBlock = m_blocks[*nextBlockId];
}
if(nextBlock != NULL)
{
m_blocks.Free(*nextBlockId);
*nextBlockId = nextBlock->nextBlock;
}
else
{
CLog::GetInstance().Print(LOG_NAME, "%s: Trying to unallocate an unexisting memory block (0x%0.8X).\r\n", __FUNCTION__, address);
}
return 0;
}
uint32 CSysmem::SifAllocate(uint32 nSize)
{
uint32 result = AllocateMemory(nSize, 0, 0);
CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = Allocate(size = 0x%0.8X);\r\n",
result, nSize);
return result;
}
uint32 CSysmem::SifAllocateSystemMemory(uint32 nSize, uint32 nFlags, uint32 nPtr)
{
uint32 result = AllocateMemory(nSize, nFlags, nPtr);
CLog::GetInstance().Print(LOG_NAME, "result = 0x%0.8X = AllocateSystemMemory(flags = 0x%0.8X, size = 0x%0.8X, ptr = 0x%0.8X);\r\n",
result, nFlags, nSize, nPtr);
return result;
}
uint32 CSysmem::SifLoadMemory(uint32 address, const char* filePath)
{
CLog::GetInstance().Print(LOG_NAME, "LoadMemory(address = 0x%0.8X, filePath = '%s');\r\n",
address, filePath);
auto fd = m_ioman.Open(Ioman::CDevice::OPEN_FLAG_RDONLY, filePath);
if(static_cast<int32>(fd) < 0)
{
return fd;
}
uint32 fileSize = m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_END);
m_ioman.Seek(fd, 0, CIoman::SEEK_DIR_SET);
m_ioman.Read(fd, fileSize, m_iopRam + address);
m_ioman.Close(fd);
return 0;
}
uint32 CSysmem::SifFreeMemory(uint32 address)
{
CLog::GetInstance().Print(LOG_NAME, "FreeMemory(address = 0x%0.8X);\r\n", address);
FreeMemory(address);
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
File: KeyMappings.cpp
Created: 10/3/2017 11:57:46 AM
Copyright (c) 2017 Turn Tactics
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.
Purpose: Contains all of the key mapping functions and data for keyboard input
from SDL
Author: James Womack
********************************************************************************/
#include "KeyMappings.h"
#include "../Math/Common.h"
#include <SDL.h>
namespace lse {
// A map that maps KeyType to a string.
const containers::UnorderedMap<KeyType, String> gc_keyTextMappings{
{ KeyType::Key0, "0" },{ KeyType::Key1, "1" },
{ KeyType::Key2, "2" },{ KeyType::Key3, "3" },
{ KeyType::Key4, "4" },{ KeyType::Key5, "5" },
{ KeyType::Key6, "6" },{ KeyType::Key7, "7" },
{ KeyType::Key8, "8" },{ KeyType::Key9, "9" },
{ KeyType::KeyA, "a" },{ KeyType::KeyB, "b" },
{ KeyType::KeyC, "c" },{ KeyType::KeyD, "d" },
{ KeyType::KeyE, "e" },{ KeyType::KeyF, "f" },
{ KeyType::KeyG, "g" },{ KeyType::KeyH, "h" },
{ KeyType::KeyI, "i" },{ KeyType::KeyJ, "j" },
{ KeyType::KeyL, "l" },{ KeyType::KeyK, "k" },
{ KeyType::KeyN, "n" },{ KeyType::KeyM, "m" },
{ KeyType::KeyP, "p" },{ KeyType::KeyO, "o" },
{ KeyType::KeyR, "r" },{ KeyType::KeyQ, "q" },
{ KeyType::KeyT, "t" },{ KeyType::KeyS, "s" },
{ KeyType::KeyV, "v" },{ KeyType::KeyU, "u" },
{ KeyType::KeyW, "w" },{ KeyType::KeyX, "x" },
{ KeyType::KeyY, "y" },{ KeyType::KeyZ, "z" },
{ KeyType::KeyTab, "\t" },{ KeyType::KeyEnter, "\n" },
{ KeyType::KeyBracketLeft, "[" },{ KeyType::KeyBracketRight, "]" },
{ KeyType::KeyLeftParenthesis, "(" },{ KeyType::KeyRightParenthesis, ")" },
{ KeyType::KeyCurlyBracketLeft, "{" },{ KeyType::KeyCurlyBracketRight, "}" },
{ KeyType::KeyAngleBracketLeft, "{" },{ KeyType::KeyAngleBracketRight, "}" },
{ KeyType::KeyColon, ":" },{ KeyType::KeySemicolon, ";" },
{ KeyType::KeyComma, "," },{ KeyType::KeyEnter, "\n" },
{ KeyType::KeySlash, "/" },{ KeyType::KeyBackslash, "\\" },
{ KeyType::KeyExclamation, "!" },{ KeyType::KeyAt, "@" },
{ KeyType::KeyHash, "#" },{ KeyType::KeyPercent, "%" },
{ KeyType::KeyHat, "^" },{ KeyType::KeyAmpersand, "&" },
{ KeyType::KeyStar, "*" },{ KeyType::KeyMinus, "-" },
{ KeyType::KeyUnderscore, "_" },{ KeyType::KeyEquals, "=" },
{ KeyType::KeyPlus, "+" },
{ KeyType::KeyApostrophe, "'" },{ KeyType::KeyQuotes, "\"" },
{ KeyType::KeyBacktick, "`" },{ KeyType::KeyQuestion, "?" },
{ KeyType::KeyBackspace, "\\backspace\\" },{ KeyType::KeyDelete, "\\delete\\" },
{ KeyType::KeyDollar, "$" },{ KeyType::KeyHome, "\\home\\" },
{ KeyType::KeyPageDown, "\\pg-down\\" },{ KeyType::KeyPageUp, "\\pg-up\\" },
{ KeyType::KeyEnd, "\\end\\" },{ KeyType::KeyInsert, "\\insert\\" },
{ KeyType::KeyF1, "\\f1\\" },{ KeyType::KeyF2, "\\f2\\" },
{ KeyType::KeyF3, "\\f3\\" },{ KeyType::KeyF4, "\\f4\\" },
{ KeyType::KeyF5, "\\f5\\" },{ KeyType::KeyF6, "\\f6\\" },
{ KeyType::KeyF7, "\\f7\\" },{ KeyType::KeyF8, "\\f8\\" },
{ KeyType::KeyF9, "\\f9\\" },{ KeyType::KeyF10, "\\f10\\" },
{ KeyType::KeyF11, "\\f11\\" },{ KeyType::KeyF12, "\\f12\\" },
{ KeyType::KeyArrowUp, "\\^\\" },{ KeyType::KeyArrowDown, "\\v\\" },
{ KeyType::KeyArrowLeft, "\\<\\" },{ KeyType::KeyArrowRight, "\\>\\" },
{ KeyType::KeyPeriod, "." },{KeyType::KeyPipe, "|" },
{ KeyType::KeyNone, "" }
};
const containers::UnorderedMap<KeyModiferType, String> gc_keyModiferTextMappings {
{ KeyModiferType::KeyNone, "" }, { KeyModiferType::KeyAlt, "Alt" },
{ KeyModiferType::KeyCtrl, "Ctrl" }, { KeyModiferType::KeyCtrlAlt, "Ctrl+Alt"},
{ KeyModiferType::KeyCtrlShift, "Ctrl+Shift" }, { KeyModiferType::KeyCtrlShiftAlt, "Ctrl+Shift+Alt"},
{ KeyModiferType::KeyShift, "Shift" }, { KeyModiferType::KeyShiftAlt, "Shift+Alt" }
};
const containers::UnorderedMap<SDL_Keycode, KeyType> gc_sdlKeyMapping {
{ SDLK_0, KeyType::Key0 },{ SDLK_1, KeyType::Key1 },
{ SDLK_2, KeyType::Key2 },{ SDLK_3, KeyType::Key3 },
{ SDLK_4, KeyType::Key4 },{ SDLK_5, KeyType::Key5 },
{ SDLK_6, KeyType::Key6 },{ SDLK_7, KeyType::Key7 },
{ SDLK_8, KeyType::Key8 },{ SDLK_9, KeyType::Key9 },
{ SDLK_a, KeyType::KeyA },{ SDLK_b, KeyType::KeyB },
{ SDLK_c, KeyType::KeyC },{ SDLK_d, KeyType::KeyD },
{ SDLK_e, KeyType::KeyE },{ SDLK_f, KeyType::KeyF },
{ SDLK_g, KeyType::KeyG },{ SDLK_h, KeyType::KeyH },
{ SDLK_i, KeyType::KeyI },{ SDLK_j, KeyType::KeyJ },
{ SDLK_k, KeyType::KeyK },{ SDLK_l, KeyType::KeyL },
{ SDLK_m, KeyType::KeyM },{ SDLK_n, KeyType::KeyN },
{ SDLK_o, KeyType::KeyO },{ SDLK_p, KeyType::KeyP },
{ SDLK_q, KeyType::KeyQ },{ SDLK_r, KeyType::KeyR },
{ SDLK_s, KeyType::KeyS },{ SDLK_t, KeyType::KeyT },
{ SDLK_u, KeyType::KeyU },{ SDLK_v, KeyType::KeyV },
{ SDLK_w, KeyType::KeyW },{ SDLK_x, KeyType::KeyX },
{ SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyZ },
{ SDLK_y, KeyType::KeyY },{ SDLK_z, KeyType::KeyAccent },
};
// Maps SDL_Event type to a KeyState type if applicable
inline KeyState get_sdl_key_state(SDL_Event& e)
{
return e.type == SDL_KEYDOWN ? KeyState::KeyDown
: e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;
}
inline
inline String get_text_character(KeyEvent& keyEvent)
{
auto keyStr = gc_keyTextMappings.at(keyEvent.key());
if (is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift)
{
return to_upper(keyStr);
}
return keyStr;
}
inline String get_key_event_string(KeyEvent& keyEvent)
{
auto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));
auto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));
if (keyStr.length() > 0 && modiferStr.length() > 0)
{
return modiferStr + "+" + keyStr;
} else if (keyStr.length() > 0)
{
return keyStr;
} else if (modiferStr.length() > 0)
{
return modiferStr;
} else
{
return "\\none\\";
}
}
}
<commit_msg>Revert "i dont know"<commit_after>/******************************************************************************
File: KeyMappings.cpp
Created: 10/3/2017 11:57:46 AM
Copyright (c) 2017 Turn Tactics
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.
Purpose: Contains all of the key mapping functions and data for keyboard input
from SDL
Author: James Womack
********************************************************************************/
#include "KeyMappings.h"
#include "../Math/Common.h"
#include <SDL.h>
namespace lse {
// A map that maps KeyType to a string.
const containers::UnorderedMap<KeyType, String> gc_keyTextMappings {
{ KeyType::Key0, "0" }, { KeyType::Key1, "1" },
{ KeyType::Key2, "2" }, { KeyType::Key3, "3" },
{ KeyType::Key4, "4" }, { KeyType::Key5, "5" },
{ KeyType::Key6, "6" }, { KeyType::Key7, "7" },
{ KeyType::Key8, "8" }, { KeyType::Key9, "9" },
{ KeyType::KeyA, "a" }, { KeyType::KeyB, "b" },
{ KeyType::KeyC, "c" }, { KeyType::KeyD, "d" },
{ KeyType::KeyE, "e" }, { KeyType::KeyF, "f" },
{ KeyType::KeyG, "g" }, { KeyType::KeyH, "h" },
{ KeyType::KeyI, "i" }, { KeyType::KeyJ, "j" },
{ KeyType::KeyL, "l" }, { KeyType::KeyK, "k" },
{ KeyType::KeyN, "n" }, { KeyType::KeyM, "m" },
{ KeyType::KeyP, "p" }, { KeyType::KeyO, "o" },
{ KeyType::KeyR, "r" }, { KeyType::KeyQ, "q" },
{ KeyType::KeyT, "t" }, { KeyType::KeyS, "s" },
{ KeyType::KeyV, "v" }, { KeyType::KeyU, "u" },
{ KeyType::KeyW, "w" }, { KeyType::KeyX, "x" },
{ KeyType::KeyY, "y" }, { KeyType::KeyZ, "z" },
{ KeyType::KeyTab, "\t" }, { KeyType::KeyEnter, "\n" },
{ KeyType::KeyBracketLeft, "[" }, { KeyType::KeyBracketRight, "]" },
{ KeyType::KeyLeftParenthesis, "(" }, { KeyType::KeyRightParenthesis, ")" },
{ KeyType::KeyCurlyBracketLeft, "{" }, { KeyType::KeyCurlyBracketRight, "}" },
{ KeyType::KeyAngleBracketLeft, "{" }, { KeyType::KeyAngleBracketRight, "}" },
{ KeyType::KeyColon, ":" }, { KeyType::KeySemicolon, ";" },
{ KeyType::KeyComma, "," }, { KeyType::KeyEnter, "\n" },
{ KeyType::KeySlash, "/" }, { KeyType::KeyBackslash, "\\" },
{ KeyType::KeyExclamation, "!" }, { KeyType::KeyAt, "@" },
{ KeyType::KeyHash, "#" }, { KeyType::KeyPercent, "%" },
{ KeyType::KeyHat, "^" }, { KeyType::KeyAmpersand, "&" },
{ KeyType::KeyStar, "*" }, { KeyType::KeyMinus, "-" },
{ KeyType::KeyUnderscore, "_" }, { KeyType::KeyEquals, "=" },
{ KeyType::KeyPlus, "+" },
{ KeyType::KeyApostrophe, "'" }, { KeyType::KeyQuotes, "\"" },
{ KeyType::KeyBacktick, "`" }, { KeyType::KeyQuestion, "?" },
{ KeyType::KeyBackspace, "\\backspace\\" }, { KeyType::KeyDelete, "\\delete\\" },
{ KeyType::KeyDollar, "$" }, { KeyType::KeyHome, "\\home\\" },
{ KeyType::KeyPageDown, "\\pg-down\\" }, { KeyType::KeyPageUp, "\\pg-up\\" },
{ KeyType::KeyEnd, "\\end\\" }, { KeyType::KeyInsert, "\\insert\\" },
{ KeyType::KeyF1, "\\f1\\" }, { KeyType::KeyF2, "\\f2\\" },
{ KeyType::KeyF3, "\\f3\\" }, { KeyType::KeyF4, "\\f4\\" },
{ KeyType::KeyF5, "\\f5\\" }, { KeyType::KeyF6, "\\f6\\" },
{ KeyType::KeyF7, "\\f7\\" }, { KeyType::KeyF8, "\\f8\\" },
{ KeyType::KeyF9, "\\f9\\" }, { KeyType::KeyF10, "\\f10\\" },
{ KeyType::KeyF11, "\\f11\\" }, { KeyType::KeyF12, "\\f12\\" },
{ KeyType::KeyArrowUp, "\\^\\" }, { KeyType::KeyArrowDown, "\\v\\" },
{ KeyType::KeyArrowLeft, "\\<\\" }, { KeyType::KeyArrowRight, "\\>\\" },
{ KeyType::KeyPeriod, "." }, { KeyType::KeyPipe, "|" },
{ KeyType::KeyNone, "" }
};
const containers::UnorderedMap<KeyModiferType, String> gc_keyModiferTextMappings {
{ KeyModiferType::KeyNone, "" }, { KeyModiferType::KeyAlt, "Alt" },
{ KeyModiferType::KeyCtrl, "Ctrl" }, { KeyModiferType::KeyCtrlAlt, "Ctrl+Alt" },
{ KeyModiferType::KeyCtrlShift, "Ctrl+Shift" }, { KeyModiferType::KeyCtrlShiftAlt, "Ctrl+Shift+Alt" },
{ KeyModiferType::KeyShift, "Shift" }, { KeyModiferType::KeyShiftAlt, "Shift+Alt" }
};
const containers::UnorderedMap<SDL_Keycode, KeyType> gc_sdlKeyMapping {
{ SDLK_0, KeyType::Key0 }, { SDLK_1, KeyType::Key1 },
{ SDLK_2, KeyType::Key2 }, { SDLK_3, KeyType::Key3 },
{ SDLK_4, KeyType::Key4 }, { SDLK_5, KeyType::Key5 },
{ SDLK_6, KeyType::Key6 }, { SDLK_7, KeyType::Key7 },
{ SDLK_8, KeyType::Key8 }, { SDLK_9, KeyType::Key9 },
{ SDLK_a, KeyType::KeyA }, { SDLK_b, KeyType::KeyB },
{ SDLK_c, KeyType::KeyC }, { SDLK_d, KeyType::KeyD },
{ SDLK_e, KeyType::KeyE }, { SDLK_f, KeyType::KeyF },
{ SDLK_g, KeyType::KeyG }, { SDLK_h, KeyType::KeyH },
{ SDLK_i, KeyType::KeyI }, { SDLK_j, KeyType::KeyJ },
{ SDLK_k, KeyType::KeyK }, { SDLK_l, KeyType::KeyL },
{ SDLK_m, KeyType::KeyM }, { SDLK_n, KeyType::KeyN },
{ SDLK_o, KeyType::KeyO }, { SDLK_p, KeyType::KeyP },
{ SDLK_q, KeyType::KeyQ }, { SDLK_r, KeyType::KeyR },
{ SDLK_s, KeyType::KeyS }, { SDLK_t, KeyType::KeyT },
{ SDLK_u, KeyType::KeyU }, { SDLK_v, KeyType::KeyV },
{ SDLK_w, KeyType::KeyW }, { SDLK_x, KeyType::KeyX },
{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyZ },
{ SDLK_y, KeyType::KeyY }, { SDLK_z, KeyType::KeyAccent },
};
// Maps SDL_Event type to a KeyState type if applicable
inline KeyState get_sdl_key_state(SDL_Event& e) {
return e.type == SDL_KEYDOWN ? KeyState::KeyDown
: e.type == SDL_KEYUP ? KeyState::KeyUp : KeyState::KeyNone;
}
inline
inline String get_text_character(KeyEvent& keyEvent) {
auto keyStr = gc_keyTextMappings.at(keyEvent.key());
if(is_alpha_keystroke(keyEvent) && keyEvent.modifier() == KeyModiferType::KeyShift) {
return to_upper(keyStr);
}
return keyStr;
}
inline String get_key_event_string(KeyEvent& keyEvent) {
auto keyStr = to_upper(gc_keyTextMappings.at(keyEvent.key()));
auto modiferStr = to_upper(gc_keyModiferTextMappings.at(keyEvent.modifier()));
if(keyStr.length() > 0 && modiferStr.length() > 0) {
return modiferStr + "+" + keyStr;
} else if(keyStr.length() > 0) {
return keyStr;
} else if(modiferStr.length() > 0) {
return modiferStr;
} else {
return "\\none\\";
}
}
}<|endoftext|> |
<commit_before>#include "TableToTreeProxyModel.h"
#include <QItemSelection>
#include <QSqlQueryModel>
#include <QDebug>
#include <QStringList>
struct TreeNode {
TreeNode(int row=-1, int column=-1, TreeNode *parent=0)
: row(row), column(column), parent(parent)
{
if (parent)
parent->children.append(this);
};
int row;
int column;
TreeNode *parent;
QList<TreeNode*> children;
QString text;
};
TableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)
: QAbstractProxyModel(parent)
{
}
QModelIndex TableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());
Q_ASSERT(node);
if (!node)
return QModelIndex();
Q_ASSERT(false);
return index(sourceIndex.row(), 0);
}
QModelIndex TableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid())
return QModelIndex();
const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
Q_ASSERT(node);
if (!node)
return QModelIndex();
return sourceModel()->index(node->row, node->column);
}
QVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
if (!proxyIndex.isValid())
return QVariant();
const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
Q_ASSERT(node);
if (!node)
return QVariant();
const QModelIndex index = sourceModel()->index(node->row, node->column);
return sourceModel()->data(index, role);
}
QModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
const TreeNode *parentNode = static_cast<TreeNode*>(parent.internalPointer());
if (!parentNode)
parentNode = rootNode;
TreeNode *node = parentNode->children.at(row);
Q_ASSERT(node);
if (!node)
return QModelIndex();
return createIndex(row, column, node);
}
QModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
const TreeNode *childNode = static_cast<TreeNode*>(child.internalPointer());
Q_ASSERT(childNode);
if (!childNode)
return QModelIndex();
TreeNode *parentNode = childNode->parent;
Q_ASSERT(parentNode);
if (!parentNode)
return QModelIndex();
return createIndex(parentNode->row, parentNode->column, parentNode);
}
int TableToTreeProxyModel::rowCount(const QModelIndex &parent) const
{
const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
if (!node)
node = rootNode;
return node->children.size();
}
int TableToTreeProxyModel::columnCount(const QModelIndex &) const
{
return 1;
}
bool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const
{
const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
if (!node)
node = rootNode;
return node->children.size() > 0;
}
void TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
{
// TODO: cleanup on already existing
tableNodes.clear();
rootNode = new TreeNode;
for (int row=0; row < sourceModel->rowCount(); ++row) {
QList<TreeNode*> rowNodes;
TreeNode *previousNode = rootNode;
for (int column=0; column < sourceModel->columnCount(); ++column) {
const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();
TreeNode *node = 0;
foreach (TreeNode *siblingNode, previousNode->children) {
Q_ASSERT(siblingNode);
if (!siblingNode)
continue;
if (siblingNode->text == nodeText) {
node = siblingNode;
break;
}
}
if (!node) {
node = new TreeNode(row, column, previousNode);
node->text = nodeText;
}
rowNodes.insert(column, node);
previousNode = node;
}
tableNodes.insert(row, rowNodes);
}
QAbstractProxyModel::setSourceModel(sourceModel);
}
<commit_msg>Remove ugly tabs.<commit_after>#include "TableToTreeProxyModel.h"
#include <QItemSelection>
#include <QSqlQueryModel>
#include <QDebug>
#include <QStringList>
struct TreeNode {
TreeNode(int row=-1, int column=-1, TreeNode *parent=0)
: row(row), column(column), parent(parent)
{
if (parent)
parent->children.append(this);
};
int row;
int column;
TreeNode *parent;
QList<TreeNode*> children;
QString text;
};
TableToTreeProxyModel::TableToTreeProxyModel(QObject *parent)
: QAbstractProxyModel(parent)
{
}
QModelIndex TableToTreeProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
{
TreeNode *node = tableNodes.at(sourceIndex.column()).at(sourceIndex.row());
Q_ASSERT(node);
if (!node)
return QModelIndex();
Q_ASSERT(false);
return index(sourceIndex.row(), 0);
}
QModelIndex TableToTreeProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid())
return QModelIndex();
const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
Q_ASSERT(node);
if (!node)
return QModelIndex();
return sourceModel()->index(node->row, node->column);
}
QVariant TableToTreeProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
if (!proxyIndex.isValid())
return QVariant();
const TreeNode *node = static_cast<TreeNode*>(proxyIndex.internalPointer());
Q_ASSERT(node);
if (!node)
return QVariant();
const QModelIndex index = sourceModel()->index(node->row, node->column);
return sourceModel()->data(index, role);
}
QModelIndex TableToTreeProxyModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
const TreeNode *parentNode = static_cast<TreeNode*>(parent.internalPointer());
if (!parentNode)
parentNode = rootNode;
TreeNode *node = parentNode->children.at(row);
Q_ASSERT(node);
if (!node)
return QModelIndex();
return createIndex(row, column, node);
}
QModelIndex TableToTreeProxyModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
const TreeNode *childNode = static_cast<TreeNode*>(child.internalPointer());
Q_ASSERT(childNode);
if (!childNode)
return QModelIndex();
TreeNode *parentNode = childNode->parent;
Q_ASSERT(parentNode);
if (!parentNode)
return QModelIndex();
return createIndex(parentNode->row, parentNode->column, parentNode);
}
int TableToTreeProxyModel::rowCount(const QModelIndex &parent) const
{
const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
if (!node)
node = rootNode;
return node->children.size();
}
int TableToTreeProxyModel::columnCount(const QModelIndex &) const
{
return 1;
}
bool TableToTreeProxyModel::hasChildren(const QModelIndex &parent) const
{
const TreeNode *node = static_cast<TreeNode*>(parent.internalPointer());
if (!node)
node = rootNode;
return node->children.size() > 0;
}
void TableToTreeProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
{
// TODO: cleanup on already existing
tableNodes.clear();
rootNode = new TreeNode;
for (int row=0; row < sourceModel->rowCount(); ++row) {
QList<TreeNode*> rowNodes;
TreeNode *previousNode = rootNode;
for (int column=0; column < sourceModel->columnCount(); ++column) {
const QString &nodeText = sourceModel->data(sourceModel->index(row, column)).toString();
TreeNode *node = 0;
foreach (TreeNode *siblingNode, previousNode->children) {
Q_ASSERT(siblingNode);
if (!siblingNode)
continue;
if (siblingNode->text == nodeText) {
node = siblingNode;
break;
}
}
if (!node) {
node = new TreeNode(row, column, previousNode);
node->text = nodeText;
}
rowNodes.insert(column, node);
previousNode = node;
}
tableNodes.insert(row, rowNodes);
}
QAbstractProxyModel::setSourceModel(sourceModel);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
// Are included by FileUtility.hpp
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "compare dirname [-out -gold]"
<< endl
<< endl
<< "dirname (base directory for testcases)"
<< endl
<< "-out dirname (base directory for output)"
<< endl
<< "-gold dirname (base directory for gold files)"
<< endl;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
{
int transResult = 0;
bool setGold = true;
XalanDOMString fileName;
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "DOMCOM-RESULTS", setGold) == true)
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultFilePrefix("cpp");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Comparison Testing:");
// Specify the "test" directory for both input and output.
//
const XalanDOMString currentDir("domcomtests");
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Get the files found in the test directory
//
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
fileName = files[i];
h.data.reset();
h.data.testOrFile = fileName;
const XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + fileName;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + fileName;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + fileName;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
// Use a XalanSourceTreeDocument to create the XSLTResultTarget.
//
XalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();
FormatterToSourceTree domOut(dom);
XSLTResultTarget domResultTarget;
domResultTarget.setDocumentHandler(&domOut);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
continue;
}
// Parsing the input XML and report the results..
//
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
continue;
}
// Perform One transform using parsed stylesheet and unparsed xml source, report results...
//
xalan.transform(*parsedSource, compiledSS, domResultTarget);
h.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("DomCom ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
XalanTransformer::terminate();
return 0;
}
<commit_msg>Clean of includes.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
#include <XalanSourceTree/FormatterToSourceTree.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
void
setHelp(FileUtility& h)
{
h.args.getHelpStream() << endl
<< "compare dirname [-out -gold]"
<< endl
<< endl
<< "dirname (base directory for testcases)"
<< endl
<< "-out dirname (base directory for output)"
<< endl
<< "-gold dirname (base directory for gold files)"
<< endl;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
{
FileUtility h;
int transResult = 0;
bool setGold = true;
XalanDOMString fileName;
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "DOMCOM-RESULTS", setGold) == true)
{
XalanTransformer::initialize();
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultFilePrefix("cpp");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Comparison Testing:");
// Specify the "test" directory for both input and output.
//
const XalanDOMString currentDir("domcomtests");
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Get the files found in the test directory
//
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
fileName = files[i];
h.data.reset();
h.data.testOrFile = fileName;
const XalanDOMString theXSLFile= h.args.base + currentDir + FileUtility::s_pathSep + fileName;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + fileName;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + FileUtility::s_pathSep + fileName;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
// Use a XalanSourceTreeDocument to create the XSLTResultTarget.
//
XalanSourceTreeDocument* dom = parserLiaison.createXalanSourceTreeDocument();
FormatterToSourceTree domOut(dom);
XSLTResultTarget domResultTarget;
domResultTarget.setDocumentHandler(&domOut);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
continue;
}
// Parsing the input XML and report the results..
//
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
continue;
}
// Perform One transform using parsed stylesheet and unparsed xml source, report results...
//
xalan.transform(*parsedSource, compiledSS, domResultTarget);
h.checkDOMResults(theOutputFile, compiledSS, dom, goldInputSource, logFile);
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("DomCom ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
XalanTransformer::terminate();
}
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliVZERODataDCS.h"
#include "AliDCSValue.h"
#include "AliLog.h"
#include <TGraph.h>
#include <TAxis.h>
#include <TCanvas.h>
#include <TTimeStamp.h>
#include <TMap.h>
#include <TString.h>
#include <TH1F.h>
class TH2;
class AliCDBMetaData;
class TDatime;
// AliVZERODataDCS class
// main aim to introduce the aliases for the VZERO DCS
// data points to be then
// stored in the OCDB, and to process them.
// ProcessData() method called by VZEROPreprocessor
ClassImp(AliVZERODataDCS)
//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS():
TObject(),
fRun(0),
fStartTime(0),
fEndTime(0),
fGraphs("TGraph",kNGraphs),
fIsProcessed(kFALSE)
{
// Default constructor
for(int i=0;i<kNHvChannel;i++) fDeadChannel[i] = kFALSE;
}
//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS(Int_t nRun, UInt_t startTime, UInt_t endTime):
TObject(),
fRun(nRun),
fStartTime(startTime),
fEndTime(endTime),
fGraphs("TGraph",kNGraphs),
fIsProcessed(kFALSE)
{
// constructor with arguments
for(int i=0;i<kNHvChannel;i++) fDeadChannel[i] = kFALSE;
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", nRun,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
Init();
}
//_____________________________________________________________________________
AliVZERODataDCS::~AliVZERODataDCS() {
// destructor
fGraphs.Clear("C");
}
//_____________________________________________________________________________
void AliVZERODataDCS::ProcessData(TMap& aliasMap){
// method to process the data
if(!(fAliasNames[0])) Init();
TObjArray *aliasArr;
AliDCSValue* aValue;
// starting loop on aliases
for(int iAlias=0; iAlias<kNAliases; iAlias++){
aliasArr = (TObjArray*) aliasMap.GetValue(fAliasNames[iAlias].Data());
if(!aliasArr){
AliError(Form("Alias %s not found!", fAliasNames[iAlias].Data()));
return;
}
//Introduce(iAlias, aliasArr);
if(aliasArr->GetEntries()<2){
AliError(Form("Alias %s has just %d entries!",
fAliasNames[iAlias].Data(),aliasArr->GetEntries()));
continue;
}
TIter iterarray(aliasArr);
Int_t nentries = aliasArr->GetEntries();
Double_t *times = new Double_t[nentries];
Double_t *values = new Double_t[nentries];
UInt_t iValue=0;
while((aValue = (AliDCSValue*) iterarray.Next())) {
values[iValue] = aValue->GetFloat();
if(iValue>0) {
Float_t variation ;
if(values[iValue-1]>0.) variation = TMath::Abs(values[iValue]-values[iValue-1])/values[iValue-1];
if(variation > 0.10) fDeadChannel[GetOfflineChannel(iAlias)] = kTRUE;
}
times[iValue] = (Double_t) (aValue->GetTimeStamp());
fHv[iAlias]->Fill(values[iValue]);
printf("%s %f Dead=%d\n",fAliasNames[iAlias].Data(),values[iValue],fDeadChannel[GetOfflineChannel(iAlias)]);
iValue++;
}
CreateGraph(iAlias, aliasArr->GetEntries(), times, values); // fill graphs
delete[] values;
delete[] times;
}
// calculate mean and rms of the first two histos
// and convert index to aliroot channel
for(int i=0;i<kNAliases;i++){
Int_t iChannel = GetOfflineChannel(i);
fMeanHV[iChannel] = fHv[i]->GetMean();
fWidthHV[iChannel] = fHv[i]->GetRMS();
}
fIsProcessed=kTRUE;
}
//_____________________________________________________________________________
void AliVZERODataDCS::Init(){
// initialization of aliases and DCS data
TString sindex;
int iAlias = 0;
for(int iSide = 0; iSide<2 ; iSide++){
for(int iRing = 0; iRing<4 ; iRing++){
for(int iSector = 0; iSector<8 ; iSector++){
if(iSide == 0) fAliasNames[iAlias] = "V00/HV/V0A/SECTOR";
else fAliasNames[iAlias] = "V00/HV/V0C/SECTOR";
sindex.Form("%d/RING%d",iSector,iRing);
fAliasNames[iAlias] += sindex;
fHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);
fHv[iAlias]->GetXaxis()->SetTitle("Hv");
iAlias++;
}
}
}
if(iAlias!=kNAliases)
AliError(Form("Number of DCS Aliases defined not correct"));
}
//_____________________________________________________________________________
void AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const
{
// method to introduce new aliases
int entries=aliasArr->GetEntries();
AliInfo(Form("************ Alias: %s **********",fAliasNames[numAlias].Data()));
AliInfo(Form(" %d DP values collected",entries));
}
//_____________________________________________________________________________
void AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)
{
// Create graphics
TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);
gr->GetXaxis()->SetTimeDisplay(1);
gr->SetTitle(fAliasNames[i].Data());
AliInfo(Form("Array entries: %d",fGraphs.GetEntriesFast()));
}
//_____________________________________________________________________________
void AliVZERODataDCS::Draw(const Option_t* /*option*/)
{
// Draw all histos and graphs
if(!fIsProcessed) return;
if(fGraphs.GetEntries()==0) return;
TString canvasName;
TCanvas *cHV[8];
for(int iSide = 0 ;iSide<2;iSide++){
for(int iRing=0;iRing<4;iRing++){
if(iSide == 0) canvasName = "V0A_Ring";
else canvasName = "V0C_Ring";
canvasName += iRing;
int iCanvas = iSide*4 + iRing;
cHV[iCanvas] = new TCanvas(canvasName,canvasName);
cHV[iCanvas]->Divide(3,3);
for(int iSector=0;iSector<8;iSector++){
cHV[iCanvas]->cd(iSector+1);
int iChannel = iSide*32 + iRing*8 + iSector;
((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);
((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw("ALP");
}
}
}
}
<commit_msg>Warning fixed<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliVZERODataDCS.h"
#include "AliDCSValue.h"
#include "AliLog.h"
#include <TGraph.h>
#include <TAxis.h>
#include <TCanvas.h>
#include <TTimeStamp.h>
#include <TMap.h>
#include <TString.h>
#include <TH1F.h>
class TH2;
class AliCDBMetaData;
class TDatime;
// AliVZERODataDCS class
// main aim to introduce the aliases for the VZERO DCS
// data points to be then
// stored in the OCDB, and to process them.
// ProcessData() method called by VZEROPreprocessor
ClassImp(AliVZERODataDCS)
//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS():
TObject(),
fRun(0),
fStartTime(0),
fEndTime(0),
fGraphs("TGraph",kNGraphs),
fIsProcessed(kFALSE)
{
// Default constructor
for(int i=0;i<kNHvChannel;i++) fDeadChannel[i] = kFALSE;
}
//_____________________________________________________________________________
AliVZERODataDCS::AliVZERODataDCS(Int_t nRun, UInt_t startTime, UInt_t endTime):
TObject(),
fRun(nRun),
fStartTime(startTime),
fEndTime(endTime),
fGraphs("TGraph",kNGraphs),
fIsProcessed(kFALSE)
{
// constructor with arguments
for(int i=0;i<kNHvChannel;i++) fDeadChannel[i] = kFALSE;
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", nRun,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
Init();
}
//_____________________________________________________________________________
AliVZERODataDCS::~AliVZERODataDCS() {
// destructor
fGraphs.Clear("C");
}
//_____________________________________________________________________________
void AliVZERODataDCS::ProcessData(TMap& aliasMap){
// method to process the data
if(!(fAliasNames[0])) Init();
TObjArray *aliasArr;
AliDCSValue* aValue;
// starting loop on aliases
for(int iAlias=0; iAlias<kNAliases; iAlias++){
aliasArr = (TObjArray*) aliasMap.GetValue(fAliasNames[iAlias].Data());
if(!aliasArr){
AliError(Form("Alias %s not found!", fAliasNames[iAlias].Data()));
return;
}
//Introduce(iAlias, aliasArr);
if(aliasArr->GetEntries()<2){
AliError(Form("Alias %s has just %d entries!",
fAliasNames[iAlias].Data(),aliasArr->GetEntries()));
continue;
}
TIter iterarray(aliasArr);
Int_t nentries = aliasArr->GetEntries();
Double_t *times = new Double_t[nentries];
Double_t *values = new Double_t[nentries];
UInt_t iValue=0;
Float_t variation = 0.0;
while((aValue = (AliDCSValue*) iterarray.Next())) {
values[iValue] = aValue->GetFloat();
if(iValue>0) {
if(values[iValue-1]>0.) variation = TMath::Abs(values[iValue]-values[iValue-1])/values[iValue-1];
if(variation > 0.10) fDeadChannel[GetOfflineChannel(iAlias)] = kTRUE;
}
times[iValue] = (Double_t) (aValue->GetTimeStamp());
fHv[iAlias]->Fill(values[iValue]);
printf("%s %f Dead=%d\n",fAliasNames[iAlias].Data(),values[iValue],fDeadChannel[GetOfflineChannel(iAlias)]);
iValue++;
}
CreateGraph(iAlias, aliasArr->GetEntries(), times, values); // fill graphs
delete[] values;
delete[] times;
}
// calculate mean and rms of the first two histos
// and convert index to aliroot channel
for(int i=0;i<kNAliases;i++){
Int_t iChannel = GetOfflineChannel(i);
fMeanHV[iChannel] = fHv[i]->GetMean();
fWidthHV[iChannel] = fHv[i]->GetRMS();
}
fIsProcessed=kTRUE;
}
//_____________________________________________________________________________
void AliVZERODataDCS::Init(){
// initialization of aliases and DCS data
TString sindex;
int iAlias = 0;
for(int iSide = 0; iSide<2 ; iSide++){
for(int iRing = 0; iRing<4 ; iRing++){
for(int iSector = 0; iSector<8 ; iSector++){
if(iSide == 0) fAliasNames[iAlias] = "V00/HV/V0A/SECTOR";
else fAliasNames[iAlias] = "V00/HV/V0C/SECTOR";
sindex.Form("%d/RING%d",iSector,iRing);
fAliasNames[iAlias] += sindex;
fHv[iAlias] = new TH1F(fAliasNames[iAlias].Data(),fAliasNames[iAlias].Data(), 2000, kHvMin, kHvMax);
fHv[iAlias]->GetXaxis()->SetTitle("Hv");
iAlias++;
}
}
}
if(iAlias!=kNAliases)
AliError(Form("Number of DCS Aliases defined not correct"));
}
//_____________________________________________________________________________
void AliVZERODataDCS::Introduce(UInt_t numAlias, const TObjArray* aliasArr)const
{
// method to introduce new aliases
int entries=aliasArr->GetEntries();
AliInfo(Form("************ Alias: %s **********",fAliasNames[numAlias].Data()));
AliInfo(Form(" %d DP values collected",entries));
}
//_____________________________________________________________________________
void AliVZERODataDCS::CreateGraph(int i, int dim, const Double_t *x, const Double_t *y)
{
// Create graphics
TGraph *gr = new(fGraphs[fGraphs.GetEntriesFast()]) TGraph(dim, x, y);
gr->GetXaxis()->SetTimeDisplay(1);
gr->SetTitle(fAliasNames[i].Data());
AliInfo(Form("Array entries: %d",fGraphs.GetEntriesFast()));
}
//_____________________________________________________________________________
void AliVZERODataDCS::Draw(const Option_t* /*option*/)
{
// Draw all histos and graphs
if(!fIsProcessed) return;
if(fGraphs.GetEntries()==0) return;
TString canvasName;
TCanvas *cHV[8];
for(int iSide = 0 ;iSide<2;iSide++){
for(int iRing=0;iRing<4;iRing++){
if(iSide == 0) canvasName = "V0A_Ring";
else canvasName = "V0C_Ring";
canvasName += iRing;
int iCanvas = iSide*4 + iRing;
cHV[iCanvas] = new TCanvas(canvasName,canvasName);
cHV[iCanvas]->Divide(3,3);
for(int iSector=0;iSector<8;iSector++){
cHV[iCanvas]->cd(iSector+1);
int iChannel = iSide*32 + iRing*8 + iSector;
((TGraph*) fGraphs.UncheckedAt(iChannel))->SetMarkerStyle(20);
((TGraph*) fGraphs.UncheckedAt(iChannel))->Draw("ALP");
}
}
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
ViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);
}
ViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);
}
ViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);
}
DropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)
{
m_ulDropList = ulDropList;
m_lpuidDropList = lpuidDropList;
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
m_lpnaeDropList = lpnaeDropList;
m_bGUID = bGUID;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
wstring GetLBText(CComboBox& box, int nIndex)
{
auto len = box.GetLBTextLen(nIndex);
auto buffer = new TCHAR[len];
memset(buffer, 0, sizeof(TCHAR)* len);
box.GetLBText(nIndex, buffer);
auto szOut = LPCTSTRToWstring(buffer);
delete[] buffer;
return szOut;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
SIZE sizeDrop = { 0 };
auto szDropString = GetLBText(m_DropDown, iDropString);
::GetTextExtentPoint32W(hdc, szDropString.c_str(), szDropString.length(), &sizeDrop);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, dropHeight),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
DoInit(iControl, pParent, hdc);
if (m_lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = loadstring(m_lpuidDropList[iDropNum]);
InsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);
}
}
else if (m_lpnaeDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);
InsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);
}
}
// If this is a GUID list, load up our list of guids
if (m_bGUID)
{
for (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)
{
InsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue)
{
m_DropDown.InsertString(iRow, wstringToCString(szText));
m_DropDown.SetItemData(iRow, ulValue);
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
CString szText;
m_DropDown.GetWindowText(szText);
return LPCTSTRToWstring(szText);
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const
{
if (!lpSelectedGUID) return NULL;
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
memcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));
return true;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
memcpy(lpSelectedGUID, lpGUID, sizeof(GUID));
delete[] lpGUID;
return true;
}
return false;
}
void DropDownPane::SetDropDownSelection(_In_ wstring szText)
{
auto hRes = S_OK;
auto text = wstringToCString(szText);
auto iSelect = m_DropDown.SelectString(0, text);
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<commit_msg>kill final CString variable<commit_after>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
ViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);
}
ViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);
}
ViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);
}
DropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)
{
m_ulDropList = ulDropList;
m_lpuidDropList = lpuidDropList;
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
m_lpnaeDropList = lpnaeDropList;
m_bGUID = bGUID;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
wstring GetLBText(const CComboBox& box, int nIndex)
{
auto len = box.GetLBTextLen(nIndex) + 1;
auto buffer = new TCHAR[len];
memset(buffer, 0, sizeof(TCHAR)* len);
box.GetLBText(nIndex, buffer);
auto szOut = LPCTSTRToWstring(buffer);
delete[] buffer;
return szOut;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
SIZE sizeDrop = { 0 };
auto szDropString = GetLBText(m_DropDown, iDropString);
::GetTextExtentPoint32W(hdc, szDropString.c_str(), szDropString.length(), &sizeDrop);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, dropHeight),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
DoInit(iControl, pParent, hdc);
if (m_lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = loadstring(m_lpuidDropList[iDropNum]);
InsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);
}
}
else if (m_lpnaeDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);
InsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);
}
}
// If this is a GUID list, load up our list of guids
if (m_bGUID)
{
for (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)
{
InsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue)
{
m_DropDown.InsertString(iRow, wstringToCString(szText));
m_DropDown.SetItemData(iRow, ulValue);
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
auto len = m_DropDown.GetWindowTextLength() + 1;
auto buffer = new WCHAR[len];
memset(buffer, 0, sizeof(WCHAR)* len);
::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);
wstring szOut = buffer;
delete[] buffer;
return szOut;
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const
{
if (!lpSelectedGUID) return NULL;
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
memcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));
return true;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
memcpy(lpSelectedGUID, lpGUID, sizeof(GUID));
delete[] lpGUID;
return true;
}
return false;
}
void DropDownPane::SetDropDownSelection(_In_ wstring szText)
{
auto hRes = S_OK;
auto text = wstringToCString(szText);
auto iSelect = m_DropDown.SelectString(0, text);
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
DropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane && lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)
{
pane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)
{
pane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane::DropDownPane()
{
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
auto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);
auto sizeDrop = GetTextExtentPoint32(hdc, szDropString);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (!m_szLabel.empty())
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
iHeight += m_iLargeHeightMargin; // Bottom margin
return iHeight;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
}
if (!m_szLabel.empty())
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
}
// Note - Real height of a combo box is fixed at m_iEditHeight
// Height we set here influences the amount of dropdown entries we see
// This will give us something between 4 and 10 entries
ULONG ulDrops = min(10, 1 + max(m_DropList.size(), 4));
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight * ulDrops, SWP_NOZORDER));
}
void DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| CBS_NOINTEGRALHEIGHT
| dwDropStyle,
CRect(0, 0, 0, static_cast<int>(dropHeight)),
pParent,
m_nID));
SendMessage(m_DropDown.m_hWnd, WM_SETFONT, reinterpret_cast<WPARAM>(GetSegoeFont()), false);
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
CreateControl(iControl, pParent, hdc);
auto iDropNum = 0;
for (const auto& drop : m_DropList)
{
m_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());
m_DropDown.SetItemData(iDropNum, drop.second);
iDropNum++;
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
SetDropDownSelection(m_lpszSelectionString);
}
void DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)
{
m_DropList.push_back({ szText, ulValue });
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
auto len = m_DropDown.GetWindowTextLength() + 1;
auto buffer = new WCHAR[len];
memset(buffer, 0, sizeof(WCHAR)* len);
GetWindowTextW(m_DropDown.m_hWnd, buffer, len);
wstring szOut = buffer;
delete[] buffer;
return szOut;
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const
{
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
return *PropGuidArray[iCurSel].lpGuid;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
auto guid = *lpGUID;
delete[] lpGUID;
return guid;
}
return{ 0 };
}
void DropDownPane::SetDropDownSelection(_In_ const wstring& szText)
{
m_lpszSelectionString = szText;
if (!m_bInitialized) return;
auto hRes = S_OK;
auto text = wstringTotstring(m_lpszSelectionString);
auto iSelect = m_DropDown.SelectString(0, text.c_str());
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text.c_str()))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<commit_msg>Use better type for unicode<commit_after>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
DropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane && lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)
{
pane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)
{
pane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane::DropDownPane()
{
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
auto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);
auto sizeDrop = GetTextExtentPoint32(hdc, szDropString);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (!m_szLabel.empty())
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
iHeight += m_iLargeHeightMargin; // Bottom margin
return iHeight;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
}
if (!m_szLabel.empty())
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
}
// Note - Real height of a combo box is fixed at m_iEditHeight
// Height we set here influences the amount of dropdown entries we see
// This will give us something between 4 and 10 entries
auto ulDrops = static_cast<int>(min(10, 1 + max(m_DropList.size(), 4)));
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight * ulDrops, SWP_NOZORDER));
}
void DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| CBS_NOINTEGRALHEIGHT
| dwDropStyle,
CRect(0, 0, 0, static_cast<int>(dropHeight)),
pParent,
m_nID));
SendMessage(m_DropDown.m_hWnd, WM_SETFONT, reinterpret_cast<WPARAM>(GetSegoeFont()), false);
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
CreateControl(iControl, pParent, hdc);
auto iDropNum = 0;
for (const auto& drop : m_DropList)
{
m_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());
m_DropDown.SetItemData(iDropNum, drop.second);
iDropNum++;
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
SetDropDownSelection(m_lpszSelectionString);
}
void DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)
{
m_DropList.push_back({ szText, ulValue });
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
auto len = m_DropDown.GetWindowTextLength() + 1;
auto buffer = new WCHAR[len];
memset(buffer, 0, sizeof(WCHAR)* len);
GetWindowTextW(m_DropDown.m_hWnd, buffer, len);
wstring szOut = buffer;
delete[] buffer;
return szOut;
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const
{
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
return *PropGuidArray[iCurSel].lpGuid;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
auto guid = *lpGUID;
delete[] lpGUID;
return guid;
}
return{ 0 };
}
void DropDownPane::SetDropDownSelection(_In_ const wstring& szText)
{
m_lpszSelectionString = szText;
if (!m_bInitialized) return;
auto hRes = S_OK;
auto text = wstringTotstring(m_lpszSelectionString);
auto iSelect = m_DropDown.SelectString(0, text.c_str());
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text.c_str()))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
DropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)
{
pane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)
{
pane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane::DropDownPane()
{
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
auto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);
auto sizeDrop = GetTextExtentPoint32(hdc, szDropString);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, dropHeight),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
CreateControl(iControl, pParent, hdc);
auto iDropNum = 0;
for (auto drop : m_DropList)
{
m_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());
m_DropDown.SetItemData(iDropNum, drop.second);
iDropNum++;
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)
{
m_DropList.push_back({ szText, ulValue });
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
auto len = m_DropDown.GetWindowTextLength() + 1;
auto buffer = new WCHAR[len];
memset(buffer, 0, sizeof(WCHAR)* len);
::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);
wstring szOut = buffer;
delete[] buffer;
return szOut;
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const
{
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
return *PropGuidArray[iCurSel].lpGuid;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
auto guid = *lpGUID;
delete[] lpGUID;
return guid;
}
return{ 0 };
}
void DropDownPane::SetDropDownSelection(_In_ const wstring& szText)
{
auto hRes = S_OK;
auto text = wstringTotstring(szText);
auto iSelect = m_DropDown.SelectString(0, text.c_str());
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text.c_str()))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<commit_msg>Casting issue<commit_after>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
DropDownPane* DropDownPane::Create(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < ulDropList; iDropNum++)
{
pane->InsertDropString(loadstring(lpuidDropList[iDropNum]), lpuidDropList[iDropNum]);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane* DropDownPane::CreateGuid(UINT uidLabel, bool bReadOnly)
{
auto pane = new DropDownPane();
if (pane)
{
for (ULONG iDropNum = 0; iDropNum < PropGuidArray.size(); iDropNum++)
{
pane->InsertDropString(GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
pane->SetLabel(uidLabel, bReadOnly);
}
return pane;
}
DropDownPane::DropDownPane()
{
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
auto szDropString = GetLBText(m_DropDown.m_hWnd, iDropString);
auto sizeDrop = GetTextExtentPoint32(hdc, szDropString);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::CreateControl(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_DropList.size() ? min(m_DropList.size(), 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_HASSTRINGS
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, static_cast<int>(dropHeight)),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
CreateControl(iControl, pParent, hdc);
auto iDropNum = 0;
for (auto drop : m_DropList)
{
m_DropDown.InsertString(iDropNum, wstringTotstring(drop.first).c_str());
m_DropDown.SetItemData(iDropNum, drop.second);
iDropNum++;
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(_In_ const wstring& szText, ULONG ulValue)
{
m_DropList.push_back({ szText, ulValue });
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
auto len = m_DropDown.GetWindowTextLength() + 1;
auto buffer = new WCHAR[len];
memset(buffer, 0, sizeof(WCHAR)* len);
::GetWindowTextW(m_DropDown.m_hWnd, buffer, len);
wstring szOut = buffer;
delete[] buffer;
return szOut;
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ GUID DropDownPane::GetSelectedGUID(bool bByteSwapped) const
{
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
return *PropGuidArray[iCurSel].lpGuid;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
auto guid = *lpGUID;
delete[] lpGUID;
return guid;
}
return{ 0 };
}
void DropDownPane::SetDropDownSelection(_In_ const wstring& szText)
{
auto hRes = S_OK;
auto text = wstringTotstring(szText);
auto iSelect = m_DropDown.SelectString(0, text.c_str());
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text.c_str()))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<|endoftext|> |
<commit_before>/* Copyright 2020 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 <memory>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_kernel.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_mock_test.h"
#include "tensorflow/lite/experimental/acceleration/configuration/configuration_generated.h"
#include "tensorflow/lite/experimental/acceleration/configuration/delegate_registry.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/test_util.h"
// Tests for checking that the NNAPI Delegate plugin correctly handles all the
// options from the flatbuffer.
//
// Checking done at NNAPI call level, as that is where we have a mockable
// layer.
namespace tflite {
namespace {
using delegate::nnapi::NnApiMock;
class SingleAddOpModel : tflite::SingleOpModel {
public:
void Build() {
int input = AddInput({tflite::TensorType_FLOAT32, {1, 2, 2}});
int constant = AddConstInput({tflite::TensorType_FLOAT32, {1, 2, 2}},
{1.0f, 1.0f, 1.0f, 1.0f});
AddOutput({tflite::TensorType_FLOAT32, {}});
SetBuiltinOp(tflite::BuiltinOperator_ADD, tflite::BuiltinOptions_AddOptions,
tflite::CreateAddOptions(builder_).Union());
BuildInterpreter({GetShape(input), GetShape(constant)});
}
tflite::Interpreter* Interpreter() const { return interpreter_.get(); }
};
class NNAPIPluginTest : public ::testing::Test {
protected:
NNAPIPluginTest() : delegate_(nullptr, [](TfLiteDelegate*) {}) {}
void SetUp() override {
nnapi_ = const_cast<NnApi*>(NnApiImplementation());
nnapi_mock_ = absl::make_unique<NnApiMock>(nnapi_);
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
return 0;
};
model_.Build();
}
template <NNAPIExecutionPreference input, int output>
void CheckExecutionPreference() {
// Note - this uses a template since the NNAPI functions are C function
// pointers rather than lambdas so can't capture variables.
nnapi_->ANeuralNetworksCompilation_setPreference =
[](ANeuralNetworksCompilation* compilation, int32_t preference) {
return preference - output;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0, input));
// Since delegation succeeds, the model becomes immutable and hence can't
// reuse it.
SingleAddOpModel model;
model.Build();
EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk)
<< " given input: " << input << " expected output: " << output;
}
template <NNAPIExecutionPriority input, int output>
void CheckExecutionPriority() {
// Note - this uses a template since the NNAPI functions are C function
// pointers rather than lambdas so can't capture variables.
nnapi_->ANeuralNetworksCompilation_setPriority =
[](ANeuralNetworksCompilation* compilation, int32_t priority) {
return priority - output;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/*allow CPU=*/true, input));
// Since delegation succeeds, the model becomes immutable and hence can't
// reuse it.
SingleAddOpModel model;
model.Build();
EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk)
<< " given input: " << input << " expected output: " << output;
}
void CreateDelegate(flatbuffers::Offset<NNAPISettings> settings) {
settings_ = flatbuffers::GetTemporaryPointer(
fbb_, CreateTFLiteSettings(fbb_, tflite::Delegate_NNAPI, settings));
plugin_ = delegates::DelegatePluginRegistry::CreateByName("NnapiPlugin",
*settings_);
delegate_ = plugin_->Create();
}
NnApi* nnapi_;
std::unique_ptr<NnApiMock> nnapi_mock_;
SingleAddOpModel model_;
flatbuffers::FlatBufferBuilder fbb_;
const TFLiteSettings* settings_ = nullptr;
delegates::TfLiteDelegatePtr delegate_;
std::unique_ptr<delegates::DelegatePluginInterface> plugin_;
};
TEST_F(NNAPIPluginTest, PassesAcceleratorName) {
// Fails with non-existent "foo".
CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString("foo")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteDelegateError);
// Succeeds with "test-device" supported by the mock.
CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString("test-device")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesExecutionPreference) {
CheckExecutionPreference<NNAPIExecutionPreference_UNDEFINED,
StatefulNnApiDelegate::Options::kUndefined>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_LOW_POWER,
StatefulNnApiDelegate::Options::kLowPower>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_FAST_SINGLE_ANSWER,
StatefulNnApiDelegate::Options::kFastSingleAnswer>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_SUSTAINED_SPEED,
StatefulNnApiDelegate::Options::kSustainedSpeed>();
}
TEST_F(NNAPIPluginTest, PassesExecutionPriority) {
nnapi_->android_sdk_version =
tflite::delegate::nnapi::kMinSdkVersionForNNAPI13;
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_UNDEFINED,
ANEURALNETWORKS_PRIORITY_DEFAULT>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_LOW,
ANEURALNETWORKS_PRIORITY_LOW>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_MEDIUM,
ANEURALNETWORKS_PRIORITY_MEDIUM>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_HIGH,
ANEURALNETWORKS_PRIORITY_HIGH>();
}
TEST_F(NNAPIPluginTest, PassesCachingParameters) {
nnapi_->ANeuralNetworksCompilation_setCaching =
[](ANeuralNetworksCompilation* compilation, const char* cacheDir,
const uint8_t* token) -> int {
if (std::string(cacheDir) != "d") return 1;
// Token is hashed with other bits, just check that it's not empty.
if (std::string(reinterpret_cast<const char*>(token)).empty()) return 2;
return 0;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, fbb_.CreateString("d"),
fbb_.CreateString("t")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesFalseNNAPICpuFlag) {
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/* allow CPU */ false));
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
// Since no CPU, should only pass one device.
return numDevices - 1;
};
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesTrueNNAPICpuFlag) {
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/* allow CPU */ true));
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
// With CPU allowed, should pass two devices.
return numDevices - 2;
};
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
} // namespace
} // namespace tflite
<commit_msg>Skip applying TfLite default delegates for the nnapi_plugin_test.<commit_after>/* Copyright 2020 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 <memory>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_kernel.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_mock_test.h"
#include "tensorflow/lite/experimental/acceleration/configuration/configuration_generated.h"
#include "tensorflow/lite/experimental/acceleration/configuration/delegate_registry.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/test_util.h"
// Tests for checking that the NNAPI Delegate plugin correctly handles all the
// options from the flatbuffer.
//
// Checking done at NNAPI call level, as that is where we have a mockable
// layer.
namespace tflite {
namespace {
using delegate::nnapi::NnApiMock;
class SingleAddOpModel : tflite::SingleOpModel {
public:
void Build() {
int input = AddInput({tflite::TensorType_FLOAT32, {1, 2, 2}});
int constant = AddConstInput({tflite::TensorType_FLOAT32, {1, 2, 2}},
{1.0f, 1.0f, 1.0f, 1.0f});
AddOutput({tflite::TensorType_FLOAT32, {}});
SetBuiltinOp(tflite::BuiltinOperator_ADD, tflite::BuiltinOptions_AddOptions,
tflite::CreateAddOptions(builder_).Union());
// Set apply_delegate to false to skip applying TfLite default delegates.
BuildInterpreter({GetShape(input), GetShape(constant)},
/*num_threads=*/-1,
/*allow_fp32_relax_to_fp16=*/false,
/*apply_delegate=*/false,
/*allocate_and_delegate=*/true);
}
tflite::Interpreter* Interpreter() const { return interpreter_.get(); }
};
class NNAPIPluginTest : public ::testing::Test {
protected:
NNAPIPluginTest() : delegate_(nullptr, [](TfLiteDelegate*) {}) {}
void SetUp() override {
nnapi_ = const_cast<NnApi*>(NnApiImplementation());
nnapi_mock_ = absl::make_unique<NnApiMock>(nnapi_);
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
return 0;
};
model_.Build();
}
template <NNAPIExecutionPreference input, int output>
void CheckExecutionPreference() {
// Note - this uses a template since the NNAPI functions are C function
// pointers rather than lambdas so can't capture variables.
nnapi_->ANeuralNetworksCompilation_setPreference =
[](ANeuralNetworksCompilation* compilation, int32_t preference) {
return preference - output;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0, input));
// Since delegation succeeds, the model becomes immutable and hence can't
// reuse it.
SingleAddOpModel model;
model.Build();
EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk)
<< " given input: " << input << " expected output: " << output;
}
template <NNAPIExecutionPriority input, int output>
void CheckExecutionPriority() {
// Note - this uses a template since the NNAPI functions are C function
// pointers rather than lambdas so can't capture variables.
nnapi_->ANeuralNetworksCompilation_setPriority =
[](ANeuralNetworksCompilation* compilation, int32_t priority) {
return priority - output;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/*allow CPU=*/true, input));
// Since delegation succeeds, the model becomes immutable and hence can't
// reuse it.
SingleAddOpModel model;
model.Build();
EXPECT_EQ(model.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk)
<< " given input: " << input << " expected output: " << output;
}
void CreateDelegate(flatbuffers::Offset<NNAPISettings> settings) {
settings_ = flatbuffers::GetTemporaryPointer(
fbb_, CreateTFLiteSettings(fbb_, tflite::Delegate_NNAPI, settings));
plugin_ = delegates::DelegatePluginRegistry::CreateByName("NnapiPlugin",
*settings_);
delegate_ = plugin_->Create();
}
NnApi* nnapi_;
std::unique_ptr<NnApiMock> nnapi_mock_;
SingleAddOpModel model_;
flatbuffers::FlatBufferBuilder fbb_;
const TFLiteSettings* settings_ = nullptr;
delegates::TfLiteDelegatePtr delegate_;
std::unique_ptr<delegates::DelegatePluginInterface> plugin_;
};
TEST_F(NNAPIPluginTest, PassesAcceleratorName) {
// Fails with non-existent "foo".
CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString("foo")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteDelegateError);
// Succeeds with "test-device" supported by the mock.
CreateDelegate(CreateNNAPISettings(fbb_, fbb_.CreateString("test-device")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesExecutionPreference) {
CheckExecutionPreference<NNAPIExecutionPreference_UNDEFINED,
StatefulNnApiDelegate::Options::kUndefined>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_LOW_POWER,
StatefulNnApiDelegate::Options::kLowPower>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_FAST_SINGLE_ANSWER,
StatefulNnApiDelegate::Options::kFastSingleAnswer>();
CheckExecutionPreference<NNAPIExecutionPreference_NNAPI_SUSTAINED_SPEED,
StatefulNnApiDelegate::Options::kSustainedSpeed>();
}
TEST_F(NNAPIPluginTest, PassesExecutionPriority) {
nnapi_->android_sdk_version =
tflite::delegate::nnapi::kMinSdkVersionForNNAPI13;
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_UNDEFINED,
ANEURALNETWORKS_PRIORITY_DEFAULT>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_LOW,
ANEURALNETWORKS_PRIORITY_LOW>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_MEDIUM,
ANEURALNETWORKS_PRIORITY_MEDIUM>();
CheckExecutionPriority<NNAPIExecutionPriority_NNAPI_PRIORITY_HIGH,
ANEURALNETWORKS_PRIORITY_HIGH>();
}
TEST_F(NNAPIPluginTest, PassesCachingParameters) {
nnapi_->ANeuralNetworksCompilation_setCaching =
[](ANeuralNetworksCompilation* compilation, const char* cacheDir,
const uint8_t* token) -> int {
if (std::string(cacheDir) != "d") return 1;
// Token is hashed with other bits, just check that it's not empty.
if (std::string(reinterpret_cast<const char*>(token)).empty()) return 2;
return 0;
};
CreateDelegate(CreateNNAPISettings(fbb_, 0, fbb_.CreateString("d"),
fbb_.CreateString("t")));
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesFalseNNAPICpuFlag) {
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/* allow CPU */ false));
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
// Since no CPU, should only pass one device.
return numDevices - 1;
};
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
TEST_F(NNAPIPluginTest, PassesTrueNNAPICpuFlag) {
CreateDelegate(CreateNNAPISettings(fbb_, 0, 0, 0,
NNAPIExecutionPreference_UNDEFINED, 0, 0,
/* allow CPU */ true));
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices =
[](const ANeuralNetworksModel* model,
const ANeuralNetworksDevice* const* devices, uint32_t numDevices,
bool* supportedOps) -> int {
supportedOps[0] = true;
// With CPU allowed, should pass two devices.
return numDevices - 2;
};
EXPECT_EQ(model_.Interpreter()->ModifyGraphWithDelegate(delegate_.get()),
kTfLiteOk);
}
} // namespace
} // namespace tflite
<|endoftext|> |
<commit_before>/*! \file unitTestCoefficientGenerator.cpp
* This file contains the unit test of the hypersonic local inclination
* analysis.
*
* Path : /Astrodynamics/ForceModels/Aerothermodynamics/
* Version : 1
* Check status : Checked
*
* Author : Dominic Dirkx
* Affiliation : Delft University of Technology
* E-mail address : [email protected]
*
* Checker : Bart Romgens
* Affiliation : Delft University of Technology
* E-mail address : [email protected]
*
* Date created : 25 November, 2010
* Last modified : 9 February, 2011
*
* References
* Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic
* Arbitrary Body Program, Volume II - Program Formulation, Douglas Aircraft
* Aircraft Company, 1973.
*
* Notes
*
* Copyright (c) 2010 Delft University of Technology.
*
* This software is protected by national and international copyright.
* Any unauthorized use, reproduction or modification is unlawful and
* will be prosecuted. Commercial and non-private application of the
* software in any form is strictly prohibited unless otherwise granted
* by the authors.
*
* The code is provided without any warranty; without even the implied
* warranty of merchantibility or fitness for a particular purpose.
*
* Changelog
* YYMMDD Author Comment
* 102511 D. Dirkx First version of file.
*/
// Include statements.
#include "unitTestCoefficientGenerator.h"
#include "writingOutputToFile.h"
bool unit_tests::testCoefficientGenerator( )
{
// Declare test variable.
bool isCoefficientGeneratorBad_ = 0;
// Create test sphere.
SphereSegment sphere = SphereSegment( );
sphere.setRadius( 1.0 );
sphere.setMinimumAzimuthAngle( 0.0 );
sphere.setMaximumAzimuthAngle( 2.0 * M_PI);
sphere.setMinimumZenithAngle( 0.0 );
sphere.setMaximumZenithAngle( M_PI );
VehicleExternalModel externalModel = VehicleExternalModel();
externalModel.setVehicleGeometry( sphere );
Vehicle vehicle = Vehicle();
vehicle.setExternalModel( externalModel );
// Create analysis object.
HypersonicLocalInclinationAnalysis analysis =
HypersonicLocalInclinationAnalysis( );
// Set vehicle in analysis with 10,000 panels.
int* numberOfLines = new int[ 1 ];
int* numberOfPoints = new int[ 1 ];
bool* invertOrder = new bool[ 1 ];
numberOfLines[ 0 ] = 101;
numberOfPoints[ 0 ] = 101;
invertOrder[ 0 ] = 0;
analysis.setVehicle( vehicle, numberOfLines, numberOfPoints, invertOrder );
// Set reference quantities.
analysis.setReferenceArea( M_PI );
analysis.setReferenceLength( 1.0 );
analysis.setMomentReferencePoint( Vector3d( 0, 0, 0) );
// Set pure Newtonian compression method for test purposes.
analysis.setSelectedMethod( 0, 0, 0 );
// Generate sphere database.
analysis.generateDatabase( );
// Allocate memory for independent variables
// to pass to analysis for retrieval.
int* independentVariables = new int[ 3 ];
independentVariables[ 0 ] = 0;
independentVariables[ 1 ] = 0;
independentVariables[ 2 ] = 0;
// Declare local test variables.
VectorXd aerodynamicCoefficients_;
double forceCoefficient_;
// Iterate over all angles of attack to verify sphere coefficients.
for( int i = 0; i < analysis.getNumberOfMachPoints(); i++ )
{
independentVariables[ 0 ] = i;
for( int j = 0; j < analysis.getNumberOfAngleOfAttackPoints( ); j++ )
{
independentVariables[ 1 ] = j;
for( int k = 0; k < analysis.getNumberOfAngleOfSideslipPoints( ); k++ )
{
independentVariables[ 2 ] = k;
// Retrieve aerodynamic coefficients.
aerodynamicCoefficients_ = analysis.getAerodynamicCoefficients(
independentVariables );
forceCoefficient_ = sqrt( aerodynamicCoefficients_.x( )
* aerodynamicCoefficients_.x( )
+ aerodynamicCoefficients_.y( )
* aerodynamicCoefficients_.y( )
+ aerodynamicCoefficients_.z( )
* aerodynamicCoefficients_.z( ) );
// Check if 'total' aerodynamic coefficient is always
// sufficiently close to zero.
if( fabs( forceCoefficient_ - 1.0 ) > 1.0E-3 )
{
std::cout<<"Total magnitude of aerodynamic force wrong in "
<<"sphere."<<std::endl;
isCoefficientGeneratorBad_ = true;
}
// Check if moment coefficients are approximately zero. Deviations
// for pitch moment are greater due to greater range of angles of
// attack than sideslip.
if( fabs( aerodynamicCoefficients_[ 3 ] ) > 1.0E-5 )
{
std::cerr<<" Error, sphere roll moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 4 ] ) > 1.0E-3 )
{
std::cerr<<" Error, sphere pitch moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 5 ] ) > 1.0E-5 )
{
std::cerr<<" Error, sphere yaw moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
}
}
}
// Set Apollo capsule for validation.
Capsule capsule = Capsule( );
capsule.setNoseRadius( 4.694 );
capsule.setMiddleRadius( 1.956 );
capsule.setRearAngle( -1*33.0 * M_PI / 180.0 );
capsule.setRearLength( 2.662 );
capsule.setSideRadius( 0.196 );
capsule.setCapsule( );
externalModel.setVehicleGeometry( capsule );
vehicle.setExternalModel( externalModel );
// Declare new analysis object
HypersonicLocalInclinationAnalysis analysis2 =
HypersonicLocalInclinationAnalysis( );
int * numberOfLines2 = new int[ 4 ];
int * numberOfPoints2 = new int[ 4 ];
bool * invertOrders2 = new bool[ 4 ];
// Set number of analysis points
numberOfLines2[ 0 ] = 51;
numberOfPoints2[ 0 ] = 51;
numberOfLines2[ 1 ] = 51;
numberOfPoints2[ 1 ] = 51;
numberOfLines2[ 2 ] = 51;
numberOfPoints2[ 2 ] = 2;
numberOfLines2[ 3 ] = 51;
numberOfPoints2[ 3 ] = 51;
invertOrders2[ 0 ] = 1;
invertOrders2[ 1 ] = 1;
invertOrders2[ 2 ] = 1;
invertOrders2[ 3 ] = 1;
// Set capsule for analysis.
analysis2.setVehicle( vehicle, numberOfLines2, numberOfPoints2, invertOrders2 );
// Set reference quantities.
analysis2.setReferenceArea( M_PI * pow( capsule.getMiddleRadius( ), 2.0 ) );
analysis2.setReferenceLength( 3.9116 );
VectorXd momentReference = VectorXd( 3 );
momentReference( 0 ) = 0.6624;//27.334;
momentReference( 1 ) = 0;
momentReference( 2 ) = 0.1369;//9.398;
analysis2.setMomentReferencePoint( momentReference );
// Set angle of attack analysis points.
analysis2.setNumberOfAngleOfAttackPoints( 7 );
int i;
for( i = 0; i < 7; i++ )
{
analysis2.setAngleOfAttackPoint( i,
static_cast< double >( i - 6 )
* 5.0 * M_PI / 180.0 );
}
// Generate database.
analysis2.generateDatabase( );
// Retrieve coefficients at zero angle of attack for comparison.
independentVariables[ 0 ] = analysis2.getNumberOfMachPoints( ) - 1;
independentVariables[ 1 ] = analysis2.getNumberOfMachPoints( ) - 1;
independentVariables[ 2 ] = 0;
aerodynamicCoefficients_ = analysis2.getAerodynamicCoefficients( independentVariables );
// Compare values to database values.
if( fabs( aerodynamicCoefficients_[ 0 ] - 1.51 ) > 0.1 )
{
std::cerr<<" Error in Apollo drag coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 1 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo side force coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 2 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo normal force coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 3 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo roll moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 4 ] +0.052 ) > 0.01 )
{
std::cerr<<" Error in Apollo pitch moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 5 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo yaw moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
return isCoefficientGeneratorBad_;
}
// End of file.
<commit_msg>Commit of update to unit test of aerodynamics coefficient generator.<commit_after>/*! \file unitTestCoefficientGenerator.cpp
* This file contains the unit test of the hypersonic local inclination
* analysis.
*
* Path : /Astrodynamics/ForceModels/Aerothermodynamics/
* Version : 1
* Check status : Checked
*
* Author : Dominic Dirkx
* Affiliation : Delft University of Technology
* E-mail address : [email protected]
*
* Checker : Bart Romgens
* Affiliation : Delft University of Technology
* E-mail address : [email protected]
*
* Date created : 25 November, 2010
* Last modified : 9 February, 2011
*
* References
* Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic
* Arbitrary Body Program, Volume II - Program Formulation, Douglas Aircraft
* Aircraft Company, 1973.
*
* Notes
*
* Copyright (c) 2010 Delft University of Technology.
*
* This software is protected by national and international copyright.
* Any unauthorized use, reproduction or modification is unlawful and
* will be prosecuted. Commercial and non-private application of the
* software in any form is strictly prohibited unless otherwise granted
* by the authors.
*
* The code is provided without any warranty; without even the implied
* warranty of merchantibility or fitness for a particular purpose.
*
* Changelog
* YYMMDD Author Comment
* 102511 D. Dirkx First version of file.
*/
// Include statements.
#include "unitTestCoefficientGenerator.h"
#include "writingOutputToFile.h"
bool unit_tests::testCoefficientGenerator( )
{
// Declare test variable.
bool isCoefficientGeneratorBad_ = 0;
// Create test sphere.
SphereSegment sphere = SphereSegment( );
sphere.setRadius( 1.0 );
sphere.setMinimumAzimuthAngle( 0.0 );
sphere.setMaximumAzimuthAngle( 2.0 * M_PI);
sphere.setMinimumZenithAngle( 0.0 );
sphere.setMaximumZenithAngle( M_PI );
VehicleExternalModel externalModel = VehicleExternalModel();
externalModel.setVehicleGeometry( sphere );
Vehicle vehicle = Vehicle();
vehicle.setExternalModel( externalModel );
// Create analysis object.
HypersonicLocalInclinationAnalysis analysis =
HypersonicLocalInclinationAnalysis( );
// Set vehicle in analysis with 10,000 panels.
int* numberOfLines = new int[ 1 ];
int* numberOfPoints = new int[ 1 ];
bool* invertOrder = new bool[ 1 ];
numberOfLines[ 0 ] = 31;
numberOfPoints[ 0 ] = 31;
invertOrder[ 0 ] = 0;
analysis.setVehicle( vehicle, numberOfLines, numberOfPoints, invertOrder );
// Set reference quantities.
analysis.setReferenceArea( M_PI );
analysis.setReferenceLength( 1.0 );
analysis.setMomentReferencePoint( Vector3d( 0, 0, 0) );
// Set pure Newtonian compression method for test purposes.
analysis.setSelectedMethod( 0, 0, 0 );
// Generate sphere database.
analysis.generateDatabase( );
// Allocate memory for independent variables
// to pass to analysis for retrieval.
int* independentVariables = new int[ 3 ];
independentVariables[ 0 ] = 0;
independentVariables[ 1 ] = 0;
independentVariables[ 2 ] = 0;
// Declare local test variables.
VectorXd aerodynamicCoefficients_;
double forceCoefficient_;
// Iterate over all angles of attack to verify sphere coefficients.
for( int i = 0; i < analysis.getNumberOfMachPoints(); i++ )
{
independentVariables[ 0 ] = i;
for( int j = 0; j < analysis.getNumberOfAngleOfAttackPoints( ); j++ )
{
independentVariables[ 1 ] = j;
for( int k = 0; k < analysis.getNumberOfAngleOfSideslipPoints( ); k++ )
{
independentVariables[ 2 ] = k;
// Retrieve aerodynamic coefficients.
aerodynamicCoefficients_ = analysis.getAerodynamicCoefficients(
independentVariables );
forceCoefficient_ = sqrt( aerodynamicCoefficients_.x( )
* aerodynamicCoefficients_.x( )
+ aerodynamicCoefficients_.y( )
* aerodynamicCoefficients_.y( )
+ aerodynamicCoefficients_.z( )
* aerodynamicCoefficients_.z( ) );
// Check if 'total' aerodynamic coefficient is always
// sufficiently close to zero.
if( fabs( forceCoefficient_ - 1.0 ) > 1.0E-2 )
{
std::cout<<"Total magnitude of aerodynamic force wrong in "
<<"sphere."<<std::endl;
isCoefficientGeneratorBad_ = true;
}
// Check if moment coefficients are approximately zero. Deviations
// for pitch moment are greater due to greater range of angles of
// attack than sideslip.
if( fabs( aerodynamicCoefficients_[ 3 ] ) > 1.0E-4 )
{
std::cerr<<" Error, sphere roll moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 4 ] ) > 1.0E-2 )
{
std::cerr<<" Error, sphere pitch moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 5 ] ) > 1.0E-2 )
{
std::cerr<<" Error, sphere yaw moment coefficient not zero. "
<<std::endl;
isCoefficientGeneratorBad_ = true;
}
}
}
}
// Set Apollo capsule for validation.
Capsule capsule = Capsule( );
capsule.setNoseRadius( 4.694 );
capsule.setMiddleRadius( 1.956 );
capsule.setRearAngle( -1*33.0 * M_PI / 180.0 );
capsule.setRearLength( 2.662 );
capsule.setSideRadius( 0.196 );
capsule.setCapsule( );
externalModel.setVehicleGeometry( capsule );
vehicle.setExternalModel( externalModel );
// Declare new analysis object
HypersonicLocalInclinationAnalysis analysis2 =
HypersonicLocalInclinationAnalysis( );
int * numberOfLines2 = new int[ 4 ];
int * numberOfPoints2 = new int[ 4 ];
bool * invertOrders2 = new bool[ 4 ];
// Set number of analysis points
numberOfLines2[ 0 ] = 31;
numberOfPoints2[ 0 ] = 31;
numberOfLines2[ 1 ] = 31;
numberOfPoints2[ 1 ] = 31;
numberOfLines2[ 2 ] = 31;
numberOfPoints2[ 2 ] = 2;
numberOfLines2[ 3 ] = 11;
numberOfPoints2[ 3 ] = 11;
invertOrders2[ 0 ] = 1;
invertOrders2[ 1 ] = 1;
invertOrders2[ 2 ] = 1;
invertOrders2[ 3 ] = 1;
// Set capsule for analysis.
analysis2.setVehicle( vehicle, numberOfLines2, numberOfPoints2, invertOrders2 );
// Set reference quantities.
analysis2.setReferenceArea( M_PI * pow( capsule.getMiddleRadius( ), 2.0 ) );
analysis2.setReferenceLength( 3.9116 );
VectorXd momentReference = VectorXd( 3 );
momentReference( 0 ) = 0.6624;//27.334;
momentReference( 1 ) = 0;
momentReference( 2 ) = 0.1369;//9.398;
analysis2.setMomentReferencePoint( momentReference );
// Set angle of attack analysis points.
analysis2.setNumberOfAngleOfAttackPoints( 7 );
int i;
for( i = 0; i < 7; i++ )
{
analysis2.setAngleOfAttackPoint( i,
static_cast< double >( i - 6 )
* 5.0 * M_PI / 180.0 );
}
// Generate database.
analysis2.generateDatabase( );
// Retrieve coefficients at zero angle of attack for comparison.
independentVariables[ 0 ] = analysis2.getNumberOfMachPoints( ) - 1;
independentVariables[ 1 ] = analysis2.getNumberOfMachPoints( ) - 1;
independentVariables[ 2 ] = 0;
aerodynamicCoefficients_ = analysis2.getAerodynamicCoefficients( independentVariables );
// Compare values to database values.
if( fabs( aerodynamicCoefficients_[ 0 ] - 1.51 ) > 0.1 )
{
std::cerr<<" Error in Apollo drag coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 1 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo side force coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 2 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo normal force coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 3 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo roll moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( fabs( aerodynamicCoefficients_[ 4 ] +0.052 ) > 0.01 )
{
std::cerr<<" Error in Apollo pitch moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
if( aerodynamicCoefficients_[ 5 ] > 1.0E-15 )
{
std::cerr<<" Error in Apollo yaw moment coefficient "<<std::endl;
isCoefficientGeneratorBad_ = true;
}
return isCoefficientGeneratorBad_;
}
// End of file.
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <itkImageFileWriter.h>
#include <itkMetaDataObject.h>
#include <itkVectorImage.h>
#include <mitkBaseData.h>
#include <mitkFiberBundle.h>
#include "mitkCommandLineParser.h"
#include <mitkLexicalCast.h>
#include <mitkCoreObjectFactory.h>
#include <mitkIOUtil.h>
#include <itkFiberCurvatureFilter.h>
mitk::FiberBundle::Pointer LoadFib(std::string filename)
{
std::vector<mitk::BaseData::Pointer> fibInfile = mitk::IOUtil::Load(filename);
if( fibInfile.empty() )
std::cout << "File " << filename << " could not be read!";
mitk::BaseData::Pointer baseData = fibInfile.at(0);
return dynamic_cast<mitk::FiberBundle*>(baseData.GetPointer());
}
/*!
\brief Modify input tractogram: fiber resampling, compression, pruning and transformation.
*/
int main(int argc, char* argv[])
{
mitkCommandLineParser parser;
parser.setTitle("Fiber Processing");
parser.setCategory("Fiber Tracking and Processing Methods");
parser.setDescription("Modify input tractogram: fiber resampling, compression, pruning and transformation.");
parser.setContributor("MIC");
parser.setArgumentPrefix("--", "-");
parser.beginGroup("1. Mandatory arguments:");
parser.addArgument("", "i", mitkCommandLineParser::String, "Input:", "Input fiber bundle (.fib, .trk, .tck)", us::Any(), false, false, false, mitkCommandLineParser::Input);
parser.addArgument("", "o", mitkCommandLineParser::String, "Output:", "Output fiber bundle (.fib, .trk)", us::Any(), false, false, false, mitkCommandLineParser::Output);
parser.endGroup();
parser.beginGroup("2. Resampling:");
parser.addArgument("spline_resampling", "", mitkCommandLineParser::Float, "Spline resampling:", "Resample fiber using splines with the given point distance (in mm)");
parser.addArgument("linear_resampling", "", mitkCommandLineParser::Float, "Linear resampling:", "Resample fiber linearly with the given point distance (in mm)");
parser.addArgument("num_resampling", "", mitkCommandLineParser::Int, "Num. fiber points resampling:", "Resample all fibers to the given number of points");
parser.addArgument("compress", "", mitkCommandLineParser::Float, "Compress:", "Compress fiber using the given error threshold (in mm)");
parser.endGroup();
parser.beginGroup("3. Filtering:");
parser.addArgument("min_length", "", mitkCommandLineParser::Float, "Minimum length:", "Minimum fiber length (in mm)");
parser.addArgument("max_length", "", mitkCommandLineParser::Float, "Maximum length:", "Maximum fiber length (in mm)");
parser.addArgument("max_angle", "", mitkCommandLineParser::Float, "Maximum angle:", "Maximum angular STDEV (in degree) over given distance");
parser.addArgument("max_angle_dist", "", mitkCommandLineParser::Float, "Distance:", "Distance in mm", 10);
parser.addArgument("remove", "", mitkCommandLineParser::Bool, "Remove fibers exceeding curvature threshold:", "If false, only the high curvature parts are removed");
parser.addArgument("subsample", "", mitkCommandLineParser::Float, "Randomly select fraction of streamlines:", "Randomly select the specified fraction of streamlines from the input tractogram");
parser.addArgument("random_subsample", "", mitkCommandLineParser::Bool, "Randomly seed subsampling:", "Randomly seed subsampling. Else, use seed 0.");
parser.endGroup();
parser.beginGroup("4. Transformation:");
parser.addArgument("mirror", "", mitkCommandLineParser::Int, "Invert coordinates:", "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)");
parser.addArgument("rotate_x", "", mitkCommandLineParser::Float, "Rotate x-axis:", "Rotate around x-axis (in deg)");
parser.addArgument("rotate_y", "", mitkCommandLineParser::Float, "Rotate y-axis:", "Rotate around y-axis (in deg)");
parser.addArgument("rotate_z", "", mitkCommandLineParser::Float, "Rotate z-axis:", "Rotate around z-axis (in deg)");
parser.addArgument("scale_x", "", mitkCommandLineParser::Float, "Scale x-axis:", "Scale in direction of x-axis");
parser.addArgument("scale_y", "", mitkCommandLineParser::Float, "Scale y-axis:", "Scale in direction of y-axis");
parser.addArgument("scale_z", "", mitkCommandLineParser::Float, "Scale z-axis", "Scale in direction of z-axis");
parser.addArgument("translate_x", "", mitkCommandLineParser::Float, "Translate x-axis:", "Translate in direction of x-axis (in mm)");
parser.addArgument("translate_y", "", mitkCommandLineParser::Float, "Translate y-axis:", "Translate in direction of y-axis (in mm)");
parser.addArgument("translate_z", "", mitkCommandLineParser::Float, "Translate z-axis:", "Translate in direction of z-axis (in mm)");
parser.endGroup();
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
bool remove = false;
if (parsedArgs.count("remove"))
remove = us::any_cast<bool>(parsedArgs["remove"]);
bool random_subsample = false;
if (parsedArgs.count("random_subsample"))
random_subsample = us::any_cast<bool>(parsedArgs["random_subsample"]);
float spline_resampling = -1;
if (parsedArgs.count("spline_resampling"))
spline_resampling = us::any_cast<float>(parsedArgs["spline_resampling"]);
float linear_resampling = -1;
if (parsedArgs.count("linear_resampling"))
linear_resampling = us::any_cast<float>(parsedArgs["linear_resampling"]);
int num_resampling = -1;
if (parsedArgs.count("num_resampling"))
num_resampling = us::any_cast<int>(parsedArgs["num_resampling"]);
float subsample = -1;
if (parsedArgs.count("subsample"))
subsample = us::any_cast<float>(parsedArgs["subsample"]);
float compress = -1;
if (parsedArgs.count("compress"))
compress = us::any_cast<float>(parsedArgs["compress"]);
float minFiberLength = -1;
if (parsedArgs.count("min_length"))
minFiberLength = us::any_cast<float>(parsedArgs["min_length"]);
float maxFiberLength = -1;
if (parsedArgs.count("max_length"))
maxFiberLength = us::any_cast<float>(parsedArgs["max_length"]);
float max_angle_dist = 10;
if (parsedArgs.count("max_angle_dist"))
max_angle_dist = us::any_cast<float>(parsedArgs["max_angle_dist"]);
float maxAngularDev = -1;
if (parsedArgs.count("max_angle"))
maxAngularDev = us::any_cast<float>(parsedArgs["max_angle"]);
int axis = 0;
if (parsedArgs.count("mirror"))
axis = us::any_cast<int>(parsedArgs["mirror"]);
float rotateX = 0;
if (parsedArgs.count("rotate_x"))
rotateX = us::any_cast<float>(parsedArgs["rotate_x"]);
float rotateY = 0;
if (parsedArgs.count("rotate_y"))
rotateY = us::any_cast<float>(parsedArgs["rotate_y"]);
float rotateZ = 0;
if (parsedArgs.count("rotate_z"))
rotateZ = us::any_cast<float>(parsedArgs["rotate_z"]);
float scaleX = 0;
if (parsedArgs.count("scale_x"))
scaleX = us::any_cast<float>(parsedArgs["scale_x"]);
float scaleY = 0;
if (parsedArgs.count("scale_y"))
scaleY = us::any_cast<float>(parsedArgs["scale_y"]);
float scaleZ = 0;
if (parsedArgs.count("scale_z"))
scaleZ = us::any_cast<float>(parsedArgs["scale_z"]);
float translateX = 0;
if (parsedArgs.count("translate_x"))
translateX = us::any_cast<float>(parsedArgs["translate_x"]);
float translateY = 0;
if (parsedArgs.count("translate_y"))
translateY = us::any_cast<float>(parsedArgs["translate_y"]);
float translateZ = 0;
if (parsedArgs.count("translate_z"))
translateZ = us::any_cast<float>(parsedArgs["translate_z"]);
std::string inFileName = us::any_cast<std::string>(parsedArgs["i"]);
std::string outFileName = us::any_cast<std::string>(parsedArgs["o"]);
try
{
mitk::FiberBundle::Pointer fib = LoadFib(inFileName);
if (subsample>0)
fib = fib->SubsampleFibers(subsample, random_subsample);
if (maxAngularDev>0)
{
auto filter = itk::FiberCurvatureFilter::New();
filter->SetInputFiberBundle(fib);
filter->SetAngularDeviation(maxAngularDev);
filter->SetDistance(max_angle_dist);
filter->SetRemoveFibers(remove);
filter->Update();
fib = filter->GetOutputFiberBundle();
}
if (minFiberLength>0)
fib->RemoveShortFibers(minFiberLength);
if (maxFiberLength>0)
fib->RemoveLongFibers(maxFiberLength);
if (spline_resampling>0)
fib->ResampleSpline(spline_resampling);
if (linear_resampling>0)
fib->ResampleLinear(linear_resampling);
if (num_resampling>0)
fib->ResampleToNumPoints(num_resampling);
if (compress>0)
fib->Compress(compress);
if (axis/100==1)
fib->MirrorFibers(0);
if ((axis%100)/10==1)
fib->MirrorFibers(1);
if (axis%10==1)
fib->MirrorFibers(2);
if (rotateX > 0 || rotateY > 0 || rotateZ > 0){
std::cout << "Rotate " << rotateX << " " << rotateY << " " << rotateZ;
fib->RotateAroundAxis(rotateX, rotateY, rotateZ);
}
if (translateX > 0 || translateY > 0 || translateZ > 0){
fib->TranslateFibers(translateX, translateY, translateZ);
}
if (scaleX > 0 || scaleY > 0 || scaleZ > 0)
fib->ScaleFibers(scaleX, scaleY, scaleZ);
mitk::IOUtil::Save(fib.GetPointer(), outFileName );
}
catch (itk::ExceptionObject e)
{
std::cout << e;
return EXIT_FAILURE;
}
catch (std::exception e)
{
std::cout << e.what();
return EXIT_FAILURE;
}
catch (...)
{
std::cout << "ERROR!?!";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Fiber cutting<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <itkImageFileWriter.h>
#include <itkMetaDataObject.h>
#include <itkVectorImage.h>
#include <mitkBaseData.h>
#include <mitkFiberBundle.h>
#include "mitkCommandLineParser.h"
#include <mitkLexicalCast.h>
#include <mitkCoreObjectFactory.h>
#include <mitkIOUtil.h>
#include <itkFiberCurvatureFilter.h>
#include <mitkDiffusionDataIOHelper.h>
#include <itkImage.h>
mitk::FiberBundle::Pointer LoadFib(std::string filename)
{
std::vector<mitk::BaseData::Pointer> fibInfile = mitk::IOUtil::Load(filename);
if( fibInfile.empty() )
std::cout << "File " << filename << " could not be read!";
mitk::BaseData::Pointer baseData = fibInfile.at(0);
return dynamic_cast<mitk::FiberBundle*>(baseData.GetPointer());
}
/*!
\brief Modify input tractogram: fiber resampling, compression, pruning and transformation.
*/
int main(int argc, char* argv[])
{
mitkCommandLineParser parser;
parser.setTitle("Fiber Processing");
parser.setCategory("Fiber Tracking and Processing Methods");
parser.setDescription("Modify input tractogram: fiber resampling, compression, pruning and transformation.");
parser.setContributor("MIC");
parser.setArgumentPrefix("--", "-");
parser.beginGroup("1. Mandatory arguments:");
parser.addArgument("", "i", mitkCommandLineParser::String, "Input:", "Input fiber bundle (.fib, .trk, .tck)", us::Any(), false, false, false, mitkCommandLineParser::Input);
parser.addArgument("", "o", mitkCommandLineParser::String, "Output:", "Output fiber bundle (.fib, .trk)", us::Any(), false, false, false, mitkCommandLineParser::Output);
parser.endGroup();
parser.beginGroup("2. Resampling:");
parser.addArgument("spline_resampling", "", mitkCommandLineParser::Float, "Spline resampling:", "Resample fiber using splines with the given point distance (in mm)");
parser.addArgument("linear_resampling", "", mitkCommandLineParser::Float, "Linear resampling:", "Resample fiber linearly with the given point distance (in mm)");
parser.addArgument("num_resampling", "", mitkCommandLineParser::Int, "Num. fiber points resampling:", "Resample all fibers to the given number of points");
parser.addArgument("compress", "", mitkCommandLineParser::Float, "Compress:", "Compress fiber using the given error threshold (in mm)");
parser.endGroup();
parser.beginGroup("3. Filtering:");
parser.addArgument("min_length", "", mitkCommandLineParser::Float, "Minimum length:", "Minimum fiber length (in mm)");
parser.addArgument("max_length", "", mitkCommandLineParser::Float, "Maximum length:", "Maximum fiber length (in mm)");
parser.addArgument("max_angle", "", mitkCommandLineParser::Float, "Maximum angle:", "Maximum angular STDEV (in degree) over given distance");
parser.addArgument("max_angle_dist", "", mitkCommandLineParser::Float, "Distance:", "Distance in mm", 10);
parser.addArgument("remove", "", mitkCommandLineParser::Bool, "Remove fibers exceeding curvature threshold:", "If false, only the high curvature parts are removed");
parser.addArgument("subsample", "", mitkCommandLineParser::Float, "Randomly select fraction of streamlines:", "Randomly select the specified fraction of streamlines from the input tractogram");
parser.addArgument("random_subsample", "", mitkCommandLineParser::Bool, "Randomly seed subsampling:", "Randomly seed subsampling. Else, use seed 0.");
parser.endGroup();
parser.beginGroup("4. Transformation:");
parser.addArgument("mirror", "", mitkCommandLineParser::Int, "Invert coordinates:", "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)");
parser.addArgument("rotate_x", "", mitkCommandLineParser::Float, "Rotate x-axis:", "Rotate around x-axis (in deg)");
parser.addArgument("rotate_y", "", mitkCommandLineParser::Float, "Rotate y-axis:", "Rotate around y-axis (in deg)");
parser.addArgument("rotate_z", "", mitkCommandLineParser::Float, "Rotate z-axis:", "Rotate around z-axis (in deg)");
parser.addArgument("scale_x", "", mitkCommandLineParser::Float, "Scale x-axis:", "Scale in direction of x-axis");
parser.addArgument("scale_y", "", mitkCommandLineParser::Float, "Scale y-axis:", "Scale in direction of y-axis");
parser.addArgument("scale_z", "", mitkCommandLineParser::Float, "Scale z-axis", "Scale in direction of z-axis");
parser.addArgument("translate_x", "", mitkCommandLineParser::Float, "Translate x-axis:", "Translate in direction of x-axis (in mm)");
parser.addArgument("translate_y", "", mitkCommandLineParser::Float, "Translate y-axis:", "Translate in direction of y-axis (in mm)");
parser.addArgument("translate_z", "", mitkCommandLineParser::Float, "Translate z-axis:", "Translate in direction of z-axis (in mm)");
parser.endGroup();
parser.beginGroup("5. Remove fiber parts:");
parser.addArgument("remove_inside", "", mitkCommandLineParser::Bool, "Remove fibers inside mask:", "remove fibers inside mask");
parser.addArgument("remove_outside", "", mitkCommandLineParser::Bool, "Remove fibers outside mask:", "remove fibers outside mask");
parser.addArgument("mask", "", mitkCommandLineParser::String, "Mask image:", "mask image", us::Any(), true, false, false, mitkCommandLineParser::Input);
parser.endGroup();
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
bool remove_outside = false;
if (parsedArgs.count("remove_outside"))
remove_outside = us::any_cast<bool>(parsedArgs["remove_outside"]);
bool remove_inside = false;
if (!remove_outside && parsedArgs.count("remove_inside"))
remove_inside = us::any_cast<bool>(parsedArgs["remove_inside"]);
typedef itk::Image< unsigned char, 3 > UcharImageType;
UcharImageType::Pointer mask = nullptr;
if (remove_inside || remove_outside)
{
if (parsedArgs.count("mask"))
mask = mitk::DiffusionDataIOHelper::load_itk_image< UcharImageType >(us::any_cast<std::string>(parsedArgs["mask"]));
else {
MITK_INFO << "Mask needed to remove fibers inside or outside mask!";
return EXIT_FAILURE;
}
}
bool remove = false;
if (parsedArgs.count("remove"))
remove = us::any_cast<bool>(parsedArgs["remove"]);
bool random_subsample = false;
if (parsedArgs.count("random_subsample"))
random_subsample = us::any_cast<bool>(parsedArgs["random_subsample"]);
float spline_resampling = -1;
if (parsedArgs.count("spline_resampling"))
spline_resampling = us::any_cast<float>(parsedArgs["spline_resampling"]);
float linear_resampling = -1;
if (parsedArgs.count("linear_resampling"))
linear_resampling = us::any_cast<float>(parsedArgs["linear_resampling"]);
int num_resampling = -1;
if (parsedArgs.count("num_resampling"))
num_resampling = us::any_cast<int>(parsedArgs["num_resampling"]);
float subsample = -1;
if (parsedArgs.count("subsample"))
subsample = us::any_cast<float>(parsedArgs["subsample"]);
float compress = -1;
if (parsedArgs.count("compress"))
compress = us::any_cast<float>(parsedArgs["compress"]);
float minFiberLength = -1;
if (parsedArgs.count("min_length"))
minFiberLength = us::any_cast<float>(parsedArgs["min_length"]);
float maxFiberLength = -1;
if (parsedArgs.count("max_length"))
maxFiberLength = us::any_cast<float>(parsedArgs["max_length"]);
float max_angle_dist = 10;
if (parsedArgs.count("max_angle_dist"))
max_angle_dist = us::any_cast<float>(parsedArgs["max_angle_dist"]);
float maxAngularDev = -1;
if (parsedArgs.count("max_angle"))
maxAngularDev = us::any_cast<float>(parsedArgs["max_angle"]);
int axis = 0;
if (parsedArgs.count("mirror"))
axis = us::any_cast<int>(parsedArgs["mirror"]);
float rotateX = 0;
if (parsedArgs.count("rotate_x"))
rotateX = us::any_cast<float>(parsedArgs["rotate_x"]);
float rotateY = 0;
if (parsedArgs.count("rotate_y"))
rotateY = us::any_cast<float>(parsedArgs["rotate_y"]);
float rotateZ = 0;
if (parsedArgs.count("rotate_z"))
rotateZ = us::any_cast<float>(parsedArgs["rotate_z"]);
float scaleX = 0;
if (parsedArgs.count("scale_x"))
scaleX = us::any_cast<float>(parsedArgs["scale_x"]);
float scaleY = 0;
if (parsedArgs.count("scale_y"))
scaleY = us::any_cast<float>(parsedArgs["scale_y"]);
float scaleZ = 0;
if (parsedArgs.count("scale_z"))
scaleZ = us::any_cast<float>(parsedArgs["scale_z"]);
float translateX = 0;
if (parsedArgs.count("translate_x"))
translateX = us::any_cast<float>(parsedArgs["translate_x"]);
float translateY = 0;
if (parsedArgs.count("translate_y"))
translateY = us::any_cast<float>(parsedArgs["translate_y"]);
float translateZ = 0;
if (parsedArgs.count("translate_z"))
translateZ = us::any_cast<float>(parsedArgs["translate_z"]);
std::string inFileName = us::any_cast<std::string>(parsedArgs["i"]);
std::string outFileName = us::any_cast<std::string>(parsedArgs["o"]);
try
{
mitk::FiberBundle::Pointer fib = LoadFib(inFileName);
if (subsample>0)
fib = fib->SubsampleFibers(subsample, random_subsample);
if (maxAngularDev>0)
{
auto filter = itk::FiberCurvatureFilter::New();
filter->SetInputFiberBundle(fib);
filter->SetAngularDeviation(maxAngularDev);
filter->SetDistance(max_angle_dist);
filter->SetRemoveFibers(remove);
filter->Update();
fib = filter->GetOutputFiberBundle();
}
if (minFiberLength>0)
fib->RemoveShortFibers(minFiberLength);
if (maxFiberLength>0)
fib->RemoveLongFibers(maxFiberLength);
if (spline_resampling>0)
fib->ResampleSpline(spline_resampling);
if (linear_resampling>0)
fib->ResampleLinear(linear_resampling);
if (num_resampling>0)
fib->ResampleToNumPoints(num_resampling);
if (compress>0)
fib->Compress(compress);
if ( mask.IsNotNull() )
{
if (remove_outside)
fib = fib->RemoveFibersOutside(mask, false);
else if (remove_inside)
fib = fib->RemoveFibersOutside(mask, true);
}
if (axis/100==1)
fib->MirrorFibers(0);
if ((axis%100)/10==1)
fib->MirrorFibers(1);
if (axis%10==1)
fib->MirrorFibers(2);
if (rotateX > 0 || rotateY > 0 || rotateZ > 0){
std::cout << "Rotate " << rotateX << " " << rotateY << " " << rotateZ;
fib->RotateAroundAxis(rotateX, rotateY, rotateZ);
}
if (translateX > 0 || translateY > 0 || translateZ > 0){
fib->TranslateFibers(translateX, translateY, translateZ);
}
if (scaleX > 0 || scaleY > 0 || scaleZ > 0)
fib->ScaleFibers(scaleX, scaleY, scaleZ);
mitk::IOUtil::Save(fib.GetPointer(), outFileName );
}
catch (itk::ExceptionObject e)
{
std::cout << e;
return EXIT_FAILURE;
}
catch (std::exception e)
{
std::cout << e.what();
return EXIT_FAILURE;
}
catch (...)
{
std::cout << "ERROR!?!";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev *AddTaskSEpPbCorrelationsJetV2Kine(TString sMode = "TPCTPCFMDA")
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskKineAmpt.C::AddTaskKineAmpt", "No analysis manager to connect to");
return nullptr;
}
//=============================================================================
AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev *task = new AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev("AliAnalysisTaskSEpPbCorrelationsJetV2Kine_dev");
Double_t trigPtLimits[] = {0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 8.0};
const Int_t nBinTrigPt = sizeof(trigPtLimits) / sizeof(Double_t) - 1;
task->SetTrigPtBinning(nBinTrigPt, trigPtLimits);
Double_t assocPtLimits[] = {0.5, 1., 1.5, 50.};
const Int_t nBinAssocPt = sizeof(assocPtLimits) / sizeof(Double_t) - 1;
task->SetAssocPtBinning(nBinAssocPt, assocPtLimits);
task->SetAnaMode(sMode);
task->SetAssoCut(1.0);
task->SetPtMin(0.5);
task->SetPtMax(50.);
task->SetCen1(0);
task->SetCen2(10);
// Input File
TGrid::Connect("alien://");
TFile *file = TFile::Open("alien:///alice/cern.ch/user/s/sitang/AMPT_Centrality_Calibration/Centrality.root");
//TFile *file = TFile::Open("./Centrality/Centrality.root");
TH1D *h_Charge = (TH1D*)file->Get("hChargeV0A"); h_Charge->SetDirectory(0);
file->Close();
// create input container
AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("h_centrality",
TH1D::Class(),
AliAnalysisManager::kInputContainer);
cinput1->SetData(h_Charge);
mgr->AddTask(task);
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput(task, 1, cinput1);
mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("listKineAmpt_%s",sMode.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
AliAnalysisManager::GetCommonFileName()));
//=============================================================================
return task;
}
<commit_msg>Update Jet particle v2 MC<commit_after>AliAnalysisTaskSEpPbCorrelationsJetV2Kine *AddTaskSEpPbCorrelationsJetV2Kine(TString sMode = "TPCTPCFMDA")
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskKineAmpt.C::AddTaskKineAmpt", "No analysis manager to connect to");
return nullptr;
}
//=============================================================================
AliAnalysisTaskSEpPbCorrelationsJetV2Kine *task = new AliAnalysisTaskSEpPbCorrelationsJetV2Kine("AliAnalysisTaskSEpPbCorrelationsJetV2Kine");
Double_t trigPtLimits[] = {0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 8.0};
const Int_t nBinTrigPt = sizeof(trigPtLimits) / sizeof(Double_t) - 1;
task->SetTrigPtBinning(nBinTrigPt, trigPtLimits);
Double_t assocPtLimits[] = {0.5, 1., 1.5, 50.};
const Int_t nBinAssocPt = sizeof(assocPtLimits) / sizeof(Double_t) - 1;
task->SetAssocPtBinning(nBinAssocPt, assocPtLimits);
task->SetAnaMode(sMode);
task->SetAssoCut(1.0);
task->SetPtMin(0.5);
task->SetPtMax(50.);
task->SetCen1(0);
task->SetCen2(10);
// Input File
TGrid::Connect("alien://");
TFile *file = TFile::Open("alien:///alice/cern.ch/user/s/sitang/AMPT_Centrality_Calibration/Centrality.root");
//TFile *file = TFile::Open("./Centrality/Centrality.root");
TH1D *h_Charge = (TH1D*)file->Get("hChargeV0A"); h_Charge->SetDirectory(0);
file->Close();
// create input container
AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("h_centrality",
TH1D::Class(),
AliAnalysisManager::kInputContainer);
cinput1->SetData(h_Charge);
mgr->AddTask(task);
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput(task, 1, cinput1);
mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("listKineAmpt_%s",sMode.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
AliAnalysisManager::GetCommonFileName()));
//=============================================================================
return task;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------------------------
// File: LineFollower.cpp
// Project: LG Exec Ed Program
// Versions:
// 1.0 April 2017 - initial version
// Main line follower Program. This is the main program follows a line.
// To invoke LineFollower <hostname> <port>. This program will send the processed camera image
// via UDP to the RecvImage_UDP program that will display the image
//
// Use the following keys
// r key - run mode (starts the robot following the line
// s key - disables run mode and stops the robot
// j key - moves the camera pan servo left
// l key - moves the camera pan servo right
// i key - moves the camera tilt servo up
// m key - moves the camera tilt servo down
// k key - moves the camera pan and tilt servos to center
// q key - descreases the speed of the robot (manual control only both wheels move at the same speed)
// w key - stops the robot (manual control only)
// e key - increases the speed of the robot (manual control only both wheels move at the same speed)
//----------------------------------------------------------------------------------------------
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include <stdio.h>
#include <signal.h>
#include <iostream>
#include "ImageProcessing.h"
#include "PI3OpencvCompat.h"
#include "PID.h"
#include "Servos.h"
#include "NetworkUDP.h"
#include "UdpSendJpeg.h"
#include "UdpSendMap.h"
#include "KeyboardSetup.h"
#ifndef UBUNTU // For building in ubuntu. Below code sould be built in raspberry pi.
#include <wiringPi.h>
#endif //UBUNTU
#include "sensor_manager.h"
#include "servos_manager.h"
#define INIT 0
#define STOP 1
#define FOWARD 2
#define LEFT 3
#define RIGHT 4
using namespace cv;
using namespace std;
#define WIDTH 640
#define HEIGHT 480
static int AWidth;
static int AHeight;
static int Pan;
static int Tilt;
static CvCapture * capture=NULL;
static UdpSendJpeg VideoSender;
static UdpSendMap MapSender;
static TPID PID;
static int Run=INIT;
float offset; // computed robot deviation from the line
static void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void);
static void CleanUp(void);
static void Control_C_Handler(int s);
static void HandleInputChar(void);
//----------------------------------------------------------------
// main - This is the main program for the line follower and
// contains the control loop
//-----------------------------------------------------------------
int main(int argc, const char** argv)
{
IplImage * iplCameraImage; // camera image in IplImage format
Mat image; // camera image in Mat format
if (argc !=3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(); // Set Control-c handler to properly exit cleanly
if (VideoSender.OpenUdp(argv[1],argv[2]) == 0) // Setup remote network destination to send images
{
printf("VideoSender.OpenUdp Failed\n");
CleanUp();
return(-1);
}
if (MapSender.OpenUdp(argv[1], "30002") == 0) // Setup remote network destination to send images
{
printf("MapSender.OpenUdp Failed\n");
CleanUp();
return(-1);
}
printf("cvCreateCameraCapture()\n");
capture =cvCreateCameraCapture(0); // Open default Camera
if(!capture)
{
printf("Camera Not Initialized\n");
CleanUp();
return 0;
}
if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH)==0) // Set camera width
{
printf("cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH) Failed)\n");
}
if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT)==0) // Set camera height
{
printf("cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT) Failed)\n");
}
AWidth=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
AHeight=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
printf("Width = %d\n",AWidth );
printf("Height = %d\n", AHeight);
if (!IsPi3) namedWindow( "camera", CV_WINDOW_AUTOSIZE ); // If not running on PI3 open local Window
//if (!IsPi3) namedWindow( "processed", CV_WINDOW_AUTOSIZE ); // If not running on PI3 open local Window
do
{
sensor_manager_main();
servos_manager_main();
iplCameraImage = cvQueryFrame(capture); // Get Camera image
image= cv::cvarrToMat(iplCameraImage); // Convert Camera image to Mat format
if (IsPi3) flip(image, image,-1); // if running on PI3 flip(-1)=180 degrees
offset=FindLineInImageAndComputeOffset(image); // Process camera image / locat line and compute offset from line
VideoSender.UdpSendImageAsJpeg(image);
if (!IsPi3) imshow("camera", image ); // Show image locally if not running on PI 3
HandleInputChar(); // Handle Keyboard Input
if (!IsPi3) cv::waitKey(1); // must be call show image locally work with imshow
} while (1);
return 0;
}
//-----------------------------------------------------------------
// END main
//-----------------------------------------------------------------
//----------------------------------------------------------------
// Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter - This
// sets uo the Control-c Handler and put the keyboard in a mode
// where it will not
// 1. echo input
// 2. need enter hit to get a character
// 3. block waiting for input
//-----------------------------------------------------------------
static void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = Control_C_Handler; // Setup control-c callback
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
ConfigKeyboardNoEnterBlockEcho(); // set keyboard configuration
}
//-----------------------------------------------------------------
// END Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter
//-----------------------------------------------------------------
//----------------------------------------------------------------
// CleanUp - Performs cleanup processing before exiting the
// the program
//-----------------------------------------------------------------
static void CleanUp(void)
{
RestoreKeyboard(); // restore Keyboard
if (capture!=NULL)
{
cvReleaseCapture(&capture); // Close camera
capture=NULL;
}
VideoSender.CloseUdp();
MapSender.CloseUdp();
ResetServos(); // Reset servos to center or stopped
CloseServos(); // Close servo device driver
printf("restored\n");
}
//-----------------------------------------------------------------
// END CleanUp
//-----------------------------------------------------------------
//----------------------------------------------------------------
// Control_C_Handler - called when control-c pressed
//-----------------------------------------------------------------
static void Control_C_Handler(int s)
{
CleanUp();
printf("Caught signal %d\n",s);
printf("exiting\n");
exit(1);
}
//-----------------------------------------------------------------
// END Control_C_Handler
//-----------------------------------------------------------------
//----------------------------------------------------------------
// HandleInputChar - check if keys are press and proccess keys of
// interest.
//-----------------------------------------------------------------
static void HandleInputChar(void)
{
int ch;
static int speed=0;
if ((ch=getchar())==EOF) // no key pressed return
{
return;
}
if (ch=='w')
{
robot_mode_setting(ROBOT_FOWARD_MOVING,offset);
}
else if (ch=='x')
{
robot_mode_setting(ROBOT_BACKWARD_MOVING,offset);
}
else if (ch=='d')
{
robot_mode_setting(ROBOT_RIGHT_ROTATING,offset);
}
else if (ch=='a')
{
robot_mode_setting(ROBOT_LEFT_ROTATING,offset);
}
else
{
robot_mode_setting(ROBOT_STOP,offset);
}
}
//-----------------------------------------------------------------
// END HandleInputChar
//-----------------------------------------------------------------
//-----------------------------------------------------------------
// END of File
//-----------------------------------------------------------------
<commit_msg>add map_port to command line!<commit_after>//------------------------------------------------------------------------------------------------
// File: LineFollower.cpp
// Project: LG Exec Ed Program
// Versions:
// 1.0 April 2017 - initial version
// Main line follower Program. This is the main program follows a line.
// To invoke LineFollower <hostname> <port>. This program will send the processed camera image
// via UDP to the RecvImage_UDP program that will display the image
//
// Use the following keys
// r key - run mode (starts the robot following the line
// s key - disables run mode and stops the robot
// j key - moves the camera pan servo left
// l key - moves the camera pan servo right
// i key - moves the camera tilt servo up
// m key - moves the camera tilt servo down
// k key - moves the camera pan and tilt servos to center
// q key - descreases the speed of the robot (manual control only both wheels move at the same speed)
// w key - stops the robot (manual control only)
// e key - increases the speed of the robot (manual control only both wheels move at the same speed)
//----------------------------------------------------------------------------------------------
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include <stdio.h>
#include <signal.h>
#include <iostream>
#include "ImageProcessing.h"
#include "PI3OpencvCompat.h"
#include "PID.h"
#include "Servos.h"
#include "NetworkUDP.h"
#include "UdpSendJpeg.h"
#include "UdpSendMap.h"
#include "KeyboardSetup.h"
#ifndef UBUNTU // For building in ubuntu. Below code sould be built in raspberry pi.
#include <wiringPi.h>
#endif //UBUNTU
#include "sensor_manager.h"
#include "servos_manager.h"
#define INIT 0
#define STOP 1
#define FOWARD 2
#define LEFT 3
#define RIGHT 4
using namespace cv;
using namespace std;
#define WIDTH 640
#define HEIGHT 480
static int AWidth;
static int AHeight;
static int Pan;
static int Tilt;
static CvCapture * capture=NULL;
static UdpSendJpeg VideoSender;
static UdpSendMap MapSender;
static TPID PID;
static int Run=INIT;
float offset; // computed robot deviation from the line
static void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void);
static void CleanUp(void);
static void Control_C_Handler(int s);
static void HandleInputChar(void);
//----------------------------------------------------------------
// main - This is the main program for the line follower and
// contains the control loop
//-----------------------------------------------------------------
int main(int argc, const char** argv)
{
IplImage * iplCameraImage; // camera image in IplImage format
Mat image; // camera image in Mat format
if (argc !=4) {
fprintf(stderr,"usage %s hostname video_port map_port\n", argv[0]);
exit(0);
}
Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(); // Set Control-c handler to properly exit cleanly
if (VideoSender.OpenUdp(argv[1],argv[2]) == 0) // Setup remote network destination to send images
{
printf("VideoSender.OpenUdp Failed\n");
CleanUp();
return(-1);
}
if (MapSender.OpenUdp(argv[1], argv[3]) == 0) // Setup remote network destination to send images
{
printf("MapSender.OpenUdp Failed\n");
CleanUp();
return(-1);
}
printf("cvCreateCameraCapture()\n");
capture =cvCreateCameraCapture(0); // Open default Camera
if(!capture)
{
printf("Camera Not Initialized\n");
CleanUp();
return 0;
}
if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH)==0) // Set camera width
{
printf("cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,WIDTH) Failed)\n");
}
if (cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT)==0) // Set camera height
{
printf("cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,HEIGHT) Failed)\n");
}
AWidth=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
AHeight=cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
printf("Width = %d\n",AWidth );
printf("Height = %d\n", AHeight);
if (!IsPi3) namedWindow( "camera", CV_WINDOW_AUTOSIZE ); // If not running on PI3 open local Window
//if (!IsPi3) namedWindow( "processed", CV_WINDOW_AUTOSIZE ); // If not running on PI3 open local Window
do
{
sensor_manager_main();
servos_manager_main();
iplCameraImage = cvQueryFrame(capture); // Get Camera image
image= cv::cvarrToMat(iplCameraImage); // Convert Camera image to Mat format
if (IsPi3) flip(image, image,-1); // if running on PI3 flip(-1)=180 degrees
offset=FindLineInImageAndComputeOffset(image); // Process camera image / locat line and compute offset from line
VideoSender.UdpSendImageAsJpeg(image);
if (!IsPi3) imshow("camera", image ); // Show image locally if not running on PI 3
HandleInputChar(); // Handle Keyboard Input
if (!IsPi3) cv::waitKey(1); // must be call show image locally work with imshow
} while (1);
return 0;
}
//-----------------------------------------------------------------
// END main
//-----------------------------------------------------------------
//----------------------------------------------------------------
// Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter - This
// sets uo the Control-c Handler and put the keyboard in a mode
// where it will not
// 1. echo input
// 2. need enter hit to get a character
// 3. block waiting for input
//-----------------------------------------------------------------
static void Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter(void)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = Control_C_Handler; // Setup control-c callback
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
ConfigKeyboardNoEnterBlockEcho(); // set keyboard configuration
}
//-----------------------------------------------------------------
// END Setup_Control_C_Signal_Handler_And_Keyboard_No_Enter
//-----------------------------------------------------------------
//----------------------------------------------------------------
// CleanUp - Performs cleanup processing before exiting the
// the program
//-----------------------------------------------------------------
static void CleanUp(void)
{
RestoreKeyboard(); // restore Keyboard
if (capture!=NULL)
{
cvReleaseCapture(&capture); // Close camera
capture=NULL;
}
VideoSender.CloseUdp();
MapSender.CloseUdp();
ResetServos(); // Reset servos to center or stopped
CloseServos(); // Close servo device driver
printf("restored\n");
}
//-----------------------------------------------------------------
// END CleanUp
//-----------------------------------------------------------------
//----------------------------------------------------------------
// Control_C_Handler - called when control-c pressed
//-----------------------------------------------------------------
static void Control_C_Handler(int s)
{
CleanUp();
printf("Caught signal %d\n",s);
printf("exiting\n");
exit(1);
}
//-----------------------------------------------------------------
// END Control_C_Handler
//-----------------------------------------------------------------
//----------------------------------------------------------------
// HandleInputChar - check if keys are press and proccess keys of
// interest.
//-----------------------------------------------------------------
static void HandleInputChar(void)
{
int ch;
static int speed=0;
if ((ch=getchar())==EOF) // no key pressed return
{
return;
}
if (ch=='w')
{
robot_mode_setting(ROBOT_FOWARD_MOVING,offset);
}
else if (ch=='x')
{
robot_mode_setting(ROBOT_BACKWARD_MOVING,offset);
}
else if (ch=='d')
{
robot_mode_setting(ROBOT_RIGHT_ROTATING,offset);
}
else if (ch=='a')
{
robot_mode_setting(ROBOT_LEFT_ROTATING,offset);
}
else
{
robot_mode_setting(ROBOT_STOP,offset);
}
}
//-----------------------------------------------------------------
// END HandleInputChar
//-----------------------------------------------------------------
//-----------------------------------------------------------------
// END of File
//-----------------------------------------------------------------
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/side.h"
#include "libmesh/cell_pyramid5.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_tri3.h"
#include "libmesh/face_quad4.h"
namespace libMesh
{
// ------------------------------------------------------------
// Pyramid5 class static member initializations
const unsigned int Pyramid5::side_nodes_map[5][4] =
{
{0, 1, 4, 99}, // Side 0
{1, 2, 4, 99}, // Side 1
{2, 3, 4, 99}, // Side 2
{3, 0, 4, 99}, // Side 3
{0, 3, 2, 1} // Side 4
};
const unsigned int Pyramid5::edge_nodes_map[8][2] =
{
{0, 1}, // Side 0
{1, 2}, // Side 1
{2, 3}, // Side 2
{0, 3}, // Side 3
{0, 4}, // Side 4
{1, 4}, // Side 5
{2, 4}, // Side 6
{3, 4} // Side 7
};
// ------------------------------------------------------------
// Pyramid5 class member functions
bool Pyramid5::is_vertex(const unsigned int) const
{
return true;
}
bool Pyramid5::is_edge(const unsigned int) const
{
return false;
}
bool Pyramid5::is_face(const unsigned int) const
{
return false;
}
bool Pyramid5::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 4; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Pyramid5::is_node_on_edge(const unsigned int n,
const unsigned int e) const
{
libmesh_assert_less (e, n_edges());
for (unsigned int i = 0; i != 2; ++i)
if (edge_nodes_map[e][i] == n)
return true;
return false;
}
bool Pyramid5::has_affine_map() const
{
// Point v = this->point(3) - this->point(0);
// return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));
return false;
}
UniquePtr<Elem> Pyramid5::build_side (const unsigned int i,
bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
return UniquePtr<Elem>(new Side<Tri3,Pyramid5>(this,i));
case 4:
return UniquePtr<Elem>(new Side<Quad4,Pyramid5>(this,i));
default:
libmesh_error_msg("Invalid side i = " << i);
}
}
else
{
// Create NULL pointer to be initialized, returned later.
Elem * face = libmesh_nullptr;
switch (i)
{
case 0: // triangular face 1
case 1: // triangular face 2
case 2: // triangular face 3
case 3: // triangular face 4
{
face = new Tri3;
break;
}
case 4: // the quad face at z=0
{
face = new Quad4;
break;
}
default:
libmesh_error_msg("Invalid side i = " << i);
}
face->subdomain_id() = this->subdomain_id();
// Set the nodes
for (unsigned n=0; n<face->n_nodes(); ++n)
face->set_node(n) = this->get_node(Pyramid5::side_nodes_map[i][n]);
return UniquePtr<Elem>(face);
}
libmesh_error_msg("We'll never get here!");
return UniquePtr<Elem>();
}
UniquePtr<Elem> Pyramid5::build_edge (const unsigned int i) const
{
libmesh_assert_less (i, this->n_edges());
return UniquePtr<Elem>(new SideEdge<Edge2,Pyramid5>(this,i));
}
void Pyramid5::connectivity(const unsigned int libmesh_dbg_var(sc),
const IOPackage iop,
std::vector<dof_id_type> & conn) const
{
libmesh_assert(_nodes);
libmesh_assert_less (sc, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
switch (iop)
{
case TECPLOT:
{
conn.resize(8);
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
conn[4] = this->node(4)+1;
conn[5] = this->node(4)+1;
conn[6] = this->node(4)+1;
conn[7] = this->node(4)+1;
return;
}
case VTK:
{
conn.resize(5);
conn[0] = this->node(3);
conn[1] = this->node(2);
conn[2] = this->node(1);
conn[3] = this->node(0);
conn[4] = this->node(4);
return;
}
default:
libmesh_error_msg("Unsupported IO package " << iop);
}
}
Real Pyramid5::volume () const
{
// Make copies of our points. It makes the subsequent calculations a bit
// shorter and avoids dereferencing the same pointer multiple times.
Point
x0 = point(0), x1 = point(1), x2 = point(2), x3 = point(3), x4 = point(4);
// The number of components in the dx_dxi, dx_deta, and dx_dzeta arrays.
const int n_components = 4;
Point dx_dxi[n_components] =
{
-x0/4 + x1/4 + x2/4 - x3/4, // const
x0/4 - x1/4 - x2/4 + x3/4, // zeta
x0/4 - x1/4 + x2/4 - x3/4 // eta
};
Point dx_deta[n_components] =
{
-x0/4 - x1/4 + x2/4 + x3/4, // const
x0/4 + x1/4 - x2/4 - x3/4, // zeta
x0/4 - x1/4 + x2/4 - x3/4, // xi
};
Point dx_dzeta[n_components] =
{
-x0/4 - x1/4 - x2/4 - x3/4 + x4, // const
x0/2 + x1/2 + x2/2 + x3/2 - 2*x4, // zeta
-x0/4 - x1/4 - x2/4 - x3/4 + x4, // zeta**2
x0/4 - x1/4 + x2/4 - x3/4 // xi*eta
};
// Number of points in the 2D quadrature rule
const int N = 8;
// Parameters of the quadrature rule
static const Real
a1 = -5.0661630334978742377431469429037e-01L,
a2 = -2.6318405556971359557121701304557e-01L,
b1 = 1.2251482265544137786674043037115e-01L,
b2 = 5.4415184401122528879992623629551e-01L,
w1 = 2.3254745125350790274997694884235e-01L,
w2 = 1.0078588207982543058335638449098e-01L;
// The points and weights of the 2x2x2 quadrature rule
static const Real xi[8] = {a1, a2, a1, a2, -a1, -a2, -a1, -a2};
static const Real eta[8] = {a1, a2, -a1, -a2, a1, a2, -a1, -a2};
static const Real zeta[8] = {b1, b2, b1, b2, b1, b2, b1, b2};
static const Real w[8] = {w1, w2, w1, w2, w1, w2, w1, w2};
Real vol = 0.;
for (int q=0; q<N; ++q)
{
// Note: we need to scale dx/dxi and dx/deta by (1-z), and dx/dzeta by (1-z)**2
Point
dx_dxi_q = (dx_dxi[0] + zeta[q]*dx_dxi[1] + eta[q]*dx_dxi[2]) / (1. - zeta[q]),
dx_deta_q = (dx_deta[0] + zeta[q]*dx_deta[1] + xi[q]*dx_deta[2]) / (1. - zeta[q]),
dx_dzeta_q = (dx_dzeta[0] + zeta[q]*dx_dzeta[1] + zeta[q]*zeta[q]*dx_dzeta[2] + xi[q]*eta[q]*dx_dzeta[3]) / (1. - zeta[q]) / (1. - zeta[q]);
// Compute scalar triple product, multiply by weight, and accumulate volume.
vol += w[q] * dx_dxi_q * dx_deta_q.cross(dx_dzeta_q);
}
return vol;
}
} // namespace libMesh
<commit_msg>Revert "Add quadrature-based volume() implementation for Pyramid5."<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/side.h"
#include "libmesh/cell_pyramid5.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_tri3.h"
#include "libmesh/face_quad4.h"
namespace libMesh
{
// ------------------------------------------------------------
// Pyramid5 class static member initializations
const unsigned int Pyramid5::side_nodes_map[5][4] =
{
{0, 1, 4, 99}, // Side 0
{1, 2, 4, 99}, // Side 1
{2, 3, 4, 99}, // Side 2
{3, 0, 4, 99}, // Side 3
{0, 3, 2, 1} // Side 4
};
const unsigned int Pyramid5::edge_nodes_map[8][2] =
{
{0, 1}, // Side 0
{1, 2}, // Side 1
{2, 3}, // Side 2
{0, 3}, // Side 3
{0, 4}, // Side 4
{1, 4}, // Side 5
{2, 4}, // Side 6
{3, 4} // Side 7
};
// ------------------------------------------------------------
// Pyramid5 class member functions
bool Pyramid5::is_vertex(const unsigned int) const
{
return true;
}
bool Pyramid5::is_edge(const unsigned int) const
{
return false;
}
bool Pyramid5::is_face(const unsigned int) const
{
return false;
}
bool Pyramid5::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 4; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Pyramid5::is_node_on_edge(const unsigned int n,
const unsigned int e) const
{
libmesh_assert_less (e, n_edges());
for (unsigned int i = 0; i != 2; ++i)
if (edge_nodes_map[e][i] == n)
return true;
return false;
}
bool Pyramid5::has_affine_map() const
{
// Point v = this->point(3) - this->point(0);
// return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));
return false;
}
UniquePtr<Elem> Pyramid5::build_side (const unsigned int i,
bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
return UniquePtr<Elem>(new Side<Tri3,Pyramid5>(this,i));
case 4:
return UniquePtr<Elem>(new Side<Quad4,Pyramid5>(this,i));
default:
libmesh_error_msg("Invalid side i = " << i);
}
}
else
{
// Create NULL pointer to be initialized, returned later.
Elem * face = libmesh_nullptr;
switch (i)
{
case 0: // triangular face 1
case 1: // triangular face 2
case 2: // triangular face 3
case 3: // triangular face 4
{
face = new Tri3;
break;
}
case 4: // the quad face at z=0
{
face = new Quad4;
break;
}
default:
libmesh_error_msg("Invalid side i = " << i);
}
face->subdomain_id() = this->subdomain_id();
// Set the nodes
for (unsigned n=0; n<face->n_nodes(); ++n)
face->set_node(n) = this->get_node(Pyramid5::side_nodes_map[i][n]);
return UniquePtr<Elem>(face);
}
libmesh_error_msg("We'll never get here!");
return UniquePtr<Elem>();
}
UniquePtr<Elem> Pyramid5::build_edge (const unsigned int i) const
{
libmesh_assert_less (i, this->n_edges());
return UniquePtr<Elem>(new SideEdge<Edge2,Pyramid5>(this,i));
}
void Pyramid5::connectivity(const unsigned int libmesh_dbg_var(sc),
const IOPackage iop,
std::vector<dof_id_type> & conn) const
{
libmesh_assert(_nodes);
libmesh_assert_less (sc, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
switch (iop)
{
case TECPLOT:
{
conn.resize(8);
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
conn[4] = this->node(4)+1;
conn[5] = this->node(4)+1;
conn[6] = this->node(4)+1;
conn[7] = this->node(4)+1;
return;
}
case VTK:
{
conn.resize(5);
conn[0] = this->node(3);
conn[1] = this->node(2);
conn[2] = this->node(1);
conn[3] = this->node(0);
conn[4] = this->node(4);
return;
}
default:
libmesh_error_msg("Unsupported IO package " << iop);
}
}
Real Pyramid5::volume () const
{
// The pyramid with a bilinear base has volume given by the
// formula in: "Calculation of the Volume of a General Hexahedron
// for Flow Predictions", AIAA Journal v.23, no.6, 1984, p.954-
Node * node0 = this->get_node(0);
Node * node1 = this->get_node(1);
Node * node2 = this->get_node(2);
Node * node3 = this->get_node(3);
Node * node4 = this->get_node(4);
// Construct Various edge and diagonal vectors
Point v40 ( *node0 - *node4 );
Point v13 ( *node3 - *node1 );
Point v02 ( *node2 - *node0 );
Point v03 ( *node3 - *node0 );
Point v01 ( *node1 - *node0 );
// Finally, ready to return the volume!
return (1./6.)*(v40*(v13.cross(v02))) + (1./12.)*(v02*(v01.cross(v03)));
}
} // namespace libMesh
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file ir_validate.cpp
*
* Attempts to verify that various invariants of the IR tree are true.
*
* In particular, at the moment it makes sure that no single
* ir_instruction node except for ir_variable appears multiple times
* in the ir tree. ir_variable does appear multiple times: Once as a
* declaration in an exec_list, and multiple times as the endpoint of
* a dereference chain.
*/
#include <inttypes.h>
#include "ir.h"
#include "ir_hierarchical_visitor.h"
#include "hash_table.h"
class ir_validate : public ir_hierarchical_visitor {
public:
ir_validate()
{
this->ht = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
this->current_function = NULL;
this->callback = ir_validate::validate_ir;
this->data = ht;
}
~ir_validate()
{
hash_table_dtor(this->ht);
}
virtual ir_visitor_status visit(ir_variable *v);
virtual ir_visitor_status visit(ir_dereference_variable *ir);
virtual ir_visitor_status visit_enter(ir_function *ir);
virtual ir_visitor_status visit_leave(ir_function *ir);
virtual ir_visitor_status visit_enter(ir_function_signature *ir);
static void validate_ir(ir_instruction *ir, void *data);
ir_function *current_function;
struct hash_table *ht;
};
ir_visitor_status
ir_validate::visit(ir_dereference_variable *ir)
{
if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {
printf("ir_dereference_variable @ %p does not specify a variable %p\n",
ir, ir->var);
abort();
}
if (hash_table_find(ht, ir->var) == NULL) {
printf("ir_dereference_variable @ %p specifies undeclared variable "
"`%s' @ %p\n",
ir, ir->var->name, ir->var);
abort();
}
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit_enter(ir_function *ir)
{
/* Function definitions cannot be nested.
*/
if (this->current_function != NULL) {
printf("Function definition nested inside another function "
"definition:\n");
printf("%s %p inside %s %p\n",
ir->name, ir,
this->current_function->name, this->current_function);
abort();
}
/* Store the current function hierarchy being traversed. This is used
* by the function signature visitor to ensure that the signatures are
* linked with the correct functions.
*/
this->current_function = ir;
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit_leave(ir_function *ir)
{
(void) ir;
this->current_function = NULL;
return visit_continue;
}
ir_visitor_status
ir_validate::visit_enter(ir_function_signature *ir)
{
if (this->current_function != ir->function()) {
printf("Function signature nested inside wrong function "
"definition:\n");
printf("%p inside %s %p instead of %s %p\n",
ir,
this->current_function->name, this->current_function,
ir->function_name(), ir->function());
abort();
}
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit(ir_variable *ir)
{
/* An ir_variable is the one thing that can (and will) appear multiple times
* in an IR tree. It is added to the hashtable so that it can be used
* in the ir_dereference_variable handler to ensure that a variable is
* declared before it is dereferenced.
*/
hash_table_insert(ht, ir, ir);
return visit_continue;
}
void
ir_validate::validate_ir(ir_instruction *ir, void *data)
{
struct hash_table *ht = (struct hash_table *) data;
if (hash_table_find(ht, ir)) {
printf("Instruction node present twice in ir tree:\n");
ir->print();
printf("\n");
abort();
}
hash_table_insert(ht, ir, ir);
}
void
check_node_type(ir_instruction *ir, void *data)
{
if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {
printf("Instruction node with unset type\n");
ir->print(); printf("\n");
}
}
void
validate_ir_tree(exec_list *instructions)
{
ir_validate v;
v.run(instructions);
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
visit_tree(ir, check_node_type, NULL);
}
}
<commit_msg>glsl2: Check that nodes in a valid tree aren't error-type.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file ir_validate.cpp
*
* Attempts to verify that various invariants of the IR tree are true.
*
* In particular, at the moment it makes sure that no single
* ir_instruction node except for ir_variable appears multiple times
* in the ir tree. ir_variable does appear multiple times: Once as a
* declaration in an exec_list, and multiple times as the endpoint of
* a dereference chain.
*/
#include <inttypes.h>
#include "ir.h"
#include "ir_hierarchical_visitor.h"
#include "hash_table.h"
#include "glsl_types.h"
class ir_validate : public ir_hierarchical_visitor {
public:
ir_validate()
{
this->ht = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
this->current_function = NULL;
this->callback = ir_validate::validate_ir;
this->data = ht;
}
~ir_validate()
{
hash_table_dtor(this->ht);
}
virtual ir_visitor_status visit(ir_variable *v);
virtual ir_visitor_status visit(ir_dereference_variable *ir);
virtual ir_visitor_status visit_enter(ir_function *ir);
virtual ir_visitor_status visit_leave(ir_function *ir);
virtual ir_visitor_status visit_enter(ir_function_signature *ir);
static void validate_ir(ir_instruction *ir, void *data);
ir_function *current_function;
struct hash_table *ht;
};
ir_visitor_status
ir_validate::visit(ir_dereference_variable *ir)
{
if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {
printf("ir_dereference_variable @ %p does not specify a variable %p\n",
ir, ir->var);
abort();
}
if (hash_table_find(ht, ir->var) == NULL) {
printf("ir_dereference_variable @ %p specifies undeclared variable "
"`%s' @ %p\n",
ir, ir->var->name, ir->var);
abort();
}
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit_enter(ir_function *ir)
{
/* Function definitions cannot be nested.
*/
if (this->current_function != NULL) {
printf("Function definition nested inside another function "
"definition:\n");
printf("%s %p inside %s %p\n",
ir->name, ir,
this->current_function->name, this->current_function);
abort();
}
/* Store the current function hierarchy being traversed. This is used
* by the function signature visitor to ensure that the signatures are
* linked with the correct functions.
*/
this->current_function = ir;
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit_leave(ir_function *ir)
{
(void) ir;
this->current_function = NULL;
return visit_continue;
}
ir_visitor_status
ir_validate::visit_enter(ir_function_signature *ir)
{
if (this->current_function != ir->function()) {
printf("Function signature nested inside wrong function "
"definition:\n");
printf("%p inside %s %p instead of %s %p\n",
ir,
this->current_function->name, this->current_function,
ir->function_name(), ir->function());
abort();
}
this->validate_ir(ir, this->data);
return visit_continue;
}
ir_visitor_status
ir_validate::visit(ir_variable *ir)
{
/* An ir_variable is the one thing that can (and will) appear multiple times
* in an IR tree. It is added to the hashtable so that it can be used
* in the ir_dereference_variable handler to ensure that a variable is
* declared before it is dereferenced.
*/
hash_table_insert(ht, ir, ir);
return visit_continue;
}
void
ir_validate::validate_ir(ir_instruction *ir, void *data)
{
struct hash_table *ht = (struct hash_table *) data;
if (hash_table_find(ht, ir)) {
printf("Instruction node present twice in ir tree:\n");
ir->print();
printf("\n");
abort();
}
hash_table_insert(ht, ir, ir);
}
void
check_node_type(ir_instruction *ir, void *data)
{
if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {
printf("Instruction node with unset type\n");
ir->print(); printf("\n");
}
assert(ir->type != glsl_type::error_type);
}
void
validate_ir_tree(exec_list *instructions)
{
ir_validate v;
v.run(instructions);
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
visit_tree(ir, check_node_type, NULL);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************/
/* Sockets.cpp Copyright (c) Ladislav Zezula 2021 */
/*---------------------------------------------------------------------------*/
/* Don't call this module "Socket.cpp", otherwise VS 2019 will not link it */
/* Socket functions for CascLib. */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 13.02.21 1.00 Lad Created */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "../CascLib.h"
#include "../CascCommon.h"
//-----------------------------------------------------------------------------
// Local variables
CASC_SOCKET_CACHE SocketCache;
//-----------------------------------------------------------------------------
// CASC_SOCKET functions
// Guarantees that there is zero terminator after the response
char * CASC_SOCKET::ReadResponse(const char * request, size_t request_length, size_t * PtrLength)
{
CASC_MIME_HTTP HttpInfo;
char * server_response = NULL;
size_t total_received = 0;
size_t block_increment = 0x8000;
size_t buffer_size = block_increment;
int bytes_received = 0;
// Pre-set the result length
if(PtrLength != NULL)
PtrLength[0] = 0;
if(request_length == 0)
request_length = strlen(request);
// Lock the socket
CascLock(Lock);
// Send the request to the remote host. On Linux, this call may send signal(SIGPIPE),
// we need to prevend that by using the MSG_NOSIGNAL flag. On Windows, it fails normally.
while(send(sock, request, (int)request_length, MSG_NOSIGNAL) == SOCKET_ERROR)
{
// If the connection was closed by the remote host, we try to reconnect
if(ReconnectAfterShutdown(sock, remoteItem) == INVALID_SOCKET)
{
SetCascError(ERROR_NETWORK_NOT_AVAILABLE);
CascUnlock(Lock);
return NULL;
}
}
// Allocate buffer for server response. Allocate one extra byte for zero terminator
if((server_response = CASC_ALLOC<char>(buffer_size + 1)) != NULL)
{
for(;;)
{
// Reallocate the buffer size, if needed
if(total_received == buffer_size)
{
if((server_response = CASC_REALLOC(char, server_response, buffer_size + block_increment + 1)) == NULL)
{
SetCascError(ERROR_NOT_ENOUGH_MEMORY);
CascUnlock(Lock);
return NULL;
}
buffer_size += block_increment;
}
// Receive the next part of the response, up to buffer size
// Return value 0 means "connection closed", -1 means an error
bytes_received = recv(sock, server_response + total_received, (int)(buffer_size - total_received), 0);
if(bytes_received <= 0)
break;
// Append the number of bytes received. Also terminate response with zero
total_received += bytes_received;
server_response[total_received] = 0;
// On a HTTP protocol, we need to check whether we received all data
if(HttpInfo.IsDataComplete(server_response, total_received))
break;
}
}
// Unlock the socket
CascUnlock(Lock);
// Give the result to the caller
if(PtrLength != NULL)
PtrLength[0] = total_received;
return server_response;
}
DWORD CASC_SOCKET::AddRef()
{
return CascInterlockedIncrement(&dwRefCount);
}
void CASC_SOCKET::Release()
{
// Note: If this is a cached socket, there will be extra reference from the cache
if(CascInterlockedDecrement(&dwRefCount) == 0)
{
Delete();
}
}
int CASC_SOCKET::GetSockError()
{
#ifdef CASCLIB_PLATFORM_WINDOWS
return WSAGetLastError();
#else
return errno;
#endif
}
DWORD CASC_SOCKET::GetAddrInfoWrapper(const char * hostName, unsigned portNum, PADDRINFO hints, PADDRINFO * ppResult)
{
char portNumString[16];
// Prepare the port number
CascStrPrintf(portNumString, _countof(portNumString), "%d", portNum);
// Attempt to connect
for(;;)
{
// Attempt to call the addrinfo
DWORD dwErrCode = getaddrinfo(hostName, portNumString, hints, ppResult);
// Error-specific handling
switch(dwErrCode)
{
#ifdef CASCLIB_PLATFORM_WINDOWS
case WSANOTINITIALISED: // Windows-specific: WSAStartup not called
{
WSADATA wsd;
WSAStartup(MAKEWORD(2, 2), &wsd);
continue;
}
#endif
case EAI_AGAIN: // Temporary error, try again
continue;
default: // Any other result, incl. ERROR_SUCCESS
return dwErrCode;
}
}
}
SOCKET CASC_SOCKET::CreateAndConnect(addrinfo * remoteItem)
{
SOCKET sock;
// Create new socket
// On error, returns returns INVALID_SOCKET (-1) on Windows, -1 on Linux
if((sock = socket(remoteItem->ai_family, remoteItem->ai_socktype, remoteItem->ai_protocol)) > 0)
{
// Connect to the remote host
// On error, returns SOCKET_ERROR (-1) on Windows, -1 on Linux
if(connect(sock, remoteItem->ai_addr, (int)remoteItem->ai_addrlen) == 0)
return sock;
// Failed. Close the socket and return 0
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
SOCKET CASC_SOCKET::ReconnectAfterShutdown(SOCKET & sock, addrinfo * remoteItem)
{
// Retrieve the error code related to previous socket operation
switch(GetSockError())
{
case EPIPE: // Non-Windows
case WSAECONNRESET: // Windows
{
// Close the old socket
if(sock != INVALID_SOCKET)
closesocket(sock);
// Attempt to reconnect
sock = CreateAndConnect(remoteItem);
return sock;
}
}
// Another problem
return INVALID_SOCKET;
}
PCASC_SOCKET CASC_SOCKET::New(addrinfo * remoteList, addrinfo * remoteItem, const char * hostName, unsigned portNum, SOCKET sock)
{
PCASC_SOCKET pSocket;
size_t length = strlen(hostName);
// Allocate enough bytes
pSocket = (PCASC_SOCKET)CASC_ALLOC<BYTE>(sizeof(CASC_SOCKET) + length);
if(pSocket != NULL)
{
// Fill the entire object with zero
memset(pSocket, 0, sizeof(CASC_SOCKET) + length);
pSocket->remoteList = remoteList;
pSocket->remoteItem = remoteItem;
pSocket->dwRefCount = 1;
pSocket->portNum = portNum;
pSocket->sock = sock;
// Init the remote host name
CascStrCopy((char *)pSocket->hostName, length + 1, hostName);
// Init the socket lock
CascInitLock(pSocket->Lock);
}
return pSocket;
}
PCASC_SOCKET CASC_SOCKET::Connect(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
addrinfo * remoteList;
addrinfo * remoteItem;
addrinfo hints = {0};
SOCKET sock;
int nErrCode;
// Retrieve the information about the remote host
// This will fail immediately if there is no connection to the internet
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
nErrCode = GetAddrInfoWrapper(hostName, portNum, &hints, &remoteList);
// Handle error code
if(nErrCode == 0)
{
// Try to connect to any address provided by the getaddrinfo()
for(remoteItem = remoteList; remoteItem != NULL; remoteItem = remoteItem->ai_next)
{
// Create new socket and connect to the remote host
if((sock = CreateAndConnect(remoteItem)) != 0)
{
// Create new instance of the CASC_SOCKET structure
if((pSocket = CASC_SOCKET::New(remoteList, remoteItem, hostName, portNum, sock)) != NULL)
{
return pSocket;
}
// Close the socket
closesocket(sock);
}
}
// Couldn't find a network
nErrCode = ERROR_NETWORK_NOT_AVAILABLE;
}
SetCascError(nErrCode);
return NULL;
}
void CASC_SOCKET::Delete()
{
PCASC_SOCKET pThis = this;
// Remove the socket from the cache
if(pCache != NULL)
pCache->UnlinkSocket(this);
pCache = NULL;
// Close the socket, if any
if(sock != 0)
closesocket(sock);
sock = 0;
// Free the lock
CascFreeLock(Lock);
// Free the socket itself
CASC_FREE(pThis);
}
//-----------------------------------------------------------------------------
// The CASC_SOCKET_CACHE class
CASC_SOCKET_CACHE::CASC_SOCKET_CACHE()
{
pFirst = pLast = NULL;
dwRefCount = 0;
}
CASC_SOCKET_CACHE::~CASC_SOCKET_CACHE()
{
PurgeAll();
}
PCASC_SOCKET CASC_SOCKET_CACHE::Find(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)
{
if(!_stricmp(pSocket->hostName, hostName) && (pSocket->portNum == portNum))
break;
}
return pSocket;
}
PCASC_SOCKET CASC_SOCKET_CACHE::InsertSocket(PCASC_SOCKET pSocket)
{
if(pSocket != NULL && pSocket->pCache == NULL)
{
// Do we have caching turned on?
if(dwRefCount > 0)
{
// Insert one reference to the socket to mark it as cached
pSocket->AddRef();
// Insert the socket to the chain
if(pFirst == NULL && pLast == NULL)
{
pFirst = pLast = pSocket;
}
else
{
pSocket->pPrev = pLast;
pLast->pNext = pSocket;
pLast = pSocket;
}
// Mark the socket as cached
pSocket->pCache = this;
}
}
return pSocket;
}
void CASC_SOCKET_CACHE::UnlinkSocket(PCASC_SOCKET pSocket)
{
// Only if it's a valid socket
if(pSocket != NULL)
{
// Check the first and the last items
if(pSocket == pFirst)
pFirst = pSocket->pNext;
if(pSocket == pLast)
pLast = pSocket->pPrev;
// Disconnect the socket from the chain
if(pSocket->pPrev != NULL)
pSocket->pPrev->pNext = pSocket->pNext;
if(pSocket->pNext != NULL)
pSocket->pNext->pPrev = pSocket->pPrev;
}
}
void CASC_SOCKET_CACHE::SetCaching(bool bAddRef)
{
PCASC_SOCKET pSocket;
PCASC_SOCKET pNext;
// We need to increment reference count for each enabled caching
if(bAddRef)
{
// Add one reference to all currently held sockets
if(dwRefCount == 0)
{
for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)
pSocket->AddRef();
}
// Increment of references for the future sockets
CascInterlockedIncrement(&dwRefCount);
}
else
{
// Sanity check for multiple calls to dereference
assert(dwRefCount > 0);
// Dereference the reference count. If drops to zero, dereference all sockets as well
if(CascInterlockedDecrement(&dwRefCount) == 0)
{
for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)
{
pNext = pSocket->pNext;
pSocket->Release();
}
}
}
}
void CASC_SOCKET_CACHE::PurgeAll()
{
PCASC_SOCKET pSocket;
PCASC_SOCKET pNext;
// Dereference all current sockets
for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)
{
pNext = pSocket->pNext;
pSocket->Delete();
}
}
//-----------------------------------------------------------------------------
// Public functions
PCASC_SOCKET sockets_connect(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
// Try to find the item in the cache
if((pSocket = SocketCache.Find(hostName, portNum)) != NULL)
{
pSocket->AddRef();
}
else
{
// Create new socket and connect it to the remote host
pSocket = CASC_SOCKET::Connect(hostName, portNum);
// Insert it to the cache, if it's a HTTP connection
if(pSocket->portNum == CASC_PORT_HTTP)
pSocket = SocketCache.InsertSocket(pSocket);
}
return pSocket;
}
void sockets_set_caching(bool caching)
{
SocketCache.SetCaching(caching);
}
<commit_msg>Fix build with clang<commit_after>/*****************************************************************************/
/* Sockets.cpp Copyright (c) Ladislav Zezula 2021 */
/*---------------------------------------------------------------------------*/
/* Don't call this module "Socket.cpp", otherwise VS 2019 will not link it */
/* Socket functions for CascLib. */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 13.02.21 1.00 Lad Created */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "../CascLib.h"
#include "../CascCommon.h"
//-----------------------------------------------------------------------------
// Local variables
CASC_SOCKET_CACHE SocketCache;
//-----------------------------------------------------------------------------
// CASC_SOCKET functions
// Guarantees that there is zero terminator after the response
char * CASC_SOCKET::ReadResponse(const char * request, size_t request_length, size_t * PtrLength)
{
CASC_MIME_HTTP HttpInfo;
char * server_response = NULL;
size_t total_received = 0;
size_t block_increment = 0x8000;
size_t buffer_size = block_increment;
int bytes_received = 0;
// Pre-set the result length
if(PtrLength != NULL)
PtrLength[0] = 0;
if(request_length == 0)
request_length = strlen(request);
// Lock the socket
CascLock(Lock);
// Send the request to the remote host. On Linux, this call may send signal(SIGPIPE),
// we need to prevend that by using the MSG_NOSIGNAL flag. On Windows, it fails normally.
while(send(sock, request, (int)request_length, MSG_NOSIGNAL) == SOCKET_ERROR)
{
// If the connection was closed by the remote host, we try to reconnect
if(ReconnectAfterShutdown(sock, remoteItem) == INVALID_SOCKET)
{
SetCascError(ERROR_NETWORK_NOT_AVAILABLE);
CascUnlock(Lock);
return NULL;
}
}
// Allocate buffer for server response. Allocate one extra byte for zero terminator
if((server_response = CASC_ALLOC<char>(buffer_size + 1)) != NULL)
{
for(;;)
{
// Reallocate the buffer size, if needed
if(total_received == buffer_size)
{
if((server_response = CASC_REALLOC(char, server_response, buffer_size + block_increment + 1)) == NULL)
{
SetCascError(ERROR_NOT_ENOUGH_MEMORY);
CascUnlock(Lock);
return NULL;
}
buffer_size += block_increment;
}
// Receive the next part of the response, up to buffer size
// Return value 0 means "connection closed", -1 means an error
bytes_received = recv(sock, server_response + total_received, (int)(buffer_size - total_received), 0);
if(bytes_received <= 0)
break;
// Append the number of bytes received. Also terminate response with zero
total_received += bytes_received;
server_response[total_received] = 0;
// On a HTTP protocol, we need to check whether we received all data
if(HttpInfo.IsDataComplete(server_response, total_received))
break;
}
}
// Unlock the socket
CascUnlock(Lock);
// Give the result to the caller
if(PtrLength != NULL)
PtrLength[0] = total_received;
return server_response;
}
DWORD CASC_SOCKET::AddRef()
{
return CascInterlockedIncrement(&dwRefCount);
}
void CASC_SOCKET::Release()
{
// Note: If this is a cached socket, there will be extra reference from the cache
if(CascInterlockedDecrement(&dwRefCount) == 0)
{
Delete();
}
}
int CASC_SOCKET::GetSockError()
{
#ifdef CASCLIB_PLATFORM_WINDOWS
return WSAGetLastError();
#else
return errno;
#endif
}
DWORD CASC_SOCKET::GetAddrInfoWrapper(const char * hostName, unsigned portNum, PADDRINFO hints, PADDRINFO * ppResult)
{
char portNumString[16];
// Prepare the port number
CascStrPrintf(portNumString, _countof(portNumString), "%d", portNum);
// Attempt to connect
for(;;)
{
// Attempt to call the addrinfo
DWORD dwErrCode = getaddrinfo(hostName, portNumString, hints, ppResult);
// Error-specific handling
switch(dwErrCode)
{
#ifdef CASCLIB_PLATFORM_WINDOWS
case WSANOTINITIALISED: // Windows-specific: WSAStartup not called
{
WSADATA wsd;
WSAStartup(MAKEWORD(2, 2), &wsd);
continue;
}
#endif
case (DWORD)EAI_AGAIN: // Temporary error, try again
continue;
default: // Any other result, incl. ERROR_SUCCESS
return dwErrCode;
}
}
}
SOCKET CASC_SOCKET::CreateAndConnect(addrinfo * remoteItem)
{
SOCKET sock;
// Create new socket
// On error, returns returns INVALID_SOCKET (-1) on Windows, -1 on Linux
if((sock = socket(remoteItem->ai_family, remoteItem->ai_socktype, remoteItem->ai_protocol)) > 0)
{
// Connect to the remote host
// On error, returns SOCKET_ERROR (-1) on Windows, -1 on Linux
if(connect(sock, remoteItem->ai_addr, (int)remoteItem->ai_addrlen) == 0)
return sock;
// Failed. Close the socket and return 0
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
SOCKET CASC_SOCKET::ReconnectAfterShutdown(SOCKET & sock, addrinfo * remoteItem)
{
// Retrieve the error code related to previous socket operation
switch(GetSockError())
{
case EPIPE: // Non-Windows
case WSAECONNRESET: // Windows
{
// Close the old socket
if(sock != INVALID_SOCKET)
closesocket(sock);
// Attempt to reconnect
sock = CreateAndConnect(remoteItem);
return sock;
}
}
// Another problem
return INVALID_SOCKET;
}
PCASC_SOCKET CASC_SOCKET::New(addrinfo * remoteList, addrinfo * remoteItem, const char * hostName, unsigned portNum, SOCKET sock)
{
PCASC_SOCKET pSocket;
size_t length = strlen(hostName);
// Allocate enough bytes
pSocket = (PCASC_SOCKET)CASC_ALLOC<BYTE>(sizeof(CASC_SOCKET) + length);
if(pSocket != NULL)
{
// Fill the entire object with zero
memset(pSocket, 0, sizeof(CASC_SOCKET) + length);
pSocket->remoteList = remoteList;
pSocket->remoteItem = remoteItem;
pSocket->dwRefCount = 1;
pSocket->portNum = portNum;
pSocket->sock = sock;
// Init the remote host name
CascStrCopy((char *)pSocket->hostName, length + 1, hostName);
// Init the socket lock
CascInitLock(pSocket->Lock);
}
return pSocket;
}
PCASC_SOCKET CASC_SOCKET::Connect(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
addrinfo * remoteList;
addrinfo * remoteItem;
addrinfo hints = {0};
SOCKET sock;
int nErrCode;
// Retrieve the information about the remote host
// This will fail immediately if there is no connection to the internet
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
nErrCode = GetAddrInfoWrapper(hostName, portNum, &hints, &remoteList);
// Handle error code
if(nErrCode == 0)
{
// Try to connect to any address provided by the getaddrinfo()
for(remoteItem = remoteList; remoteItem != NULL; remoteItem = remoteItem->ai_next)
{
// Create new socket and connect to the remote host
if((sock = CreateAndConnect(remoteItem)) != 0)
{
// Create new instance of the CASC_SOCKET structure
if((pSocket = CASC_SOCKET::New(remoteList, remoteItem, hostName, portNum, sock)) != NULL)
{
return pSocket;
}
// Close the socket
closesocket(sock);
}
}
// Couldn't find a network
nErrCode = ERROR_NETWORK_NOT_AVAILABLE;
}
SetCascError(nErrCode);
return NULL;
}
void CASC_SOCKET::Delete()
{
PCASC_SOCKET pThis = this;
// Remove the socket from the cache
if(pCache != NULL)
pCache->UnlinkSocket(this);
pCache = NULL;
// Close the socket, if any
if(sock != 0)
closesocket(sock);
sock = 0;
// Free the lock
CascFreeLock(Lock);
// Free the socket itself
CASC_FREE(pThis);
}
//-----------------------------------------------------------------------------
// The CASC_SOCKET_CACHE class
CASC_SOCKET_CACHE::CASC_SOCKET_CACHE()
{
pFirst = pLast = NULL;
dwRefCount = 0;
}
CASC_SOCKET_CACHE::~CASC_SOCKET_CACHE()
{
PurgeAll();
}
PCASC_SOCKET CASC_SOCKET_CACHE::Find(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)
{
if(!_stricmp(pSocket->hostName, hostName) && (pSocket->portNum == portNum))
break;
}
return pSocket;
}
PCASC_SOCKET CASC_SOCKET_CACHE::InsertSocket(PCASC_SOCKET pSocket)
{
if(pSocket != NULL && pSocket->pCache == NULL)
{
// Do we have caching turned on?
if(dwRefCount > 0)
{
// Insert one reference to the socket to mark it as cached
pSocket->AddRef();
// Insert the socket to the chain
if(pFirst == NULL && pLast == NULL)
{
pFirst = pLast = pSocket;
}
else
{
pSocket->pPrev = pLast;
pLast->pNext = pSocket;
pLast = pSocket;
}
// Mark the socket as cached
pSocket->pCache = this;
}
}
return pSocket;
}
void CASC_SOCKET_CACHE::UnlinkSocket(PCASC_SOCKET pSocket)
{
// Only if it's a valid socket
if(pSocket != NULL)
{
// Check the first and the last items
if(pSocket == pFirst)
pFirst = pSocket->pNext;
if(pSocket == pLast)
pLast = pSocket->pPrev;
// Disconnect the socket from the chain
if(pSocket->pPrev != NULL)
pSocket->pPrev->pNext = pSocket->pNext;
if(pSocket->pNext != NULL)
pSocket->pNext->pPrev = pSocket->pPrev;
}
}
void CASC_SOCKET_CACHE::SetCaching(bool bAddRef)
{
PCASC_SOCKET pSocket;
PCASC_SOCKET pNext;
// We need to increment reference count for each enabled caching
if(bAddRef)
{
// Add one reference to all currently held sockets
if(dwRefCount == 0)
{
for(pSocket = pFirst; pSocket != NULL; pSocket = pSocket->pNext)
pSocket->AddRef();
}
// Increment of references for the future sockets
CascInterlockedIncrement(&dwRefCount);
}
else
{
// Sanity check for multiple calls to dereference
assert(dwRefCount > 0);
// Dereference the reference count. If drops to zero, dereference all sockets as well
if(CascInterlockedDecrement(&dwRefCount) == 0)
{
for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)
{
pNext = pSocket->pNext;
pSocket->Release();
}
}
}
}
void CASC_SOCKET_CACHE::PurgeAll()
{
PCASC_SOCKET pSocket;
PCASC_SOCKET pNext;
// Dereference all current sockets
for(pSocket = pFirst; pSocket != NULL; pSocket = pNext)
{
pNext = pSocket->pNext;
pSocket->Delete();
}
}
//-----------------------------------------------------------------------------
// Public functions
PCASC_SOCKET sockets_connect(const char * hostName, unsigned portNum)
{
PCASC_SOCKET pSocket;
// Try to find the item in the cache
if((pSocket = SocketCache.Find(hostName, portNum)) != NULL)
{
pSocket->AddRef();
}
else
{
// Create new socket and connect it to the remote host
pSocket = CASC_SOCKET::Connect(hostName, portNum);
// Insert it to the cache, if it's a HTTP connection
if(pSocket->portNum == CASC_PORT_HTTP)
pSocket = SocketCache.InsertSocket(pSocket);
}
return pSocket;
}
void sockets_set_caching(bool caching)
{
SocketCache.SetCaching(caching);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2016 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// OptionsSystem.cpp : implementation file
//
#include "stdafx.h"
#include "passwordsafe.h"
#include "ThisMfcApp.h" // For Help
#include "Options_PropertySheet.h"
#include "GeneralMsgBox.h"
#include "core/PwsPlatform.h"
#include "core/PWSprefs.h"
#include "resource.h"
#include "resource2.h" // Menu, Toolbar & Accelerator resources
#include "resource3.h" // String resources
#include "OptionsSystem.h" // Must be after resource.h
extern bool OfferConfigMigration();
extern bool PerformConfigMigration();
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsSystem property page
bool COptionsSystem::m_bShowConfigFile = false;
IMPLEMENT_DYNAMIC(COptionsSystem, COptions_PropertyPage)
COptionsSystem::COptionsSystem(CWnd *pParent, st_Opt_master_data *pOPTMD)
: COptions_PropertyPage(pParent,
COptionsSystem::IDD, COptionsSystem::IDD_SHORT,
pOPTMD),
m_DeleteRegistry(FALSE), m_saveDeleteRegistry(FALSE),
m_Migrate2Appdata(FALSE), m_saveMigrate2Appdata(FALSE)
{
#ifdef _DEBUG
m_bShowConfigFile = true;
#endif
m_UseSystemTray = M_UseSystemTray();
m_HideSystemTray = M_HideSystemTray();
m_Startup = M_Startup();
m_MRUOnFileMenu = M_MRUOnFileMenu();
m_DefaultOpenRO = M_DefaultOpenRO();
m_MultipleInstances = M_MultipleInstances();
m_MaxREItems = M_MaxREItems();
m_MaxMRUItems = M_MaxMRUItems();
m_InitialHotkeyState = M_AppHotKeyEnabled();
}
void COptionsSystem::DoDataExchange(CDataExchange *pDX)
{
CPWPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COptionsSystem)
DDX_Text(pDX, IDC_MAXREITEMS, m_MaxREItems);
DDV_MinMaxInt(pDX, m_MaxREItems, 0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);
DDX_Check(pDX, IDC_DEFPWUSESYSTRAY, m_UseSystemTray);
DDX_Check(pDX, IDC_DEFPWHIDESYSTRAY, m_HideSystemTray);
DDX_Check(pDX, IDC_STARTUP, m_Startup);
DDX_Text(pDX, IDC_MAXMRUITEMS, m_MaxMRUItems);
DDV_MinMaxInt(pDX, m_MaxMRUItems, 0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);
DDX_Check(pDX, IDC_MRU_ONFILEMENU, m_MRUOnFileMenu);
DDX_Check(pDX, IDC_REGDEL, m_DeleteRegistry);
DDX_Check(pDX, IDC_MIGRATETOAPPDATA, m_Migrate2Appdata);
DDX_Check(pDX, IDC_DEFAULTOPENRO, m_DefaultOpenRO);
DDX_Check(pDX, IDC_MULTIPLEINSTANCES, m_MultipleInstances);
DDX_Control(pDX, IDC_REGDELHELP, m_Help1);
DDX_Control(pDX, IDC_MIGRATETOAPPDATAHELP, m_Help2);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(COptionsSystem, CPWPropertyPage)
//{{AFX_MSG_MAP(COptionsSystem)
ON_BN_CLICKED(ID_HELP, OnHelp)
ON_BN_CLICKED(IDC_DEFPWUSESYSTRAY, OnUseSystemTray)
ON_BN_CLICKED(IDC_STARTUP, OnStartup)
ON_BN_CLICKED(IDC_REGDEL, OnSetDeleteRegistry)
ON_BN_CLICKED(IDC_MIGRATETOAPPDATA, OnSetMigrate2Appdata)
ON_BN_CLICKED(IDC_APPLYCONFIGCHANGES, OnApplyConfigChanges)
ON_MESSAGE(PSM_QUERYSIBLINGS, OnQuerySiblings)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COptionsSystem message handlers
BOOL COptionsSystem::OnInitDialog()
{
COptions_PropertyPage::OnInitDialog();
PWSprefs *prefs = PWSprefs::GetInstance();
if (!m_bShowConfigFile) {
GetDlgItem(IDC_STATIC_CONFIGFILE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC_RWSTATUS)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CONFIGFILE)->ShowWindow(SW_HIDE);
} else {
PWSprefs::ConfigOption configoption;
std::wstring wsCF = prefs->GetConfigFile(configoption);
std::wstring wsCO(L"");
switch (configoption) {
case PWSprefs::CF_NONE:
LoadAString(wsCF, IDS_NONE);
break;
case PWSprefs::CF_REGISTRY:
LoadAString(wsCF, IDS_REGISTRY);
break;
case PWSprefs::CF_FILE_RO:
LoadAString(wsCO, IDS_READ_ONLY);
break;
case PWSprefs::CF_FILE_RW:
case PWSprefs::CF_FILE_RW_NEW:
LoadAString(wsCO, IDS_READ_WRITE);
break;
default:
ASSERT(0);
}
GetDlgItem(IDC_CONFIGFILE)->SetWindowText(wsCF.c_str());
GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());
}
bool bofferdeleteregistry = prefs->OfferDeleteRegistry();
bool boffermigrate2appdata = OfferConfigMigration();
if (!bofferdeleteregistry) {
GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
}
if (!boffermigrate2appdata) {
GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
}
if (!bofferdeleteregistry && !boffermigrate2appdata) {
GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);
} else {
GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);
}
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);
CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);
pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));
pspin->SetRange(0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);
pspin->SetBase(10);
pspin->SetPos(m_MaxREItems);
pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);
pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));
pspin->SetRange(0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);
pspin->SetBase(10);
pspin->SetPos(m_MaxMRUItems);
OnUseSystemTray();
if (InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 0)) {
m_Help1.Init(IDB_QUESTIONMARK);
m_Help2.Init(IDB_QUESTIONMARK);
// Note naming convention: string IDS_xxx corresponds to control IDC_xxx_HELP
AddTool(IDC_REGDELHELP, IDS_REGDEL);
AddTool(IDC_MIGRATETOAPPDATAHELP, IDS_MIGRATETOAPPDATA);
ActivateToolTip();
} else {
m_Help1.EnableWindow(FALSE);
m_Help1.ShowWindow(SW_HIDE);
m_Help2.EnableWindow(FALSE);
m_Help2.ShowWindow(SW_HIDE);
}
if (!boffermigrate2appdata) {
m_Help2.EnableWindow(FALSE);
m_Help2.ShowWindow(SW_HIDE);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
LRESULT COptionsSystem::OnQuerySiblings(WPARAM wParam, LPARAM )
{
UpdateData(TRUE);
// Have any of my fields been changed?
switch (wParam) {
case PP_DATA_CHANGED:
if (M_UseSystemTray() != m_UseSystemTray ||
M_HideSystemTray() != m_HideSystemTray ||
(m_UseSystemTray == TRUE &&
M_MaxREItems() != m_MaxREItems) ||
M_Startup() != m_Startup ||
M_MaxMRUItems() != m_MaxMRUItems ||
M_MRUOnFileMenu() != m_MRUOnFileMenu ||
M_DefaultOpenRO() != m_DefaultOpenRO ||
M_MultipleInstances() != m_MultipleInstances ||
m_saveDeleteRegistry != m_DeleteRegistry ||
m_saveMigrate2Appdata != m_Migrate2Appdata)
return 1L;
break;
case PP_UPDATE_VARIABLES:
// Since OnOK calls OnApply after we need to verify and/or
// copy data into the entry - we do it ourselves here first
if (OnApply() == FALSE)
return 1L;
}
return 0L;
}
BOOL COptionsSystem::OnApply()
{
UpdateData(TRUE);
M_UseSystemTray() = m_UseSystemTray;
M_HideSystemTray() = m_HideSystemTray;
M_Startup() = m_Startup;
M_MRUOnFileMenu() = m_MRUOnFileMenu;
M_DefaultOpenRO() = m_DefaultOpenRO;
M_MultipleInstances() = m_MultipleInstances;
M_MaxREItems() = m_MaxREItems;
M_MaxMRUItems() = m_MaxMRUItems;
M_AppHotKeyEnabled() = m_InitialHotkeyState;
return COptions_PropertyPage::OnApply();
}
BOOL COptionsSystem::PreTranslateMessage(MSG* pMsg)
{
RelayToolTipEvent(pMsg);
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_F1) {
PostMessage(WM_COMMAND, MAKELONG(ID_HELP, BN_CLICKED), NULL);
return TRUE;
}
return COptions_PropertyPage::PreTranslateMessage(pMsg);
}
BOOL COptionsSystem::OnKillActive()
{
// Needed as we have DDV routines.
return CPWPropertyPage::OnKillActive();
}
void COptionsSystem::OnHelp()
{
ShowHelp(L"::/html/system_tab.html");
}
void COptionsSystem::OnUseSystemTray()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==
BST_CHECKED) ? TRUE : FALSE;
GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(enable);
GetDlgItem(IDC_MAXREITEMS)->EnableWindow(enable);
GetDlgItem(IDC_RESPIN)->EnableWindow(enable);
if (enable == TRUE) {
// Check if user has the Misc PP open and hot key set
if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {
// Yes - open and hot key is set
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);
} else {
// No - Not open - then take initial value as the answer
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);
}
}
}
void COptionsSystem::OnStartup()
{
// Startup implies System tray
bool enable = ((CButton*)GetDlgItem(IDC_STARTUP))->GetCheck() == BST_CHECKED;
if (enable) {
((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->SetCheck(BST_CHECKED);
GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(TRUE);
GetDlgItem(IDC_MAXREITEMS)->EnableWindow(TRUE);
GetDlgItem(IDC_RESPIN)->EnableWindow(TRUE);
}
}
void COptionsSystem::OnSetDeleteRegistry()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_REGDEL))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);
}
void COptionsSystem::OnSetMigrate2Appdata()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_MIGRATETOAPPDATA))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);
}
void COptionsSystem::OnApplyConfigChanges()
{
UpdateData(TRUE);
CGeneralMsgBox gmb;
if (m_DeleteRegistry == TRUE) {
if (gmb.AfxMessageBox(IDS_CONFIRMDELETEREG, MB_YESNO | MB_ICONSTOP) == IDYES) {
PWSprefs::GetInstance()->DeleteRegistryEntries();
GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
}
}
if (m_Migrate2Appdata == TRUE) {
GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
PerformConfigMigration();
}
if (!GetDlgItem(IDC_REGDEL)->IsWindowEnabled() &&
!GetDlgItem(IDC_MIGRATETOAPPDATA)->IsWindowEnabled())
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);
UpdateData(FALSE);
}
BOOL COptionsSystem::OnSetActive()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==
BST_CHECKED) ? TRUE : FALSE;
if (enable == TRUE) {
// Check if user has the Misc PP open and hot key set
if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {
// Yes - open and hot key is set
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);
} else {
// No - Not open - then take initial value as the answer
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);
}
}
return CPWPropertyPage::OnSetActive();
}
<commit_msg>BR1357: Hide Options->System Reg cleanup tooltip button<commit_after>/*
* Copyright (c) 2003-2016 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// OptionsSystem.cpp : implementation file
//
#include "stdafx.h"
#include "passwordsafe.h"
#include "ThisMfcApp.h" // For Help
#include "Options_PropertySheet.h"
#include "GeneralMsgBox.h"
#include "core/PwsPlatform.h"
#include "core/PWSprefs.h"
#include "resource.h"
#include "resource2.h" // Menu, Toolbar & Accelerator resources
#include "resource3.h" // String resources
#include "OptionsSystem.h" // Must be after resource.h
extern bool OfferConfigMigration();
extern bool PerformConfigMigration();
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsSystem property page
bool COptionsSystem::m_bShowConfigFile = false;
IMPLEMENT_DYNAMIC(COptionsSystem, COptions_PropertyPage)
COptionsSystem::COptionsSystem(CWnd *pParent, st_Opt_master_data *pOPTMD)
: COptions_PropertyPage(pParent,
COptionsSystem::IDD, COptionsSystem::IDD_SHORT,
pOPTMD),
m_DeleteRegistry(FALSE), m_saveDeleteRegistry(FALSE),
m_Migrate2Appdata(FALSE), m_saveMigrate2Appdata(FALSE)
{
#ifdef _DEBUG
m_bShowConfigFile = true;
#endif
m_UseSystemTray = M_UseSystemTray();
m_HideSystemTray = M_HideSystemTray();
m_Startup = M_Startup();
m_MRUOnFileMenu = M_MRUOnFileMenu();
m_DefaultOpenRO = M_DefaultOpenRO();
m_MultipleInstances = M_MultipleInstances();
m_MaxREItems = M_MaxREItems();
m_MaxMRUItems = M_MaxMRUItems();
m_InitialHotkeyState = M_AppHotKeyEnabled();
}
void COptionsSystem::DoDataExchange(CDataExchange *pDX)
{
CPWPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COptionsSystem)
DDX_Text(pDX, IDC_MAXREITEMS, m_MaxREItems);
DDV_MinMaxInt(pDX, m_MaxREItems, 0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);
DDX_Check(pDX, IDC_DEFPWUSESYSTRAY, m_UseSystemTray);
DDX_Check(pDX, IDC_DEFPWHIDESYSTRAY, m_HideSystemTray);
DDX_Check(pDX, IDC_STARTUP, m_Startup);
DDX_Text(pDX, IDC_MAXMRUITEMS, m_MaxMRUItems);
DDV_MinMaxInt(pDX, m_MaxMRUItems, 0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);
DDX_Check(pDX, IDC_MRU_ONFILEMENU, m_MRUOnFileMenu);
DDX_Check(pDX, IDC_REGDEL, m_DeleteRegistry);
DDX_Check(pDX, IDC_MIGRATETOAPPDATA, m_Migrate2Appdata);
DDX_Check(pDX, IDC_DEFAULTOPENRO, m_DefaultOpenRO);
DDX_Check(pDX, IDC_MULTIPLEINSTANCES, m_MultipleInstances);
DDX_Control(pDX, IDC_REGDELHELP, m_Help1);
DDX_Control(pDX, IDC_MIGRATETOAPPDATAHELP, m_Help2);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(COptionsSystem, CPWPropertyPage)
//{{AFX_MSG_MAP(COptionsSystem)
ON_BN_CLICKED(ID_HELP, OnHelp)
ON_BN_CLICKED(IDC_DEFPWUSESYSTRAY, OnUseSystemTray)
ON_BN_CLICKED(IDC_STARTUP, OnStartup)
ON_BN_CLICKED(IDC_REGDEL, OnSetDeleteRegistry)
ON_BN_CLICKED(IDC_MIGRATETOAPPDATA, OnSetMigrate2Appdata)
ON_BN_CLICKED(IDC_APPLYCONFIGCHANGES, OnApplyConfigChanges)
ON_MESSAGE(PSM_QUERYSIBLINGS, OnQuerySiblings)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COptionsSystem message handlers
BOOL COptionsSystem::OnInitDialog()
{
COptions_PropertyPage::OnInitDialog();
PWSprefs *prefs = PWSprefs::GetInstance();
if (!m_bShowConfigFile) {
GetDlgItem(IDC_STATIC_CONFIGFILE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC_RWSTATUS)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CONFIGFILE)->ShowWindow(SW_HIDE);
} else {
PWSprefs::ConfigOption configoption;
std::wstring wsCF = prefs->GetConfigFile(configoption);
std::wstring wsCO(L"");
switch (configoption) {
case PWSprefs::CF_NONE:
LoadAString(wsCF, IDS_NONE);
break;
case PWSprefs::CF_REGISTRY:
LoadAString(wsCF, IDS_REGISTRY);
break;
case PWSprefs::CF_FILE_RO:
LoadAString(wsCO, IDS_READ_ONLY);
break;
case PWSprefs::CF_FILE_RW:
case PWSprefs::CF_FILE_RW_NEW:
LoadAString(wsCO, IDS_READ_WRITE);
break;
default:
ASSERT(0);
}
GetDlgItem(IDC_CONFIGFILE)->SetWindowText(wsCF.c_str());
GetDlgItem(IDC_STATIC_RWSTATUS)->SetWindowText(wsCO.c_str());
}
bool bofferdeleteregistry = prefs->OfferDeleteRegistry();
bool boffermigrate2appdata = OfferConfigMigration();
if (!bofferdeleteregistry) {
GetDlgItem(IDC_REGDEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
}
if (!boffermigrate2appdata) {
GetDlgItem(IDC_MIGRATETOAPPDATA)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
}
if (!bofferdeleteregistry && !boffermigrate2appdata) {
GetDlgItem(IDC_CONFIG_GRP)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_HIDE);
} else {
GetDlgItem(IDC_APPLYCONFIGCHANGES)->ShowWindow(SW_SHOW);
}
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);
CSpinButtonCtrl *pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_RESPIN);
pspin->SetBuddy(GetDlgItem(IDC_MAXREITEMS));
pspin->SetRange(0, ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1);
pspin->SetBase(10);
pspin->SetPos(m_MaxREItems);
pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_MRUSPIN);
pspin->SetBuddy(GetDlgItem(IDC_MAXMRUITEMS));
pspin->SetRange(0, ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1);
pspin->SetBase(10);
pspin->SetPos(m_MaxMRUItems);
OnUseSystemTray();
if (InitToolTip(TTS_BALLOON | TTS_NOPREFIX, 0)) {
m_Help1.Init(IDB_QUESTIONMARK);
m_Help2.Init(IDB_QUESTIONMARK);
// Note naming convention: string IDS_xxx corresponds to control IDC_xxx_HELP
AddTool(IDC_REGDELHELP, IDS_REGDEL);
AddTool(IDC_MIGRATETOAPPDATAHELP, IDS_MIGRATETOAPPDATA);
ActivateToolTip();
} else {
m_Help1.EnableWindow(FALSE);
m_Help1.ShowWindow(SW_HIDE);
m_Help2.EnableWindow(FALSE);
m_Help2.ShowWindow(SW_HIDE);
}
if (!bofferdeleteregistry) {
m_Help1.EnableWindow(FALSE);
m_Help1.ShowWindow(SW_HIDE);
}
if (!boffermigrate2appdata) {
m_Help2.EnableWindow(FALSE);
m_Help2.ShowWindow(SW_HIDE);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
LRESULT COptionsSystem::OnQuerySiblings(WPARAM wParam, LPARAM )
{
UpdateData(TRUE);
// Have any of my fields been changed?
switch (wParam) {
case PP_DATA_CHANGED:
if (M_UseSystemTray() != m_UseSystemTray ||
M_HideSystemTray() != m_HideSystemTray ||
(m_UseSystemTray == TRUE &&
M_MaxREItems() != m_MaxREItems) ||
M_Startup() != m_Startup ||
M_MaxMRUItems() != m_MaxMRUItems ||
M_MRUOnFileMenu() != m_MRUOnFileMenu ||
M_DefaultOpenRO() != m_DefaultOpenRO ||
M_MultipleInstances() != m_MultipleInstances ||
m_saveDeleteRegistry != m_DeleteRegistry ||
m_saveMigrate2Appdata != m_Migrate2Appdata)
return 1L;
break;
case PP_UPDATE_VARIABLES:
// Since OnOK calls OnApply after we need to verify and/or
// copy data into the entry - we do it ourselves here first
if (OnApply() == FALSE)
return 1L;
}
return 0L;
}
BOOL COptionsSystem::OnApply()
{
UpdateData(TRUE);
M_UseSystemTray() = m_UseSystemTray;
M_HideSystemTray() = m_HideSystemTray;
M_Startup() = m_Startup;
M_MRUOnFileMenu() = m_MRUOnFileMenu;
M_DefaultOpenRO() = m_DefaultOpenRO;
M_MultipleInstances() = m_MultipleInstances;
M_MaxREItems() = m_MaxREItems;
M_MaxMRUItems() = m_MaxMRUItems;
M_AppHotKeyEnabled() = m_InitialHotkeyState;
return COptions_PropertyPage::OnApply();
}
BOOL COptionsSystem::PreTranslateMessage(MSG* pMsg)
{
RelayToolTipEvent(pMsg);
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_F1) {
PostMessage(WM_COMMAND, MAKELONG(ID_HELP, BN_CLICKED), NULL);
return TRUE;
}
return COptions_PropertyPage::PreTranslateMessage(pMsg);
}
BOOL COptionsSystem::OnKillActive()
{
// Needed as we have DDV routines.
return CPWPropertyPage::OnKillActive();
}
void COptionsSystem::OnHelp()
{
ShowHelp(L"::/html/system_tab.html");
}
void COptionsSystem::OnUseSystemTray()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==
BST_CHECKED) ? TRUE : FALSE;
GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(enable);
GetDlgItem(IDC_MAXREITEMS)->EnableWindow(enable);
GetDlgItem(IDC_RESPIN)->EnableWindow(enable);
if (enable == TRUE) {
// Check if user has the Misc PP open and hot key set
if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {
// Yes - open and hot key is set
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);
} else {
// No - Not open - then take initial value as the answer
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);
}
}
}
void COptionsSystem::OnStartup()
{
// Startup implies System tray
bool enable = ((CButton*)GetDlgItem(IDC_STARTUP))->GetCheck() == BST_CHECKED;
if (enable) {
((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->SetCheck(BST_CHECKED);
GetDlgItem(IDC_STATIC_MAXREITEMS)->EnableWindow(TRUE);
GetDlgItem(IDC_MAXREITEMS)->EnableWindow(TRUE);
GetDlgItem(IDC_RESPIN)->EnableWindow(TRUE);
}
}
void COptionsSystem::OnSetDeleteRegistry()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_REGDEL))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);
}
void COptionsSystem::OnSetMigrate2Appdata()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_MIGRATETOAPPDATA))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(enable);
}
void COptionsSystem::OnApplyConfigChanges()
{
UpdateData(TRUE);
CGeneralMsgBox gmb;
if (m_DeleteRegistry == TRUE) {
if (gmb.AfxMessageBox(IDS_CONFIRMDELETEREG, MB_YESNO | MB_ICONSTOP) == IDYES) {
PWSprefs::GetInstance()->DeleteRegistryEntries();
GetDlgItem(IDC_REGDEL)->EnableWindow(FALSE);
}
}
if (m_Migrate2Appdata == TRUE) {
GetDlgItem(IDC_MIGRATETOAPPDATA)->EnableWindow(FALSE);
PerformConfigMigration();
}
if (!GetDlgItem(IDC_REGDEL)->IsWindowEnabled() &&
!GetDlgItem(IDC_MIGRATETOAPPDATA)->IsWindowEnabled())
GetDlgItem(IDC_APPLYCONFIGCHANGES)->EnableWindow(FALSE);
UpdateData(FALSE);
}
BOOL COptionsSystem::OnSetActive()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_DEFPWUSESYSTRAY))->GetCheck() ==
BST_CHECKED) ? TRUE : FALSE;
if (enable == TRUE) {
// Check if user has the Misc PP open and hot key set
if (QuerySiblings(PPOPT_HOTKEY_SET, 0L) == 1L) {
// Yes - open and hot key is set
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(TRUE);
} else {
// No - Not open - then take initial value as the answer
GetDlgItem(IDC_DEFPWHIDESYSTRAY)->EnableWindow(m_InitialHotkeyState);
}
}
return CPWPropertyPage::OnSetActive();
}
<|endoftext|> |
<commit_before>#include "vector3.h"
#include "catch.hpp"
template <typename V> void vectorTestSuite() {
auto REQUIRE_VECS_EQ = [](V a, V b) {
REQUIRE(a.x() == Approx(b.x()));
REQUIRE(a.y() == Approx(b.y()));
REQUIRE(a.z() == Approx(b.z()));
};
SECTION("Vector magSq is correct") {
REQUIRE(V(2, 3, 6).magSq() == Approx(49));
}
SECTION("Vector mag is correct") {
REQUIRE(V(2, 3, 6).mag() == Approx(7));
}
SECTION("Vector negation is correct") {
REQUIRE_VECS_EQ(-V(2.0, -3.0, 1.5), V(-2.0, 3.0, -1.5));
}
SECTION("Vector normalization is correct") {
REQUIRE_VECS_EQ(V(2.0, 3.0, 6.0).norm(), V(2.0/7.0, 3.0/7.0, 6.0/7.0));
}
SECTION("Vector scaling is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)*4, V(8.0, -12.0, 6.0));
}
SECTION("Vector scaling (by division) is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 4.0)/4.0, V(0.5, -0.75, 1.0));
}
SECTION("Vector addition is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)+V(-1.5, 1.5, 0.5), V(0.5, -1.5, 2.0));
}
SECTION("Vector subtraction is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)-V(-1.5, 1.5, 0.5), V(3.5, -4.5, 1.0));
}
SECTION("Vector dot product is correct") {
REQUIRE(V(5, 3, 2).dot(V(-2, 3, 4)) == Approx(7));
}
SECTION("Vector cross product is correct") {
REQUIRE_VECS_EQ(V(1, 2, 3).cross(V(2, 3, 4)), V(-1, 2, -1));
}
SECTION("Vector scalar projection is correct") {
REQUIRE(V(3, 4, 5).scalarProj(V(2, 0, 0)) == Approx(3));
REQUIRE(V(3, 4, 5).scalarProj(V(0, 2, 0)) == Approx(4));
REQUIRE(V(3, 4, 5).scalarProj(V(2, 6, 9)) == Approx(75.0/11.0));
}
SECTION("Vector project is correct") {
REQUIRE_VECS_EQ(V(3, 1, 4).proj(V(6, 0, 8)), V(3, 0, 4));
}
SECTION("Vector distance is correct") {
REQUIRE(V(2, 1, 3).distance(V(6, 2, -5)) == Approx(9.0));
}
}
TEST_CASE("Vector3f math operations are accurate", "[vector3]") {
vectorTestSuite<Vector3f>();
}
TEST_CASE("Vector3d math operations are accurate", "[vector3]") {
vectorTestSuite<Vector3d>();
}<commit_msg>Add license<commit_after>/* The MIT License (MIT)
*
* Copyright (c) 2014 Colin Wallace
*
* 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 "vector3.h"
#include "catch.hpp"
template <typename V> void vectorTestSuite() {
auto REQUIRE_VECS_EQ = [](V a, V b) {
REQUIRE(a.x() == Approx(b.x()));
REQUIRE(a.y() == Approx(b.y()));
REQUIRE(a.z() == Approx(b.z()));
};
SECTION("Vector magSq is correct") {
REQUIRE(V(2, 3, 6).magSq() == Approx(49));
}
SECTION("Vector mag is correct") {
REQUIRE(V(2, 3, 6).mag() == Approx(7));
}
SECTION("Vector negation is correct") {
REQUIRE_VECS_EQ(-V(2.0, -3.0, 1.5), V(-2.0, 3.0, -1.5));
}
SECTION("Vector normalization is correct") {
REQUIRE_VECS_EQ(V(2.0, 3.0, 6.0).norm(), V(2.0/7.0, 3.0/7.0, 6.0/7.0));
}
SECTION("Vector scaling is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)*4, V(8.0, -12.0, 6.0));
}
SECTION("Vector scaling (by division) is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 4.0)/4.0, V(0.5, -0.75, 1.0));
}
SECTION("Vector addition is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)+V(-1.5, 1.5, 0.5), V(0.5, -1.5, 2.0));
}
SECTION("Vector subtraction is correct") {
REQUIRE_VECS_EQ(V(2.0, -3.0, 1.5)-V(-1.5, 1.5, 0.5), V(3.5, -4.5, 1.0));
}
SECTION("Vector dot product is correct") {
REQUIRE(V(5, 3, 2).dot(V(-2, 3, 4)) == Approx(7));
}
SECTION("Vector cross product is correct") {
REQUIRE_VECS_EQ(V(1, 2, 3).cross(V(2, 3, 4)), V(-1, 2, -1));
}
SECTION("Vector scalar projection is correct") {
REQUIRE(V(3, 4, 5).scalarProj(V(2, 0, 0)) == Approx(3));
REQUIRE(V(3, 4, 5).scalarProj(V(0, 2, 0)) == Approx(4));
REQUIRE(V(3, 4, 5).scalarProj(V(2, 6, 9)) == Approx(75.0/11.0));
}
SECTION("Vector project is correct") {
REQUIRE_VECS_EQ(V(3, 1, 4).proj(V(6, 0, 8)), V(3, 0, 4));
}
SECTION("Vector distance is correct") {
REQUIRE(V(2, 1, 3).distance(V(6, 2, -5)) == Approx(9.0));
}
}
TEST_CASE("Vector3f math operations are accurate", "[vector3]") {
vectorTestSuite<Vector3f>();
}
TEST_CASE("Vector3d math operations are accurate", "[vector3]") {
vectorTestSuite<Vector3d>();
}<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mcbist/address.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 address.H
/// @brief Class for mcbist related addresses (addresses below the hash translation)
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_MCBIST_ADDRESS_H_
#define _MSS_MCBIST_ADDRESS_H_
#include <fapi2.H>
#include <utility>
namespace mss
{
namespace mcbist
{
///
/// @class address
/// @brief Represents a physical address in memory
/// @note
/// 0:1 port select
/// 2 dimm select
/// 3:4 mrank(0 to 1)
/// 5:7 srank(0 to 2)
/// 8:25 row(0 to 17)
/// 26:32 col(3 to 9)
/// 33:35 bank(0 to 2)
/// 36:37 bank_group(0 to 1)
///
class address
{
private:
// How far over we shift to align the address in either the register or a buffer
enum { MAGIC_PAD = 26 };
public:
// first is the start bit of the field, second is the length
typedef std::pair<uint64_t, uint64_t> field;
constexpr static field PORT = {0, 2};
constexpr static field DIMM = {2, 1};
constexpr static field MRANK = {3, 2};
constexpr static field SRANK = {5, 3};
constexpr static field ROW = {8, 18};
constexpr static field COL = {26, 7};
constexpr static field BANK = {33, 3};
constexpr static field BANK_GROUP = {36, 2};
constexpr static field LAST_VALID = BANK_GROUP;
address() = default;
///
/// @brief Construct an address from a uint64_t (scom'ed value)
/// @param[in] i_value representing an address; say from a trap register
///
/// @note This assumes input has the same bit layout as this address
/// structure, and this is presently not the case for the trap registers (3/16).
/// These are presently unused, however. There is an open defect against the
/// design team to correct this.
/// @warn Assumes right-aligned value; bit 63 is shifted to represent the Bank Group
address( const uint64_t i_value ):
iv_address(i_value << MAGIC_PAD)
{
}
///
/// @brief Conversion operator to uint64_t
/// @warn Right-aligns the address
///
inline operator uint64_t() const
{
return iv_address >> MAGIC_PAD;
}
///
/// @brief Set a field for an address
/// @tparam F the field to set
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
template< const field& F >
inline address& set_field( const uint64_t i_value )
{
iv_address.insertFromRight<F.first, F.second>(i_value);
return *this;
}
///
/// @brief Get a field from an address
/// @tparam F the field to get
/// @return right-aligned uint64_t representing the value
///
template< const field& F >
inline uint64_t get_field() const
{
uint64_t l_value = 0;
iv_address.extractToRight<F.first, F.second>(l_value);
return l_value;
}
///
/// @brief Get a range of addresses.
/// @tparam[in] F the left-most valid field. So, if the address was for master rank,
/// the left-most valid field would be MRANK
/// @param[out] o_end representing an address to end at
/// @note this pointer is the start address
///
template< const field& F >
inline void get_range( address& o_end ) const
{
constexpr uint64_t START = F.first + F.second;
constexpr uint64_t LEN = (LAST_VALID.first + LAST_VALID.second) - START;
// All we need to do is fill in the bits to the right of the last valid field
o_end.iv_address = iv_address;
o_end.iv_address.setBit<START, LEN>();
}
///
/// @brief Get a range of addresses given a master rank
/// @param[in] i_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_mrank_range( const address& i_start, address& o_end )
{
i_start.get_range<MRANK>(o_end);
}
///
/// @brief Get a range of addresses given a master rank
/// @param[in] i_port representing the port for the starting address
/// @param[in] i_dimm representing the dimm for the starting address
/// @param[in] i_mrank representing the master rank for the starting address
/// @param[out] o_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_mrank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank,
address& o_start, address& o_end )
{
o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank);
get_mrank_range(o_start, o_end);
}
///
/// @brief Get a range of addresses given a slave rank
/// @param[in] i_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_srank_range( const address& i_start, address& o_end )
{
i_start.get_range<SRANK>(o_end);
}
///
/// @brief Get a range of addresses given a slave rank
/// @param[in] i_port representing the port for the starting address
/// @param[in] i_dimm representing the dimm for the starting address
/// @param[in] i_mrank representing the master rank for the starting address
/// @param[in] i_srank representing the slave rank for the starting address
/// @param[out] o_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_srank_range( const uint64_t i_port, const uint64_t i_dimm,
const uint64_t i_mrank, const uint64_t i_srank,
address& o_start, address& o_end )
{
o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank).set_slave_rank(i_srank);
get_srank_range(o_start, o_end);
}
///
/// @brief Set the port value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_port( const uint64_t i_value )
{
return set_field<PORT>(i_value);
}
///
/// @brief Get the port value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_port() const
{
return get_field<PORT>();
}
///
/// @brief Set the DIMM value for an address
/// @param[in] i_value the value to set
/// @note 0 is the DIMM[0] != 0 is DIMM[1]
/// @return address& for method chaining
///
inline address& set_dimm( const uint64_t i_value )
{
return set_field<DIMM>(i_value);
}
///
/// @brief Get the DIMM value for an address
/// @return right-aligned uint64_t representing the vaule
///
inline uint64_t get_dimm() const
{
return (get_field<DIMM>() == true ? 1 : 0);
}
///
/// @brief Set the master rank value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_master_rank( const uint64_t i_value )
{
return set_field<MRANK>(i_value);
}
///
/// @brief Get the master rank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_master_rank() const
{
return get_field<MRANK>();
}
///
/// @brief Set the slave rank value for an address
/// @param[in] i_value the value to set
///
inline void set_slave_rank( const uint64_t i_value )
{
set_field<SRANK>(i_value);
}
///
/// @brief Get the slave rank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_slave_rank() const
{
return get_field<SRANK>();
}
///
/// @brief Set the row value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_row( const uint64_t i_value )
{
return set_field<ROW>(i_value);
}
///
/// @brief Get the row value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_row() const
{
return get_field<ROW>();
}
///
/// @brief Set the column value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_column( const uint64_t i_value )
{
return set_field<COL>(i_value);
}
///
/// @brief Get the column value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_column() const
{
return get_field<COL>();
}
///
/// @brief Set the bank value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_bank( const uint64_t i_value )
{
return set_field<BANK>(i_value);
}
///
/// @brief Get the bank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_bank() const
{
return get_field<BANK>();
}
///
/// @brief Set the bank group value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_bank_group( const uint64_t i_value )
{
return set_field<BANK_GROUP>(i_value);
}
///
/// @brief Get the bank group value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_bank_group() const
{
return get_field<BANK_GROUP>();
}
private:
// We use a fapi2 buffer as it has static compile-time support
fapi2::buffer<uint64_t> iv_address;
};
} // namespace
} // namespace
#endif
<commit_msg>Add memdiags scrub capability<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mcbist/address.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 address.H
/// @brief Class for mcbist related addresses (addresses below the hash translation)
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_MCBIST_ADDRESS_H_
#define _MSS_MCBIST_ADDRESS_H_
#include <fapi2.H>
#include <utility>
namespace mss
{
namespace mcbist
{
///
/// @class address
/// @brief Represents a physical address in memory
/// @note
/// 0:1 port select
/// 2 dimm select
/// 3:4 mrank(0 to 1)
/// 5:7 srank(0 to 2)
/// 8:25 row(0 to 17)
/// 26:32 col(3 to 9)
/// 33:35 bank(0 to 2)
/// 36:37 bank_group(0 to 1)
///
class address
{
private:
// How far over we shift to align the address in either the register or a buffer
enum { MAGIC_PAD = 26 };
public:
// first is the start bit of the field, second is the length
typedef std::pair<uint64_t, uint64_t> field;
constexpr static field PORT = {0, 2};
constexpr static field DIMM = {2, 1};
constexpr static field MRANK = {3, 2};
constexpr static field SRANK = {5, 3};
constexpr static field ROW = {8, 18};
constexpr static field COL = {26, 7};
constexpr static field BANK = {33, 3};
constexpr static field BANK_GROUP = {36, 2};
constexpr static field LAST_VALID = BANK_GROUP;
address() = default;
///
/// @brief Construct an address from a uint64_t (scom'ed value)
/// @param[in] i_value representing an address; say from a trap register
///
/// @note This assumes input has the same bit layout as this address
/// structure, and this is presently not the case for the trap registers (3/16).
/// These are presently unused, however. There is an open defect against the
/// design team to correct this.
/// @warn Assumes right-aligned value; bit 63 is shifted to represent the Bank Group
address( const uint64_t i_value ):
iv_address(i_value << MAGIC_PAD)
{
}
///
/// @brief Conversion operator to uint64_t
/// @warn Right-aligns the address
///
inline operator uint64_t() const
{
return iv_address >> MAGIC_PAD;
}
///
/// @brief Set a field for an address
/// @tparam F the field to set
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
template< const field& F >
inline address& set_field( const uint64_t i_value )
{
iv_address.insertFromRight<F.first, F.second>(i_value);
return *this;
}
///
/// @brief Get a field from an address
/// @tparam F the field to get
/// @return right-aligned uint64_t representing the value
///
template< const field& F >
inline uint64_t get_field() const
{
uint64_t l_value = 0;
iv_address.extractToRight<F.first, F.second>(l_value);
return l_value;
}
///
/// @brief Get a range of addresses.
/// @tparam[in] F the left-most valid field. So, if the address was for master rank,
/// the left-most valid field would be MRANK
/// @param[out] o_end representing an address to end at
/// @note this pointer is the start address
///
template< const field& F >
inline void get_range( address& o_end ) const
{
constexpr uint64_t START = F.first + F.second;
constexpr uint64_t LEN = (LAST_VALID.first + LAST_VALID.second) - START;
// All we need to do is fill in the bits to the right of the last valid field
o_end.iv_address = iv_address;
o_end.iv_address.setBit<START, LEN>();
}
///
/// @brief Get an end address for sim mode
/// @param[out] o_end representing an address to end at
/// @note this pointer is the start address
///
inline void get_sim_end_address( address& o_end ) const
{
// This magic number represents a range of addresses which cover all
// cache lines the training algorithms touch. By effecting 0 - this end
// address you'll effect everything which has bad ECC in the sim.
constexpr uint64_t l_magic_sim_number = 0b1000000;
get_range<COL>(o_end);
o_end.set_column(l_magic_sim_number);
return;
}
///
/// @brief Get a range of addresses given a master rank
/// @param[in] i_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_mrank_range( const address& i_start, address& o_end )
{
i_start.get_range<MRANK>(o_end);
}
///
/// @brief Get a range of addresses given a master rank
/// @param[in] i_port representing the port for the starting address
/// @param[in] i_dimm representing the dimm for the starting address
/// @param[in] i_mrank representing the master rank for the starting address
/// @param[out] o_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_mrank_range( const uint64_t i_port, const uint64_t i_dimm, const uint64_t i_mrank,
address& o_start, address& o_end )
{
o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank);
get_mrank_range(o_start, o_end);
}
///
/// @brief Get a range of addresses given a slave rank
/// @param[in] i_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_srank_range( const address& i_start, address& o_end )
{
i_start.get_range<SRANK>(o_end);
}
///
/// @brief Get a range of addresses given a slave rank
/// @param[in] i_port representing the port for the starting address
/// @param[in] i_dimm representing the dimm for the starting address
/// @param[in] i_mrank representing the master rank for the starting address
/// @param[in] i_srank representing the slave rank for the starting address
/// @param[out] o_start representing an address to start from
/// @param[out] o_end representing an address to end at
///
inline static void get_srank_range( const uint64_t i_port, const uint64_t i_dimm,
const uint64_t i_mrank, const uint64_t i_srank,
address& o_start, address& o_end )
{
o_start.set_port(i_port).set_dimm(i_dimm).set_master_rank(i_mrank).set_slave_rank(i_srank);
get_srank_range(o_start, o_end);
}
///
/// @brief Set the port value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_port( const uint64_t i_value )
{
return set_field<PORT>(i_value);
}
///
/// @brief Get the port value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_port() const
{
return get_field<PORT>();
}
///
/// @brief Set the DIMM value for an address
/// @param[in] i_value the value to set
/// @note 0 is the DIMM[0] != 0 is DIMM[1]
/// @return address& for method chaining
///
inline address& set_dimm( const uint64_t i_value )
{
return set_field<DIMM>(i_value);
}
///
/// @brief Get the DIMM value for an address
/// @return right-aligned uint64_t representing the vaule
///
inline uint64_t get_dimm() const
{
return (get_field<DIMM>() == true ? 1 : 0);
}
///
/// @brief Set the master rank value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_master_rank( const uint64_t i_value )
{
return set_field<MRANK>(i_value);
}
///
/// @brief Get the master rank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_master_rank() const
{
return get_field<MRANK>();
}
///
/// @brief Set the slave rank value for an address
/// @param[in] i_value the value to set
///
inline void set_slave_rank( const uint64_t i_value )
{
set_field<SRANK>(i_value);
}
///
/// @brief Get the slave rank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_slave_rank() const
{
return get_field<SRANK>();
}
///
/// @brief Set the row value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_row( const uint64_t i_value )
{
return set_field<ROW>(i_value);
}
///
/// @brief Get the row value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_row() const
{
return get_field<ROW>();
}
///
/// @brief Set the column value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_column( const uint64_t i_value )
{
return set_field<COL>(i_value);
}
///
/// @brief Get the column value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_column() const
{
return get_field<COL>();
}
///
/// @brief Set the bank value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_bank( const uint64_t i_value )
{
return set_field<BANK>(i_value);
}
///
/// @brief Get the bank value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_bank() const
{
return get_field<BANK>();
}
///
/// @brief Set the bank group value for an address
/// @param[in] i_value the value to set
/// @return address& for method chaining
///
inline address& set_bank_group( const uint64_t i_value )
{
return set_field<BANK_GROUP>(i_value);
}
///
/// @brief Get the bank group value for an address
/// @return right-aligned uint64_t representing the value
///
inline uint64_t get_bank_group() const
{
return get_field<BANK_GROUP>();
}
private:
// We use a fapi2 buffer as it has static compile-time support
fapi2::buffer<uint64_t> iv_address;
};
} // namespace
} // namespace
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.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 p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V. Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C,
HANG_PULSE_0X05 = 0x05
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<commit_msg>Level 2 HWP for p9_sbe_chiplet_reset<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.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 p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V. Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C,
HANG_PULSE_0X05 = 0x05,
HANG_PULSE_0X08 = 0x08
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2011-2015 Blender 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.
*/
#include "util_aligned_malloc.h"
#include <cassert>
/* Adopted from Libmv. */
#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
/* Needed for memalign on Linux and _aligned_alloc on Windows. */
# ifdef FREE_WINDOWS
/* Make sure _aligned_malloc is included. */
# ifdef __MSVCRT_VERSION__
# undef __MSVCRT_VERSION__
# endif
# define __MSVCRT_VERSION__ 0x0700
# endif /* FREE_WINDOWS */
# include <malloc.h>
#else
/* Apple's malloc is 16-byte aligned, and does not have malloc.h, so include
* stdilb instead.
*/
# include <cstdlib>
#endif
CCL_NAMESPACE_BEGIN
void *util_aligned_malloc(int size, int alignment)
{
#ifdef _WIN32
return _aligned_malloc(size, alignment);
#elif defined(__APPLE__)
/* On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so
* they work natively with SSE types with no further work.
*/
assert(alignment == 16);
return malloc(size);
#elif defined(__FreeBSD__) || defined(__NetBSD__)
void *result;
if (posix_memalign(&result, alignment, size)) {
/* Non-zero means allocation error
* either no allocation or bad alignment value.
*/
return NULL;
}
return result;
#else /* This is for Linux. */
return memalign(alignment, size);
#endif
}
void util_aligned_free(void *ptr)
{
#ifdef _WIN32
_aligned_free(ptr);
#else
free(ptr);
#endif
}
CCL_NAMESPACE_END
<commit_msg>Make aligned allocation to respect WITH_BLENDER_GUARDEDALLOC<commit_after>/*
* Copyright 2011-2015 Blender 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.
*/
#include "util_aligned_malloc.h"
#include "util_guarded_allocator.h"
#include <cassert>
/* Adopted from Libmv. */
#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
/* Needed for memalign on Linux and _aligned_alloc on Windows. */
# ifdef FREE_WINDOWS
/* Make sure _aligned_malloc is included. */
# ifdef __MSVCRT_VERSION__
# undef __MSVCRT_VERSION__
# endif
# define __MSVCRT_VERSION__ 0x0700
# endif /* FREE_WINDOWS */
# include <malloc.h>
#else
/* Apple's malloc is 16-byte aligned, and does not have malloc.h, so include
* stdilb instead.
*/
# include <cstdlib>
#endif
CCL_NAMESPACE_BEGIN
void *util_aligned_malloc(int size, int alignment)
{
#ifdef WITH_BLENDER_GUARDEDALLOC
return MEM_mallocN_aligned(size, alignment, "Cycles Aligned Alloc");
#endif
#ifdef _WIN32
return _aligned_malloc(size, alignment);
#elif defined(__APPLE__)
/* On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so
* they work natively with SSE types with no further work.
*/
assert(alignment == 16);
return malloc(size);
#elif defined(__FreeBSD__) || defined(__NetBSD__)
void *result;
if (posix_memalign(&result, alignment, size)) {
/* Non-zero means allocation error
* either no allocation or bad alignment value.
*/
return NULL;
}
return result;
#else /* This is for Linux. */
return memalign(alignment, size);
#endif
}
void util_aligned_free(void *ptr)
{
#if defined(WITH_BLENDER_GUARDEDALLOC)
if(ptr != NULL) {
MEM_freeN(ptr);
}
#elif defined(_WIN32)
_aligned_free(ptr);
#else
free(ptr);
#endif
}
CCL_NAMESPACE_END
<|endoftext|> |
<commit_before>//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ClContextDeserializer.hpp"
#include "ClContextSchema_generated.h"
#include <armnn/Exceptions.hpp>
#include <armnn/utility/NumericCast.hpp>
#include <flatbuffers/flexbuffers.h>
#include <fmt/format.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
namespace armnn
{
void ClContextDeserializer::Deserialize(arm_compute::CLCompileContext& clCompileContext,
cl::Context& context,
cl::Device& device,
const std::string& filePath)
{
std::ifstream inputFileStream(filePath, std::ios::binary);
std::vector<std::uint8_t> binaryContent;
while (inputFileStream)
{
char input;
inputFileStream.get(input);
if (inputFileStream)
{
binaryContent.push_back(static_cast<std::uint8_t>(input));
}
}
inputFileStream.close();
DeserializeFromBinary(clCompileContext, context, device, binaryContent);
}
void ClContextDeserializer::DeserializeFromBinary(arm_compute::CLCompileContext& clCompileContext,
cl::Context& context,
cl::Device& device,
const std::vector<uint8_t>& binaryContent)
{
if (binaryContent.data() == nullptr)
{
throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
CHECK_LOCATION().AsString()));
}
size_t binaryContentSize = binaryContent.size();
flatbuffers::Verifier verifier(binaryContent.data(), binaryContentSize);
if (verifier.VerifyBuffer<ClContext>() == false)
{
throw ParseException(fmt::format("Buffer doesn't conform to the expected Armnn "
"flatbuffers format. size:{0} {1}",
binaryContentSize,
CHECK_LOCATION().AsString()));
}
auto clContext = GetClContext(binaryContent.data());
for (Program const* program : *clContext->programs())
{
const char* volatile programName = program->name()->c_str();
auto programBinary = program->binary();
std::vector<uint8_t> binary(programBinary->begin(), programBinary->begin() + programBinary->size());
cl::Program::Binaries binaries{ binary };
std::vector<cl::Device> devices {device};
cl::Program theProgram(context, devices, binaries);
theProgram.build();
clCompileContext.add_built_program(programName, theProgram);
}
}
} // namespace armnn
<commit_msg>Use mmap to load the clcache file<commit_after>//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ClContextDeserializer.hpp"
#include "ClContextSchema_generated.h"
#include <armnn/Exceptions.hpp>
#include <armnn/utility/NumericCast.hpp>
#include <armnn/Logging.hpp>
#include <flatbuffers/flexbuffers.h>
#include <fmt/format.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
#if defined(__linux__)
#define SERIALIZER_USE_MMAP 1
#if SERIALIZER_USE_MMAP
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#endif
namespace armnn
{
void ClContextDeserializer::Deserialize(arm_compute::CLCompileContext& clCompileContext,
cl::Context& context,
cl::Device& device,
const std::string& filePath)
{
std::vector<std::uint8_t> binaryContent;
#if !SERIALIZER_USE_MMAP
std::ifstream inputFileStream(filePath, std::ios::binary);
while (inputFileStream)
{
char input;
inputFileStream.get(input);
if (inputFileStream)
{
binaryContent.push_back(static_cast<std::uint8_t>(input));
}
}
inputFileStream.close();
#else
struct stat statbuf;
int fp = open(filePath.c_str(),O_RDONLY);
if (!fp)
{
ARMNN_LOG(error) << (std::string("Cannot open file ") + filePath);
return;
}
fstat(fp,&statbuf);
const unsigned long dataSize = static_cast<unsigned long>(statbuf.st_size);
binaryContent.resize(static_cast<long unsigned int>(dataSize));
void* ptrmem = mmap(NULL, dataSize,PROT_READ,MAP_PRIVATE,fp,0);
if(ptrmem!=MAP_FAILED)
{
memcpy (binaryContent.data(), ptrmem, dataSize);
}
close(fp);
if(ptrmem == MAP_FAILED)
{
ARMNN_LOG(error) << (std::string("Cannot map file ") + filePath);
return;
}
#endif
DeserializeFromBinary(clCompileContext, context, device, binaryContent);
}
void ClContextDeserializer::DeserializeFromBinary(arm_compute::CLCompileContext& clCompileContext,
cl::Context& context,
cl::Device& device,
const std::vector<uint8_t>& binaryContent)
{
if (binaryContent.data() == nullptr)
{
throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
CHECK_LOCATION().AsString()));
}
size_t binaryContentSize = binaryContent.size();
flatbuffers::Verifier verifier(binaryContent.data(), binaryContentSize);
if (verifier.VerifyBuffer<ClContext>() == false)
{
throw ParseException(fmt::format("Buffer doesn't conform to the expected Armnn "
"flatbuffers format. size:{0} {1}",
binaryContentSize,
CHECK_LOCATION().AsString()));
}
auto clContext = GetClContext(binaryContent.data());
for (Program const* program : *clContext->programs())
{
const char* volatile programName = program->name()->c_str();
auto programBinary = program->binary();
std::vector<uint8_t> binary(programBinary->begin(), programBinary->begin() + programBinary->size());
cl::Program::Binaries binaries{ binary };
std::vector<cl::Device> devices {device};
cl::Program theProgram(context, devices, binaries);
theProgram.build();
clCompileContext.add_built_program(programName, theProgram);
}
}
} // namespace armnn
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <image_transport/image_transport.h>
#include <kinect_tomato_searcher/SearchConfig.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
class ShowImage {
public:
ShowImage()
: m_gamma(2048),
RGB_WINDOW_NAME {"RGB image"},
DEPTH_WINDOW_NAME {"Depth image"},
BINARY_WINDOW_NAME {"Binary image"}
{
for(int i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = std::pow(v, 3) * 6;
m_gamma[i] = v * 6 * 256;
}
cv::namedWindow(RGB_WINDOW_NAME);
cv::namedWindow(DEPTH_WINDOW_NAME);
cv::namedWindow(BINARY_WINDOW_NAME);
}
~ShowImage() {
cv::destroyWindow(RGB_WINDOW_NAME);
cv::destroyWindow(DEPTH_WINDOW_NAME);
cv::destroyWindow(BINARY_WINDOW_NAME);
}
void showRGB(const cv::Mat& rgb) {
imshow(RGB_WINDOW_NAME, rgb);
}
void showBinary(const cv::Mat& binary) {
imshow(BINARY_WINDOW_NAME, binary);
}
void showDepth(const cv::Mat& depth) {
cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);
cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);
cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);
for (int i = 0; i < depth.rows * depth.cols; i++) {
int y = (int)(i / depth.cols);
int x = (int)(i % depth.cols);
int pval = m_gamma[buf.at<uint16_t>(i)];
int lb = pval & 0xff;
switch(pval >> 8) {
case 0:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
case 1:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = lb;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 2:
output.at<cv::Vec3b>(y,x)[2] = 255-lb;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 3:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = lb;
break;
case 4:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255;
break;
case 5:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
default:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
}
}
imshow(DEPTH_WINDOW_NAME, output);
}
private:
std::vector<uint16_t> m_gamma;
const std::string RGB_WINDOW_NAME;
const std::string DEPTH_WINDOW_NAME;
const std::string BINARY_WINDOW_NAME;
};
class SearchTomato
{
public:
SearchTomato()
: tomato_contours {},
siObj {},
server {},
f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))
{
server.setCallback(f);
}
void update(const cv::Mat& capture_rgb) {
siObj.showRGB(capture_rgb);
cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);
imageProsessing(capture_rgb, binary_mat);
siObj.showBinary(binary_mat);
searchTomatoContours(binary_mat, tomato_contours);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
return findClosePoint(maskedDepth, tomato_point);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {
tomato_poses.poses.clear();
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
for (std::size_t i {0}; i < tomato_contours.size(); ++i) {
cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
findClosePoint(maskedDepth, tomato_poses);
}
return tomato_poses.poses.empty() ? false : true;
}
private:
static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)
{
h_min_ = config.h_min;
h_max_ = config.h_max;
s_min_ = config.s_min;
s_max_ = config.s_max;
v_min_ = config.v_min;
v_max_ = config.v_max;
}
void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {
cv::Mat blur, hsv;
cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);
cv::cvtColor(blur, hsv, CV_BGR2HSV);
redFilter(hsv, binary);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);
cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);
}
void searchTomatoContours(const cv::Mat& binary, std::vector<std::vector<cv::Point> >& tomato_contours) {
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Point> contour;
cv::Rect bounding_box;
float ratio_balance;
cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
tomato_contours.clear();
while (!contours.empty()) {
contour = contours.back();
contours.pop_back();
bounding_box = cv::boundingRect(contour);
ratio_balance = (float)bounding_box.width / (float)bounding_box.height;
if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance;
// delete mismach. that is smaller or spier or empty
if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)
tomato_contours.push_back(contour);
}
}
void redFilter(const cv::Mat& hsv, cv::Mat& binary) {
int a, x, y;
for(y = 0; y < hsv.rows; y++) {
for(x = 0; x < hsv.cols; x++) {
a = hsv.step*y+(x*3);
if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&
(hsv.data[a+1] >= s_min_ && hsv.data[a+1] <= s_max_) &&
(hsv.data[a+2] >= v_min_ && hsv.data[a+2] <= v_max_))
binary.at<unsigned char>(y,x) = 255;
else
binary.at<unsigned char>(y,x) = 0;
}
}
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {
uint16_t depth;
constexpr uint16_t OVER_RANGE = 3000;
uint16_t close_depth = OVER_RANGE;
for (int y = 0; y < maskedDepth.rows; y++) {
const uint16_t* line_point = maskedDepth.ptr<uint16_t>(y);
for (int x = 0; x < maskedDepth.cols; x++) {
depth = line_point[x];
if (512 < depth && depth < close_depth) {
tomato_point.x = depth; // for ros coordinate system
tomato_point.y = x - maskedDepth.cols / 2; // for ros coordinate system
tomato_point.z = -(y - maskedDepth.rows / 2); // for ros coordinate system
close_depth = depth;
}
}
}
return (close_depth != OVER_RANGE ? true : false);
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {
geometry_msgs::Point tomato_point {};
if (findClosePoint(maskedDepth, tomato_point)) {
geometry_msgs::Pose tomato_pose {};
tomato_pose.position = tomato_point;
tomato_pose.orientation.w = 1.0;
tomato_poses.poses.push_back(tomato_pose);
return true;
}
return false;
}
static uint16_t h_min_;
static uint16_t h_max_;
static uint16_t s_min_;
static uint16_t s_max_;
static uint16_t v_min_;
static uint16_t v_max_;
std::vector<std::vector<cv::Point> > tomato_contours;
ShowImage siObj;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig> server;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig>::CallbackType f;
};
uint16_t SearchTomato::h_min_;
uint16_t SearchTomato::h_max_;
uint16_t SearchTomato::s_min_;
uint16_t SearchTomato::s_max_;
uint16_t SearchTomato::v_min_;
uint16_t SearchTomato::v_max_;
class ImageConverter {
private:
ros::NodeHandle nh;
ros::NodeHandle tomapo_nh;
ros::Publisher poses_pub;
geometry_msgs::PoseArray pub_msg;
image_transport::ImageTransport it;
image_transport::Subscriber rgb_sub;
image_transport::Subscriber depth_sub;
cv_bridge::CvImageConstPtr rgb_ptr;
cv_bridge::CvImageConstPtr depth_ptr;
SearchTomato stObj;
const std::size_t height_;
const double angle_x_per_piccell_;
const double angle_y_per_piccell_;
static constexpr double PI {3.141592653589793};
public:
ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)
: nh {},
tomapo_nh {nh, "tomato_point"},
poses_pub {tomapo_nh.advertise<geometry_msgs::PoseArray>("array", 1)},
it {nh},
rgb_sub {it.subscribe("color", 1, &ImageConverter::rgbCb, this)},
depth_sub {it.subscribe("depth", 1, &ImageConverter::depthCb, this)},
stObj {},
height_ {height},
angle_x_per_piccell_ {(angle_of_view_x * PI / 180.0) / width},
angle_y_per_piccell_ {(angle_of_view_y * PI / 180.0) / height}
{
pub_msg.header.frame_id = "kinect";
}
/**
* search tomato function.
* get rgb image, and search tomato.
* will tomato_point have data.
*
* @author Yusuke Doi
*/
void rgbCb(const sensor_msgs::ImageConstPtr& msg) {
// get rgb image on kinect
try {
rgb_ptr = cv_bridge::toCvShare(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by rgb: %s", e.what());
}
stObj.update(rgb_ptr->image);
cv::waitKey(100);
}
void depthCb(const sensor_msgs::ImageConstPtr& msg) {
try {
depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by depth: %s", e.what());
}
if (stObj.searchTomato(depth_ptr->image, pub_msg)) {
pub_msg.header.stamp = ros::Time::now();
for (auto& tomato_pose : pub_msg.poses) {
tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) / 1000.0; // convert to m
tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) / 1000.0; // convert to m
tomato_pose.position.x = tomato_pose.position.x / 1000.0; // convert to m
}
poses_pub.publish(pub_msg);
}
cv::waitKey(100);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "kinect_tomato_searcher_node");
ImageConverter ic {512, 424, 70, 60};
ros::spin();
return 0;
}
<commit_msg>Remove max; unkown max value<commit_after>#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <image_transport/image_transport.h>
#include <kinect_tomato_searcher/SearchConfig.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
class ShowImage {
public:
ShowImage()
: m_gamma(2048),
RGB_WINDOW_NAME {"RGB image"},
DEPTH_WINDOW_NAME {"Depth image"},
BINARY_WINDOW_NAME {"Binary image"}
{
for(int i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = std::pow(v, 3) * 6;
m_gamma[i] = v * 6 * 256;
}
cv::namedWindow(RGB_WINDOW_NAME);
cv::namedWindow(DEPTH_WINDOW_NAME);
cv::namedWindow(BINARY_WINDOW_NAME);
}
~ShowImage() {
cv::destroyWindow(RGB_WINDOW_NAME);
cv::destroyWindow(DEPTH_WINDOW_NAME);
cv::destroyWindow(BINARY_WINDOW_NAME);
}
void showRGB(const cv::Mat& rgb) {
imshow(RGB_WINDOW_NAME, rgb);
}
void showBinary(const cv::Mat& binary) {
imshow(BINARY_WINDOW_NAME, binary);
}
void showDepth(const cv::Mat& depth) {
cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);
cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);
cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);
for (int i = 0; i < depth.rows * depth.cols; i++) {
int y = (int)(i / depth.cols);
int x = (int)(i % depth.cols);
int pval = m_gamma[buf.at<uint16_t>(i)];
int lb = pval & 0xff;
switch(pval >> 8) {
case 0:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
case 1:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = lb;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 2:
output.at<cv::Vec3b>(y,x)[2] = 255-lb;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 3:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = lb;
break;
case 4:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255;
break;
case 5:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
default:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
}
}
imshow(DEPTH_WINDOW_NAME, output);
}
private:
std::vector<uint16_t> m_gamma;
const std::string RGB_WINDOW_NAME;
const std::string DEPTH_WINDOW_NAME;
const std::string BINARY_WINDOW_NAME;
};
class SearchTomato
{
public:
SearchTomato()
: tomato_contours {},
siObj {},
server {},
f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))
{
server.setCallback(f);
}
void update(const cv::Mat& capture_rgb) {
siObj.showRGB(capture_rgb);
cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);
imageProsessing(capture_rgb, binary_mat);
siObj.showBinary(binary_mat);
searchTomatoContours(binary_mat, tomato_contours);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
return findClosePoint(maskedDepth, tomato_point);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {
tomato_poses.poses.clear();
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
for (std::size_t i {0}; i < tomato_contours.size(); ++i) {
cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
findClosePoint(maskedDepth, tomato_poses);
}
return tomato_poses.poses.empty() ? false : true;
}
private:
static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)
{
h_min_ = config.h_min;
h_max_ = config.h_max;
s_min_ = config.s_min;
s_max_ = config.s_max;
v_min_ = config.v_min;
v_max_ = config.v_max;
}
void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {
cv::Mat blur, hsv;
cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);
cv::cvtColor(blur, hsv, CV_BGR2HSV);
redFilter(hsv, binary);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);
cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);
}
void searchTomatoContours(const cv::Mat& binary, std::vector<std::vector<cv::Point> >& tomato_contours) {
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Point> contour;
cv::Rect bounding_box;
float ratio_balance;
cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
tomato_contours.clear();
while (!contours.empty()) {
contour = contours.back();
contours.pop_back();
bounding_box = cv::boundingRect(contour);
ratio_balance = (float)bounding_box.width / (float)bounding_box.height;
if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance;
// delete mismach. that is smaller or spier or empty
if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)
tomato_contours.push_back(contour);
}
}
void redFilter(const cv::Mat& hsv, cv::Mat& binary) {
int a, x, y;
for(y = 0; y < hsv.rows; y++) {
for(x = 0; x < hsv.cols; x++) {
a = hsv.step*y+(x*3);
if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&
(hsv.data[a+1] >= s_min_) &&
(hsv.data[a+2] >= v_min_))
binary.at<unsigned char>(y,x) = 255;
else
binary.at<unsigned char>(y,x) = 0;
}
}
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {
uint16_t depth;
constexpr uint16_t OVER_RANGE = 3000;
uint16_t close_depth = OVER_RANGE;
for (int y = 0; y < maskedDepth.rows; y++) {
const uint16_t* line_point = maskedDepth.ptr<uint16_t>(y);
for (int x = 0; x < maskedDepth.cols; x++) {
depth = line_point[x];
if (512 < depth && depth < close_depth) {
tomato_point.x = depth; // for ros coordinate system
tomato_point.y = x - maskedDepth.cols / 2; // for ros coordinate system
tomato_point.z = -(y - maskedDepth.rows / 2); // for ros coordinate system
close_depth = depth;
}
}
}
return (close_depth != OVER_RANGE ? true : false);
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {
geometry_msgs::Point tomato_point {};
if (findClosePoint(maskedDepth, tomato_point)) {
geometry_msgs::Pose tomato_pose {};
tomato_pose.position = tomato_point;
tomato_pose.orientation.w = 1.0;
tomato_poses.poses.push_back(tomato_pose);
return true;
}
return false;
}
static uint16_t h_min_;
static uint16_t h_max_;
static uint16_t s_min_;
static uint16_t s_max_;
static uint16_t v_min_;
static uint16_t v_max_;
std::vector<std::vector<cv::Point> > tomato_contours;
ShowImage siObj;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig> server;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig>::CallbackType f;
};
uint16_t SearchTomato::h_min_;
uint16_t SearchTomato::h_max_;
uint16_t SearchTomato::s_min_;
uint16_t SearchTomato::s_max_;
uint16_t SearchTomato::v_min_;
uint16_t SearchTomato::v_max_;
class ImageConverter {
private:
ros::NodeHandle nh;
ros::NodeHandle tomapo_nh;
ros::Publisher poses_pub;
geometry_msgs::PoseArray pub_msg;
image_transport::ImageTransport it;
image_transport::Subscriber rgb_sub;
image_transport::Subscriber depth_sub;
cv_bridge::CvImageConstPtr rgb_ptr;
cv_bridge::CvImageConstPtr depth_ptr;
SearchTomato stObj;
const std::size_t height_;
const double angle_x_per_piccell_;
const double angle_y_per_piccell_;
static constexpr double PI {3.141592653589793};
public:
ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)
: nh {},
tomapo_nh {nh, "tomato_point"},
poses_pub {tomapo_nh.advertise<geometry_msgs::PoseArray>("array", 1)},
it {nh},
rgb_sub {it.subscribe("color", 1, &ImageConverter::rgbCb, this)},
depth_sub {it.subscribe("depth", 1, &ImageConverter::depthCb, this)},
stObj {},
height_ {height},
angle_x_per_piccell_ {(angle_of_view_x * PI / 180.0) / width},
angle_y_per_piccell_ {(angle_of_view_y * PI / 180.0) / height}
{
pub_msg.header.frame_id = "kinect";
}
/**
* search tomato function.
* get rgb image, and search tomato.
* will tomato_point have data.
*
* @author Yusuke Doi
*/
void rgbCb(const sensor_msgs::ImageConstPtr& msg) {
// get rgb image on kinect
try {
rgb_ptr = cv_bridge::toCvShare(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by rgb: %s", e.what());
}
stObj.update(rgb_ptr->image);
cv::waitKey(100);
}
void depthCb(const sensor_msgs::ImageConstPtr& msg) {
try {
depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by depth: %s", e.what());
}
if (stObj.searchTomato(depth_ptr->image, pub_msg)) {
pub_msg.header.stamp = ros::Time::now();
for (auto& tomato_pose : pub_msg.poses) {
tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) / 1000.0; // convert to m
tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) / 1000.0; // convert to m
tomato_pose.position.x = tomato_pose.position.x / 1000.0; // convert to m
}
poses_pub.publish(pub_msg);
}
cv::waitKey(100);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "kinect_tomato_searcher_node");
ImageConverter ic {512, 424, 70, 60};
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
#include "constants.hpp"
namespace cutehmi {
/**
* Epsilon for a number. Get epsilon for real number @a r, that means smallest number which added to @a r changes value of @a r.
* @param r real number.
* @return smallest number, which added to @a r changes value of @a r. If @a r is positive number, then returned number is also
* positive. Otherwise negative number is returned.
*
* @see absEps().
*/
inline
qreal eps(qreal r)
{
static constexpr qreal MACHINE_EPS = std::numeric_limits<qreal>::epsilon() * 0.5;
int exp;
std::frexp(r, & exp);
return std::ldexp(std::signbit(r) ? -MACHINE_EPS : MACHINE_EPS, exp);
}
/**
* Absolute epsilon for a number. Works in similar way to eps() function, except that absolute value is returned instead of signed
* one.
* @param r real number.
* @return smallest number which added to @a r changes value of @a r. Always non-negative value is returned.
*
* @see eps().
*/
inline
qreal absEps(qreal r)
{
static constexpr qreal MACHINE_EPS = std::numeric_limits<qreal>::epsilon() * 0.5;
int exp;
std::frexp(r, & exp);
return std::ldexp(MACHINE_EPS, exp);
}
/**
* Approximately equal. Compares real numbers @a r1, @a r2.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 and @a r2 are approximately equal, @p false otherwise.
*
* @see ale().
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool ape(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
// For some reason <= is used in the book to compare both sides. There may be a reason for this, so I'll leave it for now, but
// the consequence is that image of a function is a bit weird, e.g.:
// ape(1.0, 1.99, 0.25) -> false, ape(1.0, 2.0, 0.25) -> true, ape(1.0, 2.01, 0.25) -> false
return std::abs(r2 - r1) <= std::ldexp(eps, std::max(exp1, exp2));
}
/**
* Almost equal. Compares real numbers @a r1, @a r2. Function similar to ape(), however ale() is slightly stronger than ape() (@a r1
* and @a r2 must be slightly closer to each other to manifest equality). This function can be problematic, when one of the values
* is exactly zero, because in such case it returns @p true only if second argument is also exactly zero.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 and @a r2 are almost equal, @p false otherwise.
*
* @see ape().
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool ale(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return std::abs(r2 - r1) <= std::ldexp(eps, std::min(exp1, exp2));
}
/**
* Considerably less than.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 is considerably less than @a r2, @p false otherwise.
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool clt(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return r2 - r1 > std::ldexp(eps, std::max(exp1, exp2));
}
/**
* Considerably greater than.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 is considerably greater than @a r2, @p false otherwise.
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool cgt(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return r1 - r2 > std::ldexp(eps, std::max(exp1, exp2));
}
}
#endif // FUNCTIONS_HPP
<commit_msg>Rename constants.<commit_after>#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
#include "constants.hpp"
namespace cutehmi {
/**
* Epsilon for a number. Get epsilon for real number @a r, that means smallest number which added to @a r changes value of @a r.
* @param r real number.
* @return smallest number, which added to @a r changes value of @a r. If @a r is positive number, then returned number is also
* positive. Otherwise negative number is returned.
*
* @see absEps().
*/
inline
qreal eps(qreal r)
{
static constexpr qreal HALF_EPS = std::numeric_limits<qreal>::epsilon() * 0.5;
int exp;
std::frexp(r, & exp);
return std::ldexp(std::signbit(r) ? -HALF_EPS : HALF_EPS, exp);
}
/**
* Absolute epsilon for a number. Works in similar way to eps() function, except that absolute value is returned instead of signed
* one.
* @param r real number.
* @return smallest number which added to @a r changes value of @a r. Always non-negative value is returned.
*
* @see eps().
*/
inline
qreal absEps(qreal r)
{
static constexpr qreal HALF_EPS = std::numeric_limits<qreal>::epsilon() * 0.5;
int exp;
std::frexp(r, & exp);
return std::ldexp(HALF_EPS, exp);
}
/**
* Approximately equal. Compares real numbers @a r1, @a r2.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 and @a r2 are approximately equal, @p false otherwise.
*
* @see ale().
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool ape(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
// For some reason <= is used in the book to compare both sides. There may be a reason for this, so I'll leave it for now, but
// the consequence is that image of a function is a bit weird, e.g.:
// ape(1.0, 1.99, 0.25) -> false, ape(1.0, 2.0, 0.25) -> true, ape(1.0, 2.01, 0.25) -> false
return std::abs(r2 - r1) <= std::ldexp(eps, std::max(exp1, exp2));
}
/**
* Almost equal. Compares real numbers @a r1, @a r2. Function similar to ape(), however ale() is slightly stronger than ape() (@a r1
* and @a r2 must be slightly closer to each other to manifest equality). This function can be problematic, when one of the values
* is exactly zero, because in such case it returns @p true only if second argument is also exactly zero.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 and @a r2 are almost equal, @p false otherwise.
*
* @see ape().
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool ale(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return std::abs(r2 - r1) <= std::ldexp(eps, std::min(exp1, exp2));
}
/**
* Considerably less than.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 is considerably less than @a r2, @p false otherwise.
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool clt(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return r2 - r1 > std::ldexp(eps, std::max(exp1, exp2));
}
/**
* Considerably greater than.
* @param r1 first number to compare.
* @param r2 second number to compare.
* @param eps epsilon tolerance parameter used in comparison.
* @return @p true when @a r1 is considerably greater than @a r2, @p false otherwise.
*
* @internal Donald E. Knuth "Art of Computer Programming" [P 4.2.2 Vol2].
*/
inline
bool cgt(qreal r1, qreal r2, qreal eps = EPS)
{
int exp1, exp2;
std::frexp(r1, & exp1);
std::frexp(r2, & exp2);
return r1 - r2 > std::ldexp(eps, std::max(exp1, exp2));
}
}
#endif // FUNCTIONS_HPP
<|endoftext|> |
<commit_before>// Copyright 2014 BVLC and contributors.
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
template <typename TypeParam>
class ConvolutionLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
ConvolutionLayerTest()
: blob_bottom_(new Blob<Dtype>(2, 3, 6, 4)),
blob_bottom_2_(new Blob<Dtype>(2, 3, 6, 4)),
blob_top_(new Blob<Dtype>()),
blob_top_2_(new Blob<Dtype>()) {}
virtual void SetUp() {
// fill the values
FillerParameter filler_param;
filler_param.set_value(1.);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
filler.Fill(this->blob_bottom_2_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~ConvolutionLayerTest() {
delete blob_bottom_;
delete blob_bottom_2_;
delete blob_top_;
delete blob_top_2_;
}
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_bottom_2_;
Blob<Dtype>* const blob_top_;
Blob<Dtype>* const blob_top_2_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(ConvolutionLayerTest, TestDtypesAndDevices);
TYPED_TEST(ConvolutionLayerTest, TestSetup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(4);
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 4);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
EXPECT_EQ(this->blob_top_2_->num(), 2);
EXPECT_EQ(this->blob_top_2_->channels(), 4);
EXPECT_EQ(this->blob_top_2_->height(), 2);
EXPECT_EQ(this->blob_top_2_->width(), 1);
// setting group should not change the shape
convolution_param->set_num_output(3);
convolution_param->set_group(3);
layer.reset(new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 3);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
EXPECT_EQ(this->blob_top_2_->num(), 2);
EXPECT_EQ(this->blob_top_2_->channels(), 3);
EXPECT_EQ(this->blob_top_2_->height(), 2);
EXPECT_EQ(this->blob_top_2_->width(), 1);
}
TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolution) {
// We will simply see if the convolution layer carries out averaging well.
typedef typename TypeParam::Dtype Dtype;
shared_ptr<ConstantFiller<Dtype> > filler;
FillerParameter filler_param;
filler_param.set_value(1.);
filler.reset(new ConstantFiller<Dtype>(filler_param));
filler->Fill(this->blob_bottom_);
filler_param.set_value(2.);
filler.reset(new ConstantFiller<Dtype>(filler_param));
filler->Fill(this->blob_bottom_2_);
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(4);
convolution_param->mutable_weight_filler()->set_type("constant");
convolution_param->mutable_weight_filler()->set_value(1);
convolution_param->mutable_bias_filler()->set_type("constant");
convolution_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
// After the convolution, the output should all have output values 27.1
const Dtype* top_data = this->blob_top_->cpu_data();
for (int i = 0; i < this->blob_top_->count(); ++i) {
EXPECT_NEAR(top_data[i], 27.1, 1e-4);
}
top_data = this->blob_top_2_->cpu_data();
for (int i = 0; i < this->blob_top_2_->count(); ++i) {
EXPECT_NEAR(top_data[i], 54.1, 1e-4);
}
}
TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolutionGroup) {
// We will simply see if the convolution layer carries out averaging well.
typedef typename TypeParam::Dtype Dtype;
FillerParameter filler_param;
filler_param.set_value(1.);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();
for (int n = 0; n < this->blob_bottom_->num(); ++n) {
for (int c = 0; c < this->blob_bottom_->channels(); ++c) {
for (int h = 0; h < this->blob_bottom_->height(); ++h) {
for (int w = 0; w < this->blob_bottom_->width(); ++w) {
bottom_data[this->blob_bottom_->offset(n, c, h, w)] = c;
}
}
}
}
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(3);
convolution_param->set_group(3);
convolution_param->mutable_weight_filler()->set_type("constant");
convolution_param->mutable_weight_filler()->set_value(1);
convolution_param->mutable_bias_filler()->set_type("constant");
convolution_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
// After the convolution, the output should all have output values 9.1
const Dtype* top_data = this->blob_top_->cpu_data();
for (int n = 0; n < this->blob_top_->num(); ++n) {
for (int c = 0; c < this->blob_top_->channels(); ++c) {
for (int h = 0; h < this->blob_top_->height(); ++h) {
for (int w = 0; w < this->blob_top_->width(); ++w) {
Dtype data = top_data[this->blob_top_->offset(n, c, h, w)];
EXPECT_NEAR(data, c * 9 + 0.1, 1e-4);
}
}
}
}
}
TYPED_TEST(ConvolutionLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(2);
convolution_param->mutable_weight_filler()->set_type("gaussian");
convolution_param->mutable_bias_filler()->set_type("gaussian");
ConvolutionLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_));
}
TYPED_TEST(ConvolutionLayerTest, TestGradientGroup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(3);
convolution_param->set_group(3);
convolution_param->mutable_weight_filler()->set_type("gaussian");
convolution_param->mutable_bias_filler()->set_type("gaussian");
ConvolutionLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_));
}
} // namespace caffe
<commit_msg>test non-square filters by separable convolution of Sobel operator<commit_after>// Copyright 2014 BVLC and contributors.
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
template <typename TypeParam>
class ConvolutionLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
ConvolutionLayerTest()
: blob_bottom_(new Blob<Dtype>(2, 3, 6, 4)),
blob_bottom_2_(new Blob<Dtype>(2, 3, 6, 4)),
blob_top_(new Blob<Dtype>()),
blob_top_2_(new Blob<Dtype>()) {}
virtual void SetUp() {
// fill the values
FillerParameter filler_param;
filler_param.set_value(1.);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
filler.Fill(this->blob_bottom_2_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~ConvolutionLayerTest() {
delete blob_bottom_;
delete blob_bottom_2_;
delete blob_top_;
delete blob_top_2_;
}
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_bottom_2_;
Blob<Dtype>* const blob_top_;
Blob<Dtype>* const blob_top_2_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(ConvolutionLayerTest, TestDtypesAndDevices);
TYPED_TEST(ConvolutionLayerTest, TestSetup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(4);
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 4);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
EXPECT_EQ(this->blob_top_2_->num(), 2);
EXPECT_EQ(this->blob_top_2_->channels(), 4);
EXPECT_EQ(this->blob_top_2_->height(), 2);
EXPECT_EQ(this->blob_top_2_->width(), 1);
// setting group should not change the shape
convolution_param->set_num_output(3);
convolution_param->set_group(3);
layer.reset(new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
EXPECT_EQ(this->blob_top_->num(), 2);
EXPECT_EQ(this->blob_top_->channels(), 3);
EXPECT_EQ(this->blob_top_->height(), 2);
EXPECT_EQ(this->blob_top_->width(), 1);
EXPECT_EQ(this->blob_top_2_->num(), 2);
EXPECT_EQ(this->blob_top_2_->channels(), 3);
EXPECT_EQ(this->blob_top_2_->height(), 2);
EXPECT_EQ(this->blob_top_2_->width(), 1);
}
TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolution) {
// We will simply see if the convolution layer carries out averaging well.
typedef typename TypeParam::Dtype Dtype;
shared_ptr<ConstantFiller<Dtype> > filler;
FillerParameter filler_param;
filler_param.set_value(1.);
filler.reset(new ConstantFiller<Dtype>(filler_param));
filler->Fill(this->blob_bottom_);
filler_param.set_value(2.);
filler.reset(new ConstantFiller<Dtype>(filler_param));
filler->Fill(this->blob_bottom_2_);
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(4);
convolution_param->mutable_weight_filler()->set_type("constant");
convolution_param->mutable_weight_filler()->set_value(1);
convolution_param->mutable_bias_filler()->set_type("constant");
convolution_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
// After the convolution, the output should all have output values 27.1
const Dtype* top_data = this->blob_top_->cpu_data();
for (int i = 0; i < this->blob_top_->count(); ++i) {
EXPECT_NEAR(top_data[i], 27.1, 1e-4);
}
top_data = this->blob_top_2_->cpu_data();
for (int i = 0; i < this->blob_top_2_->count(); ++i) {
EXPECT_NEAR(top_data[i], 54.1, 1e-4);
}
}
TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolutionGroup) {
// We will simply see if the convolution layer carries out averaging well.
typedef typename TypeParam::Dtype Dtype;
FillerParameter filler_param;
filler_param.set_value(1.);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();
for (int n = 0; n < this->blob_bottom_->num(); ++n) {
for (int c = 0; c < this->blob_bottom_->channels(); ++c) {
for (int h = 0; h < this->blob_bottom_->height(); ++h) {
for (int w = 0; w < this->blob_bottom_->width(); ++w) {
bottom_data[this->blob_bottom_->offset(n, c, h, w)] = c;
}
}
}
}
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(3);
convolution_param->set_group(3);
convolution_param->mutable_weight_filler()->set_type("constant");
convolution_param->mutable_weight_filler()->set_value(1);
convolution_param->mutable_bias_filler()->set_type("constant");
convolution_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
// After the convolution, the output should all have output values 9.1
const Dtype* top_data = this->blob_top_->cpu_data();
for (int n = 0; n < this->blob_top_->num(); ++n) {
for (int c = 0; c < this->blob_top_->channels(); ++c) {
for (int h = 0; h < this->blob_top_->height(); ++h) {
for (int w = 0; w < this->blob_top_->width(); ++w) {
Dtype data = top_data[this->blob_top_->offset(n, c, h, w)];
EXPECT_NEAR(data, c * 9 + 0.1, 1e-4);
}
}
}
}
}
TYPED_TEST(ConvolutionLayerTest, TestSobelConvolution) {
// Test separable convolution by computing the Sobel operator
// as a single filter then comparing the result
// as the convolution of two rectangular filters.
typedef typename TypeParam::Dtype Dtype;
// Fill bottoms with identical Gaussian noise.
shared_ptr<GaussianFiller<Dtype> > filler;
FillerParameter filler_param;
filler_param.set_value(1.);
filler.reset(new GaussianFiller<Dtype>(filler_param));
filler->Fill(this->blob_bottom_);
this->blob_bottom_2_->CopyFrom(*this->blob_bottom_);
// Compute Sobel G_x operator as 3 x 3 convolution.
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(1);
convolution_param->set_bias_term(false);
shared_ptr<Layer<Dtype> > layer(
new ConvolutionLayer<Dtype>(layer_param));
layer->blobs().resize(1);
layer->blobs()[0].reset(new Blob<Dtype>(1, 3, 3, 3));
Dtype* weights = layer->blobs()[0]->mutable_cpu_data();
for (int c = 0; c < 3; ++c) {
int i = c * 9; // 3 x 3 filter
weights[i + 0] = -1;
weights[i + 1] = 0;
weights[i + 2] = 1;
weights[i + 3] = -2;
weights[i + 4] = 0;
weights[i + 5] = 2;
weights[i + 6] = -1;
weights[i + 7] = 0;
weights[i + 8] = 1;
}
layer->SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
layer->Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
// Compute Sobel G_x operator as separable 3 x 1 and 1 x 3 convolutions.
// (1) the [1 2 1] column filter
vector<Blob<Dtype>*> sep_blob_bottom_vec;
vector<Blob<Dtype>*> sep_blob_top_vec;
shared_ptr<Blob<Dtype> > blob_sep(new Blob<Dtype>());
sep_blob_bottom_vec.push_back(this->blob_bottom_2_);
sep_blob_top_vec.push_back(this->blob_top_2_);
convolution_param->clear_kernel_size();
convolution_param->clear_stride();
convolution_param->set_kernel_h(3);
convolution_param->set_kernel_w(1);
convolution_param->set_stride_h(2);
convolution_param->set_stride_w(1);
convolution_param->set_num_output(1);
convolution_param->set_bias_term(false);
layer.reset(new ConvolutionLayer<Dtype>(layer_param));
layer->blobs().resize(1);
layer->blobs()[0].reset(new Blob<Dtype>(1, 3, 3, 1));
Dtype* weights_1 = layer->blobs()[0]->mutable_cpu_data();
for (int c = 0; c < 3; ++c) {
int i = c * 3; // 3 x 1 filter
weights_1[i + 0] = 1;
weights_1[i + 1] = 2;
weights_1[i + 2] = 1;
}
layer->SetUp(sep_blob_bottom_vec, &(sep_blob_top_vec));
layer->Forward(sep_blob_bottom_vec, &(sep_blob_top_vec));
// (2) the [-1 0 1] row filter
blob_sep->CopyFrom(*this->blob_top_2_, false, true);
sep_blob_bottom_vec.clear();
sep_blob_bottom_vec.push_back(blob_sep.get());
convolution_param->set_kernel_h(1);
convolution_param->set_kernel_w(3);
convolution_param->set_stride_h(1);
convolution_param->set_stride_w(2);
convolution_param->set_num_output(1);
convolution_param->set_bias_term(false);
layer.reset(new ConvolutionLayer<Dtype>(layer_param));
layer->blobs().resize(1);
layer->blobs()[0].reset(new Blob<Dtype>(1, 3, 1, 3));
Dtype* weights_2 = layer->blobs()[0]->mutable_cpu_data();
for (int c = 0; c < 3; ++c) {
int i = c * 3; // 1 x 3 filter
weights_2[i + 0] = -1;
weights_2[i + 1] = 0;
weights_2[i + 2] = 1;
}
layer->SetUp(sep_blob_bottom_vec, &(sep_blob_top_vec));
layer->Forward(sep_blob_bottom_vec, &(sep_blob_top_vec));
// Test equivalence of full and separable filters.
const Dtype* top_data = this->blob_top_->cpu_data();
const Dtype* sep_top_data = this->blob_top_2_->cpu_data();
for (int i = 0; i < this->blob_top_->count(); ++i) {
EXPECT_NEAR(top_data[i], sep_top_data[i], 1e-4);
}
}
TYPED_TEST(ConvolutionLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
this->blob_bottom_vec_.push_back(this->blob_bottom_2_);
this->blob_top_vec_.push_back(this->blob_top_2_);
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(2);
convolution_param->mutable_weight_filler()->set_type("gaussian");
convolution_param->mutable_bias_filler()->set_type("gaussian");
ConvolutionLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_));
}
TYPED_TEST(ConvolutionLayerTest, TestGradientGroup) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
ConvolutionParameter* convolution_param =
layer_param.mutable_convolution_param();
convolution_param->set_kernel_size(3);
convolution_param->set_stride(2);
convolution_param->set_num_output(3);
convolution_param->set_group(3);
convolution_param->mutable_weight_filler()->set_type("gaussian");
convolution_param->mutable_bias_filler()->set_type("gaussian");
ConvolutionLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_));
}
} // namespace caffe
<|endoftext|> |
<commit_before>//
// partlistvisitor.cpp
// libmusicxml2
//
// Created by Arshia Cont on 05/01/17.
//
//
#include <algorithm>
#include "partlistvisitor.h"
#include "rational.h"
#include "xml_tree_browser.h"
#include "tree_browser.h"
using namespace std;
namespace MusicXML2
{
partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)
{
}
partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)
{
// search if this part ID exists in any grouping
// Guido Limitation: One \accol tag per staff ONLY (for nested definitions)
// IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.
std::map<int, partGroup>::iterator partGroupIt;
for (partGroupIt=fPartGroups.begin();
partGroupIt != fPartGroups.end();
partGroupIt++)
{
if (partGroupIt->second.visited == false) {
if (std::find(partGroupIt->second.partIDs.begin()
, partGroupIt->second.partIDs.end(),
partID) != partGroupIt->second.partIDs.end() )
{
// this partID is in group number partGroupIt->first
//cerr << "\t ID found in group " << partGroupIt->first <<" "<<endl;
break;
}
}
}
if (partGroupIt != fPartGroups.end())
{
return &partGroupIt->second;
}
return NULL;
}
void partlistvisitor::partID2range(partGroup &pGroup)
{
std::vector<int> staves;
for (size_t i=0; i<pGroup.partIDs.size();i++)
{
staves.push_back(part2staffmap[pGroup.partIDs[i]]);
}
std::vector<int>::iterator rangeEnd = std::max_element(staves.begin(), staves.end());
std::vector<int>::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());
stringstream rangeStream;
rangeStream << "\""<< (*rangeBegin)<<"-"<<(*rangeEnd)<<"\"";
pGroup.guidoRange = rangeStream.str();
pGroup.guidoRangeStart = *rangeBegin;
pGroup.guidoRangeStop = *rangeEnd;
}
bool partlistvisitor::checkLonelyBarFormat(int staffID)
{
std::map<int, partGroup>::iterator partGroupIt;
for (partGroupIt=fPartGroups.begin();
partGroupIt != fPartGroups.end();
partGroupIt++)
{
if (partGroupIt->second.barlineGrouping == true)
{
// see if this staff is in range
if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))
{
return false;
}
}
}
return true;
}
/// Visitors
void partlistvisitor::visitStart ( S_part_group& elt )
{
int partGroupNumber = elt->getAttributeIntValue("number", 0);
/// IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.
std::string partGroupType = elt->getAttributeValue("type");
if (partGroupType=="start")
{
int groupIndex = fPartGroupIncrementer;
fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;
if (elt->getValue(k_group_symbol)=="bracket")
{
fPartGroups[groupIndex].bracket = true;
} else
fPartGroups[groupIndex].bracket = false;
if (elt->getValue(k_group_barline)=="yes")
{
fPartGroups[groupIndex].barlineGrouping = true;
} else
fPartGroups[groupIndex].barlineGrouping = false;
// Add optional names
fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);
fPartGroups[groupIndex].visited = false;
fCurrentPartGroupIndex.push_back(groupIndex);
fPartGroupIncrementer++;
//cerr << "Started group " << partGroupNumber << " index " << groupIndex<<" (" << fCurrentPartGroupIndex.size() << ")" << endl;
}else
if (partGroupType=="stop")
{
// Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber
std::vector<int>::iterator ito;
for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)
{
if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)
break;
}
// calculate Guido Range and set
partID2range(fPartGroups[*ito]);
// Do Erase
if (ito != fCurrentPartGroupIndex.end())
{
fCurrentPartGroupIndex.erase(ito);
}else
cerr << "Something is really wrong in S_PART_GROUP visitor!" << endl;
}
}
void partlistvisitor::visitStart( S_score_part& elt)
{
std::string PartID = elt->getAttributeValue("id");
part2staffmap[PartID] = staffCreatorCounter;
staffCreatorCounter++;
fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);
fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);
// add groupings if any
if (fCurrentPartGroupIndex.size())
{
for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)
{
fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);
}
}
}
}
<commit_msg>fix crash bug in partID2range<commit_after>//
// partlistvisitor.cpp
// libmusicxml2
//
// Created by Arshia Cont on 05/01/17.
//
//
#include <algorithm>
#include "partlistvisitor.h"
#include "rational.h"
#include "xml_tree_browser.h"
#include "tree_browser.h"
using namespace std;
namespace MusicXML2
{
partlistvisitor::partlistvisitor() : fPartGroupIncrementer(0), staffCreatorCounter(1)
{
}
partGroup* partlistvisitor::find_first_of_partID_inGroup(std::string partID)
{
// search if this part ID exists in any grouping
// Guido Limitation: One \accol tag per staff ONLY (for nested definitions)
// IDEA: Treat the FIRST occurence of partID in grouping and get rid of it.
std::map<int, partGroup>::iterator partGroupIt;
for (partGroupIt=fPartGroups.begin();
partGroupIt != fPartGroups.end();
partGroupIt++)
{
if (partGroupIt->second.visited == false) {
if (std::find(partGroupIt->second.partIDs.begin()
, partGroupIt->second.partIDs.end(),
partID) != partGroupIt->second.partIDs.end() )
{
// this partID is in group number partGroupIt->first
//cerr << "\t ID found in group " << partGroupIt->first <<" "<<endl;
break;
}
}
}
if (partGroupIt != fPartGroups.end())
{
return &partGroupIt->second;
}
return NULL;
}
void partlistvisitor::partID2range(partGroup &pGroup)
{
std::vector<int> staves;
for (size_t i=0; i<pGroup.partIDs.size();i++)
{
staves.push_back(part2staffmap[pGroup.partIDs[i]]);
}
if (staves.empty()) return;
std::vector<int>::iterator rangeEnd = std::max_element(staves.begin(), staves.end());
std::vector<int>::iterator rangeBegin = std::min_element(staves.begin(), staves.begin());
stringstream rangeStream;
rangeStream << "\"" << (*rangeBegin) << "-" << (*rangeEnd) << "\"";
pGroup.guidoRange = rangeStream.str();
pGroup.guidoRangeStart = *rangeBegin;
pGroup.guidoRangeStop = *rangeEnd;
}
bool partlistvisitor::checkLonelyBarFormat(int staffID)
{
std::map<int, partGroup>::iterator partGroupIt;
for (partGroupIt=fPartGroups.begin();
partGroupIt != fPartGroups.end();
partGroupIt++)
{
if (partGroupIt->second.barlineGrouping == true)
{
// see if this staff is in range
if ( (staffID>= partGroupIt->second.guidoRangeStart)&&(staffID<=partGroupIt->second.guidoRangeStop))
{
return false;
}
}
}
return true;
}
/// Visitors
void partlistvisitor::visitStart ( S_part_group& elt )
{
int partGroupNumber = elt->getAttributeIntValue("number", 0);
/// IMPORTANT NOTE: the number attribute is NOT sequential and can be repeated! So we need to do further book-keeping.
std::string partGroupType = elt->getAttributeValue("type");
if (partGroupType=="start")
{
int groupIndex = fPartGroupIncrementer;
fPartGroups[groupIndex].xmlGroupNumber = partGroupNumber;
if (elt->getValue(k_group_symbol)=="bracket")
{
fPartGroups[groupIndex].bracket = true;
} else
fPartGroups[groupIndex].bracket = false;
if (elt->getValue(k_group_barline)=="yes")
{
fPartGroups[groupIndex].barlineGrouping = true;
} else
fPartGroups[groupIndex].barlineGrouping = false;
// Add optional names
fPartGroups[groupIndex].fGroupName = elt->getValue(k_group_name);
fPartGroups[groupIndex].visited = false;
fCurrentPartGroupIndex.push_back(groupIndex);
fPartGroupIncrementer++;
//cerr << "Started group " << partGroupNumber << " index " << groupIndex<<" (" << fCurrentPartGroupIndex.size() << ")" << endl;
}else
if (partGroupType=="stop")
{
// Erase the INDEX whose xmlGroupNumber is equal to partGroupNumber
std::vector<int>::iterator ito;
for (ito = fCurrentPartGroupIndex.begin(); ito < fCurrentPartGroupIndex.end(); ito++)
{
if (fPartGroups[*ito].xmlGroupNumber == partGroupNumber)
break;
}
// calculate Guido Range and set
partID2range(fPartGroups[*ito]);
// Do Erase
if (ito != fCurrentPartGroupIndex.end())
{
fCurrentPartGroupIndex.erase(ito);
}else
cerr << "Something is really wrong in S_PART_GROUP visitor!" << endl;
}
}
void partlistvisitor::visitStart( S_score_part& elt)
{
std::string PartID = elt->getAttributeValue("id");
part2staffmap[PartID] = staffCreatorCounter;
staffCreatorCounter++;
fPartHeaders[PartID].fPartName = elt->getValue(k_part_name);
fPartHeaders[PartID].fPartNameAbbr = elt->getValue(k_part_abbreviation);
// add groupings if any
if (fCurrentPartGroupIndex.size())
{
for (size_t ind=0; ind < fCurrentPartGroupIndex.size(); ind++)
{
fPartGroups[fCurrentPartGroupIndex[ind]].partIDs.push_back(PartID);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* VehicleExtraProperties.cpp
*
* Created on: Apr 25, 2015
* Author: arman
*/
#include "VehicleExtraProperties.h"
// Arman : maybe too many includes
#include "core/ChStream.h"
//#include "chrono_parallel/lcp/ChLcpSystemDescriptorParallel.h"
//#include "chrono_parallel/collision/ChCNarrowphaseRUtils.h"
#include "chrono_vehicle/ChVehicleModelData.h"
int chassisFam = 2;
int tireFam = 3;
//#include "hmmwvParams.h"
using namespace chrono;
using namespace collision;
// Tire Coefficient of friction
float mu_t = 0.8;
// Callback class for providing driver inputs.
MyDriverInputs::MyDriverInputs(double delay) : m_delay(delay) {}
void MyDriverInputs::onCallback(double time, double& throttle, double& steering, double& braking) {
throttle = 0;
steering = 0;
braking = 0;
double eff_time = time - m_delay;
// Do not generate any driver inputs for a duration equal to m_delay.
if (eff_time < 0)
return;
if (eff_time > 0.2)
throttle = 1.0;
else if (eff_time > 0.1)
throttle = 10 * (eff_time - 0.1);
}
// Callback class for specifying rigid tire contact model.
// This version uses cylindrical contact shapes.
void MyCylindricalTire::onCallback(ChSharedPtr<ChBody> wheelBody, double radius, double width) {
wheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
wheelBody->GetCollisionModel()->ClearModel();
wheelBody->GetCollisionModel()->AddCylinder(0.46, 0.46, width / 2);
wheelBody->GetCollisionModel()->BuildModel();
wheelBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying rigid tire contact model.
// This version uses a collection of convex contact shapes (meshes).
MyLuggedTire::MyLuggedTire() {
std::string lugged_file("hmmwv/lugged_wheel_section.obj");
geometry::ChTriangleMeshConnected lugged_mesh;
utils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);
num_hulls = lugged_convex.GetHullCount();
}
void MyLuggedTire::onCallback(ChSharedPtr<ChBody> wheelBody, double radius, double width) {
wheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
ChCollisionModelParallel* coll_model = (ChCollisionModelParallel*)wheelBody->GetCollisionModel();
coll_model->ClearModel();
// Assemble the tire contact from 15 segments, properly offset.
// Each segment is further decomposed in convex hulls.
for (int iseg = 0; iseg < 15; iseg++) {
ChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);
for (int ihull = 0; ihull < num_hulls; ihull++) {
std::vector<ChVector<> > convexhull;
lugged_convex.GetConvexHullResult(ihull, convexhull);
coll_model->AddConvexHull(convexhull, VNULL, rot);
}
}
// Add a cylinder to represent the wheel hub.
coll_model->AddCylinder(0.223, 0.223, 0.126);
coll_model->BuildModel();
wheelBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying chassis contact model.
// This version uses a box representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
void MyChassisBoxModel_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
// Clear any existing assets (will be overriden)
chassisBody->GetCollisionModel()->ClearModel();
ChVector<> chLoc = ChVector<>(0, 0, 0);
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->AddBox(size.x, size.y, size.z, chLoc, rot);
// utils::AddBoxGeometry(
// chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
chassisBody->GetAssets().clear();
ChSharedPtr<ChBoxShape> box(new ChBoxShape);
box->GetBoxGeometry().Size = size;
box->Rot = rot;
chassisBody->GetAssets().push_back(box);
}
void MyChassisBoxModel_vis::SetAttributes(const ChVector<>& otherSize,
const ChQuaternion<>& otherRot,
const ChVector<>& otherLoc) {
size = otherSize;
rot = otherRot;
loc = otherLoc;
}
// Callback class for specifying chassis contact model.
// This version uses a sphere representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
void MyChassisSphereModel_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
// Clear any existing assets (will be overriden)
chassisBody->GetCollisionModel()->ClearModel();
ChVector<> chLoc = ChVector<>(0, 0, 0);
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->AddSphere(rad, chLoc);
// utils::AddBoxGeometry(
// chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
chassisBody->GetAssets().clear();
ChSharedPtr<ChSphereShape> sphere(new ChSphereShape);
sphere->GetSphereGeometry().rad = rad;
chassisBody->GetAssets().push_back(sphere);
}
void MyChassisSphereModel_vis::SetAttributes(double otherRad,
const ChQuaternion<>& otherRot,
const ChVector<>& otherLoc) {
rad = otherRad;
rot = otherRot;
loc = otherLoc;
}
// Callback class for specifying chassis contact model.
// This version uses a convex decomposition of an obj representing the chassis.
MyChassisSimpleConvexMesh::MyChassisSimpleConvexMesh() :
pos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {
// std::string chassis_obj_file("hmmwv/lugged_wheel_section.obj");
// std::string chassis_obj_file("hmmwv/lugged_wheel.obj");
// std::string chassis_obj_file("hmmwv/myHumvee.obj");
// chassis_obj_file = std::string("hmmwv/myHumvee1.obj");
chassis_obj_file = std::string("hmmwv/hmmwv_chassis_simple.obj");
utils::LoadConvexMesh(vehicle::GetDataFile(chassis_obj_file), chassis_mesh, chassis_convex);
}
void MyChassisSimpleConvexMesh::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
ChVector<> chLoc = ChVector<>(0, 0, 0); // chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->ClearModel();
// utils::AddConvexCollisionModel(chassisBody, chassis_mesh, chassis_convex, chLoc, ChQuaternion<>(1, 0, 0, 0),
// false);
// **************************
ChSharedPtr<ChBody> body = chassisBody;
geometry::ChTriangleMeshConnected& convex_mesh = chassis_mesh;
ChConvexDecompositionHACDv2& convex_shape = chassis_convex;
ChConvexDecomposition* used_decomposition = &convex_shape;
//*****
int hull_count = used_decomposition->GetHullCount();
for (int c = 0; c < hull_count; c++) {
std::vector<ChVector<double> > convexhull;
used_decomposition->GetConvexHullResult(c, convexhull);
((collision::ChCollisionModelParallel*)body->GetCollisionModel())->AddConvexHull(convexhull, chLoc, rot);
}
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
// printf("chassis family %d \n", chassisBody->GetCollisionModel()->GetFamily());
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
// **************************
// chassisBody->RecomputeCollisionModel();
// chassisBody->SetCollide(false);
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying chassis contact model.
// This version uses a triangular given in an obj representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
MyChassisSimpleTriMesh_vis::MyChassisSimpleTriMesh_vis() :
pos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {
// chassis_obj_file = std::string("hmmwv/myHumvee1.obj");
chassis_obj_file = std::string("hmmwv/hmmwv_chassis_simple.obj");
}
void MyChassisSimpleTriMesh_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
// Clear any existing assets (will be overriden)
const std::string mesh_name("chassis");
chassisBody->GetAssets().clear();
// ChVector<> chLoc = ChVector<>(0,0,0);//chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->ClearModel();
// utils::AddTriangleMeshGeometry(chassisBody.get_ptr(), vehicle::GetDataFile(chassis_obj_file), mesh_name, pos,
// rot, true);
ChVector<> chLoc = ChVector<>(0, 0, 0); // chassisBody->GetFrame_REF_to_COG().GetPos();
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
// *** here
std::string obj_filename = vehicle::GetDataFile(chassis_obj_file);
const std::string& name = mesh_name;
ChBody* body = chassisBody.get_ptr();
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(obj_filename, false, false);
for (int i = 0; i < trimesh.m_vertices.size(); i++)
trimesh.m_vertices[i] = pos + rot.Rotate(trimesh.m_vertices[i]);
body->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, chLoc);
if (true) {
ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName(name);
trimesh_shape->Pos = ChVector<>(0, 0, 0);
trimesh_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
body->GetAssets().push_back(trimesh_shape);
}
// *** to here
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
}
<commit_msg>collision model need to be set for contact geometries<commit_after>/*
* VehicleExtraProperties.cpp
*
* Created on: Apr 25, 2015
* Author: arman
*/
#include "VehicleExtraProperties.h"
// Arman : maybe too many includes
#include "core/ChStream.h"
//#include "chrono_parallel/lcp/ChLcpSystemDescriptorParallel.h"
//#include "chrono_parallel/collision/ChCNarrowphaseRUtils.h"
#include "chrono_vehicle/ChVehicleModelData.h"
int chassisFam = 2;
int tireFam = 3;
//#include "hmmwvParams.h"
using namespace chrono;
using namespace collision;
// Tire Coefficient of friction
float mu_t = 0.8;
// Callback class for providing driver inputs.
MyDriverInputs::MyDriverInputs(double delay) : m_delay(delay) {}
void MyDriverInputs::onCallback(double time, double& throttle, double& steering, double& braking) {
throttle = 0;
steering = 0;
braking = 0;
double eff_time = time - m_delay;
// Do not generate any driver inputs for a duration equal to m_delay.
if (eff_time < 0)
return;
if (eff_time > 0.2)
throttle = 1.0;
else if (eff_time > 0.1)
throttle = 10 * (eff_time - 0.1);
}
// Callback class for specifying rigid tire contact model.
// This version uses cylindrical contact shapes.
void MyCylindricalTire::onCallback(ChSharedPtr<ChBody> wheelBody, double radius, double width) {
wheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
wheelBody->GetCollisionModel()->ClearModel();
wheelBody->GetCollisionModel()->AddCylinder(0.46, 0.46, width / 2);
wheelBody->GetCollisionModel()->BuildModel();
wheelBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying rigid tire contact model.
// This version uses a collection of convex contact shapes (meshes).
MyLuggedTire::MyLuggedTire() {
std::string lugged_file("hmmwv/lugged_wheel_section.obj");
geometry::ChTriangleMeshConnected lugged_mesh;
utils::LoadConvexMesh(vehicle::GetDataFile(lugged_file), lugged_mesh, lugged_convex);
num_hulls = lugged_convex.GetHullCount();
}
void MyLuggedTire::onCallback(ChSharedPtr<ChBody> wheelBody, double radius, double width) {
wheelBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
ChCollisionModelParallel* coll_model = (ChCollisionModelParallel*)wheelBody->GetCollisionModel();
coll_model->ClearModel();
// Assemble the tire contact from 15 segments, properly offset.
// Each segment is further decomposed in convex hulls.
for (int iseg = 0; iseg < 15; iseg++) {
ChQuaternion<> rot = Q_from_AngAxis(iseg * 24 * CH_C_DEG_TO_RAD, VECT_Y);
for (int ihull = 0; ihull < num_hulls; ihull++) {
std::vector<ChVector<> > convexhull;
lugged_convex.GetConvexHullResult(ihull, convexhull);
coll_model->AddConvexHull(convexhull, VNULL, rot);
}
}
// Add a cylinder to represent the wheel hub.
coll_model->AddCylinder(0.223, 0.223, 0.126);
coll_model->BuildModel();
wheelBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying chassis contact model.
// This version uses a box representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
void MyChassisBoxModel_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
// Clear any existing assets (will be overriden)
chassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
chassisBody->GetCollisionModel()->ClearModel();
ChVector<> chLoc = ChVector<>(0, 0, 0);
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->AddBox(size.x, size.y, size.z, chLoc, rot);
// utils::AddBoxGeometry(
// chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
chassisBody->GetAssets().clear();
ChSharedPtr<ChBoxShape> box(new ChBoxShape);
box->GetBoxGeometry().Size = size;
box->Rot = rot;
chassisBody->GetAssets().push_back(box);
}
void MyChassisBoxModel_vis::SetAttributes(const ChVector<>& otherSize,
const ChQuaternion<>& otherRot,
const ChVector<>& otherLoc) {
size = otherSize;
rot = otherRot;
loc = otherLoc;
}
// Callback class for specifying chassis contact model.
// This version uses a sphere representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
void MyChassisSphereModel_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
// Clear any existing assets (will be overriden)
chassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
chassisBody->GetCollisionModel()->ClearModel();
ChVector<> chLoc = ChVector<>(0, 0, 0);
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->AddSphere(rad, chLoc);
// utils::AddBoxGeometry(
// chassisBody.get_ptr(), ChVector<>(1, .5, .05), ChVector<>(0, 0, 0), ChQuaternion<>(1, 0, 0, 0), true);
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
chassisBody->GetAssets().clear();
ChSharedPtr<ChSphereShape> sphere(new ChSphereShape);
sphere->GetSphereGeometry().rad = rad;
chassisBody->GetAssets().push_back(sphere);
}
void MyChassisSphereModel_vis::SetAttributes(double otherRad,
const ChQuaternion<>& otherRot,
const ChVector<>& otherLoc) {
rad = otherRad;
rot = otherRot;
loc = otherLoc;
}
// Callback class for specifying chassis contact model.
// This version uses a convex decomposition of an obj representing the chassis.
MyChassisSimpleConvexMesh::MyChassisSimpleConvexMesh() :
pos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {
// std::string chassis_obj_file("hmmwv/lugged_wheel_section.obj");
// std::string chassis_obj_file("hmmwv/lugged_wheel.obj");
// std::string chassis_obj_file("hmmwv/myHumvee.obj");
// chassis_obj_file = std::string("hmmwv/myHumvee1.obj");
chassis_obj_file = std::string("hmmwv/hmmwv_chassis_simple.obj");
utils::LoadConvexMesh(vehicle::GetDataFile(chassis_obj_file), chassis_mesh, chassis_convex);
}
void MyChassisSimpleConvexMesh::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
chassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
ChVector<> chLoc = ChVector<>(0, 0, 0); // chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->ClearModel();
// utils::AddConvexCollisionModel(chassisBody, chassis_mesh, chassis_convex, chLoc, ChQuaternion<>(1, 0, 0, 0),
// false);
// **************************
ChSharedPtr<ChBody> body = chassisBody;
geometry::ChTriangleMeshConnected& convex_mesh = chassis_mesh;
ChConvexDecompositionHACDv2& convex_shape = chassis_convex;
ChConvexDecomposition* used_decomposition = &convex_shape;
//*****
int hull_count = used_decomposition->GetHullCount();
for (int c = 0; c < hull_count; c++) {
std::vector<ChVector<double> > convexhull;
used_decomposition->GetConvexHullResult(c, convexhull);
((collision::ChCollisionModelParallel*)body->GetCollisionModel())->AddConvexHull(convexhull, chLoc, rot);
}
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
// printf("chassis family %d \n", chassisBody->GetCollisionModel()->GetFamily());
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
// **************************
// chassisBody->RecomputeCollisionModel();
// chassisBody->SetCollide(false);
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
}
// Callback class for specifying chassis contact model.
// This version uses a triangular given in an obj representing the chassis.
// In addition, this version overrides the visualization assets of the provided
// chassis body with the collision meshes.
MyChassisSimpleTriMesh_vis::MyChassisSimpleTriMesh_vis() :
pos(chrono::ChVector<>(0, 0, 0)) , rot( chrono::ChQuaternion<>(1, 0, 0, 0)) {
// chassis_obj_file = std::string("hmmwv/myHumvee1.obj");
chassis_obj_file = std::string("hmmwv/hmmwv_chassis_simple.obj");
}
void MyChassisSimpleTriMesh_vis::onCallback(ChSharedPtr<ChBodyAuxRef> chassisBody) {
chassisBody->ChangeCollisionModel(new collision::ChCollisionModelParallel);
// Clear any existing assets (will be overriden)
const std::string mesh_name("chassis");
chassisBody->GetAssets().clear();
// ChVector<> chLoc = ChVector<>(0,0,0);//chassisBody->GetFrame_REF_to_COG().GetPos();
chassisBody->GetCollisionModel()->ClearModel();
// utils::AddTriangleMeshGeometry(chassisBody.get_ptr(), vehicle::GetDataFile(chassis_obj_file), mesh_name, pos,
// rot, true);
ChVector<> chLoc = ChVector<>(0, 0, 0); // chassisBody->GetFrame_REF_to_COG().GetPos();
// ChVector<> chLoc = chassisBody->GetFrame_REF_to_COG().GetPos();
// *** here
std::string obj_filename = vehicle::GetDataFile(chassis_obj_file);
const std::string& name = mesh_name;
ChBody* body = chassisBody.get_ptr();
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(obj_filename, false, false);
for (int i = 0; i < trimesh.m_vertices.size(); i++)
trimesh.m_vertices[i] = pos + rot.Rotate(trimesh.m_vertices[i]);
body->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, chLoc);
if (true) {
ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName(name);
trimesh_shape->Pos = ChVector<>(0, 0, 0);
trimesh_shape->Rot = ChQuaternion<>(1, 0, 0, 0);
body->GetAssets().push_back(trimesh_shape);
}
// *** to here
chassisBody->GetCollisionModel()->SetFamily(chassisFam);
chassisBody->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(tireFam);
chassisBody->GetCollisionModel()->BuildModel();
chassisBody->GetMaterialSurface()->SetFriction(mu_t);
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "VirtualMachineTemplate.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
std::map<std::string, std::set<std::string> > VirtualMachineTemplate::restricted;
std::map<std::string, std::set<std::string> > VirtualMachineTemplate::encrypted;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VirtualMachineTemplate::replace_disk_image(int target_id, const string&
target_name, const string& target_uname, const string& new_name,
const string& new_uname)
{
int num_disks;
int tmp_id;
string tmp_name;
string tmp_uname;
vector<VectorAttribute *> disks;
VectorAttribute * disk = 0;
num_disks = get("DISK", disks);
for(int i=0; i<num_disks; i++)
{
disk = disks[i];
if (disk->vector_value("IMAGE_ID", tmp_id) == 0) //DISK has IMAGE_ID
{
if (tmp_id == target_id)
{
break;
}
}
else //IMAGE and IMAGE_UNAME
{
tmp_name = disk->vector_value("IMAGE");
tmp_uname = disk->vector_value("IMAGE_UNAME");
bool uname = tmp_uname.empty() || tmp_uname == target_uname;
if ( tmp_name == target_name && uname )
{
break;
}
}
disk = 0;
}
if ( disk == 0 )
{
return -1;
}
disk->remove("IMAGE_ID");
disk->replace("IMAGE", new_name);
disk->replace("IMAGE_UNAME", new_uname);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& VirtualMachineTemplate::to_xml_short(string& xml) const
{
ostringstream oss;
string labels;
string schd_rank, schd_ds_rank;
string schd_req, schd_ds_req;
string user_prio;
vector<const VectorAttribute*> attrs;
if (attributes.empty())
{
oss << "<USER_TEMPLATE/>";
}
else
{
oss << "<USER_TEMPLATE>";
/* ------------------------------------------------------------------ */
/* Attributes required by Sunstone */
/* - LABELS */
/* ------------------------------------------------------------------ */
if (get("LABELS", labels))
{
oss << "<LABELS>" << one_util::escape_xml(labels) << "</LABELS>";
}
/* ------------------------------------------------------------------ */
/* Attributes required by Scheduler */
/* - SCHED_RANK (RANK - deprecated) */
/* - SCHED_DS_RANK */
/* - SCHED_REQUIREMENTS */
/* - SCHED_DS_REQUIREMENTS */
/* */
/* - SCHED_ACTION */
/* - PUBLIC_CLOUD */
/* ------------------------------------------------------------------ */
if (get("SCHED_RANK", schd_rank))
{
oss << "<SCHED_RANK>" << one_util::escape_xml(schd_rank)
<< "</SCHED_RANK>";
}
if (get("SCHED_DS_RANK", schd_ds_rank))
{
oss << "<SCHED_DS_RANK>" << one_util::escape_xml(schd_ds_rank)
<< "</SCHED_DS_RANK>";
}
if (get("SCHED_REQUIREMENTS", schd_req))
{
oss << "<SCHED_REQUIREMENTS>" << one_util::escape_xml(schd_req)
<< "</SCHED_REQUIREMENTS>";
}
if (get("SCHED_DS_REQUIREMENTS", schd_ds_req))
{
oss << "<SCHED_DS_REQUIREMENTS>" << one_util::escape_xml(schd_ds_req)
<< "</SCHED_DS_REQUIREMENTS>";
}
if (get("USER_PRIORITY", user_prio))
{
oss << "<USER_PRIORITY>" << one_util::escape_xml(user_prio)
<< "</USER_PRIORITY>";
}
if ( get("PUBLIC_CLOUD", attrs) > 0 )
{
for (auto vattr : attrs)
{
vattr->to_xml(oss);
}
}
attrs.clear();
if ( get("SCHED_ACTION", attrs) > 0 )
{
for (auto vattr : attrs)
{
vattr->to_xml(oss);
}
}
oss << "</USER_TEMPLATE>";
}
xml = oss.str();
return xml;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
std::map<std::string,std::vector<std::string>> VirtualMachineTemplate::UPDATECONF_ATTRS = {
{ "OS",
{ "ARCH",
"MACHINE",
"KERNEL",
"INITRD",
"BOOTLOADER",
"BOOT",
"KERNEL_CMD",
"ROOT",
"SD_DISK_BUS",
"UUID"}
},
{ "FEATURES",
{ "PAE",
"ACPI",
"APIC",
"LOCALTIME",
"HYPERV",
"GUEST_AGENT",
"VIRTIO_SCSI_QUEUES",
"IOTHREADS"}
},
{ "INPUT",
{ "TYPE",
"BUS"}
},
{"GRAPHICS",
{ "TYPE",
"LISTEN",
"PASSWD",
"KEYMAP",
"COMMAND"}
},
{"RAW",
{ "TYPE",
"DATA",
"DATA_VMX"}
},
{"CPU_MODEL",
{ "MODEL" }
}
};
// -----------------------------------------------------------------------------
/**
* returns a copy the values of a vector value
*/
static void copy_vector_values(const Template *old_tmpl, Template *new_tmpl,
const char * name)
{
string value;
const VectorAttribute * old_attr = old_tmpl->get(name);
if ( old_attr == 0 )
{
return;
}
VectorAttribute * new_vattr = new VectorAttribute(name);
std::vector<std::string> vnames = VirtualMachineTemplate::UPDATECONF_ATTRS[name];
for (const auto& vname : vnames)
{
std::string vval = old_attr->vector_value(vname);
if (!vval.empty())
{
new_vattr->replace(vname, vval);
}
}
if ( new_vattr->empty() )
{
delete new_vattr;
}
else
{
new_tmpl->set(new_vattr);
}
}
// -----------------------------------------------------------------------------
unique_ptr<VirtualMachineTemplate> VirtualMachineTemplate::get_updateconf_template() const
{
auto conf_tmpl = make_unique<VirtualMachineTemplate>();
copy_vector_values(this, conf_tmpl.get(), "OS");
copy_vector_values(this, conf_tmpl.get(), "FEATURES");
copy_vector_values(this, conf_tmpl.get(), "INPUT");
copy_vector_values(this, conf_tmpl.get(), "GRAPHICS");
copy_vector_values(this, conf_tmpl.get(), "RAW");
const VectorAttribute * context = get("CONTEXT");
if ( context != 0 )
{
conf_tmpl->set(context->clone());
}
return conf_tmpl;
}
<commit_msg>B #5096: fix minor bug with CPU_MODEL (#979)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "VirtualMachineTemplate.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
std::map<std::string, std::set<std::string> > VirtualMachineTemplate::restricted;
std::map<std::string, std::set<std::string> > VirtualMachineTemplate::encrypted;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VirtualMachineTemplate::replace_disk_image(int target_id, const string&
target_name, const string& target_uname, const string& new_name,
const string& new_uname)
{
int num_disks;
int tmp_id;
string tmp_name;
string tmp_uname;
vector<VectorAttribute *> disks;
VectorAttribute * disk = 0;
num_disks = get("DISK", disks);
for(int i=0; i<num_disks; i++)
{
disk = disks[i];
if (disk->vector_value("IMAGE_ID", tmp_id) == 0) //DISK has IMAGE_ID
{
if (tmp_id == target_id)
{
break;
}
}
else //IMAGE and IMAGE_UNAME
{
tmp_name = disk->vector_value("IMAGE");
tmp_uname = disk->vector_value("IMAGE_UNAME");
bool uname = tmp_uname.empty() || tmp_uname == target_uname;
if ( tmp_name == target_name && uname )
{
break;
}
}
disk = 0;
}
if ( disk == 0 )
{
return -1;
}
disk->remove("IMAGE_ID");
disk->replace("IMAGE", new_name);
disk->replace("IMAGE_UNAME", new_uname);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& VirtualMachineTemplate::to_xml_short(string& xml) const
{
ostringstream oss;
string labels;
string schd_rank, schd_ds_rank;
string schd_req, schd_ds_req;
string user_prio;
vector<const VectorAttribute*> attrs;
if (attributes.empty())
{
oss << "<USER_TEMPLATE/>";
}
else
{
oss << "<USER_TEMPLATE>";
/* ------------------------------------------------------------------ */
/* Attributes required by Sunstone */
/* - LABELS */
/* ------------------------------------------------------------------ */
if (get("LABELS", labels))
{
oss << "<LABELS>" << one_util::escape_xml(labels) << "</LABELS>";
}
/* ------------------------------------------------------------------ */
/* Attributes required by Scheduler */
/* - SCHED_RANK (RANK - deprecated) */
/* - SCHED_DS_RANK */
/* - SCHED_REQUIREMENTS */
/* - SCHED_DS_REQUIREMENTS */
/* */
/* - SCHED_ACTION */
/* - PUBLIC_CLOUD */
/* ------------------------------------------------------------------ */
if (get("SCHED_RANK", schd_rank))
{
oss << "<SCHED_RANK>" << one_util::escape_xml(schd_rank)
<< "</SCHED_RANK>";
}
if (get("SCHED_DS_RANK", schd_ds_rank))
{
oss << "<SCHED_DS_RANK>" << one_util::escape_xml(schd_ds_rank)
<< "</SCHED_DS_RANK>";
}
if (get("SCHED_REQUIREMENTS", schd_req))
{
oss << "<SCHED_REQUIREMENTS>" << one_util::escape_xml(schd_req)
<< "</SCHED_REQUIREMENTS>";
}
if (get("SCHED_DS_REQUIREMENTS", schd_ds_req))
{
oss << "<SCHED_DS_REQUIREMENTS>" << one_util::escape_xml(schd_ds_req)
<< "</SCHED_DS_REQUIREMENTS>";
}
if (get("USER_PRIORITY", user_prio))
{
oss << "<USER_PRIORITY>" << one_util::escape_xml(user_prio)
<< "</USER_PRIORITY>";
}
if ( get("PUBLIC_CLOUD", attrs) > 0 )
{
for (auto vattr : attrs)
{
vattr->to_xml(oss);
}
}
attrs.clear();
if ( get("SCHED_ACTION", attrs) > 0 )
{
for (auto vattr : attrs)
{
vattr->to_xml(oss);
}
}
oss << "</USER_TEMPLATE>";
}
xml = oss.str();
return xml;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
std::map<std::string,std::vector<std::string>> VirtualMachineTemplate::UPDATECONF_ATTRS = {
{ "OS",
{ "ARCH",
"MACHINE",
"KERNEL",
"INITRD",
"BOOTLOADER",
"BOOT",
"KERNEL_CMD",
"ROOT",
"SD_DISK_BUS",
"UUID"}
},
{ "FEATURES",
{ "PAE",
"ACPI",
"APIC",
"LOCALTIME",
"HYPERV",
"GUEST_AGENT",
"VIRTIO_SCSI_QUEUES",
"IOTHREADS"}
},
{ "INPUT",
{ "TYPE",
"BUS"}
},
{"GRAPHICS",
{ "TYPE",
"LISTEN",
"PASSWD",
"KEYMAP",
"COMMAND"}
},
{"RAW",
{ "TYPE",
"DATA",
"DATA_VMX"}
},
{"CPU_MODEL",
{ "MODEL" }
}
};
// -----------------------------------------------------------------------------
/**
* returns a copy the values of a vector value
*/
static void copy_vector_values(const Template *old_tmpl, Template *new_tmpl,
const char * name)
{
string value;
const VectorAttribute * old_attr = old_tmpl->get(name);
if ( old_attr == 0 )
{
return;
}
VectorAttribute * new_vattr = new VectorAttribute(name);
std::vector<std::string> vnames = VirtualMachineTemplate::UPDATECONF_ATTRS[name];
for (const auto& vname : vnames)
{
std::string vval = old_attr->vector_value(vname);
if (!vval.empty())
{
new_vattr->replace(vname, vval);
}
}
if ( new_vattr->empty() )
{
delete new_vattr;
}
else
{
new_tmpl->set(new_vattr);
}
}
// -----------------------------------------------------------------------------
unique_ptr<VirtualMachineTemplate> VirtualMachineTemplate::get_updateconf_template() const
{
auto conf_tmpl = make_unique<VirtualMachineTemplate>();
copy_vector_values(this, conf_tmpl.get(), "OS");
copy_vector_values(this, conf_tmpl.get(), "FEATURES");
copy_vector_values(this, conf_tmpl.get(), "INPUT");
copy_vector_values(this, conf_tmpl.get(), "GRAPHICS");
copy_vector_values(this, conf_tmpl.get(), "RAW");
copy_vector_values(this, conf_tmpl.get(), "CPU_MODEL");
const VectorAttribute * context = get("CONTEXT");
if ( context != 0 )
{
conf_tmpl->set(context->clone());
}
return conf_tmpl;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: estack.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: np $ $Date: 2002-03-08 14:45:27 $
*
* 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 ARY_ESTACK_HXX
#define ARY_ESTACK_HXX
// USED SERVICES
// BASE CLASSES
#include <slist>
// COMPONENTS
// PARAMETERS
template <class ELEM>
class EStack : private std::slist<ELEM>
{
private:
typedef std::slist<ELEM> base;
const base & Base() const { return *this; }
base & Base() { return *this; }
public:
typedef ELEM value_type;
typedef std::slist<ELEM>::size_type size_type;
// LIFECYCLE
EStack() {}
EStack(
const EStack & i_rStack )
: base( (const base &)(i_rStack) ) {}
~EStack() {}
// OPERATORS
EStack & operator=(
const EStack & i_rStack )
{ base::operator=( i_rStack.Base() );
return *this; }
bool operator==(
const EStack<ELEM> &
i_r2 ) const
{ return std::operator==( Base(), i_rStack.Base() ); }
bool operator<(
const EStack<ELEM> &
i_r2 ) const
{ return std::operator<( Base(), i_rStack.Base() ); }
// OPERATIONS
void push(
const value_type & i_rElem )
{ base::push_front(i_rElem); }
void pop() { base::pop_front(); }
void erase_all() { while (NOT empty()) pop(); }
// INQUIRY
const value_type & top() const { return base::front(); }
size_type size() const { return base::size(); }
bool empty() const { return base::empty(); }
// ACCESS
value_type & top() { return base::front(); }
};
// IMPLEMENTATION
#endif
<commit_msg>INTEGRATION: CWS adc6 (1.1.1.1.50); FILE MERGED 2003/06/26 14:43:32 np 1.1.1.1.50.1: #110259# Fix differing output on Windows vs. Unix and remove broken links from output.<commit_after>/*************************************************************************
*
* $RCSfile: estack.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-06-30 15:27:34 $
*
* 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 ARY_ESTACK_HXX
#define ARY_ESTACK_HXX
// USED SERVICES
// BASE CLASSES
#include <slist>
// COMPONENTS
// PARAMETERS
template <class ELEM>
class EStack : private std::slist<ELEM>
{
private:
typedef std::slist<ELEM> base;
const base & Base() const { return *this; }
base & Base() { return *this; }
public:
typedef ELEM value_type;
typedef typename std::slist<ELEM>::size_type size_type;
// LIFECYCLE
EStack() {}
EStack(
const EStack & i_rStack )
: base( (const base &)(i_rStack) ) {}
~EStack() {}
// OPERATORS
EStack & operator=(
const EStack & i_rStack )
{ base::operator=( i_rStack.Base() );
return *this; }
bool operator==(
const EStack<ELEM> &
i_r2 ) const
{ return std::operator==( Base(), i_rStack.Base() ); }
bool operator<(
const EStack<ELEM> &
i_r2 ) const
{ return std::operator<( Base(), i_rStack.Base() ); }
// OPERATIONS
void push(
const value_type & i_rElem )
{ base::push_front(i_rElem); }
void pop() { base::pop_front(); }
void erase_all() { while (NOT empty()) pop(); }
// INQUIRY
const value_type & top() const { return base::front(); }
size_type size() const { return base::size(); }
bool empty() const { return base::empty(); }
// ACCESS
value_type & top() { return base::front(); }
};
// IMPLEMENTATION
#endif
<|endoftext|> |
<commit_before><commit_msg>Added unit test relative displacement<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.